diff --git a/.circleci/config.yml b/.circleci/config.yml index 2f05fb9a72ed..71098116b4c3 100644 --- a/.circleci/config.yml +++ b/.circleci/config.yml @@ -57,54 +57,43 @@ commands: # a reusable command with parameters - run: docker ps -a - run: sleep 30 - run: cat /etc/hosts - # Test - - run: ./mvnw --no-snapshot-updates --quiet clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error + - run: export MAVEN_OPTS="-Xmx1024m -XX:MaxPermSize=128m" - run: name: "Setup custom environment variables" command: echo 'export CIRCLE_NODE_INDEX="<>"' >> $BASH_ENV - run: ./CI/circle_parallel.sh # Save dependency cache - - save_cache: - key: source-v2-{{ .Branch }}-{{ .Revision }} - paths: - # This is a broad list of cache paths to include many possible development environments - # You can probably delete some of these entries - - vendor/bundle - - ~/.nvm - - ~/.pyenv - - ~/virtualenvs - - ~/.m2 - - ~/.ivy2 - - ~/.sbt - - ~/.bundle - - ~/.go_workspace - - ~/.gradle - - ~/.cache/bower - - ".git" - - ~/.stack - - /home/circleci/OpenAPITools/openapi-generator/samples/client/petstore/haskell-http-client/.stack-work - - ~/R - # save "default" cache using the key "source-v2-" - - save_cache: - key: source-v2- - paths: - # This is a broad list of cache paths to include many possible development environments - # You can probably delete some of these entries - - vendor/bundle - - ~/.nvm - - ~/.pyenv - - ~/virtualenvs - - ~/.m2 - - ~/.ivy2 - - ~/.sbt - - ~/.bundle - - ~/.go_workspace - - ~/.gradle - - ~/.cache/bower - - ".git" - - ~/.stack - - /home/circleci/OpenAPITools/openapi-generator/samples/client/petstore/haskell-http-client/.stack-work - - ~/R + #- save_cache: + # key: source-v2-{{ .Branch }}-{{ .Revision }} + # paths: + # # This is a broad list of cache paths to include many possible development environments + # # You can probably delete some of these entries + # - ~/.m2 + # - ~/.ivy2 + # - ~/.sbt + # - ~/.bundle + # - ~/.go_workspace + # - ~/.gradle + # - ".git" + # - ~/.stack + # - ~/R + ## save "default" cache using the key "source-v2-" + #- save_cache: + # key: source-v2- + # paths: + # # This is a broad list of cache paths to include many possible development environments + # # You can probably delete some of these entries + # - vendor/bundle + # - ~/.m2 + # - ~/.ivy2 + # - ~/.sbt + # - ~/.bundle + # - ~/.go_workspace + # - ~/.gradle + # - ~/.cache/bower + # - ".git" + # - ~/.stack + # - ~/R # Teardown # If you break your build into multiple jobs with workflows, you will probably want to do the parts of this that are relevant in each # Save test results diff --git a/.devcontainer/devcontainer.json b/.devcontainer/devcontainer.json index aeb7cc5dc942..1f46f227a79b 100644 --- a/.devcontainer/devcontainer.json +++ b/.devcontainer/devcontainer.json @@ -9,7 +9,12 @@ "ghcr.io/devcontainers/features/node:1": { "version": "lts" }, - "ghcr.io/snebjorn/devcontainer-feature/chromium:latest": {} + "ghcr.io/snebjorn/devcontainer-feature/chromium:latest": {}, + "docker-in-docker": { + "version": "latest", + "moby": true, + "dockerDashComposeVersion": "v1" + } }, // Configure tool-specific properties. "customizations": { @@ -44,4 +49,4 @@ // "postCreateCommand": "mvn clean package -DskipTests", // Comment out to connect as root instead. More info: https://aka.ms/vscode-remote/containers/non-root. "remoteUser": "vscode" -} +} \ No newline at end of file diff --git a/.envrc b/.envrc index 3550a30f2de3..b85b26d148b6 100644 --- a/.envrc +++ b/.envrc @@ -1 +1 @@ -use flake +has nix && use flake diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 416f9199ba27..328863d4c0d2 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -28,8 +28,14 @@ modules/openapi-generator-cli/**/* @jimschubert modules/openapi-generator-gradle-plugin/**/* @jimschubert modules/openapi-generator-maven-plugin/**/* @jimschubert -# Martin Delille -/Users/martin/dev/clone/openapi-generator/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtClientCodegen.java @martindelille -/Users/martin/dev/clone/openapi-generator/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppQtAbstractCodegen.java @martindelille -/Users/martin/dev/clone/openapi-generator/modules/openapi-generator/src/main/resources/cpp-qt-client @martindelille -/Users/martin/dev/clone/openapi-generator/samples/client/petstore/cpp-qt @martindelille +# cpp-qt-client technical committee +modules/openapi-generator/src/main/resources/cpp-qt-client/**/* @ravinikam +samples/client/petstore/cpp-qt/**/* @ravinikam +modules/openapi-generator/src/main/resources/cpp-qt-client/**/* @stkrwork +samples/client/petstore/cpp-qt/**/* @stkrwork +modules/openapi-generator/src/main/resources/cpp-qt-client/**/* @etherealjoy +samples/client/petstore/cpp-qt/**/* @etherealjoy +modules/openapi-generator/src/main/resources/cpp-qt-client/**/* @martindelille +samples/client/petstore/cpp-qt/**/* @martindelille +modules/openapi-generator/src/main/resources/cpp-qt-client/**/* @muttleyxd +samples/client/petstore/cpp-qt/**/* @muttleyxd diff --git a/.github/PULL_REQUEST_TEMPLATE.md b/.github/PULL_REQUEST_TEMPLATE.md index e88ba6dda640..0e596306d9dd 100644 --- a/.github/PULL_REQUEST_TEMPLATE.md +++ b/.github/PULL_REQUEST_TEMPLATE.md @@ -11,10 +11,11 @@ ./bin/generate-samples.sh ./bin/configs/*.yaml ./bin/utils/export_docs_generators.sh ``` + (For Windows users, please run the script in [Git BASH](https://gitforwindows.org/)) Commit all changed files. This is important, as CI jobs will verify _all_ generator outputs of your HEAD commit as it would merge with master. These must match the expectations made by your contribution. You may regenerate an individual generator by passing the relevant config(s) as an argument to the script, for example `./bin/generate-samples.sh bin/configs/java*`. - For Windows users, please run the script in [Git BASH](https://gitforwindows.org/). + IMPORTANT: Do **NOT** purge/delete any folders/files (e.g. tests) when regenerating the samples as manually written tests may be removed. - [ ] File the PR against the [correct branch](https://github.com/OpenAPITools/openapi-generator/wiki/Git-Branches): `master` (upcoming 7.1.0 minor release - breaking changes with fallbacks), `8.0.x` (breaking changes without fallbacks) - [ ] If your PR is targeting a particular programming language, @mention the [technical committee](https://github.com/openapitools/openapi-generator/#62---openapi-generator-technical-committee) members, so they are more likely to review the pull request. diff --git a/.github/workflows/docker.yaml b/.github/workflows/docker.yaml index b52ce072c0d5..c0e5dd3a483c 100644 --- a/.github/workflows/docker.yaml +++ b/.github/workflows/docker.yaml @@ -1,6 +1,7 @@ name: Docker tests on: + workflow_dispatch: push: paths: - Dockerfile @@ -8,6 +9,8 @@ on: - pom.xml - modules/openapi-generator-online/pom.xml - modules/openapi-generator-online/Dockerfile + - modules/openapi-generator-cli/pom.xml + - modules/openapi-generator-cli/Dockerfile pull_request: paths: - Dockerfile @@ -15,6 +18,8 @@ on: - pom.xml - modules/openapi-generator-online/pom.xml - modules/openapi-generator-online/Dockerfile + - modules/openapi-generator-cli/pom.xml + - modules/openapi-generator-cli/Dockerfile jobs: build: name: 'Build: Docker' @@ -27,7 +32,7 @@ jobs: shell: bash run: | sed -i 's/ -it / /g' run-in-docker.sh - ./run-in-docker.sh mvn clean install + ./run-in-docker.sh mvn -B clean install - name: Build Dockerfile shell: bash @@ -37,3 +42,12 @@ jobs: shell: bash run: | docker build modules/openapi-generator-online/ -t test + - name: Build and test modules/openapi-generator-cli + shell: bash + run: | + cp docker-entrypoint.sh ./modules/openapi-generator-cli + docker build modules/openapi-generator-cli/ -t cli-test + docker run --rm -v "${PWD}:/local" cli-test generate \ + -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ + -g go \ + -o /local/out/go diff --git a/.github/workflows/gradle-plugin-tests.yaml b/.github/workflows/gradle-plugin-tests.yaml index fdf278761b01..135a74263c30 100644 --- a/.github/workflows/gradle-plugin-tests.yaml +++ b/.github/workflows/gradle-plugin-tests.yaml @@ -15,7 +15,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' diff --git a/.github/workflows/gradle-test.yaml b/.github/workflows/gradle-test.yaml index 2746851ca013..7bf6cce1d635 100644 --- a/.github/workflows/gradle-test.yaml +++ b/.github/workflows/gradle-test.yaml @@ -31,7 +31,7 @@ jobs: - samples/client/petstore/java/webclient-swagger2 steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/linux.yaml b/.github/workflows/linux.yaml index c57a41dc0043..6bb3083d76a2 100644 --- a/.github/workflows/linux.yaml +++ b/.github/workflows/linux.yaml @@ -23,7 +23,7 @@ jobs: uses: actions/checkout@v4 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: ${{ matrix.java }} @@ -45,7 +45,7 @@ jobs: ${{ runner.os }}-gradle- - name: Setup Maven - uses: s4u/setup-maven-action@v1.10.0 + uses: s4u/setup-maven-action@v1.11.0 with: java-version: ${{ matrix.java }} maven-version: 3.8.8 @@ -57,7 +57,7 @@ jobs: GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_ACCESS_KEY }} - name: Upload Maven build artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 if: matrix.java == '11' && matrix.os == 'ubuntu-latest' with: name: artifact @@ -87,12 +87,12 @@ jobs: - name: Check out code uses: actions/checkout@v4 - name: Setup Maven - uses: s4u/setup-maven-action@v1.10.0 + uses: s4u/setup-maven-action@v1.11.0 with: java-version: 11 maven-version: 3.8.8 - name: Download build artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: artifact - name: Run Ensures Script diff --git a/.github/workflows/maven-plugin-tests.yaml b/.github/workflows/maven-plugin-tests.yaml index fe46066a3351..c64c9d14748e 100644 --- a/.github/workflows/maven-plugin-tests.yaml +++ b/.github/workflows/maven-plugin-tests.yaml @@ -15,7 +15,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' diff --git a/.github/workflows/openapi-generator.yaml b/.github/workflows/openapi-generator.yaml index 5fb9a9c4cb6e..177297ad00f7 100644 --- a/.github/workflows/openapi-generator.yaml +++ b/.github/workflows/openapi-generator.yaml @@ -17,7 +17,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' @@ -41,7 +41,7 @@ jobs: GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_ACCESS_KEY }} - run: ls -la modules/openapi-generator-cli/target - name: Upload openapi-generator-cli.jar artifact - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: openapi-generator-cli.jar path: modules/openapi-generator-cli/target/openapi-generator-cli.jar @@ -55,7 +55,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' @@ -79,7 +79,7 @@ jobs: GRADLE_ENTERPRISE_ACCESS_KEY: ${{ secrets.GRADLE_ENTERPRISE_ACCESS_KEY }} - name: Publish unit test reports if: ${{ always() }} - uses: actions/upload-artifact@v3 + uses: actions/upload-artifact@v4 with: name: surefire-test-results path: '**/surefire-reports/TEST-*.xml' @@ -92,12 +92,12 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' - name: Download openapi-generator-cli.jar artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: openapi-generator-cli.jar path: modules/openapi-generator-cli/target @@ -131,12 +131,12 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: 11 distribution: 'temurin' - name: Download openapi-generator-cli.jar artifact - uses: actions/download-artifact@v3 + uses: actions/download-artifact@v4 with: name: openapi-generator-cli.jar path: modules/openapi-generator-cli/target diff --git a/.github/workflows/samples-cpp-qt-client.yaml b/.github/workflows/samples-cpp-qt-client.yaml index a01af2c0298c..b65195b8bf9d 100644 --- a/.github/workflows/samples-cpp-qt-client.yaml +++ b/.github/workflows/samples-cpp-qt-client.yaml @@ -18,18 +18,16 @@ jobs: matrix: qt-version: - '5.15.2' - - '6.4.2' + - '6.5.3' os: - ubuntu-latest - macOS-latest - windows-latest - include: - - os: windows-latest - tools: 'tools_openssl_x64' runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v4 - - uses: jurplel/install-qt-action@v3 + - name: Install Qt + uses: jurplel/install-qt-action@v3 with: version: ${{ matrix.qt-version }} tools: ${{ matrix.tools }} diff --git a/.github/workflows/samples-dart.yaml b/.github/workflows/samples-dart.yaml index b6095e56c412..a2c4f59d8108 100644 --- a/.github/workflows/samples-dart.yaml +++ b/.github/workflows/samples-dart.yaml @@ -18,7 +18,7 @@ jobs: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/samples-dotnet-standard.yaml b/.github/workflows/samples-dotnet-standard.yaml index cde1955e6931..efa9666bba59 100644 --- a/.github/workflows/samples-dotnet-standard.yaml +++ b/.github/workflows/samples-dotnet-standard.yaml @@ -19,7 +19,7 @@ jobs: - samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0 steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v3.2.0 + - uses: actions/setup-dotnet@v4.0.0 with: dotnet-version: 3.1.* - name: Build diff --git a/.github/workflows/samples-dotnet.yaml b/.github/workflows/samples-dotnet.yaml index 8ee577de2c86..9d2c9b1bc533 100644 --- a/.github/workflows/samples-dotnet.yaml +++ b/.github/workflows/samples-dotnet.yaml @@ -4,6 +4,7 @@ on: push: paths: - 'samples/client/petstore/csharp/**net6.0**/' + - 'samples/client/petstore/csharp/**net7.0**/' - 'samples/client/petstore/csharp/OpenAPIClient-generichost-netcore**/' - 'samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/**' - 'samples/server/petstore/aspnetcore-6.0/**' @@ -12,6 +13,7 @@ on: pull_request: paths: - 'samples/client/petstore/csharp/**net6.0**/' + - 'samples/client/petstore/csharp/**net7.0**/' - 'samples/client/petstore/csharp/OpenAPIClient-generichost-netcore**/' - 'samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/**' - 'samples/server/petstore/aspnetcore-6.0/**' @@ -35,6 +37,8 @@ jobs: - samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf - samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf - samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests + - samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate + - samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate - samples/server/petstore/aspnetcore-6.0 - samples/server/petstore/aspnetcore-6.0-pocoModels - samples/server/petstore/aspnetcore-6.0-project4Models @@ -43,9 +47,9 @@ jobs: - samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v3.2.0 + - uses: actions/setup-dotnet@v4.0.0 with: - dotnet-version: '7.0.x' + dotnet-version: '8.0.x' - name: Build working-directory: ${{ matrix.sample }} run: dotnet build Org.OpenAPITools.sln diff --git a/.github/workflows/samples-dotnet6-client-echo-api.yaml b/.github/workflows/samples-dotnet6-client-echo-api.yaml index a0dcb8a58c2a..0cc3f10bb429 100644 --- a/.github/workflows/samples-dotnet6-client-echo-api.yaml +++ b/.github/workflows/samples-dotnet6-client-echo-api.yaml @@ -19,7 +19,7 @@ jobs: - samples/client/echo_api/csharp-restsharp/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v3.2.0 + - uses: actions/setup-dotnet@v4.0.0 with: dotnet-version: '6.0.x' - name: Run echo server diff --git a/.github/workflows/samples-dotnet6-client.yaml b/.github/workflows/samples-dotnet6-client.yaml index fdfbdab7db55..2afe3d22e6fe 100644 --- a/.github/workflows/samples-dotnet6-client.yaml +++ b/.github/workflows/samples-dotnet6-client.yaml @@ -73,7 +73,7 @@ jobs: - samples/client/petstore/csharp-restsharp-name-parameter-mappings steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v3.2.0 + - uses: actions/setup-dotnet@v4.0.0 with: dotnet-version: '6.0.x' - name: Build diff --git a/.github/workflows/samples-dotnet6-server.yaml b/.github/workflows/samples-dotnet6-server.yaml index ea8a278a0327..377a48428f55 100644 --- a/.github/workflows/samples-dotnet6-server.yaml +++ b/.github/workflows/samples-dotnet6-server.yaml @@ -30,7 +30,7 @@ jobs: - samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes steps: - uses: actions/checkout@v4 - - uses: actions/setup-dotnet@v3.2.0 + - uses: actions/setup-dotnet@v4.0.0 with: dotnet-version: '6.0.x' - name: Build diff --git a/.github/workflows/samples-go-client-echo-api.yaml b/.github/workflows/samples-go-client-echo-api.yaml new file mode 100644 index 000000000000..f82e2a08a30e --- /dev/null +++ b/.github/workflows/samples-go-client-echo-api.yaml @@ -0,0 +1,32 @@ +name: Go Client (Echo API) + +on: + pull_request: + paths: + - samples/client/echo_api/go/** + - .github/workflows/samples-go-client-echo-api.yaml +jobs: + build: + name: Test Go client + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + # clients + - samples/client/echo_api/go + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-go@v5 + with: + go-version: "stable" + - name: Setup node.js + uses: actions/setup-node@v4 + - name: Run echo server + run: | + git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server + (cd http-echo-server && npm install && npm start &) + - run: go version + - name: Run test + working-directory: ${{ matrix.sample }} + run: go test -mod=mod -v diff --git a/.github/workflows/samples-go.yaml b/.github/workflows/samples-go.yaml index 55446d513bb9..62218739f56f 100644 --- a/.github/workflows/samples-go.yaml +++ b/.github/workflows/samples-go.yaml @@ -25,7 +25,7 @@ jobs: - samples/server/petstore/go-chi-server/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-go@v4 + - uses: actions/setup-go@v5 with: go-version: "stable" - run: go version diff --git a/.github/workflows/samples-groovy.yaml b/.github/workflows/samples-groovy.yaml index fd735ae7a9df..8a5a20bc5553 100644 --- a/.github/workflows/samples-groovy.yaml +++ b/.github/workflows/samples-groovy.yaml @@ -22,7 +22,7 @@ jobs: - samples/client/petstore/groovy steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-java-client-echo-api-jdk11.yaml b/.github/workflows/samples-java-client-echo-api-jdk11.yaml index be449320325e..f1fe59ac1fee 100644 --- a/.github/workflows/samples-java-client-echo-api-jdk11.yaml +++ b/.github/workflows/samples-java-client-echo-api-jdk11.yaml @@ -19,9 +19,11 @@ jobs: - samples/client/echo_api/java/apache-httpclient - samples/client/echo_api/java/native - samples/client/echo_api/java/feign-gson + - samples/client/echo_api/java/resttemplate + - samples/client/echo_api/java/resteasy steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 @@ -34,7 +36,7 @@ jobs: ~/.m2 key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} - name: Setup node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 - name: Run echo server run: | git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server diff --git a/.github/workflows/samples-java-client-echo-api-jdk8.yaml b/.github/workflows/samples-java-client-echo-api-jdk8.yaml index 1529b1de61ff..a8d874db664f 100644 --- a/.github/workflows/samples-java-client-echo-api-jdk8.yaml +++ b/.github/workflows/samples-java-client-echo-api-jdk8.yaml @@ -6,11 +6,14 @@ on: - samples/client/echo_api/java/apache-httpclient/** - samples/client/echo_api/java/feign-gson/** - samples/client/echo_api/java/okhttp-gson/** + - samples/client/echo_api/java/resttemplate/** + - samples/client/echo_api/java/resteasy/** pull_request: paths: - samples/client/echo_api/java/apache-httpclient/** - samples/client/echo_api/java/feign-gson/** - samples/client/echo_api/java/okhttp-gson/** + - samples/client/echo_api/java/resteasy/** jobs: build: name: Build Java Client JDK8 @@ -23,9 +26,11 @@ jobs: - samples/client/echo_api/java/apache-httpclient - samples/client/echo_api/java/feign-gson - samples/client/echo_api/java/okhttp-gson + - samples/client/echo_api/java/resttemplate + - samples/client/echo_api/java/resteasy steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 @@ -38,7 +43,7 @@ jobs: ~/.m2 key: ${{ runner.os }}-${{ github.job }}-${{ env.cache-name }}-${{ hashFiles('**/pom.xml') }} - name: Setup node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 - name: Run echo server run: | git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server diff --git a/.github/workflows/samples-java-client-jdk11.yaml b/.github/workflows/samples-java-client-jdk11.yaml index 8977db230f34..605eca642eac 100644 --- a/.github/workflows/samples-java-client-jdk11.yaml +++ b/.github/workflows/samples-java-client-jdk11.yaml @@ -10,6 +10,7 @@ on: - samples/openapi3/client/petstore/java/jersey2-java8-swagger1/** - samples/openapi3/client/petstore/java/jersey2-java8-swagger2/** - samples/openapi3/client/petstore/java/native** + - samples/client/others/java/okhttp-gson-oneOf/** - samples/client/others/java/resttemplate-useAbstractionForFiles/** - samples/client/others/java/webclient-useAbstractionForFiles/** pull_request: @@ -21,6 +22,7 @@ on: - samples/openapi3/client/petstore/java/jersey2-java8-swagger1/** - samples/openapi3/client/petstore/java/jersey2-java8-swagger2/** - samples/openapi3/client/petstore/java/native** + - samples/client/others/java/okhttp-gson-oneOf/** - samples/client/others/java/resttemplate-useAbstractionForFiles/** - samples/client/others/java/webclient-useAbstractionForFiles/** jobs: @@ -54,6 +56,7 @@ jobs: - samples/client/petstore/java/microprofile-rest-client-3.0 - samples/client/petstore/java/microprofile-rest-client-3.0-jackson - samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml + - samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter - samples/client/petstore/java/apache-httpclient - samples/client/petstore/java/feign - samples/client/petstore/java/okhttp-gson-awsv4signature @@ -65,11 +68,12 @@ jobs: - samples/client/petstore/java/okhttp-gson-swagger2/ - samples/client/petstore/java/resttemplate-swagger2/ - samples/openapi3/client/petstore/java/jersey2-java8-swagger2/ + - samples/client/others/java/okhttp-gson-oneOf/ - samples/client/others/java/resttemplate-useAbstractionForFiles/ - samples/client/others/java/webclient-useAbstractionForFiles/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/samples-java-client-jdk17.yaml b/.github/workflows/samples-java-client-jdk17.yaml index afaa76e0c68d..a0085de209db 100644 --- a/.github/workflows/samples-java-client-jdk17.yaml +++ b/.github/workflows/samples-java-client-jdk17.yaml @@ -22,7 +22,7 @@ jobs: - samples/client/petstore/java/webclient-jakarta steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/samples-java-helidon.yaml b/.github/workflows/samples-java-helidon.yaml index abc22170f3c6..3a2e97e18b13 100644 --- a/.github/workflows/samples-java-helidon.yaml +++ b/.github/workflows/samples-java-helidon.yaml @@ -24,7 +24,7 @@ jobs: version: [17] steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: ${{ matrix.version }} diff --git a/.github/workflows/samples-java-play-framework.yaml b/.github/workflows/samples-java-play-framework.yaml index 17cf0c678516..73d220624384 100644 --- a/.github/workflows/samples-java-play-framework.yaml +++ b/.github/workflows/samples-java-play-framework.yaml @@ -30,7 +30,7 @@ jobs: - samples/server/petstore/java-play-framework-no-wrap-calls steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/samples-java-server-jdk8.yaml b/.github/workflows/samples-java-server-jdk8.yaml index 342a624b0c79..b984fa19d8be 100644 --- a/.github/workflows/samples-java-server-jdk8.yaml +++ b/.github/workflows/samples-java-server-jdk8.yaml @@ -33,7 +33,7 @@ jobs: #- samples/server/petstore/java-undertow/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-jaxrs-jdk11.yaml b/.github/workflows/samples-jaxrs-jdk11.yaml index f97f134ba979..07581168ad64 100644 --- a/.github/workflows/samples-jaxrs-jdk11.yaml +++ b/.github/workflows/samples-jaxrs-jdk11.yaml @@ -19,7 +19,7 @@ jobs: - samples/server/petstore/jaxrs/jersey3 steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/samples-jaxrs.yaml b/.github/workflows/samples-jaxrs.yaml index 744216754463..1e8f80d4851d 100644 --- a/.github/workflows/samples-jaxrs.yaml +++ b/.github/workflows/samples-jaxrs.yaml @@ -39,7 +39,7 @@ jobs: - samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-jdk17.yaml b/.github/workflows/samples-jdk17.yaml index e264ec628a5b..9ea67b210e1d 100644 --- a/.github/workflows/samples-jdk17.yaml +++ b/.github/workflows/samples-jdk17.yaml @@ -8,6 +8,7 @@ on: - samples/client/petstore/java-helidon-client/se/** - samples/client/petstore/spring-http-interface-reactive/** - samples/client/petstore/spring-http-interface/** + - samples/client/petstore/java/webclient-jakarta/** # servers - samples/openapi3/server/petstore/springboot-3/** - samples/server/petstore/java-helidon-server/mp/** @@ -20,6 +21,7 @@ on: - samples/client/petstore/java-helidon-client/se/** - samples/client/petstore/spring-http-interface-reactive/** - samples/client/petstore/spring-http-interface/** + - samples/client/petstore/java/webclient-jakarta/** # servers - samples/openapi3/server/petstore/springboot-3/** - samples/server/petstore/java-helidon-server/mp/** @@ -38,6 +40,7 @@ jobs: - samples/client/petstore/java-helidon-client/se - samples/client/petstore/spring-http-interface-reactive - samples/client/petstore/spring-http-interface + - samples/client/petstore/java/webclient-jakarta # servers - samples/openapi3/server/petstore/springboot-3 - samples/server/petstore/java-helidon-server/mp @@ -46,7 +49,7 @@ jobs: - samples/client/petstore/spring-http-interface steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/samples-kotlin-client.yaml b/.github/workflows/samples-kotlin-client.yaml index ba36425e2cf2..d42d47717f0f 100644 --- a/.github/workflows/samples-kotlin-client.yaml +++ b/.github/workflows/samples-kotlin-client.yaml @@ -31,14 +31,17 @@ jobs: - samples/client/petstore/kotlin-jvm-volley - samples/client/petstore/kotlin-moshi-codegen - samples/client/petstore/kotlin-multiplatform + - samples/client/petstore/kotlin-multiplatform-kotlinx-datetime - samples/client/petstore/kotlin-nonpublic - samples/client/petstore/kotlin-nullable - samples/client/petstore/kotlin-okhttp3 - samples/client/petstore/kotlin-retrofit2 - samples/client/petstore/kotlin-retrofit2-kotlinx_serialization + - samples/client/petstore/kotlin-retrofit2-jackson - samples/client/petstore/kotlin-retrofit2-rx3 - samples/client/petstore/kotlin-string - samples/client/petstore/kotlin-threetenbp + - samples/client/petstore/kotlin-kotlinx-datetime - samples/client/petstore/kotlin-uppercase-enum - samples/client/petstore/kotlin-default-values-jvm-okhttp3 - samples/client/petstore/kotlin-default-values-jvm-okhttp4 @@ -61,12 +64,13 @@ jobs: - samples/client/petstore/kotlin-jvm-vertx-moshi - samples/client/petstore/kotlin-jvm-spring-2-webclient - samples/client/petstore/kotlin-jvm-spring-3-webclient + - samples/client/petstore/kotlin-jvm-spring-3-restclient - samples/client/petstore/kotlin-spring-cloud - samples/client/petstore/kotlin-name-parameter-mappings - samples/client/others/kotlin-jvm-okhttp-parameter-tests steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-kotlin-server-jdk17.yaml b/.github/workflows/samples-kotlin-server-jdk17.yaml index 44e918ded1f2..f79503de54fc 100644 --- a/.github/workflows/samples-kotlin-server-jdk17.yaml +++ b/.github/workflows/samples-kotlin-server-jdk17.yaml @@ -25,11 +25,12 @@ jobs: sample: # server - samples/server/petstore/kotlin-springboot-3 + - samples/server/petstore/kotlin-springboot-request # comment out due to gradle build failure # - samples/server/petstore/kotlin-spring-default/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/samples-kotlin-server.yaml b/.github/workflows/samples-kotlin-server.yaml index 61fbccaeadd8..f5ee278792f0 100644 --- a/.github/workflows/samples-kotlin-server.yaml +++ b/.github/workflows/samples-kotlin-server.yaml @@ -44,7 +44,7 @@ jobs: #- samples/server/petstore/kotlin-vertx-modelMutable steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-postman.yaml b/.github/workflows/samples-postman.yaml new file mode 100644 index 000000000000..edd6c9178256 --- /dev/null +++ b/.github/workflows/samples-postman.yaml @@ -0,0 +1,32 @@ +name: Samples Postman + +on: + pull_request: + paths: + - samples/schema/postman-collection/python/** + - .github/workflows/samples-postman.yaml +jobs: + build: + name: Test Python client + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + # schema + - samples/schema/postman-collection + python-version: + - "3.11" + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: ${{ matrix.python-version }} + - name: Install + working-directory: ${{ matrix.sample }} + run: | + pip install -r python/requirements.txt + pip install -r python/test-requirements.txt + - name: Test + working-directory: ${{ matrix.sample }} + run: python -m pytest diff --git a/.github/workflows/samples-python-client-echo-api.yaml b/.github/workflows/samples-python-client-echo-api.yaml index 38b1f24ad93b..05ce58c4e45e 100644 --- a/.github/workflows/samples-python-client-echo-api.yaml +++ b/.github/workflows/samples-python-client-echo-api.yaml @@ -24,11 +24,11 @@ jobs: - "3.11" steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Setup node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 - name: Run echo server run: | git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server @@ -42,3 +42,7 @@ jobs: - name: Test working-directory: ${{ matrix.sample }} run: python -m pytest + + - name: mypy + working-directory: ${{ matrix.sample }} + run: python -m mypy diff --git a/.github/workflows/samples-python-petstore.yaml b/.github/workflows/samples-python-petstore.yaml index 21c80cc42db6..4cf215d0c8d9 100644 --- a/.github/workflows/samples-python-petstore.yaml +++ b/.github/workflows/samples-python-petstore.yaml @@ -33,7 +33,7 @@ jobs: SWAGGER_BASE_PATH: /v2 steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 id: py with: python-version: ${{ matrix.python-version }} @@ -57,3 +57,7 @@ jobs: - name: Test working-directory: ${{ matrix.sample }} run: poetry run pytest -v + + - name: mypy + working-directory: ${{ matrix.sample }} + run: poetry run mypy diff --git a/.github/workflows/samples-python-pydantic-v1-client-echo-api.yaml b/.github/workflows/samples-python-pydantic-v1-client-echo-api.yaml index 32950c686acb..6aa3bab3b396 100644 --- a/.github/workflows/samples-python-pydantic-v1-client-echo-api.yaml +++ b/.github/workflows/samples-python-pydantic-v1-client-echo-api.yaml @@ -24,11 +24,11 @@ jobs: - "3.11" steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: ${{ matrix.python-version }} - name: Setup node.js - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 - name: Run echo server run: | git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server diff --git a/.github/workflows/samples-python-pydantic-v1-petstore.yaml b/.github/workflows/samples-python-pydantic-v1-petstore.yaml index ce5c1265d3ea..cf898074d30e 100644 --- a/.github/workflows/samples-python-pydantic-v1-petstore.yaml +++ b/.github/workflows/samples-python-pydantic-v1-petstore.yaml @@ -33,7 +33,7 @@ jobs: SWAGGER_BASE_PATH: /v2 steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 id: py with: python-version: ${{ matrix.python-version }} diff --git a/.github/workflows/samples-python-server.yaml b/.github/workflows/samples-python-server.yaml index 4ff5ca98c629..95ff583f0626 100644 --- a/.github/workflows/samples-python-server.yaml +++ b/.github/workflows/samples-python-server.yaml @@ -3,10 +3,10 @@ name: Python Server on: push: paths: - - samples/server/petstore/python-aiohttp/** + - samples/server/petstore/python-aiohttp-srclayout/** pull_request: paths: - - samples/server/petstore/python-aiohttp/** + - samples/server/petstore/python-aiohttp-srclayout/** jobs: build: name: Test Python server @@ -16,10 +16,10 @@ jobs: matrix: sample: # servers - - samples/server/petstore/python-aiohttp/ + - samples/server/petstore/python-aiohttp-srclayout/ steps: - uses: actions/checkout@v4 - - uses: actions/setup-python@v4 + - uses: actions/setup-python@v5 with: python-version: '3.7' - name: Test diff --git a/.github/workflows/samples-ruby.yaml b/.github/workflows/samples-ruby.yaml new file mode 100644 index 000000000000..237cfd0a312f --- /dev/null +++ b/.github/workflows/samples-ruby.yaml @@ -0,0 +1,43 @@ +name: Samples Ruby + +on: + push: + paths: + - 'samples/client/echo_api/ruby-httpx/**' + - 'samples/client/echo_api/ruby-faraday/**' + - 'samples/client/echo_api/ruby-typhoeus/**' + pull_request: + paths: + - 'samples/client/echo_api/ruby-httpx/**' + - 'samples/client/echo_api/ruby-faraday/**' + - 'samples/client/echo_api/ruby-typhoeus/**' + +jobs: + build: + name: Build Ruby + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + - 'samples/client/echo_api/ruby-httpx/' + - 'samples/client/echo_api/ruby-faraday/' + - 'samples/client/echo_api/ruby-typhoeus/' + steps: + - uses: actions/checkout@v4 + - name: Setup node.js + uses: actions/setup-node@v4 + - name: Run echo server + run: | + git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server + (cd http-echo-server && npm install && npm start &) + - uses: actions/setup-ruby@v1 + with: + ruby-version: 3.0 + bundler-cache: true + - name: Install bundle + working-directory: ${{ matrix.sample }} + run: bundle install + - name: Run rspec + working-directory: ${{ matrix.sample }} + run: rspec diff --git a/.github/workflows/samples-rust.yaml b/.github/workflows/samples-rust.yaml index 02d885611d6c..f54dab346c6e 100644 --- a/.github/workflows/samples-rust.yaml +++ b/.github/workflows/samples-rust.yaml @@ -6,11 +6,13 @@ on: - "samples/client/others/rust/**" - "samples/server/petstore/rust-server/**" - "samples/client/petstore/rust-server/**" + - "samples/server/petstore/rust-axum/**" pull_request: paths: - "samples/client/others/rust/**" - "samples/client/petstore/rust/**" - "samples/server/petstore/rust-server/**" + - "samples/server/petstore/rust-axum/**" jobs: build: @@ -24,6 +26,7 @@ jobs: - samples/client/others/rust/ - samples/client/petstore/rust/ - samples/server/petstore/rust-server/ + - samples/server/petstore/rust-axum/ steps: - uses: actions/checkout@v4 - uses: actions-rs/toolchain@v1 diff --git a/.github/workflows/samples-scala.yaml b/.github/workflows/samples-scala.yaml index 29fa8d8f3bbc..9e9eb8c249ed 100644 --- a/.github/workflows/samples-scala.yaml +++ b/.github/workflows/samples-scala.yaml @@ -22,6 +22,7 @@ jobs: # clients - 'samples/client/petstore/java/okhttp-gson' - samples/client/petstore/scalaz + - samples/client/petstore/scala-pekko #- samples/client/petstore/scala-sttp # won't pass while the same tests in circleci pass # servers - samples/server/petstore/scala-lagom-server @@ -30,9 +31,10 @@ jobs: - samples/server/petstore/scala-pekko-http-server - samples/server/petstore/scalatra - samples/server/petstore/scala-finch # cannot be tested with jdk11 + - samples/server/petstore/scala-http4s-server steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-spring-jdk17.yaml b/.github/workflows/samples-spring-jdk17.yaml index 9c594477a268..10206fafe070 100644 --- a/.github/workflows/samples-spring-jdk17.yaml +++ b/.github/workflows/samples-spring-jdk17.yaml @@ -19,7 +19,7 @@ jobs: - samples/openapi3/client/petstore/spring-cloud-3-with-optional steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 17 diff --git a/.github/workflows/samples-spring.yaml b/.github/workflows/samples-spring.yaml index 8baf85b44b63..60279c833753 100644 --- a/.github/workflows/samples-spring.yaml +++ b/.github/workflows/samples-spring.yaml @@ -28,6 +28,7 @@ jobs: - samples/openapi3/client/petstore/spring-cloud - samples/client/petstore/spring-cloud-date-time - samples/openapi3/client/petstore/spring-cloud-date-time + - samples/openapi3/client/petstore/spring-cloud-http-basic - samples/openapi3/client/petstore/spring-stubs - samples/openapi3/client/petstore/spring-stubs-skip-default-interface - samples/openapi3/client/petstore/spring-cloud-async @@ -58,7 +59,7 @@ jobs: - samples/server/petstore/springboot-spring-provide-args steps: - uses: actions/checkout@v4 - - uses: actions/setup-java@v3 + - uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 8 diff --git a/.github/workflows/samples-typescript-axios-echo-api.yaml b/.github/workflows/samples-typescript-axios-echo-api.yaml new file mode 100644 index 000000000000..b729b27112cf --- /dev/null +++ b/.github/workflows/samples-typescript-axios-echo-api.yaml @@ -0,0 +1,42 @@ +name: TypeScript Axios Client (Echo API) + +on: + pull_request: + paths: + - samples/client/echo_api/typescript-axios/** + - .github/workflows/samples-typescript-axios-echo-api.yaml +jobs: + build: + name: Test TypeScript Axios client + runs-on: ubuntu-latest + strategy: + fail-fast: false + matrix: + sample: + # clients + - samples/client/echo_api/typescript-axios/test + node-version: + - 16 + - 18 + - 20 + steps: + - uses: actions/checkout@v4 + + - uses: actions/setup-node@v4 + with: + node-version: ${{ matrix.node-version }} + + - name: Run echo server + run: | + git clone https://github.com/wing328/http-echo-server -b openapi-generator-test-server + (cd http-echo-server && npm install && npm start &) + + - name: Install + working-directory: ${{ matrix.sample }} + run: | + npm run preinstall + npm i + + - name: Test + working-directory: ${{ matrix.sample }} + run: npm test diff --git a/.github/workflows/samples-zapier.yaml b/.github/workflows/samples-zapier.yaml index 859721bdd3ff..820d41362b70 100644 --- a/.github/workflows/samples-zapier.yaml +++ b/.github/workflows/samples-zapier.yaml @@ -20,7 +20,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Setup node - uses: actions/setup-node@v3 + uses: actions/setup-node@v4 - name: Install dependencies working-directory: ${{ matrix.sample }} run: | diff --git a/.github/workflows/sonar.yml b/.github/workflows/sonar.yml index 4f3bf722a3fe..0fa6f44279cd 100644 --- a/.github/workflows/sonar.yml +++ b/.github/workflows/sonar.yml @@ -14,7 +14,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK 11 - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: distribution: 'temurin' java-version: 11 diff --git a/.github/workflows/windows.yaml b/.github/workflows/windows.yaml index 27d151cc86d7..ddb2d75a7138 100644 --- a/.github/workflows/windows.yaml +++ b/.github/workflows/windows.yaml @@ -20,7 +20,7 @@ jobs: steps: - uses: actions/checkout@v4 - name: Set up JDK ${{ matrix.java }} - uses: actions/setup-java@v3 + uses: actions/setup-java@v4 with: java-version: ${{ matrix.java }} distribution: 'temurin' @@ -39,7 +39,7 @@ jobs: ${{ runner.os }}-build-${{ env.cache-name }}- ${{ runner.os }}-build- - name: Setup Maven - uses: s4u/setup-maven-action@v1.10.0 + uses: s4u/setup-maven-action@v1.11.0 with: java-version: ${{ matrix.java }} maven-version: 3.8.8 diff --git a/.gitignore b/.gitignore index ab086a35e068..9f8932913749 100644 --- a/.gitignore +++ b/.gitignore @@ -49,6 +49,8 @@ nb-configuration.xml /target /generated-files test-output/ +nbactions.xml +test-output/ # website website/build/ @@ -71,6 +73,7 @@ samples/client/petstore/build samples/client/petstore/cpp-qt/PetStore/moc_* samples/client/petstore/cpp-qt/PetStore/*.o samples/client/petstore/cpp-qt/build-* +samples/client/petstore/cpp-qt/build-* samples/client/petstore/cpp-qt/PetStore/PetStore samples/client/petstore/cpp-qt/PetStore/Makefile samples/client/petstore/cpp-qt/PetStore/PetStore.pro.user @@ -97,7 +100,9 @@ samples/client/petstore/java/jersey2/build/ samples/client/petstore/java/okhttp-gson/.gradle/ samples/client/petstore/java/okhttp-gson/build/ samples/client/petstore/java/feign/build/ +samples/client/petstore/java/feign10x/build/ samples/client/petstore/java/feign/project/ +samples/client/petstore/java/feign10x/project/ samples/client/petstore/java/retrofit/build/ samples/client/petstore/java/retrofit2/build/ samples/client/petstore/java/retrofit2/hello.txt @@ -105,6 +110,7 @@ samples/client/petstore/java/retrofit2rx/build/ samples/client/petstore/java/default/build/ samples/client/petstore/scala/build/ samples/client/petstore/java/resttemplate/hello.txt +samples/client/petstore/java/retrofit2/hello.txt samples/client/petstore/java/feign/hello.txt samples/client/petstore/java/jersey2-java6/project/ samples/client/petstore/java/jersey2-java8/project/ @@ -187,7 +193,6 @@ samples/server/petstore/php-slim4/composer.lock samples/server/petstore/php-symfony/SymfonyBundle-php/composer.lock samples/server/petstore/php-mezzio-ph/composer.lock samples/server/petstore/php-mezzio-ph-modern/composer.lock -samples/client/petstore/php-nextgen/OpenAPIClient-php/.phplint.cache/ # ts samples/client/petstore/typescript-angular2/npm/npm-debug.log diff --git a/.hub.cli.dockerfile b/.hub.cli.dockerfile index fe18ad8dd3f8..5a3041dc1084 100644 --- a/.hub.cli.dockerfile +++ b/.hub.cli.dockerfile @@ -3,19 +3,19 @@ ## ## You can build _just_ this part with: ## docker --target builder -t container-name:builder -f .hub.cli.dockerfile . -FROM maven:3.6.3-jdk-11-openj9 as builder +FROM maven:3-eclipse-temurin-17 as builder ENV GEN_DIR /opt/openapi-generator WORKDIR ${GEN_DIR} COPY . ${GEN_DIR} # Pre-compile openapi-generator-cli -RUN mvn -am -pl "modules/openapi-generator-cli" package +RUN mvn -B -am -pl "modules/openapi-generator-cli" package ## The final (release) image ## The resulting container here only needs the target jar ## and ca-certificates (to be able to query HTTPS hosted specs) -FROM openjdk:11.0.8-jre-slim-buster +FROM eclipse-temurin:17-jre ENV GEN_DIR /opt/openapi-generator diff --git a/.hub.online.dockerfile b/.hub.online.dockerfile index 4c7e01e3a24a..1d0b3a4aeed6 100644 --- a/.hub.online.dockerfile +++ b/.hub.online.dockerfile @@ -3,18 +3,18 @@ ## ## You can build _just_ this part with: ## docker --target builder -t container-name:builder -f .hub.online.dockerfile . -FROM maven:3.6.3-jdk-11-openj9 as builder +FROM maven:3-eclipse-temurin-17 as builder ENV GEN_DIR /opt/openapi-generator WORKDIR ${GEN_DIR} COPY . ${GEN_DIR} # Pre-compile openapi-generator-online -RUN mvn -am -pl "modules/openapi-generator-online" package +RUN mvn -B -am -pl "modules/openapi-generator-online" package ## The final (release) image ## The resulting container here only needs the target jar -FROM openjdk:11.0.8-jre-slim-buster +FROM eclipse-temurin:17-jre ENV GEN_DIR /opt/openapi-generator ENV TARGET_DIR /generator diff --git a/.mvn/extensions.xml b/.mvn/extensions.xml index 9cd131d0e4cf..461ed5e32754 100644 --- a/.mvn/extensions.xml +++ b/.mvn/extensions.xml @@ -3,11 +3,11 @@ com.gradle gradle-enterprise-maven-extension - 1.17 + 1.20 com.gradle common-custom-user-data-maven-extension - 1.11.1 + 1.12.5 diff --git a/.mvn/gradle-enterprise.xml b/.mvn/gradle-enterprise.xml index d665b38af86b..2b694b9acd6a 100644 --- a/.mvn/gradle-enterprise.xml +++ b/.mvn/gradle-enterprise.xml @@ -46,7 +46,8 @@ true - #{env['CI'] != null} + + #{isTrue(env['CI']) and isTrue(env['GRADLE_ENTERPRISE_CACHE_USERNAME']) and isTrue(env['GRADLE_ENTERPRISE_CACHE_PASSWORD'])} diff --git a/.travis.yml b/.travis.yml index 306c1da810a1..c5c3dbc8459a 100644 --- a/.travis.yml +++ b/.travis.yml @@ -22,6 +22,7 @@ cache: - $HOME/samples/client/petstore/ruby/vendor/bundle - $HOME/samples/client/petstore/python/.venv/ - $HOME/samples/server/petstore/rust-server/target + - $HOME/samples/server/petstore/rust-axum/target - $HOME/perl5 - $HOME/.cargo - $HOME/.pub-cache diff --git a/CI/.drone.yml b/CI/.drone.yml deleted file mode 100644 index 4066ded43383..000000000000 --- a/CI/.drone.yml +++ /dev/null @@ -1,98 +0,0 @@ -kind: pipeline -type: docker -name: java11-test -steps: -# test Java 11 HTTP client -- name: java11-test - image: openjdk:11.0 - commands: - - ./mvnw --quiet clean install -Dorg.slf4j.simpleLogger.defaultLogLevel=error - - ./mvnw --quiet verify -Psamples.droneio -Dorg.slf4j.simpleLogger.defaultLogLevel=error - # test java native client - - ./mvnw clean test -f samples/client/petstore/java/native/pom.xml - - ./mvnw clean test -f samples/client/petstore/java/native-async/pom.xml - - ./mvnw clean test -f samples/openapi3/client/petstore/java/native/pom.xml - # test all generators with fake petstore spec (2.0, 3.0) - - /bin/bash bin/utils/test-fake-petstore-for-all.sh - # generate test scripts - - /bin/bash bin/tests/run-all-test - ---- -kind: pipeline -type: docker -name: nim-client-test -steps: -# test nim client -- name: nim-client-test - image: nimlang/nim - commands: - - (cd samples/client/petstore/nim/ && nim c sample_client.nim) - ---- -kind: pipeline -type: docker -name: protobuf-schema-test -steps: -# test protobuf schema generator -- name: protobuf-schema-test - image: nanoservice/protobuf-go - commands: - - protoc --version - - mkdir /var/tmp/go/ - - cd samples/config/petstore/protobuf-schema - - protoc --go_out=/var/tmp/go/ services/* - - protoc --go_out=/var/tmp/go/ models/* - ---- -kind: pipeline -type: docker -name: aspnetcore-test -steps: -# test aspnetcore 3.x -- name: aspnetcore-test - image: mcr.microsoft.com/dotnet/core/sdk:3.1 - commands: - - (cd samples/server/petstore/aspnetcore-3.1/ && /bin/sh build.sh) - - (cd samples/server/petstore/aspnetcore-3.0/ && /bin/sh build.sh) - ---- -kind: pipeline -type: docker -name: ocaml-test -steps: -# test ocaml petstore client -- name: ocaml-test - image: ocaml/opam2:4.07 - commands: - - sudo apt-get -y install m4 - - cd samples/client/petstore/ocaml - - opam install ppx_deriving_yojson cohttp ppx_deriving cohttp-lwt-unix - - opam pin add ocaml-migrate-parsetree 1.3.1 - - eval $(opam env) - - sudo chmod -R 777 . - - dune build --build-dir=./_build - ---- -kind: pipeline -type: docker -name: haskell-client-test -steps: -# test haskell client -- name: haskell-client-test - image: haskell:8.10.4 - commands: - - (cd samples/client/petstore/haskell-http-client/ && stack --allow-different-user --install-ghc --no-haddock-deps haddock --fast && stack --allow-different-user test --fast) - ---- -kind: pipeline -type: docker -name: erlang -steps: -# test erlang client and server -- name: erlang - image: erlang:alpine - commands: - - (cd samples/client/petstore/erlang-client && rebar3 compile) - - (cd samples/client/petstore/erlang-proper && rebar3 compile) - # comment out as the tests pass locally but not in the CI - #- (cd samples/server/petstore/erlang-server && rebar3 compile) diff --git a/CI/.travis.yml.ios b/CI/.travis.yml.ios deleted file mode 100644 index 31e0df639268..000000000000 --- a/CI/.travis.yml.ios +++ /dev/null @@ -1,37 +0,0 @@ -sudo: required -language: objective-c -osx_image: xcode10.3 -before_install: - - export SW=`pwd` - - rvm list - #- rvm use 2.3.3 - - gem environment - - gem install bundler -N - - gem install cocoapods -v 1.2.1 -N - - gem install xcpretty -N - - pod --version - # comment out below to avoid errors - #- pod repo update - #- pod setup --silent > /dev/null - #- mkdir -p ~/.local/bin - #- export PATH=$HOME/.local/bin:$PATH - ## start local petstore server - #- git clone -b docker --single-branch https://github.com/wing328/swagger-samples - #- cd swagger-samples/java/java-jersey-jaxrs - #- sudo mvn jetty:run & - #- cd $SW - - # show host table to confirm petstore.swagger.io is mapped to localhost - - cat /etc/hosts - # show java version - - java -version - # show brew version - - brew --version - # show xcpretty version - - xcpretty -v - # show go version - - go version - -script: - # run integration tests defined in maven pom.xml - - mvn --no-snapshot-updates -q --batch-mode verify -Psamples.ios -Dmaven.javadoc.skip=true diff --git a/CI/.travis.yml.jdk6 b/CI/.travis.yml.jdk6 deleted file mode 100644 index ced240e44617..000000000000 --- a/CI/.travis.yml.jdk6 +++ /dev/null @@ -1,29 +0,0 @@ -dist: trusty -sudo: required -language: java -addons: - apt: - packages: - - openjdk-6-jdk -jdk: openjdk6 - -cache: - directories: - - $HOME/.m2 - - $HOME/.ivy2 - - $HOME/.gradle/caches/ - - $HOME/.gradle/wrapper/ - -install: - - jdk_switcher use openjdk6 - - java -version - - curl -s "https://get.sdkman.io" | bash - - source "$HOME/.sdkman/bin/sdkman-init.sh" - - sdk version - - sdk install gradle 2.9 - - sdk list gradle - - sdk version - - gradle --version - -script: - - cd samples/client/petstore/java/jersey2-java6 && gradle test diff --git a/CI/circle_parallel.sh b/CI/circle_parallel.sh index b5baa82c9604..8b6a40983aa5 100755 --- a/CI/circle_parallel.sh +++ b/CI/circle_parallel.sh @@ -10,10 +10,13 @@ set -e export NODE_ENV=test if [ "$NODE_INDEX" = "1" ]; then - echo "Running node $NODE_INDEX to test 'samples.circleci' defined in pom.xml ..." + echo "Running node $NODE_INDEX ..." java -version - ./mvnw --no-snapshot-updates --quiet verify -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error + (cd samples/client/petstore/ruby && mvn integration-test) + (cd samples/client/petstore/ruby-faraday && mvn integration-test) + (cd samples/client/petstore/ruby-httpx && mvn integration-test) + (cd samples/client/petstore/ruby-autoload && mvn integration-test) elif [ "$NODE_INDEX" = "2" ]; then echo "Running node $NODE_INDEX to test Go" @@ -33,20 +36,14 @@ elif [ "$NODE_INDEX" = "2" ]; then export PATH="/usr/local/go1.18/go/bin:$PATH" go version - # run integration tests - ./mvnw --no-snapshot-updates --quiet verify -Psamples.misc -Dorg.slf4j.simpleLogger.defaultLogLevel=error + # run go integration tests + (cd samples/client/petstore/go && mvn integration-test) + (cd samples/openapi3/client/petstore/go && mvn integration-test) + (cd samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false && mvn integration-test) + elif [ "$NODE_INDEX" = "3" ]; then - echo "Running node $NODE_INDEX to test 'samples.circleci.node3' defined in pom.xml ..." - #wget https://www.python.org/ftp/python/3.8.9/Python-3.8.9.tgz - #tar -xf Python-3.8.9.tgz - #cd Python-3.8.9 - #./configure --enable-optimizations - #sudo make altinstall - pyenv install --list - pyenv install 3.7.12 - #pyenv install 2.7.14 #python2 no longer supported - pyenv global 3.7.12 + echo "Running node $NODE_INDEX ... " # Install node@stable (for angular 6) set +e @@ -63,23 +60,71 @@ elif [ "$NODE_INDEX" = "3" ]; then echo 'export NVM_DIR="/opt/circleci/.nvm"' >> $BASH_ENV echo "[ -s \"$NVM_DIR/nvm.sh\" ] && . \"$NVM_DIR/nvm.sh\"" >> $BASH_ENV - ./mvnw --no-snapshot-updates --quiet verify -Psamples.circleci.node3 -Dorg.slf4j.simpleLogger.defaultLogLevel=error + (cd samples/client/others/typescript-angular && mvn integration-test) + (cd samples/client/petstore/typescript-angular-v12-provided-in-root && mvn integration-test) + (cd samples/client/petstore/typescript-angular-v13-provided-in-root && mvn integration-test) + (cd samples/client/petstore/typescript-angular-v14-provided-in-root && mvn integration-test) + (cd samples/client/petstore/typescript-angular-v15-provided-in-root && mvn integration-test) + (cd samples/client/petstore/typescript-angular-v16-provided-in-root && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/builds/default && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/tests/default && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/builds/jquery && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/tests/jquery && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/builds/object_params && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/tests/object_params && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/builds/inversify && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/tests/inversify && mvn integration-test) + #(cd samples/openapi3/client/petstore/typescript/tests/deno && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/builds/browser && mvn integration-test) + (cd samples/openapi3/client/petstore/typescript/tests/browser && mvn integration-test) + (cd samples/client/petstore/typescript-fetch/builds/default && mvn integration-test) + (cd samples/client/petstore/typescript-fetch/builds/es6-target && mvn integration-test) + (cd samples/client/petstore/typescript-fetch/builds/with-npm-version && mvn integration-test) + (cd samples/client/petstore/typescript-fetch/tests/default && mvn integration-test) + (cd samples/client/petstore/typescript-node/npm && mvn integration-test) + (cd samples/client/petstore/typescript-rxjs/builds/with-npm-version && mvn integration-test) + (cd samples/client/petstore/typescript-axios/builds/with-npm-version && mvn integration-test) + (cd samples/client/petstore/typescript-axios/tests/default && mvn integration-test) + (cd samples/client/petstore/javascript-flowtyped && mvn integration-test) + (cd samples/client/petstore/javascript-es6 && mvn integration-test) + (cd samples/client/petstore/javascript-promise-es6 && mvn integration-test) elif [ "$NODE_INDEX" = "4" ]; then - echo "Running node $NODE_INDEX to test 'samples.circleci.node4' defined in pom.xml ..." + echo "Running node $NODE_INDEX ..." - #mvn --no-snapshot-updates --quiet verify -Psamples.circleci.node4 -Dorg.slf4j.simpleLogger.defaultLogLevel=error - #(cd samples/openapi3/client/petstore/python && make test) - # comment out due to ModuleNotFoundError: No module named 'urllib3.request' - #(cd samples/openapi3/client/petstore/python-prior && make test) - #(cd samples/openapi3/client/3_0_3_unit_test/python && make test) + #wget https://www.python.org/ftp/python/3.8.9/Python-3.8.9.tgz + #tar -xf Python-3.8.9.tgz + #cd Python-3.8.9 + #./configure --enable-optimizations + #sudo make altinstall + pyenv install --list + pyenv install 3.7.12 + #pyenv install 2.7.14 #python2 no longer supported + pyenv global 3.7.12 + + (cd samples/openapi3/client/petstore/python && mvn integration-test) + (cd samples/openapi3/client/petstore/python-pydantic-v1 && mvn integration-test) + (cd samples/openapi3/client/petstore/python-aiohttp && mvn integration-test) + (cd samples/openapi3/client/petstore/python-pydantic-v1-aiohttp && mvn integration-test) else - echo "Running node $NODE_INDEX to test 'samples.circleci.others' defined in pom.xml ..." + echo "Running node $NODE_INDEX ..." java -version - ./mvnw --no-snapshot-updates --quiet verify -Psamples.circleci.others -Dorg.slf4j.simpleLogger.defaultLogLevel=error - ./mvnw --no-snapshot-updates --quiet javadoc:javadoc -Psamples.circleci -Dorg.slf4j.simpleLogger.defaultLogLevel=error + (cd samples/client/petstore/scala-akka && mvn integration-test) + (cd samples/client/petstore/scala-sttp && mvn integration-test) + (cd samples/client/petstore/scala-sttp4 && mvn integration-test) + (cd samples/client/petstore/clojure && mvn integration-test) + (cd samples/client/petstore/java/jersey2-java8 && mvn integration-test) + (cd samples/openapi3/client/petstore/java/jersey2-java8 && mvn integration-test) + (cd samples/client/petstore/java/jersey3 && mvn integration-test) + (cd samples/client/others/java/okhttp-gson-streaming && mvn integration-test) + (cd samples/client/petstore/java/okhttp-gson && mvn integration-test) + (cd samples/client/petstore/java/okhttp-gson-3.1 && mvn integration-test) + (cd samples/client/petstore/java/resteasy && mvn integration-test) + (cd samples/client/petstore/java-micronaut-client && mvn integration-test) + (cd samples/client/petstore/java/apache-httpclient && mvn integration-test) + fi diff --git a/Dockerfile b/Dockerfile index b1ca47344ed0..163f62d45d4c 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,4 +1,4 @@ -FROM maven:3.6.3-jdk-11-openj9 +FROM maven:3-eclipse-temurin-17 ENV GEN_DIR /opt/openapi-generator WORKDIR ${GEN_DIR} @@ -20,7 +20,7 @@ COPY ./modules/openapi-generator ${GEN_DIR}/modules/openapi-generator COPY ./pom.xml ${GEN_DIR} # Pre-compile openapi-generator-cli -RUN mvn -am -pl "modules/openapi-generator-cli" package +RUN mvn -B -am -pl "modules/openapi-generator-cli" package # This exists at the end of the file to benefit from cached layers when modifying docker-entrypoint.sh. COPY docker-entrypoint.sh /usr/local/bin/ diff --git a/README.md b/README.md index 75e63f56d1e8..a3c9587d2bc1 100644 --- a/README.md +++ b/README.md @@ -9,13 +9,13 @@ [![Join the Slack chat room](https://img.shields.io/badge/Slack-Join%20the%20chat%20room-orange)](https://join.slack.com/t/openapi-generator/shared_invite/zt-12jxxd7p2-XUeQM~4pzsU9x~eGLQqX2g) [![Follow OpenAPI Generator Twitter account to get the latest update](https://img.shields.io/twitter/follow/oas_generator.svg?style=social&label=Follow)](https://twitter.com/oas_generator) [![Contribute with Gitpod](https://img.shields.io/badge/Contribute%20with-Gitpod-908a85?logo=gitpod)](https://gitpod.io/#https://github.com/OpenAPITools/openapi-generator) -[![Conan Center](https://shields.io/conan/v/openapi-generator)](https://conan.io/center/openapi-generator) -[![Revved up by Gradle Enterprise](https://img.shields.io/badge/Revved%20up%20by-Gradle%20Enterprise-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.openapi-generator.tech/scans) +[![Conan Center](https://shields.io/conan/v/openapi-generator)](https://conan.io/center/recipes/openapi-generator) +[![Revved up by Develocity](https://img.shields.io/badge/Revved%20up%20by-Develocity-06A0CE?logo=Gradle&labelColor=02303A)](https://ge.openapi-generator.tech/scans)
-[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.1.0`): +[Master](https://github.com/OpenAPITools/openapi-generator/tree/master) (`7.3.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) @@ -25,7 +25,7 @@
-:star::star::star: If you would like to contribute, please refer to [guidelines](CONTRIBUTING.md) and a list of [open tasks](https://github.com/openapitools/openapi-generator/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22).:star::star::star: +:star::star::star: If you would like to contribute, please refer to [guidelines](CONTRIBUTING.md) and a list of [open tasks](https://github.com/openapitools/openapi-generator/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22). :star::star::star: :bangbang: To migrate from Swagger Codegen to OpenAPI Generator, please refer to the [migration guide](docs/migration-from-swagger-codegen.md) :bangbang: @@ -62,20 +62,24 @@ If you find OpenAPI Generator useful for work, please consider asking your compa [](https://www.bileto.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) [](https://www.bairesdev.com/sponsoring-open-source-projects/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) [](https://www.dm-jobs.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) +[](https://adyen.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) +[](https://fornex.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) +[](https://runalloy.com/signup?utm_source=github&utm_medium=referral&utm_campaign=1524_openapigenerator) -#### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS and Checkly for sponsoring the API monitoring +#### Thank you GoDaddy for sponsoring the domain names, Linode for sponsoring the VPS, Checkly for sponsoring the API monitoring and Gradle for sponsoring Develocity [](https://www.godaddy.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) [![Linode](https://www.linode.com/media/images/logos/standard/light/linode-logo_standard_light_small.png)](https://www.linode.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) [](https://checklyhq.com/?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) - +[](https://gradle.org?utm_source=openapi_generator&utm_medium=github_webpage&utm_campaign=sponsor) ## Overview + OpenAPI Generator allows generation of API client libraries (SDK generation), server stubs, documentation and configuration automatically given an [OpenAPI Spec](https://github.com/OAI/OpenAPI-Specification) (both 2.0 and 3.0 are supported). Currently, the following languages/frameworks are supported: | | Languages/Frameworks | | -------------------------------- |-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------| -| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (9.x - 16.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** | +| **API clients** | **ActionScript**, **Ada**, **Apex**, **Bash**, **C**, **C#** (.net 2.0, 3.5 or later, .NET Standard 1.3 - 2.1, .NET Core 3.1, .NET 5.0. Libraries: RestSharp, GenericHost, HttpClient), **C++** (Arduino, cpp-restsdk, Qt5, Tizen, Unreal Engine 4), **Clojure**, **Crystal**, **Dart**, **Elixir**, **Elm**, **Eiffel**, **Erlang**, **Go**, **Groovy**, **Haskell** (http-client, Servant), **Java** (Apache HttpClient 4.x, Apache HttpClient 5.x, Jersey2.x, OkHttp, Retrofit1.x, Retrofit2.x, Feign, RestTemplate, RESTEasy, Vertx, Google API Client Library for Java, Rest-assured, Spring 5 Web Client, MicroProfile Rest Client, Helidon), **Jetbrains HTTP Client**, **Julia**, **k6**, **Kotlin**, **Lua**, **N4JS**, **Nim**, **Node.js/JavaScript** (ES5, ES6, AngularJS with Google Closure Compiler annotations, Flow types, Apollo GraphQL DataStore), **Objective-C**, **OCaml**, **Perl**, **PHP**, **PowerShell**, **Python**, **R**, **Ruby**, **Rust** (hyper, reqwest, rust-server), **Scala** (akka, http4s, scalaz, sttp, swagger-async-httpclient, pekko), **Swift** (2.x, 3.x, 4.x, 5.x), **Typescript** (AngularJS, Angular (9.x - 16.x), Aurelia, Axios, Fetch, Inversify, jQuery, Nestjs, Node, redux-query, Rxjs), **XoJo**, **Zapier** | | **Server stubs** | **Ada**, **C#** (ASP.NET Core, Azure Functions), **C++** (Pistache, Restbed, Qt5 QHTTPEngine), **Erlang**, **F#** (Giraffe), **Go** (net/http, Gin, Echo), **Haskell** (Servant, Yesod), **Java** (MSF4J, Spring, Undertow, JAX-RS: CDI, CXF, Inflector, Jersey, RestEasy, Play Framework, [PKMST](https://github.com/ProKarma-Inc/pkmst-getting-started-examples), [Vert.x](https://vertx.io/), [Apache Camel](https://camel.apache.org/), [Helidon](https://helidon.io/)), **Julia**, **Kotlin** (Spring Boot, [Ktor](https://github.com/ktorio/ktor), [Vert.x](https://vertx.io/)), **PHP** (Laravel, Lumen, [Mezzio (fka Zend Expressive)](https://github.com/mezzio/mezzio), Slim, Silex, [Symfony](https://symfony.com/)), **Python** (FastAPI, Flask), **NodeJS**, **Ruby** (Sinatra, Rails5), **Rust** ([rust-server](https://openapi-generator.tech/docs/generators/rust-server/)), **Scala** (Akka, [Finch](https://github.com/finagle/finch), [Lagom](https://github.com/lagom/lagom), [Play](https://www.playframework.com/), Scalatra) | | **API documentation generators** | **HTML**, **Confluence Wiki**, **Asciidoc**, **Markdown**, **PlantUML** | | **Configuration files** | [**Apache2**](https://httpd.apache.org/) | @@ -117,8 +121,8 @@ The OpenAPI Specification has undergone 3 revisions since initial creation in 20 | OpenAPI Generator Version | Release Date | Notes | | --------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------ | ------------------------------------------------- | -| 7.1.0 (upcoming patch release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.1.0-SNAPSHOT/) | 18.10.2023 | Minor release with breaking changes (with fallback) | -| [7.0.1](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.0.1) (latest stable release) | 18.09.2023 | Patch release (enhancements, bug fixes, etc) | +| 7.3.0 (upcoming minor release) [SNAPSHOT](https://oss.sonatype.org/content/repositories/snapshots/org/openapitools/openapi-generator-cli/7.3.0-SNAPSHOT/) | 30.01.2024 | Minor release with breaking changes (with fallback) | +| [7.2.0](https://github.com/OpenAPITools/openapi-generator/releases/tag/v7.2.0) (latest stable release) | 22.12.2023 | 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) | @@ -181,16 +185,16 @@ See the different versions of the [openapi-generator-cli](https://search.maven.o 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.0.1/openapi-generator-cli-7.0.1.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.0.jar` For **Mac/Linux** users: ```sh -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.0.1/openapi-generator-cli-7.0.1.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.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.0.1/openapi-generator-cli-7.0.1.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.0.jar ``` After downloading the JAR, run `java -jar openapi-generator-cli.jar help` to show the usage. @@ -253,7 +257,7 @@ To build from source, you need the following installed and available in your `$P * [Apache Maven 3.3.4 or greater](https://maven.apache.org/) (optional) -After cloning the project, you can build it from source using [maven wrapper](https://github.com/takari/maven-wrapper): +After cloning the project, you can build it from source using [maven wrapper](https://maven.apache.org/wrapper/): - Linux: `./mvnw clean install` - Windows: `mvnw.cmd clean install` @@ -474,7 +478,7 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat -i https://raw.githubusercontent.com/openapitools/openapi-generator/master/modules/openapi-generator/src/test/resources/3_0/petstore.yaml \ -g java \ -t modules/openapi-generator/src/main/resources/Java \ - --additional-properties artifactId=petstore-okhttp-gson,hideGenerationTimestamp:true \ + --additional-properties artifactId=petstore-okhttp-gson,hideGenerationTimestamp=true \ -o samples/client/petstore/java/okhttp-gson ``` @@ -614,10 +618,12 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [California State University, Northridge](https://www.csun.edu) - [CAM](https://www.cam-inc.co.jp/) - [Camptocamp](https://www.camptocamp.com/en) +- [Christopher Queen Consulting](https://www.christopherqueenconsulting.com/) - [Cisco](https://www.cisco.com/) - [codecentric AG](https://www.codecentric.de/) - [CoinAPI](https://www.coinapi.io/) - [Commencis](https://www.commencis.com/) +- [cronn GmbH](https://www.cronn.de/) - [Crossover Health](https://crossoverhealth.com/) - [Cupix](https://www.cupix.com/) - [Datadog](https://www.datadoghq.com) @@ -691,6 +697,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - [RedHat](https://www.redhat.com) - [RepreZen API Studio](https://www.reprezen.com/swagger-openapi-code-generation-api-first-microservices-enterprise-development) - [REST United](https://restunited.com) +- [Robocorp](https://www.robocorp.com) - [Robotinfra](https://www.robotinfra.com) - [SmartHR](https://smarthr.co.jp/) - [Sony Interactive Entertainment](https://www.sie.com/en/index.html) @@ -913,6 +920,7 @@ Here are some companies/projects (alphabetical order) using OpenAPI Generator in - 2023-05-18 - [如何基于 Swagger 使用 OpenAPI Generator 生成 JMeter 脚本?](https://blog.51cto.com/u_15181572/6294974) by [高楼(Zee)](https://blog.51cto.com/u_15181572) - 2023-06-28 - [Generate API contract using OpenAPI Generator Maven plugin](https://huongdanjava.com/generate-api-contract-using-openapi-generator-maven-plugin.html) by [Khanh Nguyen](https://huongdanjava.com/) - 2023-06-30 - [Generate Client SDKs with OpenApi Generator in Springboot](https://medium.com/@ramavathvinayak/generate-client-sdks-with-openapi-generator-in-springboot-f9f012e73c0b) by [Vinayak Ramavath](https://medium.com/@ramavathvinayak) +- 2023-12-10 - [UnityでOpenAPI Generatorを使う](https://www.youtube.com/watch?v=CbNwKVV5LRM) by [Soup Tori](https://www.youtube.com/@souptori8417) ## [6 - About Us](#table-of-contents) @@ -992,6 +1000,7 @@ Here is a list of template creators: * Kotlin (MultiPlatform): @andrewemery * Kotlin (Volley): @alisters * Kotlin (jvm-spring-webclient): @stefankoppier + * Kotlin (jvm-spring-restclient): @stefankoppier * Lua: @daurnimator * N4JS: @mmews-n4 * Nim: @hokamoto @@ -1013,6 +1022,7 @@ Here is a list of template creators: * Scala (Akka): @cchafer * Scala (sttp): @chameleon82 * Scala (sttp4): @flsh86 + * Scala (Pekko): @mickaelmagniez * Swift: @tkqubo * Swift 3: @hexelon * Swift 4: @ehyche @@ -1169,7 +1179,7 @@ If you want to join the committee, please kindly apply by sending an email to te | Perl | @wing328 (2017/07) [:heart:](https://www.patreon.com/wing328) @yue9944882 (2019/06) | | PHP | @jebentier (2017/07), @dkarlovi (2017/07), @mandrean (2017/08), @jfastnacht (2017/09), [@ybelenko](https://github.com/ybelenko) (2018/07), @renepardon (2018/12) | | PowerShell | @wing328 (2020/05) | -| Python | @krjakbrjak (2023/02) | +| Python | @cbornet (2017/09) @tomplus (2018/10) @krjakbrjak (2023/02) @fa0311 (2023/10) @multani (2023/10) | | R | @Ramanth (2019/07) @saigiridhar21 (2019/07) | | Ruby | @cliffano (2017/07) @zlx (2017/09) @autopp (2019/02) | | Rust | @frol (2017/07) @farcaller (2017/08) @richardwhiuk (2019/07) @paladinzh (2020/05) @jacob-pro (2022/10) | diff --git a/bin/configs/ada.yaml b/bin/configs/ada.yaml index 176853b967c1..39b9968d37ff 100644 --- a/bin/configs/ada.yaml +++ b/bin/configs/ada.yaml @@ -13,3 +13,5 @@ parameterNameMappings: additionalProperties: modelPackage: Samples.Petstore projectName: Petstore +enumNameMappings: + sold: UNAVAILABLE diff --git a/bin/configs/csharp-generichost-latest-allOf.yaml b/bin/configs/csharp-generichost-latest-allOf.yaml index e2b84e08d307..90a4f177ce36 100644 --- a/bin/configs/csharp-generichost-latest-allOf.yaml +++ b/bin/configs/csharp-generichost-latest-allOf.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false nullableReferenceTypes: true + equatable: true diff --git a/bin/configs/csharp-generichost-latest-anyOf.yaml b/bin/configs/csharp-generichost-latest-anyOf.yaml index fc6e4bd4298c..e4b2f31aed28 100644 --- a/bin/configs/csharp-generichost-latest-anyOf.yaml +++ b/bin/configs/csharp-generichost-latest-anyOf.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false nullableReferenceTypes: true + equatable: true diff --git a/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml b/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml index 392e76b045f1..30c8ad9fcb25 100644 --- a/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml +++ b/bin/configs/csharp-generichost-latest-nrt-useSourceGeneration.yaml @@ -10,3 +10,4 @@ additionalProperties: disallowAdditionalPropertiesIfNotPresent: false useSourceGeneration: true packageName: UseSourceGeneration + equatable: true diff --git a/bin/configs/csharp-generichost-latest-nrt.yaml b/bin/configs/csharp-generichost-latest-nrt.yaml index d5b834cf314e..699fd70d3f95 100644 --- a/bin/configs/csharp-generichost-latest-nrt.yaml +++ b/bin/configs/csharp-generichost-latest-nrt.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false nullableReferenceTypes: true + equatable: true diff --git a/bin/configs/csharp-generichost-latest-oneOf.yaml b/bin/configs/csharp-generichost-latest-oneOf.yaml index 01b2b4d7fcaa..5b38dc3e7fb2 100644 --- a/bin/configs/csharp-generichost-latest-oneOf.yaml +++ b/bin/configs/csharp-generichost-latest-oneOf.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false nullableReferenceTypes: true + equatable: true diff --git a/bin/configs/csharp-generichost-latest.yaml b/bin/configs/csharp-generichost-latest.yaml index e850d31280c3..82360fcae46f 100644 --- a/bin/configs/csharp-generichost-latest.yaml +++ b/bin/configs/csharp-generichost-latest.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false nullableReferenceTypes: false + equatable: true diff --git a/bin/configs/csharp-generichost-net7.0-useDateTimeForDate.yaml b/bin/configs/csharp-generichost-net7.0-useDateTimeForDate.yaml new file mode 100644 index 000000000000..c20fcdcd7f7b --- /dev/null +++ b/bin/configs/csharp-generichost-net7.0-useDateTimeForDate.yaml @@ -0,0 +1,9 @@ +# for csharp generichost +generatorName: csharp +outputDir: samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate +inputSpec: modules/openapi-generator/src/test/resources/3_0/csharp/dates-api.yaml +library: generichost +templateDir: modules/openapi-generator/src/main/resources/csharp +additionalProperties: + packageGuid: '{2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}' + useDateTimeForDate: true diff --git a/bin/configs/csharp-generichost-netstandard2.0.yaml b/bin/configs/csharp-generichost-netstandard2.0.yaml index fbe662deba01..4c9c8828291e 100644 --- a/bin/configs/csharp-generichost-netstandard2.0.yaml +++ b/bin/configs/csharp-generichost-netstandard2.0.yaml @@ -9,3 +9,4 @@ additionalProperties: useCompareNetObjects: true disallowAdditionalPropertiesIfNotPresent: false targetFramework: netstandard2.0 + equatable: true diff --git a/bin/configs/csharp-httpclient-netstandard2.0.yaml b/bin/configs/csharp-httpclient-netstandard2.0.yaml index e431b385e39b..326f8df942b7 100644 --- a/bin/configs/csharp-httpclient-netstandard2.0.yaml +++ b/bin/configs/csharp-httpclient-netstandard2.0.yaml @@ -10,3 +10,4 @@ additionalProperties: disallowAdditionalPropertiesIfNotPresent: false useOneOfDiscriminatorLookup: true targetFramework: netstandard2.0 + equatable: true diff --git a/bin/configs/csharp-restsharp-echo-api.yaml b/bin/configs/csharp-restsharp-echo-api.yaml index 3380ae3c3d2c..4d93a0d3562d 100644 --- a/bin/configs/csharp-restsharp-echo-api.yaml +++ b/bin/configs/csharp-restsharp-echo-api.yaml @@ -7,3 +7,4 @@ additionalProperties: targetFramework: net6.0 setCompareNetObjects: "true" hideGenerationTimestamp: "true" + equatable: true diff --git a/bin/configs/csharp-restsharp-net4.7-multipleFrameworks.yaml b/bin/configs/csharp-restsharp-net4.7-multipleFrameworks.yaml index 5176032c265d..9a44c9236166 100644 --- a/bin/configs/csharp-restsharp-net4.7-multipleFrameworks.yaml +++ b/bin/configs/csharp-restsharp-net4.7-multipleFrameworks.yaml @@ -6,3 +6,4 @@ additionalProperties: packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' targetFramework: netstandard2.1;net47 useCompareNetObjects: "true" + equatable: true diff --git a/bin/configs/csharp-restsharp-net4.7.yaml b/bin/configs/csharp-restsharp-net4.7.yaml index 91985cd8faa0..7222a6bbcee5 100644 --- a/bin/configs/csharp-restsharp-net4.7.yaml +++ b/bin/configs/csharp-restsharp-net4.7.yaml @@ -10,3 +10,4 @@ additionalProperties: useOneOfDiscriminatorLookup: true targetFramework: net47 skipOneOfAnyOfGetter: true + equatable: true diff --git a/bin/configs/csharp-restsharp-net4.8.yaml b/bin/configs/csharp-restsharp-net4.8.yaml index 29c4ac2b8f80..25b55bc3b820 100644 --- a/bin/configs/csharp-restsharp-net4.8.yaml +++ b/bin/configs/csharp-restsharp-net4.8.yaml @@ -9,3 +9,4 @@ additionalProperties: disallowAdditionalPropertiesIfNotPresent: false useOneOfDiscriminatorLookup: true targetFramework: net48 + equatable: true diff --git a/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml b/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml index 56af6a800cb7..e58d9e57686a 100644 --- a/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml +++ b/bin/configs/csharp-restsharp-net6.0-name-mappings.yaml @@ -16,3 +16,4 @@ additionalProperties: packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' hideGenerationTimestamp: "true" targetFramework: net6.0 + equatable: true diff --git a/bin/configs/csharp-restsharp-net7.0-compareNetObjects.yaml b/bin/configs/csharp-restsharp-net7.0-compareNetObjects.yaml index 597c7c328c75..7015e00a2779 100644 --- a/bin/configs/csharp-restsharp-net7.0-compareNetObjects.yaml +++ b/bin/configs/csharp-restsharp-net7.0-compareNetObjects.yaml @@ -6,3 +6,4 @@ additionalProperties: packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' targetFramework: net7.0 useCompareNetObjects: "true" + equatable: true diff --git a/bin/configs/csharp-restsharp-net7.0-useDateTimeForDate.yaml b/bin/configs/csharp-restsharp-net7.0-useDateTimeForDate.yaml new file mode 100644 index 000000000000..e5c65c57d206 --- /dev/null +++ b/bin/configs/csharp-restsharp-net7.0-useDateTimeForDate.yaml @@ -0,0 +1,9 @@ +# for .net standard +generatorName: csharp +outputDir: samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate +inputSpec: modules/openapi-generator/src/test/resources/3_0/csharp/dates-api.yaml +templateDir: modules/openapi-generator/src/main/resources/csharp +additionalProperties: + packageGuid: '{D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}' + targetFramework: net7.0 + useDateTimeForDate: true diff --git a/bin/configs/csharp-restsharp-net7.0.yaml b/bin/configs/csharp-restsharp-net7.0.yaml index 347ac99a2b35..000d828b465b 100644 --- a/bin/configs/csharp-restsharp-net7.0.yaml +++ b/bin/configs/csharp-restsharp-net7.0.yaml @@ -9,3 +9,6 @@ additionalProperties: disallowAdditionalPropertiesIfNotPresent: false useOneOfDiscriminatorLookup: true targetFramework: net7.0 + equatable: true +enumNameMappings: + delivered: Shipped diff --git a/bin/configs/csharp-restsharp-netstandard2.0-complexfiles.yaml b/bin/configs/csharp-restsharp-netstandard2.0-complexfiles.yaml index efd6022c6e89..a6782e9387b9 100644 --- a/bin/configs/csharp-restsharp-netstandard2.0-complexfiles.yaml +++ b/bin/configs/csharp-restsharp-netstandard2.0-complexfiles.yaml @@ -6,5 +6,6 @@ additionalProperties: packageGuid: '{321C8C3F-0156-40C1-AE42-D59761FB9B6C}' targetFramework: netstandard2.0 useCompareNetObjects: "true" + equatable: true globalProperties: skipFormModel: "false" diff --git a/bin/configs/csharp-restsharp-netstandard2.0-conditionalSerialization.yaml b/bin/configs/csharp-restsharp-netstandard2.0-conditionalSerialization.yaml index b92f3bac2243..100203b43a69 100644 --- a/bin/configs/csharp-restsharp-netstandard2.0-conditionalSerialization.yaml +++ b/bin/configs/csharp-restsharp-netstandard2.0-conditionalSerialization.yaml @@ -10,3 +10,4 @@ additionalProperties: useOneOfDiscriminatorLookup: true targetFramework: netstandard2.0 conditionalSerialization: true + equatable: true diff --git a/bin/configs/csharp-restsharp-netstandard2.0.yaml b/bin/configs/csharp-restsharp-netstandard2.0.yaml index 994fd0d40647..d4b6d3289833 100644 --- a/bin/configs/csharp-restsharp-netstandard2.0.yaml +++ b/bin/configs/csharp-restsharp-netstandard2.0.yaml @@ -9,3 +9,4 @@ additionalProperties: disallowAdditionalPropertiesIfNotPresent: false useOneOfDiscriminatorLookup: true targetFramework: netstandard2.0 + equatable: true diff --git a/bin/configs/csharp-unityWebRequest-netstandard2.0.yaml b/bin/configs/csharp-unityWebRequest-netstandard2.0.yaml index 8005d2ce78a5..0f91232f8e1e 100644 --- a/bin/configs/csharp-unityWebRequest-netstandard2.0.yaml +++ b/bin/configs/csharp-unityWebRequest-netstandard2.0.yaml @@ -6,3 +6,4 @@ templateDir: modules/openapi-generator/src/main/resources/csharp library: unityWebRequest additionalProperties: targetFramework: netstandard2.0 + equatable: true diff --git a/bin/configs/dart-petstore-client-lib.yaml b/bin/configs/dart-petstore-client-lib.yaml index 8b4a6deefd70..5ea435605816 100644 --- a/bin/configs/dart-petstore-client-lib.yaml +++ b/bin/configs/dart-petstore-client-lib.yaml @@ -4,3 +4,5 @@ inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/dart2 additionalProperties: hideGenerationTimestamp: "true" +enumNameMappings: + delivered: shipped diff --git a/bin/configs/go-petstore-generateMarshalJSON-false.yaml b/bin/configs/go-petstore-generateMarshalJSON-false.yaml new file mode 100644 index 000000000000..ea9652acba66 --- /dev/null +++ b/bin/configs/go-petstore-generateMarshalJSON-false.yaml @@ -0,0 +1,9 @@ +generatorName: go +outputDir: samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml +templateDir: modules/openapi-generator/src/main/resources/go +additionalProperties: + enumClassPrefix: "true" + packageName: petstore + disallowAdditionalPropertiesIfNotPresent: false + generateMarshalJSON: false diff --git a/bin/configs/go-petstore.yaml b/bin/configs/go-petstore.yaml index 041b751f4074..5647bf469e4b 100644 --- a/bin/configs/go-petstore.yaml +++ b/bin/configs/go-petstore.yaml @@ -15,4 +15,6 @@ additionalProperties: packageName: petstore disallowAdditionalPropertiesIfNotPresent: false generateInterfaces: true +enumNameMappings: + delivered: SHIPPED diff --git a/bin/configs/java-microprofile-rest-client-with-useSingleRequestParameter.yaml b/bin/configs/java-microprofile-rest-client-with-useSingleRequestParameter.yaml new file mode 100644 index 000000000000..bc7ba0e51486 --- /dev/null +++ b/bin/configs/java-microprofile-rest-client-with-useSingleRequestParameter.yaml @@ -0,0 +1,10 @@ +generatorName: java +outputDir: samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter +library: microprofile +inputSpec: modules/openapi-generator/src/test/resources/3_1/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + artifactId: microprofile-rest-client + configKey: petstore + useSingleRequestParameter: true + microprofileRestClientVersion: "3.0" \ No newline at end of file diff --git a/bin/configs/java-okhttp-gson-oneOf.yaml b/bin/configs/java-okhttp-gson-oneOf.yaml new file mode 100644 index 000000000000..7b048f8c17c0 --- /dev/null +++ b/bin/configs/java-okhttp-gson-oneOf.yaml @@ -0,0 +1,7 @@ +generatorName: java +outputDir: samples/client/others/java/okhttp-gson-oneOf +library: okhttp-gson +inputSpec: modules/openapi-generator/src/test/resources/3_0/oneOf_twoPrimitives.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/java-okhttp-gson.yaml b/bin/configs/java-okhttp-gson.yaml index a93c8263ddb1..d3def489a5cd 100644 --- a/bin/configs/java-okhttp-gson.yaml +++ b/bin/configs/java-okhttp-gson.yaml @@ -14,3 +14,6 @@ additionalProperties: hideGenerationTimestamp: "true" useOneOfDiscriminatorLookup: "true" disallowAdditionalPropertiesIfNotPresent: false +enumNameMappings: + s: LOWER_CASE_S + S: UPPER_CASE_S diff --git a/bin/configs/java-resteasy-echo-api.yaml b/bin/configs/java-resteasy-echo-api.yaml new file mode 100644 index 000000000000..c99ffe228d20 --- /dev/null +++ b/bin/configs/java-resteasy-echo-api.yaml @@ -0,0 +1,8 @@ +generatorName: java +outputDir: samples/client/echo_api/java/resteasy +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + artifactId: petstore-resteasy-echo + hideGenerationTimestamp: "true" + library: resteasy diff --git a/bin/configs/java-resttemplate-echo-api.yaml b/bin/configs/java-resttemplate-echo-api.yaml new file mode 100644 index 000000000000..27e9a63cfa69 --- /dev/null +++ b/bin/configs/java-resttemplate-echo-api.yaml @@ -0,0 +1,10 @@ +generatorName: java +outputDir: samples/client/echo_api/java/resttemplate +library: resttemplate +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/Java +additionalProperties: + artifactId: echo-api-resttemplate + hideGenerationTimestamp: "true" + java8: true + containerDefaultToNull: true diff --git a/bin/configs/unmaintained/jaxrs-cxf-client-jackson.yaml b/bin/configs/jaxrs-cxf-client-jackson.yaml similarity index 100% rename from bin/configs/unmaintained/jaxrs-cxf-client-jackson.yaml rename to bin/configs/jaxrs-cxf-client-jackson.yaml diff --git a/bin/configs/unmaintained/jaxrs-cxf-client.yaml b/bin/configs/jaxrs-cxf-client.yaml similarity index 100% rename from bin/configs/unmaintained/jaxrs-cxf-client.yaml rename to bin/configs/jaxrs-cxf-client.yaml diff --git a/bin/configs/unmaintained/jaxrs-spec-interface-response.yaml b/bin/configs/jaxrs-spec-interface-response.yaml similarity index 100% rename from bin/configs/unmaintained/jaxrs-spec-interface-response.yaml rename to bin/configs/jaxrs-spec-interface-response.yaml diff --git a/bin/configs/unmaintained/jmeter.yaml b/bin/configs/jmeter.yaml similarity index 62% rename from bin/configs/unmaintained/jmeter.yaml rename to bin/configs/jmeter.yaml index 79b5de0e41b3..9fcb1a082175 100644 --- a/bin/configs/unmaintained/jmeter.yaml +++ b/bin/configs/jmeter.yaml @@ -1,4 +1,4 @@ generatorName: jmeter outputDir: samples/client/petstore/jmeter -inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +inputSpec: modules/openapi-generator/src/test/resources/3_0/jmeter/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/jmeter-client diff --git a/bin/configs/kotlin-array-simple-string-multiplatform.yaml b/bin/configs/kotlin-array-simple-string-multiplatform.yaml index 8c880a679713..832743068367 100644 --- a/bin/configs/kotlin-array-simple-string-multiplatform.yaml +++ b/bin/configs/kotlin-array-simple-string-multiplatform.yaml @@ -5,3 +5,4 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: artifactId: kotlin-array-simple-string-multiplatform library: multiplatform + dateLibrary: kotlinx-datetime diff --git a/bin/configs/kotlin-bigdecimal-default-multiplatform.yaml b/bin/configs/kotlin-bigdecimal-default-multiplatform.yaml index c525b0b9edc4..26ff97c424fc 100644 --- a/bin/configs/kotlin-bigdecimal-default-multiplatform.yaml +++ b/bin/configs/kotlin-bigdecimal-default-multiplatform.yaml @@ -5,3 +5,4 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: artifactId: kotlin-bigdecimal-default-multiplatform library: multiplatform + dateLibrary: kotlinx-datetime diff --git a/bin/configs/kotlin-default-values-multiplatform.yaml b/bin/configs/kotlin-default-values-multiplatform.yaml index 7a9a0fa52e6e..320c3f30a3c9 100644 --- a/bin/configs/kotlin-default-values-multiplatform.yaml +++ b/bin/configs/kotlin-default-values-multiplatform.yaml @@ -5,4 +5,5 @@ templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: artifactId: kotlin-default-values-multiplatform library: multiplatform + dateLibrary: kotlinx-datetime sortParamsByRequiredFlag: false diff --git a/bin/configs/kotlin-enum-default-value.yaml b/bin/configs/kotlin-enum-default-value.yaml index ddb00c552830..b27ccfd73afb 100644 --- a/bin/configs/kotlin-enum-default-value.yaml +++ b/bin/configs/kotlin-enum-default-value.yaml @@ -7,3 +7,5 @@ additionalProperties: serializableModel: "true" dateLibrary: java8 enumUnknownDefaultCase: true +enumNameMappings: + CHRISTMAS_DAY: XMAS_DAY diff --git a/bin/configs/kotlin-jackson.yaml b/bin/configs/kotlin-jackson.yaml index 2d37a29f38ad..d16fee65eeeb 100644 --- a/bin/configs/kotlin-jackson.yaml +++ b/bin/configs/kotlin-jackson.yaml @@ -6,3 +6,4 @@ additionalProperties: serializationLibrary: jackson artifactId: kotlin-petstore-jackson enumPropertyNaming: UPPERCASE + enumUnknownDefaultCase: "true" diff --git a/bin/configs/kotlin-jvm-retrofit2-jackson.yaml b/bin/configs/kotlin-jvm-retrofit2-jackson.yaml new file mode 100644 index 000000000000..4a4dd362b437 --- /dev/null +++ b/bin/configs/kotlin-jvm-retrofit2-jackson.yaml @@ -0,0 +1,10 @@ +generatorName: kotlin +outputDir: samples/client/petstore/kotlin-retrofit2-jackson +library: jvm-retrofit2 +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + serializationLibrary: jackson + artifactId: kotlin-petstore-retrofit2-jackson + enumPropertyNaming: UPPERCASE + serializableModel: "true" diff --git a/bin/configs/kotlin-jvm-spring-3-restclient.yaml b/bin/configs/kotlin-jvm-spring-3-restclient.yaml new file mode 100644 index 000000000000..948caa41c8e0 --- /dev/null +++ b/bin/configs/kotlin-jvm-spring-3-restclient.yaml @@ -0,0 +1,10 @@ +generatorName: kotlin +outputDir: samples/client/petstore/kotlin-jvm-spring-3-restclient +library: jvm-spring-restclient +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + artifactId: kotlin-petstore-spring-restclient + enumUnknownDefaultCase: true + serializationLibrary: jackson + useSpringBoot3: true diff --git a/bin/configs/kotlin-kotlinx-datetime.yaml b/bin/configs/kotlin-kotlinx-datetime.yaml new file mode 100644 index 000000000000..cff9e901791a --- /dev/null +++ b/bin/configs/kotlin-kotlinx-datetime.yaml @@ -0,0 +1,7 @@ +generatorName: kotlin +outputDir: samples/client/petstore/kotlin-kotlinx-datetime +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + artifactId: kotlin-petstore-threetenbp + dateLibrary: kotlinx-datetime diff --git a/bin/configs/kotlin-multiplatform-kotlinx-datetime.yaml b/bin/configs/kotlin-multiplatform-kotlinx-datetime.yaml new file mode 100644 index 000000000000..dd5fb8f1075a --- /dev/null +++ b/bin/configs/kotlin-multiplatform-kotlinx-datetime.yaml @@ -0,0 +1,8 @@ +generatorName: kotlin +outputDir: samples/client/petstore/kotlin-multiplatform-kotlinx-datetime +library: multiplatform +dateLibrary: kotlinx-datetime +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-client +additionalProperties: + artifactId: kotlin-client-petstore-multiplatform-kotlinx-datetime diff --git a/bin/configs/kotlin-multiplatform.yaml b/bin/configs/kotlin-multiplatform.yaml index ba50f38f6780..f4bc9a60f027 100644 --- a/bin/configs/kotlin-multiplatform.yaml +++ b/bin/configs/kotlin-multiplatform.yaml @@ -1,6 +1,7 @@ generatorName: kotlin outputDir: samples/client/petstore/kotlin-multiplatform library: multiplatform +dateLibrary: kotlinx-datetime inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml templateDir: modules/openapi-generator/src/main/resources/kotlin-client additionalProperties: diff --git a/bin/configs/kotlin-spring-boot-request.yaml b/bin/configs/kotlin-spring-boot-request.yaml new file mode 100644 index 000000000000..45cd1f00334b --- /dev/null +++ b/bin/configs/kotlin-spring-boot-request.yaml @@ -0,0 +1,9 @@ +generatorName: kotlin-spring +outputDir: samples/server/petstore/kotlin-springboot-request +library: spring-boot +inputSpec: modules/openapi-generator/src/test/resources/2_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/kotlin-spring +additionalProperties: + appendRequestToHandler: true + interfaceOnly: true + useSpringBoot3: true diff --git a/bin/configs/php-nextgen.yaml b/bin/configs/php-nextgen.yaml index e8db9d729c2d..ed0f8bfd99db 100644 --- a/bin/configs/php-nextgen.yaml +++ b/bin/configs/php-nextgen.yaml @@ -2,3 +2,5 @@ generatorName: php-nextgen outputDir: samples/client/petstore/php-nextgen/OpenAPIClient-php inputSpec: modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml templateDir: modules/openapi-generator/src/main/resources/php-nextgen +enumNameMappings: + delivered: SHIPPED diff --git a/bin/configs/powershell-echo-api.yaml b/bin/configs/powershell-echo-api.yaml new file mode 100644 index 000000000000..2bf9c383c17a --- /dev/null +++ b/bin/configs/powershell-echo-api.yaml @@ -0,0 +1,7 @@ +generatorName: powershell +outputDir: samples/client/echo_api/powershell +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/powershell +additionalProperties: + hideGenerationTimestamp: "true" + packageGuid: a27b908d-2a20-467f-bc32-af6f3a654ac5 diff --git a/bin/configs/python-aiohttp.yaml b/bin/configs/python-aiohttp.yaml index 6bec6d585b66..a7515a1bdfb2 100644 --- a/bin/configs/python-aiohttp.yaml +++ b/bin/configs/python-aiohttp.yaml @@ -6,3 +6,9 @@ library: asyncio additionalProperties: packageName: petstore_api mapNumberTo: float +nameMappings: + _type: underscore_type + type_: type_with_underscore +modelNameMappings: + # The OpenAPI spec ApiResponse conflicts with the internal ApiResponse + ApiResponse: ModelApiResponse diff --git a/bin/configs/python.yaml b/bin/configs/python.yaml index b13e5b802e21..09727cdfab9a 100644 --- a/bin/configs/python.yaml +++ b/bin/configs/python.yaml @@ -10,3 +10,6 @@ additionalProperties: nameMappings: _type: underscore_type type_: type_with_underscore +modelNameMappings: + # The OpenAPI spec ApiResponse conflicts with the internal ApiResponse + ApiResponse: ModelApiResponse diff --git a/bin/configs/ruby-faraday-echo-api.yaml b/bin/configs/ruby-faraday-echo-api.yaml new file mode 100644 index 000000000000..bb8cd8b95335 --- /dev/null +++ b/bin/configs/ruby-faraday-echo-api.yaml @@ -0,0 +1,7 @@ +generatorName: ruby +outputDir: samples/client/echo_api/ruby-faraday +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/ruby-client +library: faraday +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/ruby-typhoeus-echo-api.yaml b/bin/configs/ruby-typhoeus-echo-api.yaml new file mode 100644 index 000000000000..c38918751b96 --- /dev/null +++ b/bin/configs/ruby-typhoeus-echo-api.yaml @@ -0,0 +1,7 @@ +generatorName: ruby +outputDir: samples/client/echo_api/ruby-typhoeus +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/ruby-client +library: typhoeus +additionalProperties: + hideGenerationTimestamp: "true" diff --git a/bin/configs/ruby.yaml b/bin/configs/ruby.yaml index bb8e37cbff7b..75b92f92eafe 100644 --- a/bin/configs/ruby.yaml +++ b/bin/configs/ruby.yaml @@ -15,3 +15,5 @@ nameMappings: parameterNameMappings: _type: underscore_type type_: type_with_underscore +enumNameMappings: + delivered: SHIPPED diff --git a/bin/configs/rust-axum-multipart-v3.yaml b/bin/configs/rust-axum-multipart-v3.yaml new file mode 100644 index 000000000000..13f7d4a33680 --- /dev/null +++ b/bin/configs/rust-axum-multipart-v3.yaml @@ -0,0 +1,10 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/multipart-v3 +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust-server/multipart-v3.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + allowBlockingResponseSerialize: "true" + packageName: multipart-v3 +enablePostProcessFile: true diff --git a/bin/configs/rust-axum-openapi-v3.yaml b/bin/configs/rust-axum-openapi-v3.yaml new file mode 100644 index 000000000000..35ae45d6950e --- /dev/null +++ b/bin/configs/rust-axum-openapi-v3.yaml @@ -0,0 +1,10 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/openapi-v3 +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + allowBlockingValidator: "true" + packageName: openapi-v3 +enablePostProcessFile: true diff --git a/bin/configs/rust-axum-ops-v3.yaml b/bin/configs/rust-axum-ops-v3.yaml new file mode 100644 index 000000000000..c0a217166d32 --- /dev/null +++ b/bin/configs/rust-axum-ops-v3.yaml @@ -0,0 +1,8 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/ops-v3 +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust-server/ops-v3.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + packageName: ops-v3 diff --git a/bin/configs/rust-axum-petstore-with-fake-endpoints-models-for-testing.yaml b/bin/configs/rust-axum-petstore-with-fake-endpoints-models-for-testing.yaml new file mode 100644 index 000000000000..69ca39092e45 --- /dev/null +++ b/bin/configs/rust-axum-petstore-with-fake-endpoints-models-for-testing.yaml @@ -0,0 +1,10 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing +inputSpec: modules/openapi-generator/src/test/resources/2_0/rust-server/petstore-with-fake-endpoints-models-for-testing.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + packageName: petstore-with-fake-endpoints-models-for-testing + publishRustRegistry: crates-io +enablePostProcessFile: true \ No newline at end of file diff --git a/bin/configs/rust-axum-petstore.yaml b/bin/configs/rust-axum-petstore.yaml new file mode 100644 index 000000000000..3149c7418582 --- /dev/null +++ b/bin/configs/rust-axum-petstore.yaml @@ -0,0 +1,9 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/petstore +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + packageName: petstore +enablePostProcessFile: true diff --git a/bin/configs/rust-axum-ping-bearer-auth-v3.yaml b/bin/configs/rust-axum-ping-bearer-auth-v3.yaml new file mode 100644 index 000000000000..573a6b9f1993 --- /dev/null +++ b/bin/configs/rust-axum-ping-bearer-auth-v3.yaml @@ -0,0 +1,9 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/ping-bearer-auth +inputSpec: modules/openapi-generator/src/test/resources/3_0/rust-server/ping-bearer-auth.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + packageName: ping-bearer-auth +enablePostProcessFile: true diff --git a/bin/configs/rust-axum-test.yaml b/bin/configs/rust-axum-test.yaml new file mode 100644 index 000000000000..b73b3fb53139 --- /dev/null +++ b/bin/configs/rust-axum-test.yaml @@ -0,0 +1,9 @@ +generatorName: rust-axum +outputDir: samples/server/petstore/rust-axum/output/rust-axum-test +inputSpec: modules/openapi-generator/src/test/resources/2_0/rust-server/rust-server-test.yaml +templateDir: modules/openapi-generator/src/main/resources/rust-axum +generateAliasAsModel: true +additionalProperties: + hideGenerationTimestamp: "true" + packageName: rust-server-test +enablePostProcessFile: true diff --git a/bin/configs/rust-reqwest-petstore.yaml b/bin/configs/rust-reqwest-petstore.yaml index e107582b217f..12a20cdce467 100644 --- a/bin/configs/rust-reqwest-petstore.yaml +++ b/bin/configs/rust-reqwest-petstore.yaml @@ -6,3 +6,5 @@ templateDir: modules/openapi-generator/src/main/resources/rust additionalProperties: supportAsync: false packageName: petstore-reqwest +enumNameMappings: + delivered: shipped diff --git a/bin/configs/scala-http4s-server.yaml b/bin/configs/scala-http4s-server.yaml new file mode 100644 index 000000000000..20435c437696 --- /dev/null +++ b/bin/configs/scala-http4s-server.yaml @@ -0,0 +1,6 @@ +generatorName: scala-http4s-server +outputDir: samples/server/petstore/scala-http4s-server +inputSpec: modules/openapi-generator/src/test/resources/3_0/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/scala-http4s-server +additionalProperties: + artifactId: openapi-scala-http4s-server \ No newline at end of file diff --git a/bin/configs/scala-pekko.yaml b/bin/configs/scala-pekko.yaml new file mode 100644 index 000000000000..aeba75865331 --- /dev/null +++ b/bin/configs/scala-pekko.yaml @@ -0,0 +1,6 @@ +generatorName: scala-pekko +outputDir: samples/client/petstore/scala-pekko +inputSpec: modules/openapi-generator/src/test/resources/3_0/scala-pekko/petstore.yaml +templateDir: modules/openapi-generator/src/main/resources/scala-pekko-client +additionalProperties: + artifactId: scala-pekko-petstore-client diff --git a/bin/configs/spring-boot-3.yaml b/bin/configs/spring-boot-3.yaml index 5c8b97cdad1d..5dea2cbda5ee 100644 --- a/bin/configs/spring-boot-3.yaml +++ b/bin/configs/spring-boot-3.yaml @@ -9,4 +9,5 @@ additionalProperties: snapshotVersion: "true" useSpringBoot3: true useBeanValidation: true + withXml: true hideGenerationTimestamp: "true" diff --git a/bin/configs/spring-cloud-http-basic-only.yaml b/bin/configs/spring-cloud-http-basic-only.yaml new file mode 100644 index 000000000000..b6ff990b7963 --- /dev/null +++ b/bin/configs/spring-cloud-http-basic-only.yaml @@ -0,0 +1,13 @@ +generatorName: spring +library: spring-cloud +outputDir: samples/openapi3/client/petstore/spring-cloud-http-basic +inputSpec: modules/openapi-generator/src/test/resources/3_0/http-basic-test.yaml +templateDir: modules/openapi-generator/src/main/resources/JavaSpring +additionalProperties: + groupId: org.openapitools.openapi3 + documentationProvider: springdoc + artifactId: spring-cloud-http-basic + interfaceOnly: "true" + singleContentTypes: "true" + hideGenerationTimestamp: "true" + useTags: "true" diff --git a/bin/configs/swift-combine-petstore-new.yaml b/bin/configs/swift-combine-petstore-new.yaml index 5349e056a5b8..2a132fb34e58 100644 --- a/bin/configs/swift-combine-petstore-new.yaml +++ b/bin/configs/swift-combine-petstore-new.yaml @@ -5,3 +5,5 @@ templateDir: modules/openapi-generator/src/main/resources/swift-combine additionalProperties: hideGenerationTimestamp: "true" projectName: "PetstoreOpenAPI" +enumNameMappings: + delivered: shipped diff --git a/bin/configs/swift5-default.yaml b/bin/configs/swift5-default.yaml index fffd318be1ad..c419a704699a 100644 --- a/bin/configs/swift5-default.yaml +++ b/bin/configs/swift5-default.yaml @@ -8,3 +8,5 @@ additionalProperties: podSummary: PetstoreClient projectName: PetstoreClient podHomepage: https://github.com/openapitools/openapi-generator +enumNameMappings: + delivered: shipped diff --git a/bin/configs/typescript-axios-echo-api.yaml b/bin/configs/typescript-axios-echo-api.yaml new file mode 100644 index 000000000000..c65282a5e865 --- /dev/null +++ b/bin/configs/typescript-axios-echo-api.yaml @@ -0,0 +1,9 @@ +generatorName: typescript-axios +outputDir: samples/client/echo_api/typescript-axios/build +inputSpec: modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +templateDir: modules/openapi-generator/src/main/resources/typescript-axios +additionalProperties: + artifactId: echo-api-typescript-axios + hideGenerationTimestamp: "true" + npmVersion: 1.0.0 + npmName: '@openapitools/typescript-axios-echo-api' diff --git a/bin/meta-codegen-kotlin.sh b/bin/meta-codegen-kotlin.sh index 905334f5f9fb..004a95527424 100755 --- a/bin/meta-codegen-kotlin.sh +++ b/bin/meta-codegen-kotlin.sh @@ -7,8 +7,8 @@ declare cwd="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)" declare root="$(cd "$cwd" && cd ../ && pwd)" if ! command -v gradle > /dev/null; then - echo "[WARN] This script requires a system gradle to be installed. Not treating this as an error." - exit 0 + echo "[WARN] This script requires a system gradle to be installed. Not treating this as an error." + exit 0 fi executable="${root}/modules/openapi-generator-cli/target/openapi-generator-cli.jar" diff --git a/bin/utils/test_file_list.yaml b/bin/utils/test_file_list.yaml index d2ed1a960c6b..737a881f2814 100644 --- a/bin/utils/test_file_list.yaml +++ b/bin/utils/test_file_list.yaml @@ -9,3 +9,9 @@ # java okhttp gson test files - filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ClientTest.java" sha256: db505f7801fef62c13a08a8e9ca1fc4c5c947ab46b46f12943139d353feacf17 +- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java" + sha256: 6db714e9744c150c8982c3cb18e4f37a9c1ecd8f72f6d58943986e781ab4a344 +- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java" + sha256: 0d64cdc11809a7b5b952ccdad2bd91bd0045b3894d6fabf3e368fa0be12b8217 +- filename: "samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java" + sha256: a1f8a70bf7b0c382a8def5bacf7b1fb189e687fabb40235aa799001e0597f545 diff --git a/docker-entrypoint.sh b/docker-entrypoint.sh index 5091cf3996d6..4590b56ce65d 100755 --- a/docker-entrypoint.sh +++ b/docker-entrypoint.sh @@ -4,7 +4,7 @@ set -euo pipefail # GEN_DIR allows to share the entrypoint between Dockerfile and run-in-docker.sh (backward compatible) GEN_DIR=${GEN_DIR:-/opt/openapi-generator} -JAVA_OPTS=${JAVA_OPTS:-"-Xmx1024M -DloggerPath=conf/log4j.properties"} +JAVA_OPTS=${JAVA_OPTS:-"-DloggerPath=conf/log4j.properties"} cli="${GEN_DIR}/modules/openapi-generator-cli" codegen="${cli}/target/openapi-generator-cli.jar" diff --git a/docs/customization.md b/docs/customization.md index e256c8b9b36f..ade155b1ba11 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -266,6 +266,11 @@ Upon first code generation, you may also pass the CLI option `--ignore-file-over Editor support for `.openapi-generator-ignore` files is available in IntelliJ via the [.ignore plugin](https://plugins.jetbrains.com/plugin/7495--ignore). +One may want to pre-populate `.openapi-generator-ignore` with a list of entries during the code generation process and the global/general option `openapiGeneatorIgnoreList` (e.g. --openapi-generator-ignore-list in CLI) can do exactly that. For example, +``` +java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generate -g spring -i modules/openapi-generator/src/test/resources/3_0/petstore.yaml -o /tmp/spring --additional-properties useTags=true --openapi-generator-ignore-list "README.md,pom.xml,docs/*.md,src/main/java/org/openapitools/model/*" +``` + ## Customizing the generator There are different aspects of customizing the code generator beyond just creating or modifying templates. Each language has a supporting configuration file to handle different type mappings, etc: @@ -421,7 +426,13 @@ java -jar modules/openapi-generator-cli/target/openapi-generator-cli.jar generat ``` will rename the `Tag` schema to `Label` instead. -Not all generators support thess features yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly. We also welcome PRs to add these features to generators. Related PRs for reference: #16209, #16234 (modelNameMappings), #16194, #16206 (nameMappings, parameterNameMappings). +To map enum names, use `enumNameMappings` option, e.g. +```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/ --enum-name-mappings sold=UNAVAILABLE +``` +will rename SOLD to UNAVAILABLE instead. + +Not all generators support thess features yet. Please give it a try to confirm the behaviour and open an issue (ticket) to let us know which generators you would like to have this feature enabled and we'll prioritize accordingly. We also welcome PRs to add these features to generators. Related PRs for reference: #16209, #16234 (modelNameMappings), #16194, #16206 (nameMappings, parameterNameMappings), #17108 (enumNameMappings). NOTE: some generators use `baseName` (original name obtained direclty from OpenAPI spec, e.g. `shipping-date`) mustache tag in the templates so the mapping feature won't work. diff --git a/docs/faq-generators.md b/docs/faq-generators.md index 370130dbe118..c54f151372bd 100644 --- a/docs/faq-generators.md +++ b/docs/faq-generators.md @@ -110,6 +110,6 @@ No, please use `swift3` or `swift4` generator instead as we want to focus on Swi Yes, please use the following option when generating TypeScript clients: ``` - modelPropertyNaming - Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name (Default: camelCase) + modelPropertyNaming + Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name (Default: camelCase) ``` diff --git a/docs/generators.md b/docs/generators.md index d07a0bf2abb5..81ec2934797d 100644 --- a/docs/generators.md +++ b/docs/generators.md @@ -59,6 +59,7 @@ The following generators are available: * [rust](generators/rust.md) * [scala-akka](generators/scala-akka.md) * [scala-gatling](generators/scala-gatling.md) +* [scala-pekko](generators/scala-pekko.md) * [scala-sttp](generators/scala-sttp.md) * [scala-sttp4 (beta)](generators/scala-sttp4.md) * [scalaz](generators/scalaz.md) @@ -129,9 +130,11 @@ The following generators are available: * [python-flask](generators/python-flask.md) * [ruby-on-rails](generators/ruby-on-rails.md) * [ruby-sinatra](generators/ruby-sinatra.md) +* [rust-axum (beta)](generators/rust-axum.md) * [rust-server](generators/rust-server.md) * [scala-akka-http-server (beta)](generators/scala-akka-http-server.md) * [scala-finch](generators/scala-finch.md) +* [scala-http4s-server](generators/scala-http4s-server.md) * [scala-lagom-server](generators/scala-lagom-server.md) * [scala-play-server](generators/scala-play-server.md) * [scalatra](generators/scalatra.md) diff --git a/docs/generators/README.md b/docs/generators/README.md index 648de9673e73..3b624bd8b8f6 100644 --- a/docs/generators/README.md +++ b/docs/generators/README.md @@ -12,7 +12,7 @@ The following generators are available: * [cpp-restsdk](cpp-restsdk.md) * [cpp-tizen](cpp-tizen.md) * [csharp](csharp.md) -* [csharp-netcore](csharp-netcore.md) +* [csharp-functions](csharp-functions.md) * [dart](dart.md) * [dart-dio](dart-dio.md) * [eiffel](eiffel.md) @@ -45,6 +45,7 @@ The following generators are available: * [ruby](ruby.md) * [rust](rust.md) * [scala-akka](scala-akka.md) +* [scala-pekko](scala-pekko.md) * [scala-gatling](scala-gatling.md) * [scalaz](scalaz.md) * [swift4](swift4.md) diff --git a/docs/generators/ada-server.md b/docs/generators/ada-server.md index 8484bcc14d61..8762b5e3dbaf 100644 --- a/docs/generators/ada-server.md +++ b/docs/generators/ada-server.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ada.md b/docs/generators/ada.md index 1a3a597c8df8..866f60e5c351 100644 --- a/docs/generators/ada.md +++ b/docs/generators/ada.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/android.md b/docs/generators/android.md index b486b1114bb0..44d974431739 100644 --- a/docs/generators/android.md +++ b/docs/generators/android.md @@ -257,6 +257,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/apache2.md b/docs/generators/apache2.md index 6e39ef0c929d..29c6859fe3ca 100644 --- a/docs/generators/apache2.md +++ b/docs/generators/apache2.md @@ -159,6 +159,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/apex.md b/docs/generators/apex.md index 8b7f34f8eddd..490be47dfd02 100644 --- a/docs/generators/apex.md +++ b/docs/generators/apex.md @@ -297,6 +297,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/asciidoc.md b/docs/generators/asciidoc.md index e4e44a106ca0..4dd91dc58f84 100644 --- a/docs/generators/asciidoc.md +++ b/docs/generators/asciidoc.md @@ -175,6 +175,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/aspnetcore.md b/docs/generators/aspnetcore.md index 814ed0d4bd2f..5dbedb169c54 100644 --- a/docs/generators/aspnetcore.md +++ b/docs/generators/aspnetcore.md @@ -47,6 +47,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sourceFolder|source folder for generated code| |src| |swashbuckleVersion|Swashbuckle version: 3.0.0 (deprecated), 4.0.0 (deprecated), 5.0.0 (deprecated), 6.4.0|
**3.0.0**
Swashbuckle 3.0.0
**4.0.0**
Swashbuckle 4.0.0
**5.0.0**
Swashbuckle 5.0.0
**6.4.0**
Swashbuckle 6.4.0
|3.0.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| +|useDateTimeForDate|Use DateTime to model date properties even if DateOnly supported. (.net 6.0+ only)| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useDefaultRouting|Use default routing for the ASP.NET Core version.| |true| |useFrameworkReference|Use frameworkReference for ASP.NET Core 3.0+ and PackageReference ASP.NET Core 2.2 or earlier.| |false| @@ -74,6 +75,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
  • Boolean
  • Collection
  • +
  • DateOnly
  • +
  • DateOnly?
  • DateTime
  • DateTime?
  • DateTimeOffset
  • @@ -116,6 +119,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
    • Client
    • Configuration
    • +
    • Environment
    • +
    • OperatingSystem
    • +
    • TimeZone
    • Version
    • abstract
    • as
    • @@ -326,6 +332,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/avro-schema.md b/docs/generators/avro-schema.md index d24852ff669a..82ca92af9f97 100644 --- a/docs/generators/avro-schema.md +++ b/docs/generators/avro-schema.md @@ -176,6 +176,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/bash.md b/docs/generators/bash.md index 5f765a2ec535..2975eed1ba0e 100644 --- a/docs/generators/bash.md +++ b/docs/generators/bash.md @@ -189,6 +189,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/c.md b/docs/generators/c.md index f69581c1e379..98415304de28 100644 --- a/docs/generators/c.md +++ b/docs/generators/c.md @@ -285,6 +285,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/clojure.md b/docs/generators/clojure.md index cf4afb46be4b..f8afb80b8934 100644 --- a/docs/generators/clojure.md +++ b/docs/generators/clojure.md @@ -165,6 +165,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-pistache-server.md b/docs/generators/cpp-pistache-server.md index becb24cf2175..f36d1f8c02b2 100644 --- a/docs/generators/cpp-pistache-server.md +++ b/docs/generators/cpp-pistache-server.md @@ -255,6 +255,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-qt-client.md b/docs/generators/cpp-qt-client.md index aae2bcd3fe60..b25d7fce5ff4 100644 --- a/docs/generators/cpp-qt-client.md +++ b/docs/generators/cpp-qt-client.md @@ -263,6 +263,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-qt-qhttpengine-server.md b/docs/generators/cpp-qt-qhttpengine-server.md index dc716366042f..bcff3567642d 100644 --- a/docs/generators/cpp-qt-qhttpengine-server.md +++ b/docs/generators/cpp-qt-qhttpengine-server.md @@ -260,6 +260,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-restbed-server-deprecated.md b/docs/generators/cpp-restbed-server-deprecated.md index ea61e6aee06e..605948610474 100644 --- a/docs/generators/cpp-restbed-server-deprecated.md +++ b/docs/generators/cpp-restbed-server-deprecated.md @@ -256,6 +256,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-restbed-server.md b/docs/generators/cpp-restbed-server.md index cf22f29ed845..9ea89339cc39 100644 --- a/docs/generators/cpp-restbed-server.md +++ b/docs/generators/cpp-restbed-server.md @@ -257,6 +257,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-restsdk.md b/docs/generators/cpp-restsdk.md index 3b64f38c126f..a6066965f972 100644 --- a/docs/generators/cpp-restsdk.md +++ b/docs/generators/cpp-restsdk.md @@ -261,6 +261,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-tiny.md b/docs/generators/cpp-tiny.md index 5d2ece4ff6e6..13c12e2a491b 100644 --- a/docs/generators/cpp-tiny.md +++ b/docs/generators/cpp-tiny.md @@ -254,6 +254,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-tizen.md b/docs/generators/cpp-tizen.md index caae3bc3577a..f033687c2b39 100644 --- a/docs/generators/cpp-tizen.md +++ b/docs/generators/cpp-tizen.md @@ -258,6 +258,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cpp-ue4.md b/docs/generators/cpp-ue4.md index c835f2cf3dfb..3d714b0fbf1e 100644 --- a/docs/generators/cpp-ue4.md +++ b/docs/generators/cpp-ue4.md @@ -265,6 +265,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/crystal.md b/docs/generators/crystal.md index df1f52728306..b9d588123329 100644 --- a/docs/generators/crystal.md +++ b/docs/generators/crystal.md @@ -239,6 +239,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/csharp-functions.md b/docs/generators/csharp-functions.md index 8faf39035852..8e6a6a98726a 100644 --- a/docs/generators/csharp-functions.md +++ b/docs/generators/csharp-functions.md @@ -44,6 +44,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| |sourceFolder|source folder for generated code| |src| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| +|useDateTimeForDate|Use DateTime to model date properties even if DateOnly supported. (.net 6.0+ only)| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |false| |useNewtonsoft|Uses the Newtonsoft JSON library.| |true| @@ -67,6 +68,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
      • Boolean
      • Collection
      • +
      • DateOnly
      • +
      • DateOnly?
      • DateTime
      • DateTime?
      • DateTimeOffset
      • @@ -109,6 +112,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
        • Client
        • Configuration
        • +
        • Environment
        • +
        • OperatingSystem
        • +
        • TimeZone
        • Version
        • abstract
        • as
        • @@ -319,6 +325,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/csharp.md b/docs/generators/csharp.md index 54ee3942c724..97122c156778 100644 --- a/docs/generators/csharp.md +++ b/docs/generators/csharp.md @@ -25,7 +25,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |dateFormat|The default Date format (only `generichost` library supports this option).| |yyyy'-'MM'-'dd| |dateTimeFormat|The default DateTime format (only `generichost` library supports this option).| |yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK| |disallowAdditionalPropertiesIfNotPresent|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.|
          **false**
          The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
          **true**
          Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
          |true| -|equatable|Overrides Equals and GetHashCode methods.| |true| +|equatable|Overrides Equals and GetHashCode methods.| |false| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |interfacePrefix|Prefix interfaces with a community standard or widely accepted prefix.| |I| |library|HTTP library template (sub-template) to use|
          **generichost**
          HttpClient with Generic Host dependency injection (https://docs.microsoft.com/en-us/dotnet/core/extensions/generic-host) (Experimental. Subject to breaking changes without notice.)
          **httpclient**
          HttpClient (https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient) (Experimental. Subject to breaking changes without notice.)
          **unityWebRequest**
          UnityWebRequest (...) (Experimental. Subject to breaking changes without notice.)
          **restsharp**
          RestSharp (https://github.com/restsharp/RestSharp)
          |restsharp| @@ -45,8 +45,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl |releaseNote|Release note, default to 'Minor update'.| |Minor update| |returnICollection|Return ICollection<T> instead of the concrete type.| |false| |sourceFolder|source folder for generated code| |src| -|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.1`|
          **netstandard1.3**
          .NET Standard 1.3
          **netstandard1.4**
          .NET Standard 1.4
          **netstandard1.5**
          .NET Standard 1.5
          **netstandard1.6**
          .NET Standard 1.6
          **netstandard2.0**
          .NET Standard 2.0
          **netstandard2.1**
          .NET Standard 2.1
          **net47**
          .NET Framework 4.7
          **net48**
          .NET Framework 4.8
          **net6.0**
          .NET 6.0 (End of Support 12 November 2024)
          **net7.0**
          .NET 7.0
          |net7.0| +|targetFramework|The target .NET framework version. To target multiple frameworks, use `;` as the separator, e.g. `netstandard2.1;netcoreapp3.1`|
          **netstandard1.3**
          .NET Standard 1.3
          **netstandard1.4**
          .NET Standard 1.4
          **netstandard1.5**
          .NET Standard 1.5
          **netstandard1.6**
          .NET Standard 1.6
          **netstandard2.0**
          .NET Standard 2.0
          **netstandard2.1**
          .NET Standard 2.1
          **net47**
          .NET Framework 4.7
          **net48**
          .NET Framework 4.8
          **net6.0**
          .NET 6.0 (End of Support 12 November 2024)
          **net7.0**
          .NET 7.0
          **net8.0**
          .NET 8.0
          |net8.0| |useCollection|Deserialize array types to Collection<T> instead of List<T>.| |false| +|useDateTimeForDate|Use DateTime to model date properties even if DateOnly supported. (.net 6.0+ only)| |false| |useDateTimeOffset|Use DateTimeOffset to model date-time properties| |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| @@ -73,6 +74,8 @@ These options may be applied as additional-properties (cli) or configOptions (pl
          • Boolean
          • Collection
          • +
          • DateOnly
          • +
          • DateOnly?
          • DateTime
          • DateTime?
          • DateTimeOffset
          • @@ -115,6 +118,9 @@ These options may be applied as additional-properties (cli) or configOptions (pl
            • Client
            • Configuration
            • +
            • Environment
            • +
            • OperatingSystem
            • +
            • TimeZone
            • Version
            • abstract
            • as
            • @@ -320,6 +326,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/cwiki.md b/docs/generators/cwiki.md index 1a1c03ddac5c..de77c1b89485 100644 --- a/docs/generators/cwiki.md +++ b/docs/generators/cwiki.md @@ -167,6 +167,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/dart-dio.md b/docs/generators/dart-dio.md index f06e71251264..644631f62720 100644 --- a/docs/generators/dart-dio.md +++ b/docs/generators/dart-dio.md @@ -246,6 +246,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/dart.md b/docs/generators/dart.md index 24d8c9ae07d3..45972f5e65bc 100644 --- a/docs/generators/dart.md +++ b/docs/generators/dart.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/dynamic-html.md b/docs/generators/dynamic-html.md index 42d328e069eb..d11e24d9d3d7 100644 --- a/docs/generators/dynamic-html.md +++ b/docs/generators/dynamic-html.md @@ -163,6 +163,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/eiffel.md b/docs/generators/eiffel.md index 6f0e0866128c..ec5729c7a6ac 100644 --- a/docs/generators/eiffel.md +++ b/docs/generators/eiffel.md @@ -234,6 +234,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/elixir.md b/docs/generators/elixir.md index 38d89cba8dfb..b13adcbad457 100644 --- a/docs/generators/elixir.md +++ b/docs/generators/elixir.md @@ -182,6 +182,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/elm.md b/docs/generators/elm.md index 994f08856e9b..0a22558aa2a8 100644 --- a/docs/generators/elm.md +++ b/docs/generators/elm.md @@ -172,6 +172,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/erlang-client.md b/docs/generators/erlang-client.md index 1dffb1ee26d7..9524d91d28dd 100644 --- a/docs/generators/erlang-client.md +++ b/docs/generators/erlang-client.md @@ -179,6 +179,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/erlang-proper.md b/docs/generators/erlang-proper.md index 96322eea7ca1..83eb5c155b52 100644 --- a/docs/generators/erlang-proper.md +++ b/docs/generators/erlang-proper.md @@ -179,6 +179,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/erlang-server.md b/docs/generators/erlang-server.md index 72509f92edbc..66692f029e7d 100644 --- a/docs/generators/erlang-server.md +++ b/docs/generators/erlang-server.md @@ -179,6 +179,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/fsharp-functions.md b/docs/generators/fsharp-functions.md index fb7aa7702533..a20382152aab 100644 --- a/docs/generators/fsharp-functions.md +++ b/docs/generators/fsharp-functions.md @@ -313,6 +313,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/fsharp-giraffe-server.md b/docs/generators/fsharp-giraffe-server.md index a3018030128e..abe079e504fa 100644 --- a/docs/generators/fsharp-giraffe-server.md +++ b/docs/generators/fsharp-giraffe-server.md @@ -312,6 +312,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/go-echo-server.md b/docs/generators/go-echo-server.md index b886251763dd..1bd4e6ca8d7a 100644 --- a/docs/generators/go-echo-server.md +++ b/docs/generators/go-echo-server.md @@ -216,6 +216,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/go-gin-server.md b/docs/generators/go-gin-server.md index eb912c0f6fd5..6cc2e828ec63 100644 --- a/docs/generators/go-gin-server.md +++ b/docs/generators/go-gin-server.md @@ -218,6 +218,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/go-server.md b/docs/generators/go-server.md index 52e627890f1f..77c2fabf5a5c 100644 --- a/docs/generators/go-server.md +++ b/docs/generators/go-server.md @@ -223,6 +223,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/go.md b/docs/generators/go.md index e8f9946fbcc3..72c7fa56ec5a 100644 --- a/docs/generators/go.md +++ b/docs/generators/go.md @@ -21,6 +21,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |disallowAdditionalPropertiesIfNotPresent|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.|
              **false**
              The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
              **true**
              Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
              |true| |enumClassPrefix|Prefix enum with class name| |false| |generateInterfaces|Generate interfaces for api classes| |false| +|generateMarshalJSON|Generate MarshalJSON method| |true| |hideGenerationTimestamp|Hides the generation timestamp when files are generated.| |true| |isGoSubmodule|whether the generated Go module is a submodule| |false| |packageName|Go package name (convention: lowercase).| |openapi| @@ -29,6 +30,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |structPrefix|whether to prefix struct with the class name. e.g. DeletePetOpts => PetApiDeletePetOpts| |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| |withAWSV4Signature|whether to include AWS v4 signature support| |false| +|withGoMod|Generate go.mod and go.sum| |true| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| ## IMPORT MAPPING @@ -224,6 +226,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/graphql-nodejs-express-server.md b/docs/generators/graphql-nodejs-express-server.md index f35427efd3e7..4a5418bf1165 100644 --- a/docs/generators/graphql-nodejs-express-server.md +++ b/docs/generators/graphql-nodejs-express-server.md @@ -170,6 +170,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/graphql-schema.md b/docs/generators/graphql-schema.md index a6c1e6b0f10b..7c9c8b9d33e6 100644 --- a/docs/generators/graphql-schema.md +++ b/docs/generators/graphql-schema.md @@ -170,6 +170,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/groovy.md b/docs/generators/groovy.md index ef327d98124f..36e26fceef0d 100644 --- a/docs/generators/groovy.md +++ b/docs/generators/groovy.md @@ -321,6 +321,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/haskell-http-client.md b/docs/generators/haskell-http-client.md index ff1162027795..5bb4352ec301 100644 --- a/docs/generators/haskell-http-client.md +++ b/docs/generators/haskell-http-client.md @@ -224,6 +224,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/haskell-yesod.md b/docs/generators/haskell-yesod.md index 57a81148e99a..d3694b12ed50 100644 --- a/docs/generators/haskell-yesod.md +++ b/docs/generators/haskell-yesod.md @@ -198,6 +198,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/haskell.md b/docs/generators/haskell.md index 379274a2472b..dfada1754f43 100644 --- a/docs/generators/haskell.md +++ b/docs/generators/haskell.md @@ -202,6 +202,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/html.md b/docs/generators/html.md index e5876f2486dd..09520b878cb6 100644 --- a/docs/generators/html.md +++ b/docs/generators/html.md @@ -167,6 +167,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/html2.md b/docs/generators/html2.md index 2f9e673bd272..bf51de68536b 100644 --- a/docs/generators/html2.md +++ b/docs/generators/html2.md @@ -171,6 +171,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-camel.md b/docs/generators/java-camel.md index 84a85a253a23..0b1d1ff4c0cb 100644 --- a/docs/generators/java-camel.md +++ b/docs/generators/java-camel.md @@ -360,6 +360,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-helidon-client.md b/docs/generators/java-helidon-client.md index e7c4f63d0b57..853fc7b31727 100644 --- a/docs/generators/java-helidon-client.md +++ b/docs/generators/java-helidon-client.md @@ -314,6 +314,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-helidon-server.md b/docs/generators/java-helidon-server.md index a027e1cee38d..142f9109157f 100644 --- a/docs/generators/java-helidon-server.md +++ b/docs/generators/java-helidon-server.md @@ -316,6 +316,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-inflector.md b/docs/generators/java-inflector.md index c91aa73e31bd..467d92cf5cfb 100644 --- a/docs/generators/java-inflector.md +++ b/docs/generators/java-inflector.md @@ -318,6 +318,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-micronaut-client.md b/docs/generators/java-micronaut-client.md index 76e90328b3f7..f2b3b2e31382 100644 --- a/docs/generators/java-micronaut-client.md +++ b/docs/generators/java-micronaut-client.md @@ -349,6 +349,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-micronaut-server.md b/docs/generators/java-micronaut-server.md index 2366e962c65b..96eedd4c8466 100644 --- a/docs/generators/java-micronaut-server.md +++ b/docs/generators/java-micronaut-server.md @@ -349,6 +349,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-msf4j.md b/docs/generators/java-msf4j.md index 06ba5f7141d7..5474551f3154 100644 --- a/docs/generators/java-msf4j.md +++ b/docs/generators/java-msf4j.md @@ -324,6 +324,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-pkmst.md b/docs/generators/java-pkmst.md index 56f49ef7d2f1..0d7bb6f42bba 100644 --- a/docs/generators/java-pkmst.md +++ b/docs/generators/java-pkmst.md @@ -325,6 +325,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-play-framework.md b/docs/generators/java-play-framework.md index b0205e0a4b3a..2c59edefd2f8 100644 --- a/docs/generators/java-play-framework.md +++ b/docs/generators/java-play-framework.md @@ -328,6 +328,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-undertow-server.md b/docs/generators/java-undertow-server.md index 7342fd046e8f..339a43829764 100644 --- a/docs/generators/java-undertow-server.md +++ b/docs/generators/java-undertow-server.md @@ -318,6 +318,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-vertx-web.md b/docs/generators/java-vertx-web.md index 2057fefafc98..198cdb27289a 100644 --- a/docs/generators/java-vertx-web.md +++ b/docs/generators/java-vertx-web.md @@ -318,6 +318,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java-vertx.md b/docs/generators/java-vertx.md index 57b3b487f73d..002ee2b68c7c 100644 --- a/docs/generators/java-vertx.md +++ b/docs/generators/java-vertx.md @@ -321,6 +321,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/java.md b/docs/generators/java.md index 79cc58568fd4..b4f6151d6908 100644 --- a/docs/generators/java.md +++ b/docs/generators/java.md @@ -95,7 +95,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |useRuntimeException|Use RuntimeException instead of Exception. Only jersey2, jersey3, okhttp-gson, vertx, microprofile support this option.| |false| |useRxJava2|Whether to use the RxJava2 adapter with the retrofit2 library. IMPORTANT: This option has been deprecated.| |false| |useRxJava3|Whether to use the RxJava3 adapter with the retrofit2 library. IMPORTANT: This option has been deprecated.| |false| -|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter. ONLY jersey2, jersey3, okhttp-gson support this option.| |false| +|useSingleRequestParameter|Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter. ONLY jersey2, jersey3, okhttp-gson, microprofile support this option.| |false| |webclientBlockingOperations|Making all WebClient operations blocking(sync). Note that if on operation 'x-webclient-blocking: false' then such operation won't be sync| |false| |withAWSV4Signature|whether to include AWS v4 signature support (only available for okhttp-gson library)| |false| |withXml|whether to include support for application/xml content type and include XML annotations in the model (works with libraries that provide support for JSON and XML)| |false| @@ -350,6 +350,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/javascript-apollo-deprecated.md b/docs/generators/javascript-apollo-deprecated.md index 18f9b137f303..c70d3e81b584 100644 --- a/docs/generators/javascript-apollo-deprecated.md +++ b/docs/generators/javascript-apollo-deprecated.md @@ -265,6 +265,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/javascript-closure-angular.md b/docs/generators/javascript-closure-angular.md index cc15021d3391..452a628eb943 100644 --- a/docs/generators/javascript-closure-angular.md +++ b/docs/generators/javascript-closure-angular.md @@ -211,6 +211,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/javascript-flowtyped.md b/docs/generators/javascript-flowtyped.md index 349e7f5ed9a2..b0c81d51a4fe 100644 --- a/docs/generators/javascript-flowtyped.md +++ b/docs/generators/javascript-flowtyped.md @@ -266,6 +266,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/javascript.md b/docs/generators/javascript.md index 2867335ab727..2c4a02eee8f2 100644 --- a/docs/generators/javascript.md +++ b/docs/generators/javascript.md @@ -266,6 +266,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-cxf-cdi.md b/docs/generators/jaxrs-cxf-cdi.md index 3c470946b303..e7333248e3eb 100644 --- a/docs/generators/jaxrs-cxf-cdi.md +++ b/docs/generators/jaxrs-cxf-cdi.md @@ -332,6 +332,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-cxf-client.md b/docs/generators/jaxrs-cxf-client.md index d2501c27ed7b..2d18f1b22017 100644 --- a/docs/generators/jaxrs-cxf-client.md +++ b/docs/generators/jaxrs-cxf-client.md @@ -323,6 +323,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-cxf-extended.md b/docs/generators/jaxrs-cxf-extended.md index b5e40fddf862..b405eedd6a2b 100644 --- a/docs/generators/jaxrs-cxf-extended.md +++ b/docs/generators/jaxrs-cxf-extended.md @@ -346,6 +346,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-cxf.md b/docs/generators/jaxrs-cxf.md index 19cbe9aaa0ac..6cd6db12322f 100644 --- a/docs/generators/jaxrs-cxf.md +++ b/docs/generators/jaxrs-cxf.md @@ -341,6 +341,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-jersey.md b/docs/generators/jaxrs-jersey.md index 7fb90a08c427..bde418dde2d4 100644 --- a/docs/generators/jaxrs-jersey.md +++ b/docs/generators/jaxrs-jersey.md @@ -324,6 +324,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-resteasy-eap.md b/docs/generators/jaxrs-resteasy-eap.md index f78b67963026..10a82f55a694 100644 --- a/docs/generators/jaxrs-resteasy-eap.md +++ b/docs/generators/jaxrs-resteasy-eap.md @@ -325,6 +325,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-resteasy.md b/docs/generators/jaxrs-resteasy.md index 55bb4e75cefb..dacdf35b3fe4 100644 --- a/docs/generators/jaxrs-resteasy.md +++ b/docs/generators/jaxrs-resteasy.md @@ -324,6 +324,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jaxrs-spec.md b/docs/generators/jaxrs-spec.md index 8c5c3e899c8c..cbc5ce224004 100644 --- a/docs/generators/jaxrs-spec.md +++ b/docs/generators/jaxrs-spec.md @@ -332,6 +332,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jetbrains-http-client.md b/docs/generators/jetbrains-http-client.md index 83dee15fda7a..d20d39cc3b24 100644 --- a/docs/generators/jetbrains-http-client.md +++ b/docs/generators/jetbrains-http-client.md @@ -158,6 +158,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/jmeter.md b/docs/generators/jmeter.md index 3e5b0f54327d..085b94493518 100644 --- a/docs/generators/jmeter.md +++ b/docs/generators/jmeter.md @@ -160,6 +160,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/julia-client.md b/docs/generators/julia-client.md index f855255908cf..dc7bf28ecb12 100644 --- a/docs/generators/julia-client.md +++ b/docs/generators/julia-client.md @@ -210,6 +210,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/julia-server.md b/docs/generators/julia-server.md index 36475230ed04..db8161b29779 100644 --- a/docs/generators/julia-server.md +++ b/docs/generators/julia-server.md @@ -209,6 +209,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/k6.md b/docs/generators/k6.md index 7bbab400a0f5..a8c4932adb8c 100644 --- a/docs/generators/k6.md +++ b/docs/generators/k6.md @@ -158,6 +158,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/kotlin-server.md b/docs/generators/kotlin-server.md index 692e14c1d726..b97a3267f88b 100644 --- a/docs/generators/kotlin-server.md +++ b/docs/generators/kotlin-server.md @@ -281,6 +281,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/kotlin-spring.md b/docs/generators/kotlin-spring.md index 7c68491bc1f1..f466d7ced80b 100644 --- a/docs/generators/kotlin-spring.md +++ b/docs/generators/kotlin-spring.md @@ -22,6 +22,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |annotationLibrary|Select the complementary documentation annotation library.|
              **none**
              Do not annotate Model and Api with complementary annotations.
              **swagger1**
              Annotate Model and Api using the Swagger Annotations 1.x library.
              **swagger2**
              Annotate Model and Api using the Swagger Annotations 2.x library.
              |swagger2| |apiPackage|api package for generated code| |org.openapitools.api| |apiSuffix|suffix for api classes| |Api| +|appendRequestToHandler|Append ServerHttpRequest to handler method for getting request stuff| |false| |artifactId|Generated artifact id (name of jar).| |openapi-spring| |artifactVersion|Generated artifact's package version.| |1.0.0| |basePackage|base package (invokerPackage) for generated code| |org.openapitools| @@ -291,6 +292,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/kotlin-vertx.md b/docs/generators/kotlin-vertx.md index c73360d14870..738f4d8c9610 100644 --- a/docs/generators/kotlin-vertx.md +++ b/docs/generators/kotlin-vertx.md @@ -266,6 +266,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/kotlin.md b/docs/generators/kotlin.md index 45be9d5e2a76..7493aee668f4 100644 --- a/docs/generators/kotlin.md +++ b/docs/generators/kotlin.md @@ -23,12 +23,12 @@ These options may be applied as additional-properties (cli) or configOptions (pl |artifactId|Generated artifact id (name of jar).| |kotlin-client| |artifactVersion|Generated artifact's package version.| |1.0.0| |collectionType|Option. Collection type to use|
              **array**
              kotlin.Array
              **list**
              kotlin.collections.List
              |list| -|dateLibrary|Option. Date library to use|
              **threetenbp-localdatetime**
              Threetenbp - Backport of JSR310 (jvm only, for legacy app only)
              **string**
              String
              **java8-localdatetime**
              Java 8 native JSR310 (jvm only, for legacy app only)
              **java8**
              Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)
              **threetenbp**
              Threetenbp - Backport of JSR310 (jvm only, preferred for jdk < 1.8)
              |java8| +|dateLibrary|Option. Date library to use|
              **threetenbp-localdatetime**
              Threetenbp - Backport of JSR310 (jvm only, for legacy app only)
              **kotlinx-datetime**
              kotlinx-datetime (preferred for multiplatform)
              **string**
              String
              **java8-localdatetime**
              Java 8 native JSR310 (jvm only, for legacy app only)
              **java8**
              Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)
              **threetenbp**
              Threetenbp - Backport of JSR310 (jvm only, preferred for jdk < 1.8)
              |java8| |enumPropertyNaming|Naming convention for enum properties: 'camelCase', 'PascalCase', 'snake_case', 'UPPERCASE', and 'original'| |camelCase| |generateRoomModels|Generate Android Room database models in addition to API models (JVM Volley library only)| |false| |groupId|Generated artifact package's organization (i.e. maven groupId).| |org.openapitools| |idea|Add IntellJ Idea plugin and mark Kotlin main and test folders as source folders.| |false| -|library|Library template (sub-template) to use|
              **jvm-ktor**
              Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7. JSON processing: Gson, Jackson (default).
              **jvm-okhttp4**
              [DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
              **jvm-okhttp3**
              Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0. (DEPRECATED: this option will be remove in 7.x release)
              **jvm-spring-webclient**
              Platform: Java Virtual Machine. HTTP: Spring 5 (or 6 with useSpringBoot3 enabled) WebClient. JSON processing: Jackson.
              **jvm-retrofit2**
              Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
              **multiplatform**
              Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1.
              **jvm-volley**
              Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9
              **jvm-vertx**
              Platform: Java Virtual Machine. HTTP client: Vert.x Web Client. JSON processing: Moshi, Gson or Jackson.
              |jvm-okhttp4| +|library|Library template (sub-template) to use|
              **jvm-ktor**
              Platform: Java Virtual Machine. HTTP client: Ktor 1.6.7. JSON processing: Gson, Jackson (default).
              **jvm-okhttp4**
              [DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0.
              **jvm-okhttp3**
              Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0. (DEPRECATED: this option will be remove in 7.x release)
              **jvm-spring-webclient**
              Platform: Java Virtual Machine. HTTP: Spring 5 (or 6 with useSpringBoot3 enabled) WebClient. JSON processing: Jackson.
              **jvm-spring-restclient**
              Platform: Java Virtual Machine. HTTP: Spring 6 RestClient. JSON processing: Jackson.
              **jvm-retrofit2**
              Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2.
              **multiplatform**
              Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1.
              **jvm-volley**
              Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9
              **jvm-vertx**
              Platform: Java Virtual Machine. HTTP client: Vert.x Web Client. JSON processing: Moshi, Gson or Jackson.
              |jvm-okhttp4| |modelMutable|Create mutable models| |false| |moshiCodeGen|Whether to enable codegen with the Moshi library. Refer to the [official Moshi doc](https://github.com/square/moshi#codegen) for more info.| |false| |nullableReturnType|Nullable return type| |false| @@ -282,6 +282,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ktorm-schema.md b/docs/generators/ktorm-schema.md index a59e17a74b42..f29302e8188b 100644 --- a/docs/generators/ktorm-schema.md +++ b/docs/generators/ktorm-schema.md @@ -369,6 +369,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/lua.md b/docs/generators/lua.md index 4d92b6d38140..ef3b53935078 100644 --- a/docs/generators/lua.md +++ b/docs/generators/lua.md @@ -187,6 +187,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/markdown.md b/docs/generators/markdown.md index 8a6b8e3d376c..7572bca67301 100644 --- a/docs/generators/markdown.md +++ b/docs/generators/markdown.md @@ -175,6 +175,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/mysql-schema.md b/docs/generators/mysql-schema.md index fc67a851e666..36b9fb6b22d6 100644 --- a/docs/generators/mysql-schema.md +++ b/docs/generators/mysql-schema.md @@ -440,6 +440,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/n4js.md b/docs/generators/n4js.md index 1d5f6e120078..bf9701e867d3 100644 --- a/docs/generators/n4js.md +++ b/docs/generators/n4js.md @@ -235,6 +235,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/nim.md b/docs/generators/nim.md index b18523aa66e6..d61882b2bc94 100644 --- a/docs/generators/nim.md +++ b/docs/generators/nim.md @@ -242,6 +242,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/nodejs-express-server.md b/docs/generators/nodejs-express-server.md index 5356f0461fc8..d766f4c8702a 100644 --- a/docs/generators/nodejs-express-server.md +++ b/docs/generators/nodejs-express-server.md @@ -193,6 +193,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/objc.md b/docs/generators/objc.md index f89e49e85779..c46329cf3e39 100644 --- a/docs/generators/objc.md +++ b/docs/generators/objc.md @@ -229,6 +229,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ocaml.md b/docs/generators/ocaml.md index 73478c736caf..d2bbfecfa3e0 100644 --- a/docs/generators/ocaml.md +++ b/docs/generators/ocaml.md @@ -225,6 +225,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/openapi-yaml.md b/docs/generators/openapi-yaml.md index 66fc887f32f5..22566b22a045 100644 --- a/docs/generators/openapi-yaml.md +++ b/docs/generators/openapi-yaml.md @@ -158,6 +158,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/openapi.md b/docs/generators/openapi.md index 18b5f2a54272..aea32dad388c 100644 --- a/docs/generators/openapi.md +++ b/docs/generators/openapi.md @@ -158,6 +158,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/perl.md b/docs/generators/perl.md index 904d4cf0dc00..87d4934fbf91 100644 --- a/docs/generators/perl.md +++ b/docs/generators/perl.md @@ -205,6 +205,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-dt.md b/docs/generators/php-dt.md index 9a16b14c8a7b..5f811f0d8897 100644 --- a/docs/generators/php-dt.md +++ b/docs/generators/php-dt.md @@ -257,6 +257,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-laravel.md b/docs/generators/php-laravel.md index 4a32628fbe51..0d452d056064 100644 --- a/docs/generators/php-laravel.md +++ b/docs/generators/php-laravel.md @@ -258,6 +258,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-lumen.md b/docs/generators/php-lumen.md index 9b75a15eac89..39203422b3d4 100644 --- a/docs/generators/php-lumen.md +++ b/docs/generators/php-lumen.md @@ -258,6 +258,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-mezzio-ph.md b/docs/generators/php-mezzio-ph.md index ba88d42aa90a..d724c85d0878 100644 --- a/docs/generators/php-mezzio-ph.md +++ b/docs/generators/php-mezzio-ph.md @@ -257,6 +257,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-nextgen.md b/docs/generators/php-nextgen.md index 606e12c8d57d..f0f5a44a0fdb 100644 --- a/docs/generators/php-nextgen.md +++ b/docs/generators/php-nextgen.md @@ -259,6 +259,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-slim4.md b/docs/generators/php-slim4.md index c6010777ef15..7f3ca80191de 100644 --- a/docs/generators/php-slim4.md +++ b/docs/generators/php-slim4.md @@ -259,6 +259,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php-symfony.md b/docs/generators/php-symfony.md index f502ec457bc6..0e183bc9cc2e 100644 --- a/docs/generators/php-symfony.md +++ b/docs/generators/php-symfony.md @@ -262,6 +262,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/php.md b/docs/generators/php.md index a1e5e677735c..05b9bd488874 100644 --- a/docs/generators/php.md +++ b/docs/generators/php.md @@ -260,6 +260,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/plantuml.md b/docs/generators/plantuml.md index 9832c19d0f0c..2149de62f1ef 100644 --- a/docs/generators/plantuml.md +++ b/docs/generators/plantuml.md @@ -157,6 +157,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/postman-collection.md b/docs/generators/postman-collection.md index 7c4afee83c6a..1d7717408aa8 100644 --- a/docs/generators/postman-collection.md +++ b/docs/generators/postman-collection.md @@ -157,6 +157,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/powershell.md b/docs/generators/powershell.md index f1d6e2c8f2e5..025c1e10854f 100644 --- a/docs/generators/powershell.md +++ b/docs/generators/powershell.md @@ -255,6 +255,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/protobuf-schema.md b/docs/generators/protobuf-schema.md index 530903c54f58..88e54ff6e766 100644 --- a/docs/generators/protobuf-schema.md +++ b/docs/generators/protobuf-schema.md @@ -172,6 +172,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python-aiohttp.md b/docs/generators/python-aiohttp.md index 59d023f1e3c7..a1182ff8f160 100644 --- a/docs/generators/python-aiohttp.md +++ b/docs/generators/python-aiohttp.md @@ -235,6 +235,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python-blueplanet.md b/docs/generators/python-blueplanet.md index 4f7698d343ac..474b6290f780 100644 --- a/docs/generators/python-blueplanet.md +++ b/docs/generators/python-blueplanet.md @@ -235,6 +235,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python-fastapi.md b/docs/generators/python-fastapi.md index 5597ee02e841..07543a2a1969 100644 --- a/docs/generators/python-fastapi.md +++ b/docs/generators/python-fastapi.md @@ -230,6 +230,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python-flask.md b/docs/generators/python-flask.md index 9e5bd29fbc67..6842829aa996 100644 --- a/docs/generators/python-flask.md +++ b/docs/generators/python-flask.md @@ -235,6 +235,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python-pydantic-v1.md b/docs/generators/python-pydantic-v1.md index e157b9b1a05d..0d8b836a7b29 100644 --- a/docs/generators/python-pydantic-v1.md +++ b/docs/generators/python-pydantic-v1.md @@ -222,6 +222,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/python.md b/docs/generators/python.md index 21eb6eb5c3f9..79897782b018 100644 --- a/docs/generators/python.md +++ b/docs/generators/python.md @@ -232,6 +232,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✓|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/r.md b/docs/generators/r.md index 2665c5fc0b1d..4e7f0d2e4f9c 100644 --- a/docs/generators/r.md +++ b/docs/generators/r.md @@ -186,6 +186,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ruby-on-rails.md b/docs/generators/ruby-on-rails.md index b3e71c2c2f98..e5229681cc6f 100644 --- a/docs/generators/ruby-on-rails.md +++ b/docs/generators/ruby-on-rails.md @@ -202,6 +202,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ruby-sinatra.md b/docs/generators/ruby-sinatra.md index 87e73dc3fbf6..9541bfa8a59a 100644 --- a/docs/generators/ruby-sinatra.md +++ b/docs/generators/ruby-sinatra.md @@ -201,6 +201,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/ruby.md b/docs/generators/ruby.md index e837c7b97c42..e643257b13e1 100644 --- a/docs/generators/ruby.md +++ b/docs/generators/ruby.md @@ -27,6 +27,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |gemDescription|gem description. | |This gem maps to a REST API| |gemHomepage|gem homepage. | |https://openapi-generator.tech| |gemLicense|gem license. | |unlicense| +|gemMetadata|gem metadata.| |{}| |gemName|gem name (convention: underscore_case).| |openapi_client| |gemRequiredRubyVersion|gem required Ruby version. | |>= 2.4| |gemSummary|gem summary. | |A ruby wrapper for the REST APIs| @@ -236,6 +237,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/rust-axum.md b/docs/generators/rust-axum.md new file mode 100644 index 000000000000..188ecaf27ad9 --- /dev/null +++ b/docs/generators/rust-axum.md @@ -0,0 +1,235 @@ +--- +title: Documentation for the rust-axum Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | rust-axum | pass this to the generate command after -g | +| generator stability | BETA | | +| generator type | SERVER | | +| generator language | Rust | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Rust server library which bases on Axum. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowBlockingResponseSerialize|By default, json/form-urlencoded response serialization, which might perform a lot of compute in a future without yielding, is executed on a blocking thread via tokio::task::spawn_blocking. Set this option to true will override this behaviour and allow blocking call to happen. It helps to improve the performance when response serialization (e.g. returns tiny data) is low cost.| |false| +|allowBlockingValidator|By default, validation process, which might perform a lot of compute in a future without yielding, is executed on a blocking thread via tokio::task::spawn_blocking. Set this option to true will override this behaviour and allow blocking call to happen. It helps to improve the performance when validating request-data (header, path, query, body) is low cost.| |false| +|disableValidator|Disable validating request-data (header, path, query, body) against OpenAPI Schema Specification.| |false| +|packageName|Rust crate name (convention: snake_case).| |openapi| +|packageVersion|Rust crate version.| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|Vec| +|map|std::collections::HashMap| + + +## LANGUAGE PRIMITIVES + +
                +
              • String
              • +
              • bool
              • +
              • char
              • +
              • f32
              • +
              • f64
              • +
              • i16
              • +
              • i32
              • +
              • i64
              • +
              • i8
              • +
              • isize
              • +
              • str
              • +
              • u16
              • +
              • u32
              • +
              • u64
              • +
              • u8
              • +
              • usize
              • +
              + +## RESERVED WORDS + +
                +
              • Self
              • +
              • abstract
              • +
              • as
              • +
              • async
              • +
              • await
              • +
              • become
              • +
              • box
              • +
              • break
              • +
              • const
              • +
              • continue
              • +
              • crate
              • +
              • do
              • +
              • dyn
              • +
              • else
              • +
              • enum
              • +
              • extern
              • +
              • false
              • +
              • final
              • +
              • fn
              • +
              • for
              • +
              • if
              • +
              • impl
              • +
              • in
              • +
              • let
              • +
              • loop
              • +
              • macro
              • +
              • match
              • +
              • mod
              • +
              • move
              • +
              • mut
              • +
              • override
              • +
              • priv
              • +
              • pub
              • +
              • ref
              • +
              • return
              • +
              • self
              • +
              • static
              • +
              • struct
              • +
              • super
              • +
              • trait
              • +
              • true
              • +
              • try
              • +
              • type
              • +
              • typeof
              • +
              • unsafe
              • +
              • unsized
              • +
              • use
              • +
              • virtual
              • +
              • where
              • +
              • while
              • +
              • yield
              • +
              + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✗|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✗|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✗|OAS2,OAS3 +|Examples|✗|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✓|OAS2,OAS3 +|OAuth2_Password|✓|OAS2,OAS3 +|OAuth2_ClientCredentials|✓|OAS2,OAS3 +|OAuth2_AuthorizationCode|✓|OAS2,OAS3 +|SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✗|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/rust-server.md b/docs/generators/rust-server.md index 2ebfe4eab553..84028eea45de 100644 --- a/docs/generators/rust-server.md +++ b/docs/generators/rust-server.md @@ -221,6 +221,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/rust.md b/docs/generators/rust.md index e37ca69dc3b3..13812fe15e0d 100644 --- a/docs/generators/rust.md +++ b/docs/generators/rust.md @@ -229,6 +229,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✓|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-akka-http-server.md b/docs/generators/scala-akka-http-server.md index 8419c093758b..15108cd3eb67 100644 --- a/docs/generators/scala-akka-http-server.md +++ b/docs/generators/scala-akka-http-server.md @@ -240,6 +240,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-akka.md b/docs/generators/scala-akka.md index c8b9e4acc26d..7b9cf9267b58 100644 --- a/docs/generators/scala-akka.md +++ b/docs/generators/scala-akka.md @@ -235,6 +235,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-finch.md b/docs/generators/scala-finch.md index 4ec506db150a..35aae393a08d 100644 --- a/docs/generators/scala-finch.md +++ b/docs/generators/scala-finch.md @@ -246,6 +246,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-gatling.md b/docs/generators/scala-gatling.md index 74f3f9c6be94..903f6149bbc0 100644 --- a/docs/generators/scala-gatling.md +++ b/docs/generators/scala-gatling.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-http4s-server.md b/docs/generators/scala-http4s-server.md new file mode 100644 index 000000000000..9031c8ef8948 --- /dev/null +++ b/docs/generators/scala-http4s-server.md @@ -0,0 +1,275 @@ +--- +title: Documentation for the scala-http4s-server Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | scala-http4s-server | pass this to the generate command after -g | +| generator stability | STABLE | | +| generator type | SERVER | | +| generator language | Scala | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Scala http4s server bindings. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|disallowAdditionalPropertiesIfNotPresent|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.|
              **false**
              The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
              **true**
              Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
              |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|enumUnknownDefaultCase|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.|
              **false**
              No changes to the enum's are made, this is the default option.
              **true**
              With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
              |false| +|excludeSbt|exclude sbt from generation| |null| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|
              **true**
              The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
              **false**
              The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
              |true| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceSubfolder|name of subfolder, for example to generate code in src/scala/generated| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|And|eu.timepit.refined.boolean.And| +|ArrayBuffer|scala.collection.mutable.ArrayBuffer| +|Date|java.util.Date| +|DateTime|java.time.LocalDateTime| +|File|java.io.File| +|Greater|eu.timepit.refined.numeric.Greater| +|GreaterEqual|eu.timepit.refined.numeric.GreaterEqual| +|HashMap|scala.collection.immutable.HashMap| +|Less|eu.timepit.refined.numeric.Less| +|LessEqual|eu.timepit.refined.numeric.LessEqual| +|LocalDate|java.time.LocalDate| +|LocalDateTime|java.time.LocalDateTime| +|LocalTime|java.time.LocalTime| +|Map|scala.collection.immutable.Map| +|MatchesRegex|eu.timepit.refined.string.MatchesRegex| +|MaxSize|eu.timepit.refined.collection.MaxSize| +|MinSize|eu.timepit.refined.collection.MinSize| +|OffsetDateTime|java.time.OffsetDateTime| +|Refined|eu.timepit.refined.api.Refined| +|Seq|scala.collection.immutable.Seq| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| +|ZonedDateTime|java.time.ZonedDateTime| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ArrayList| +|map|HashMap| + + +## LANGUAGE PRIMITIVES + +
                +
              • Any
              • +
              • AnyRef
              • +
              • AnyVal
              • +
              • BigDecimal
              • +
              • Boolean
              • +
              • Double
              • +
              • Float
              • +
              • Int
              • +
              • Integer
              • +
              • Long
              • +
              • Object
              • +
              • String
              • +
              + +## RESERVED WORDS + +
                +
              • abstract
              • +
              • assert
              • +
              • break
              • +
              • byte
              • +
              • case
              • +
              • catch
              • +
              • char
              • +
              • class
              • +
              • const
              • +
              • continue
              • +
              • def
              • +
              • default
              • +
              • do
              • +
              • double
              • +
              • else
              • +
              • enum
              • +
              • extends
              • +
              • false
              • +
              • final
              • +
              • finally
              • +
              • float
              • +
              • for
              • +
              • forsome
              • +
              • goto
              • +
              • if
              • +
              • implements
              • +
              • implicit
              • +
              • import
              • +
              • instanceof
              • +
              • int
              • +
              • interface
              • +
              • lazy
              • +
              • long
              • +
              • match
              • +
              • native
              • +
              • new
              • +
              • null
              • +
              • object
              • +
              • override
              • +
              • package
              • +
              • private
              • +
              • protected
              • +
              • public
              • +
              • return
              • +
              • sealed
              • +
              • short
              • +
              • static
              • +
              • strictfp
              • +
              • super
              • +
              • switch
              • +
              • synchronized
              • +
              • this
              • +
              • throw
              • +
              • throws
              • +
              • trait
              • +
              • transient
              • +
              • true
              • +
              • try
              • +
              • type
              • +
              • val
              • +
              • var
              • +
              • void
              • +
              • volatile
              • +
              • while
              • +
              • with
              • +
              • yield
              • +
              + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✗|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✗|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✗|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✗|OAS2,OAS3 +|ApiKey|✗|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✗|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 +|SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/scala-lagom-server.md b/docs/generators/scala-lagom-server.md index c0d013b68d9f..2261851ca503 100644 --- a/docs/generators/scala-lagom-server.md +++ b/docs/generators/scala-lagom-server.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-pekko.md b/docs/generators/scala-pekko.md new file mode 100644 index 000000000000..ebc33bb69870 --- /dev/null +++ b/docs/generators/scala-pekko.md @@ -0,0 +1,246 @@ +--- +title: Documentation for the scala-pekko Generator +--- + +## METADATA + +| Property | Value | Notes | +| -------- | ----- | ----- | +| generator name | scala-pekko | pass this to the generate command after -g | +| generator stability | STABLE | | +| generator type | CLIENT | | +| generator language | Scala | | +| generator default templating engine | mustache | | +| helpTxt | Generates a Scala client library (beta) base on pekko/Spray. | | + +## CONFIG OPTIONS +These options may be applied as additional-properties (cli) or configOptions (plugins). Refer to [configuration docs](https://openapi-generator.tech/docs/configuration) for more details. + +| Option | Description | Values | Default | +| ------ | ----------- | ------ | ------- | +|allowUnicodeIdentifiers|boolean, toggles whether unicode identifiers are allowed in names or not, default is false| |false| +|apiPackage|package for generated api classes| |null| +|dateLibrary|Option. Date library to use|
              **joda**
              Joda (for legacy app)
              **java8**
              Java 8 native JSR310 (preferred for JDK 1.8+)
              |java8| +|disallowAdditionalPropertiesIfNotPresent|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.|
              **false**
              The 'additionalProperties' implementation is compliant with the OAS and JSON schema specifications.
              **true**
              Keep the old (incorrect) behaviour that 'additionalProperties' is set to false by default.
              |true| +|ensureUniqueParams|Whether to ensure parameter names are unique in an operation (rename parameters that are not).| |true| +|enumUnknownDefaultCase|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.|
              **false**
              No changes to the enum's are made, this is the default option.
              **true**
              With this option enabled, each enum will have a new case, 'unknown_default_open_api', so that when the enum case sent by the server is not known by the client/spec, can safely be decoded to this case.
              |false| +|legacyDiscriminatorBehavior|Set to false for generators with better support for discriminators. (Python, Java, Go, PowerShell, C# have this enabled by default).|
              **true**
              The mapping in the discriminator includes descendent schemas that allOf inherit from self and the discriminator mapping schemas in the OAS document.
              **false**
              The mapping in the discriminator includes any descendent schemas that allOf inherit from self, any oneOf schemas, any anyOf schemas, any x-discriminator-values, and the discriminator mapping schemas in the OAS document AND Codegen validates that oneOf and anyOf schemas contain the required discriminator and throws an error if the discriminator is missing.
              |true| +|mainPackage|Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'| |org.openapitools.client| +|modelPackage|package for generated models| |null| +|modelPropertyNaming|Naming convention for the property: 'camelCase', 'PascalCase', 'snake_case' and 'original', which keeps the original name| |camelCase| +|prependFormOrBodyParameters|Add form or body parameters to the beginning of the parameter list.| |false| +|sortModelPropertiesByRequiredFlag|Sort model properties to place required parameters before optional parameters.| |true| +|sortParamsByRequiredFlag|Sort method arguments to place required parameters before optional parameters.| |true| +|sourceFolder|source folder for generated code| |null| + +## IMPORT MAPPING + +| Type/Alias | Imports | +| ---------- | ------- | +|Array|java.util.List| +|ArrayList|java.util.ArrayList| +|BigDecimal|java.math.BigDecimal| +|Date|java.util.Date| +|DateTime|org.joda.time.*| +|File|java.io.File| +|HashMap|java.util.HashMap| +|ListBuffer|scala.collection.mutable.ListBuffer| +|ListSet|scala.collection.immutable.ListSet| +|LocalDate|org.joda.time.*| +|LocalDateTime|org.joda.time.*| +|LocalTime|org.joda.time.*| +|Timestamp|java.sql.Timestamp| +|URI|java.net.URI| +|UUID|java.util.UUID| + + +## INSTANTIATION TYPES + +| Type/Alias | Instantiated By | +| ---------- | --------------- | +|array|ListBuffer| +|map|Map| +|set|Set| + + +## LANGUAGE PRIMITIVES + +
                +
              • Any
              • +
              • Array
              • +
              • Boolean
              • +
              • Byte
              • +
              • Double
              • +
              • Float
              • +
              • Int
              • +
              • List
              • +
              • Long
              • +
              • Map
              • +
              • Object
              • +
              • Seq
              • +
              • String
              • +
              • boolean
              • +
              + +## RESERVED WORDS + +
                +
              • abstract
              • +
              • case
              • +
              • catch
              • +
              • class
              • +
              • def
              • +
              • do
              • +
              • else
              • +
              • extends
              • +
              • false
              • +
              • final
              • +
              • finally
              • +
              • for
              • +
              • forsome
              • +
              • if
              • +
              • implicit
              • +
              • import
              • +
              • lazy
              • +
              • match
              • +
              • new
              • +
              • null
              • +
              • object
              • +
              • override
              • +
              • package
              • +
              • private
              • +
              • protected
              • +
              • return
              • +
              • sealed
              • +
              • super
              • +
              • this
              • +
              • throw
              • +
              • trait
              • +
              • true
              • +
              • try
              • +
              • type
              • +
              • val
              • +
              • var
              • +
              • while
              • +
              • with
              • +
              • yield
              • +
              + +## FEATURE SET + + +### Client Modification Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasePath|✓|ToolingExtension +|Authorizations|✗|ToolingExtension +|UserAgent|✓|ToolingExtension +|MockServer|✗|ToolingExtension + +### Data Type Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Custom|✗|OAS2,OAS3 +|Int32|✓|OAS2,OAS3 +|Int64|✓|OAS2,OAS3 +|Float|✓|OAS2,OAS3 +|Double|✓|OAS2,OAS3 +|Decimal|✓|ToolingExtension +|String|✓|OAS2,OAS3 +|Byte|✓|OAS2,OAS3 +|Binary|✓|OAS2,OAS3 +|Boolean|✓|OAS2,OAS3 +|Date|✓|OAS2,OAS3 +|DateTime|✓|OAS2,OAS3 +|Password|✓|OAS2,OAS3 +|File|✓|OAS2 +|Uuid|✗| +|Array|✓|OAS2,OAS3 +|Null|✗|OAS3 +|AnyType|✗|OAS2,OAS3 +|Object|✓|OAS2,OAS3 +|Maps|✓|ToolingExtension +|CollectionFormat|✓|OAS2 +|CollectionFormatMulti|✓|OAS2 +|Enum|✓|OAS2,OAS3 +|ArrayOfEnum|✓|ToolingExtension +|ArrayOfModel|✓|ToolingExtension +|ArrayOfCollectionOfPrimitives|✓|ToolingExtension +|ArrayOfCollectionOfModel|✓|ToolingExtension +|ArrayOfCollectionOfEnum|✓|ToolingExtension +|MapOfEnum|✓|ToolingExtension +|MapOfModel|✓|ToolingExtension +|MapOfCollectionOfPrimitives|✓|ToolingExtension +|MapOfCollectionOfModel|✓|ToolingExtension +|MapOfCollectionOfEnum|✓|ToolingExtension + +### Documentation Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Readme|✓|ToolingExtension +|Model|✓|ToolingExtension +|Api|✓|ToolingExtension + +### Global Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Host|✓|OAS2,OAS3 +|BasePath|✓|OAS2,OAS3 +|Info|✓|OAS2,OAS3 +|Schemes|✗|OAS2,OAS3 +|PartialSchemes|✓|OAS2,OAS3 +|Consumes|✓|OAS2 +|Produces|✓|OAS2 +|ExternalDocumentation|✓|OAS2,OAS3 +|Examples|✓|OAS2,OAS3 +|XMLStructureDefinitions|✗|OAS2,OAS3 +|MultiServer|✗|OAS3 +|ParameterizedServer|✗|OAS3 +|ParameterStyling|✗|OAS3 +|Callbacks|✗|OAS3 +|LinkObjects|✗|OAS3 + +### Parameter Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Path|✓|OAS2,OAS3 +|Query|✓|OAS2,OAS3 +|Header|✓|OAS2,OAS3 +|Body|✓|OAS2 +|FormUnencoded|✓|OAS2 +|FormMultipart|✓|OAS2 +|Cookie|✗|OAS3 + +### Schema Support Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|Simple|✓|OAS2,OAS3 +|Composite|✓|OAS2,OAS3 +|Polymorphism|✗|OAS2,OAS3 +|Union|✗|OAS3 +|allOf|✗|OAS2,OAS3 +|anyOf|✗|OAS3 +|oneOf|✗|OAS3 +|not|✗|OAS3 + +### Security Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|BasicAuth|✓|OAS2,OAS3 +|ApiKey|✓|OAS2,OAS3 +|OpenIDConnect|✗|OAS3 +|BearerToken|✓|OAS3 +|OAuth2_Implicit|✗|OAS2,OAS3 +|OAuth2_Password|✗|OAS2,OAS3 +|OAuth2_ClientCredentials|✗|OAS2,OAS3 +|OAuth2_AuthorizationCode|✗|OAS2,OAS3 +|SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension + +### Wire Format Feature +| Name | Supported | Defined By | +| ---- | --------- | ---------- | +|JSON|✓|OAS2,OAS3 +|XML|✓|OAS2,OAS3 +|PROTOBUF|✗|ToolingExtension +|Custom|✓|OAS2,OAS3 diff --git a/docs/generators/scala-play-server.md b/docs/generators/scala-play-server.md index 7386c47c19ad..cc632ff4d726 100644 --- a/docs/generators/scala-play-server.md +++ b/docs/generators/scala-play-server.md @@ -243,6 +243,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-sttp.md b/docs/generators/scala-sttp.md index e7b9eaa0d8d6..b425573a5565 100644 --- a/docs/generators/scala-sttp.md +++ b/docs/generators/scala-sttp.md @@ -242,6 +242,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scala-sttp4.md b/docs/generators/scala-sttp4.md index 77e9c995bcb7..2ff0143b0eda 100644 --- a/docs/generators/scala-sttp4.md +++ b/docs/generators/scala-sttp4.md @@ -242,6 +242,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scalatra.md b/docs/generators/scalatra.md index 9ad3ac2b73a5..6621eaae2f4d 100644 --- a/docs/generators/scalatra.md +++ b/docs/generators/scalatra.md @@ -236,6 +236,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/scalaz.md b/docs/generators/scalaz.md index ef61c871b7f0..627af71ef68d 100644 --- a/docs/generators/scalaz.md +++ b/docs/generators/scalaz.md @@ -244,6 +244,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/spring.md b/docs/generators/spring.md index 3b5f5f5f4d0a..a0066b9052ee 100644 --- a/docs/generators/spring.md +++ b/docs/generators/spring.md @@ -353,6 +353,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/swift-combine.md b/docs/generators/swift-combine.md index 69c993b8fc78..d660a47af3ba 100644 --- a/docs/generators/swift-combine.md +++ b/docs/generators/swift-combine.md @@ -318,6 +318,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/swift5.md b/docs/generators/swift5.md index a5e4db2c1f32..519ad121b837 100644 --- a/docs/generators/swift5.md +++ b/docs/generators/swift5.md @@ -345,6 +345,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-angular.md b/docs/generators/typescript-angular.md index f2f009abd3b0..132b9c94d130 100644 --- a/docs/generators/typescript-angular.md +++ b/docs/generators/typescript-angular.md @@ -272,6 +272,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-aurelia.md b/docs/generators/typescript-aurelia.md index c5626a5cd637..a4c3819c4dd0 100644 --- a/docs/generators/typescript-aurelia.md +++ b/docs/generators/typescript-aurelia.md @@ -256,6 +256,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-axios.md b/docs/generators/typescript-axios.md index 1a9c502a5dcf..253dbb0801cf 100644 --- a/docs/generators/typescript-axios.md +++ b/docs/generators/typescript-axios.md @@ -265,6 +265,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-fetch.md b/docs/generators/typescript-fetch.md index 6ae906f50ebd..20a758ccf3fd 100644 --- a/docs/generators/typescript-fetch.md +++ b/docs/generators/typescript-fetch.md @@ -290,6 +290,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-inversify.md b/docs/generators/typescript-inversify.md index ee226f6328d4..b38c0ff9afb7 100644 --- a/docs/generators/typescript-inversify.md +++ b/docs/generators/typescript-inversify.md @@ -263,6 +263,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-jquery.md b/docs/generators/typescript-jquery.md index 74a31f6de1a1..626ac5a920f5 100644 --- a/docs/generators/typescript-jquery.md +++ b/docs/generators/typescript-jquery.md @@ -258,6 +258,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-nestjs.md b/docs/generators/typescript-nestjs.md index 8bb3adffb916..9788a6139717 100644 --- a/docs/generators/typescript-nestjs.md +++ b/docs/generators/typescript-nestjs.md @@ -267,6 +267,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-node.md b/docs/generators/typescript-node.md index 73e2788e376a..f19a9f34e5a3 100644 --- a/docs/generators/typescript-node.md +++ b/docs/generators/typescript-node.md @@ -261,6 +261,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-redux-query.md b/docs/generators/typescript-redux-query.md index 951dd928abf9..0e0aa2ec3ce3 100644 --- a/docs/generators/typescript-redux-query.md +++ b/docs/generators/typescript-redux-query.md @@ -282,6 +282,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript-rxjs.md b/docs/generators/typescript-rxjs.md index 96c60baaa3c1..b5cdf9fe8a7a 100644 --- a/docs/generators/typescript-rxjs.md +++ b/docs/generators/typescript-rxjs.md @@ -275,6 +275,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/typescript.md b/docs/generators/typescript.md index a699db2c550b..ed7612a0cea4 100644 --- a/docs/generators/typescript.md +++ b/docs/generators/typescript.md @@ -266,6 +266,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✗|OAS2,OAS3 |OAuth2_AuthorizationCode|✗|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/wsdl-schema.md b/docs/generators/wsdl-schema.md index 1b40ef9bf940..0d45c1d00d68 100644 --- a/docs/generators/wsdl-schema.md +++ b/docs/generators/wsdl-schema.md @@ -163,6 +163,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/xojo-client.md b/docs/generators/xojo-client.md index 08ebe2537609..ed4358303c82 100644 --- a/docs/generators/xojo-client.md +++ b/docs/generators/xojo-client.md @@ -288,6 +288,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/generators/zapier.md b/docs/generators/zapier.md index aa6dca2ee845..220ae7e4df0a 100644 --- a/docs/generators/zapier.md +++ b/docs/generators/zapier.md @@ -168,6 +168,7 @@ These options may be applied as additional-properties (cli) or configOptions (pl |OAuth2_ClientCredentials|✓|OAS2,OAS3 |OAuth2_AuthorizationCode|✓|OAS2,OAS3 |SignatureAuth|✗|OAS3 +|AWSV4Signature|✗|ToolingExtension ### Wire Format Feature | Name | Supported | Defined By | diff --git a/docs/installation.md b/docs/installation.md index 8609f80af61f..40c792c779dd 100644 --- a/docs/installation.md +++ b/docs/installation.md @@ -103,18 +103,18 @@ docker run --rm \ 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/6.6.0/openapi-generator-cli-6.6.0.jar` +JAR location: `https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.0.jar` For **Mac/Linux** users: ```bash -wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.6.0/openapi-generator-cli-6.6.0.jar -O openapi-generator-cli.jar +wget https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.0.jar -O openapi-generator-cli.jar ``` For **Windows** users, you will need to install [wget](http://gnuwin32.sourceforge.net/packages/wget.htm) or you can use Invoke-WebRequest in PowerShell (3.0+), e.g. ```powershell -Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/6.6.0/openapi-generator-cli-6.6.0.jar +Invoke-WebRequest -OutFile openapi-generator-cli.jar https://repo1.maven.org/maven2/org/openapitools/openapi-generator-cli/7.2.0/openapi-generator-cli-7.2.0.jar ``` diff --git a/docs/templating.md b/docs/templating.md index aa7c5a1b3d89..3a4988cf7407 100644 --- a/docs/templating.md +++ b/docs/templating.md @@ -62,13 +62,13 @@ In OpenAPI Generator 5.0 and later, you can use the CLI command `author template openapi-generator author template -g java --library webclient ``` -For OpenAPI Generator versions prior to 5.0, you will want to find the [resources directory](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator/src/main/resources) for the generator you want to extend. This is generally easy to find as directories commonly follow the convention of `resources/`. In cases where you're unsure, you will need to find the `embeddedTemplateDir` assignment in your desired generator. This is almost always assigned in the constructor of the generator class. The C# .Net Core generator assigns this as: +For OpenAPI Generator versions prior to 5.0, you will want to find the [resources directory](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator/src/main/resources) for the generator you want to extend. This is generally easy to find as directories commonly follow the convention of `resources/`. In cases where you're unsure, you will need to find the `embeddedTemplateDir` assignment in your desired generator. This is almost always assigned in the constructor of the generator class. The C# generator assigns this as: ``` -embeddedTemplateDir = templateDir = "csharp-netcore"; +embeddedTemplateDir = templateDir = "csharp"; ``` -These templates are in our source repository at [modules/openapi-generator/src/main/resources/csharp-netcore](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator/src/main/resources/csharp-netcore). Be sure to select the tag or branch for the version of OpenAPI Generator you're using before grabbing the templates. +These templates are in our source repository at [modules/openapi-generator/src/main/resources/csharp](https://github.com/OpenAPITools/openapi-generator/tree/master/modules/openapi-generator/src/main/resources/csharp). Be sure to select the tag or branch for the version of OpenAPI Generator you're using before grabbing the templates. **NOTE** If you have specific logic you'd like to modify such as modifying the generated README, you _only_ need to pull and modify this individual template. OpenAPI Generator will lookup templates in this order: diff --git a/modules/openapi-generator-cli/Dockerfile b/modules/openapi-generator-cli/Dockerfile index 00fad3e7cdd8..910eff85b9be 100644 --- a/modules/openapi-generator-cli/Dockerfile +++ b/modules/openapi-generator-cli/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11.0-jre-buster +FROM eclipse-temurin:17.0.9_9-jre-focal ADD target/openapi-generator-cli.jar /opt/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar diff --git a/modules/openapi-generator-cli/pom.xml b/modules/openapi-generator-cli/pom.xml index 04f273dad27b..eff0a3009845 100644 --- a/modules/openapi-generator-cli/pom.xml +++ b/modules/openapi-generator-cli/pom.xml @@ -4,17 +4,14 @@ org.openapitools openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. 4.0.0 - openapi-generator-cli jar - openapi-generator (executable) - openapi-generator-cli @@ -82,7 +79,6 @@ - static-analysis @@ -107,9 +103,7 @@ - - org.openapitools openapi-generator @@ -135,7 +129,7 @@ ch.qos.logback logback-classic - 1.2.11 + 1.2.13 org.codehaus.janino @@ -155,5 +149,4 @@ test - diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java index fd379374fba5..070ae689611e 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/ConfigHelp.java @@ -89,6 +89,9 @@ public class ConfigHelp extends OpenApiGeneratorCommand { @Option(name = {"--model-name-mappings"}, title = "model name mappings", description = "displays the model name mappings (none)") private Boolean modelNameMappings; + @Option(name = {"--enum-name-mappings"}, title = "enum name mappings", description = "displays the enum name mappings (none)") + private Boolean enumNameMappings; + @Option(name = {"--openapi-normalizer"}, title = "openapi normalizer rules", description = "displays the OpenAPI normalizer rules (none)") private Boolean openapiNormalizer; @@ -98,6 +101,9 @@ public class ConfigHelp extends OpenApiGeneratorCommand { @Option(name = {"--language-specific-primitive"}, title = "language specific primitives", description = "displays the language specific primitives (types which require no additional imports, or which may conflict with user defined model names)") private Boolean languageSpecificPrimitives; + @Option(name = {"--openapi-generator-ignore-list"}, title = "openapi generator ignore list", description = "displays the openapi generator ignore list") + private Boolean openapiGeneratorIgnoreList; + @Option(name = {"--reserved-words"}, title = "language specific reserved words", description = "displays the reserved words which may result in renamed model or property names") private Boolean reservedWords; @@ -542,6 +548,18 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { sb.append(newline); } + if (Boolean.TRUE.equals(enumNameMappings)) { + sb.append(newline).append("ENUM NAME MAPPING").append(newline).append(newline); + Map map = config.enumNameMapping() + .entrySet() + .stream() + .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (a, b) -> { + throw new IllegalStateException(String.format(Locale.ROOT, "Duplicated options! %s and %s", a, b)); + }, TreeMap::new)); + writePlainTextFromMap(sb, map, optIndent, optNestedIndent, "enum name", "Mapped to"); + sb.append(newline); + } + if (Boolean.TRUE.equals(openapiNormalizer)) { sb.append(newline).append("OPENAPI NORMALIZER RULES").append(newline).append(newline); Map map = config.openapiNormalizer() @@ -573,6 +591,13 @@ private void generatePlainTextHelp(StringBuilder sb, CodegenConfig config) { sb.append(newline); } + if (Boolean.TRUE.equals(openapiGeneratorIgnoreList)) { + sb.append(newline).append("OPENAPI GENERATOR IGNORE LIST").append(newline).append(newline); + String[] arr = config.openapiGeneratorIgnoreList().stream().sorted().toArray(String[]::new); + writePlainTextFromArray(sb, arr, optIndent); + sb.append(newline); + } + if (Boolean.TRUE.equals(reservedWords)) { sb.append(newline).append("RESERVED WORDS").append(newline).append(newline); String[] arr = config.reservedWords().stream().sorted().toArray(String[]::new); diff --git a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java index 7d4ed09e27b1..963b626269c6 100644 --- a/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java +++ b/modules/openapi-generator-cli/src/main/java/org/openapitools/codegen/cmd/Generate.java @@ -160,6 +160,13 @@ public class Generate extends OpenApiGeneratorCommand { + " You can also have multiple occurrences of this option.") private List languageSpecificPrimitives = new ArrayList<>(); + @Option( + name = {"--openapi-generator-ignore-list"}, + title = ".openapi-generaotr-ignore list", + description = "specifies entries in the .openapi-generator-ignore file relative/path/to/file1,relative/path/to/file2. For example: README.md,pom.xml" + + " You can also have multiple occurrences of this option.") + private List openapiGeneratorIgnoreList = new ArrayList<>(); + @Option( name = {"--import-mappings"}, title = "import mappings", @@ -209,6 +216,13 @@ public class Generate extends OpenApiGeneratorCommand { + " You can also have multiple occurrences of this option.") private List modelNameMappings = new ArrayList<>(); + @Option( + name = {"--enum-name-mappings"}, + title = "enum name mappings", + description = "specifies mappings between the enum name and the new name in the format of enum_name=AnotherName,enum_name2=OtherName2." + + " You can also have multiple occurrences of this option.") + private List enumNameMappings = new ArrayList<>(); + @Option( name = {"--openapi-normalizer"}, title = "OpenAPI normalizer rules", @@ -492,10 +506,12 @@ public void execute() { applyNameMappingsKvpList(nameMappings, configurator); applyParameterNameMappingsKvpList(parameterNameMappings, configurator); applyModelNameMappingsKvpList(modelNameMappings, configurator); + applyEnumNameMappingsKvpList(enumNameMappings, configurator); applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); applyTypeMappingsKvpList(typeMappings, configurator); applyAdditionalPropertiesKvpList(additionalProperties, configurator); applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator); + applyOpenAPIGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator); applyReservedWordsMappingsKvpList(reservedWordsMappings, configurator); applyServerVariablesKvpList(serverVariableOverrides, configurator); diff --git a/modules/openapi-generator-core/pom.xml b/modules/openapi-generator-core/pom.xml index e6d65605b7f3..f8166649a039 100644 --- a/modules/openapi-generator-core/pom.xml +++ b/modules/openapi-generator-core/pom.xml @@ -6,7 +6,7 @@ openapi-generator-project org.openapitools - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java index 3aaaccf16339..5ba28f278c8b 100644 --- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java +++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/config/GeneratorSettings.java @@ -56,8 +56,10 @@ public final class GeneratorSettings implements Serializable { private final Map nameMappings; private final Map parameterNameMappings; private final Map modelNameMappings; + private final Map enumNameMappings; private final Map openapiNormalizer; private final Set languageSpecificPrimitives; + private final Set openapiGeneratorIgnoreList; private final Map reservedWordsMappings; private final Map serverVariables; @@ -295,6 +297,15 @@ public Map getModelNameMappings() { return modelNameMappings; } + /** + * Gets enum name mappings between an enum name and the new name. + * + * @return the enum name mappings + */ + public Map getEnumNameMappings() { + return enumNameMappings; + } + /** * Gets OpenAPI normalizer rules * @@ -320,6 +331,15 @@ public Set getLanguageSpecificPrimitives() { return languageSpecificPrimitives; } + /** + * Gets openapi generator ignore list. + * + * @return the openapi generator ignore list + */ + public Set getOpenAPIGeneratorIgnoreList() { + return openapiGeneratorIgnoreList; + } + /** * Gets reserved word mappings. Values defined here define how a reserved word should be escaped. *

              @@ -425,8 +445,10 @@ private GeneratorSettings(Builder builder) { nameMappings = Collections.unmodifiableMap(builder.nameMappings); parameterNameMappings = Collections.unmodifiableMap(builder.parameterNameMappings); modelNameMappings = Collections.unmodifiableMap(builder.modelNameMappings); + enumNameMappings = Collections.unmodifiableMap(builder.enumNameMappings); openapiNormalizer = Collections.unmodifiableMap(builder.openapiNormalizer); languageSpecificPrimitives = Collections.unmodifiableSet(builder.languageSpecificPrimitives); + openapiGeneratorIgnoreList = Collections.unmodifiableSet(builder.openapiGeneratorIgnoreList); reservedWordsMappings = Collections.unmodifiableMap(builder.reservedWordsMappings); serverVariables = Collections.unmodifiableMap(builder.serverVariables); gitHost = builder.gitHost; @@ -502,8 +524,10 @@ public GeneratorSettings() { nameMappings = Collections.unmodifiableMap(new HashMap<>(0)); parameterNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); modelNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); + enumNameMappings = Collections.unmodifiableMap(new HashMap<>(0)); openapiNormalizer = Collections.unmodifiableMap(new HashMap<>(0)); languageSpecificPrimitives = Collections.unmodifiableSet(new HashSet<>(0)); + openapiGeneratorIgnoreList = Collections.unmodifiableSet(new HashSet<>(0)); reservedWordsMappings = Collections.unmodifiableMap(new HashMap<>(0)); serverVariables = Collections.unmodifiableMap(new HashMap<>(0)); } @@ -572,12 +596,18 @@ public static Builder newBuilder(GeneratorSettings copy) { if (copy.getModelNameMappings() != null) { builder.modelNameMappings.putAll(copy.getModelNameMappings()); } + if (copy.getEnumNameMappings() != null) { + builder.enumNameMappings.putAll(copy.getEnumNameMappings()); + } if (copy.getOpenAPINormalizer() != null) { builder.openapiNormalizer.putAll(copy.getOpenAPINormalizer()); } if (copy.getLanguageSpecificPrimitives() != null) { builder.languageSpecificPrimitives.addAll(copy.getLanguageSpecificPrimitives()); } + if (copy.getOpenAPIGeneratorIgnoreList() != null) { + builder.openapiGeneratorIgnoreList.addAll(copy.getOpenAPIGeneratorIgnoreList()); + } if (copy.getReservedWordsMappings() != null) { builder.reservedWordsMappings.putAll(copy.getReservedWordsMappings()); } @@ -620,8 +650,10 @@ public static final class Builder { private Map nameMappings; private Map parameterNameMappings; private Map modelNameMappings; + private Map enumNameMappings; private Map openapiNormalizer; private Set languageSpecificPrimitives; + private Set openapiGeneratorIgnoreList; private Map reservedWordsMappings; private Map serverVariables; private String gitHost; @@ -644,8 +676,10 @@ public Builder() { nameMappings = new HashMap<>(); parameterNameMappings = new HashMap<>(); modelNameMappings = new HashMap<>(); + enumNameMappings = new HashMap<>(); openapiNormalizer = new HashMap<>(); languageSpecificPrimitives = new HashSet<>(); + openapiGeneratorIgnoreList = new HashSet<>(); reservedWordsMappings = new HashMap<>(); serverVariables = new HashMap<>(); @@ -1043,6 +1077,32 @@ public Builder withModelNameMapping(String key, String value) { return this; } + /** + * Sets the {@code enumNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param enumNameMappings the {@code enumNameMappings} to set + * @return a reference to this Builder + */ + public Builder withEnumNameMappings(Map enumNameMappings) { + this.enumNameMappings = enumNameMappings; + return this; + } + + /** + * Sets a single {@code enumNameMappings} and returns a reference to this Builder so that the methods can be chained together. + * + * @param key A key for the name mapping + * @param value The value of name mapping + * @return a reference to this Builder + */ + public Builder withEnumNameMapping(String key, String value) { + if (this.enumNameMappings == null) { + this.enumNameMappings = new HashMap<>(); + } + this.enumNameMappings.put(key, value); + return this; + } + /** * Sets the {@code openapiNormalizer} and returns a reference to this Builder so that the methods can be chained together. * @@ -1094,6 +1154,31 @@ public Builder withLanguageSpecificPrimitive(String value) { return this; } + /** + * Sets the {@code openapiGeneratorIgnoreList} and returns a reference to this Builder so that the methods can be chained together. + * + * @param openapiGeneratorIgnoreList the {@code openapiGeneratorIgnoreList} to set + * @return a reference to this Builder + */ + public Builder withOpenAPIGeneratorIgnoreList(Set openapiGeneratorIgnoreList) { + this.openapiGeneratorIgnoreList = openapiGeneratorIgnoreList; + return this; + } + + /** + * Sets a single {@code openapiGeneratorIgnoreList} and returns a reference to this Builder so that the methods can be chained together. + * + * @param value The value of entry to set + * @return a reference to this Builder + */ + public Builder withOpenAPIGeneratorIgnoreList(String value) { + if (this.openapiGeneratorIgnoreList == null) { + this.openapiGeneratorIgnoreList = new HashSet<>(); + } + this.openapiGeneratorIgnoreList.add(value); + return this; + } + /** * Sets the {@code reservedWordsMappings} and returns a reference to this Builder so that the methods can be chained together. * @@ -1198,7 +1283,6 @@ public Builder withHttpUserAgent(String httpUserAgent) { */ public GeneratorSettings build() { GeneratorSettings instance = new GeneratorSettings(this); - //noinspection PlaceholderCountMatchesArgumentCount LOGGER.debug("GeneratorSettings#build: {}", instance); return instance; } @@ -1224,6 +1308,7 @@ public String toString() { ", additionalProperties=" + additionalProperties + ", importMappings=" + importMappings + ", languageSpecificPrimitives=" + languageSpecificPrimitives + + ", openapiGeneratorIgnoreList=" + openapiGeneratorIgnoreList + ", reservedWordsMappings=" + reservedWordsMappings + ", gitHost='" + gitHost + '\'' + ", gitUserId='" + gitUserId + '\'' + @@ -1260,8 +1345,10 @@ public boolean equals(Object o) { Objects.equals(getNameMappings(), that.getNameMappings()) && Objects.equals(getParameterNameMappings(), that.getParameterNameMappings()) && Objects.equals(getModelNameMappings(), that.getModelNameMappings()) && + Objects.equals(getEnumNameMappings(), that.getEnumNameMappings()) && Objects.equals(getOpenAPINormalizer(), that.getOpenAPINormalizer()) && Objects.equals(getLanguageSpecificPrimitives(), that.getLanguageSpecificPrimitives()) && + Objects.equals(getOpenAPIGeneratorIgnoreList(), that.getOpenAPIGeneratorIgnoreList()) && Objects.equals(getReservedWordsMappings(), that.getReservedWordsMappings()) && Objects.equals(getGitHost(), that.getGitHost()) && Objects.equals(getGitUserId(), that.getGitUserId()) && @@ -1295,8 +1382,10 @@ public int hashCode() { getNameMappings(), getParameterNameMappings(), getModelNameMappings(), + getEnumNameMappings(), getOpenAPINormalizer(), getLanguageSpecificPrimitives(), + getOpenAPIGeneratorIgnoreList(), getReservedWordsMappings(), getGitHost(), getGitUserId(), diff --git a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/meta/features/SecurityFeature.java b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/meta/features/SecurityFeature.java index 4939ce3d99d0..bed67a827004 100644 --- a/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/meta/features/SecurityFeature.java +++ b/modules/openapi-generator-core/src/main/java/org/openapitools/codegen/meta/features/SecurityFeature.java @@ -18,6 +18,7 @@ import org.openapitools.codegen.meta.features.annotations.OAS2; import org.openapitools.codegen.meta.features.annotations.OAS3; +import org.openapitools.codegen.meta.features.annotations.ToolingExtension; /** * Defines security features supported in the generated code. @@ -80,4 +81,10 @@ public enum SecurityFeature { */ @OAS3 SignatureAuth, + + /** + * Supports AWS v4 signature, only for a few generators and with config option withAWSV4Signature=true + */ + @ToolingExtension + AWSV4Signature, } diff --git a/modules/openapi-generator-core/src/test/java/org/openapitools/codegen/config/WorkflowSettingsTest.java b/modules/openapi-generator-core/src/test/java/org/openapitools/codegen/config/WorkflowSettingsTest.java index 33638f767356..626e02aca94b 100644 --- a/modules/openapi-generator-core/src/test/java/org/openapitools/codegen/config/WorkflowSettingsTest.java +++ b/modules/openapi-generator-core/src/test/java/org/openapitools/codegen/config/WorkflowSettingsTest.java @@ -120,4 +120,23 @@ public void defaultValuesCanBeChangedBuilder(){ WorkflowSettings defaults = WorkflowSettings.newBuilder().build(); assertOnChangesToDefaults(defaults); } + @Test + public void customOutputDirIsSet() { + WorkflowSettings settings = WorkflowSettings.newBuilder() + .withOutputDir("custom/output/directory") + .build(); + + assertEquals(settings.getOutputDir(), Paths.get("custom/output/directory").toAbsolutePath().toString()); + } + + @Test + public void customGlobalPropertiesAreSet() { + WorkflowSettings settings = WorkflowSettings.newBuilder() + .withGlobalProperty("customKey", "customValue") + .build(); + + Map properties = settings.getGlobalProperties(); + assertEquals(properties.size(), 1, "Global Properties map should allow custom entries"); + assertEquals(properties.getOrDefault("customKey", ""), "customValue"); + } } \ No newline at end of file diff --git a/modules/openapi-generator-gradle-plugin/README.adoc b/modules/openapi-generator-gradle-plugin/README.adoc index 3b75426d3615..00144d2daccf 100644 --- a/modules/openapi-generator-gradle-plugin/README.adoc +++ b/modules/openapi-generator-gradle-plugin/README.adoc @@ -97,7 +97,7 @@ task validateGoodSpec(type: org.openapitools.generator.gradle.plugin.tasks.Valid [source,group] ---- plugins { - id "org.openapi.generator" version "6.6.0" + id "org.openapi.generator" version "7.2.0" } ---- @@ -113,7 +113,7 @@ buildscript { // url "https://plugins.gradle.org/m2/" } dependencies { - classpath "org.openapitools:openapi-generator-gradle-plugin:6.6.0" + classpath "org.openapitools:openapi-generator-gradle-plugin:7.2.0" } } @@ -761,7 +761,7 @@ buildscript { } dependencies { classpath 'com.android.tools.build:gradle:3.2.1' - classpath('org.openapitools:openapi-generator-gradle-plugin:6.6.0') { + classpath('org.openapitools:openapi-generator-gradle-plugin:7.2.0') { exclude group: 'com.google.guava' } } diff --git a/modules/openapi-generator-gradle-plugin/gradle.properties b/modules/openapi-generator-gradle-plugin/gradle.properties index 11df589b84bc..6dbbb27509bb 100644 --- a/modules/openapi-generator-gradle-plugin/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/gradle.properties @@ -1,5 +1,5 @@ # RELEASE_VERSION -openApiGeneratorVersion=7.1.0-SNAPSHOT +openApiGeneratorVersion=7.3.0-SNAPSHOT # /RELEASE_VERSION # BEGIN placeholders diff --git a/modules/openapi-generator-gradle-plugin/pom.xml b/modules/openapi-generator-gradle-plugin/pom.xml index eb972aa08701..2de833f7ee3b 100644 --- a/modules/openapi-generator-gradle-plugin/pom.xml +++ b/modules/openapi-generator-gradle-plugin/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md index b2b362359e6e..a9009fc49845 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/README.md @@ -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=6.3.0 openApiValidate +gradle -PopenApiGeneratorVersion=7.2.0 openApiValidate ``` diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties index b6bc0004a3eb..afce2d398300 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle.properties @@ -1,3 +1,3 @@ # RELEASE_VERSION -openApiGeneratorVersion=7.1.0-SNAPSHOT +openApiGeneratorVersion=7.3.0-SNAPSHOT # /RELEASE_VERSION diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties index 442d9132ea32..068cdb2dc260 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradle/wrapper/gradle-wrapper.properties @@ -1,5 +1,5 @@ distributionBase=GRADLE_USER_HOME distributionPath=wrapper/dists -distributionUrl=https\://services.gradle.org/distributions/gradle-6.8.3-bin.zip +distributionUrl=https\://services.gradle.org/distributions/gradle-7.6.3-bin.zip zipStoreBase=GRADLE_USER_HOME zipStorePath=wrapper/dists diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew index 20b741fb46c3..cc8078650258 100755 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew @@ -1,7 +1,7 @@ -#!/usr/bin/env sh +#!/bin/sh # -# Copyright 2015 the original author or authors. +# Copyright © 2015-2021 the original authors. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. @@ -17,67 +17,101 @@ # ############################################################################## -## -## Gradle start up script for UN*X -## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# ############################################################################## # Attempt to set APP_HOME + # Resolve links: $0 may be a link -PRG="$0" -# Need this for relative symlinks. -while [ -h "$PRG" ] ; do - ls=`ls -ld "$PRG"` - link=`expr "$ls" : '.*-> \(.*\)$'` - if expr "$link" : '/.*' > /dev/null; then - PRG="$link" - else - PRG=`dirname "$PRG"`"/$link" - fi +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac done -SAVED="`pwd`" -cd "`dirname \"$PRG\"`/" >/dev/null -APP_HOME="`pwd -P`" -cd "$SAVED" >/dev/null -APP_NAME="Gradle" -APP_BASE_NAME=`basename "$0"` +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' # Use the maximum available, or set MAX_FD != -1 to use that value. -MAX_FD="maximum" +MAX_FD=maximum warn () { echo "$*" -} +} >&2 die () { echo echo "$*" echo exit 1 -} +} >&2 # OS specific support (must be 'true' or 'false'). cygwin=false msys=false darwin=false nonstop=false -case "`uname`" in - CYGWIN* ) - cygwin=true - ;; - Darwin* ) - darwin=true - ;; - MINGW* ) - msys=true - ;; - NONSTOP* ) - nonstop=true - ;; +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; esac CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar @@ -87,97 +121,124 @@ CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar if [ -n "$JAVA_HOME" ] ; then if [ -x "$JAVA_HOME/jre/sh/java" ] ; then # IBM's JDK on AIX uses strange locations for the executables - JAVACMD="$JAVA_HOME/jre/sh/java" + JAVACMD=$JAVA_HOME/jre/sh/java else - JAVACMD="$JAVA_HOME/bin/java" + JAVACMD=$JAVA_HOME/bin/java fi if [ ! -x "$JAVACMD" ] ; then die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi else - JAVACMD="java" + JAVACMD=java which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + Please set the JAVA_HOME variable in your environment to match the location of your Java installation." fi # Increase the maximum file descriptors if we can. -if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then - MAX_FD_LIMIT=`ulimit -H -n` - if [ $? -eq 0 ] ; then - if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then - MAX_FD="$MAX_FD_LIMIT" - fi - ulimit -n $MAX_FD - if [ $? -ne 0 ] ; then - warn "Could not set maximum file descriptor limit: $MAX_FD" - fi - else - warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" - fi +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac fi -# For Darwin, add options to specify how the application appears in the dock -if $darwin; then - GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" -fi +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. # For Cygwin or MSYS, switch paths to Windows format before running java -if [ "$cygwin" = "true" -o "$msys" = "true" ] ; then - APP_HOME=`cygpath --path --mixed "$APP_HOME"` - CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` - - JAVACMD=`cygpath --unix "$JAVACMD"` - - # We build the pattern for arguments to be converted via cygpath - ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` - SEP="" - for dir in $ROOTDIRSRAW ; do - ROOTDIRS="$ROOTDIRS$SEP$dir" - SEP="|" - done - OURCYGPATTERN="(^($ROOTDIRS))" - # Add a user-defined pattern to the cygpath arguments - if [ "$GRADLE_CYGPATTERN" != "" ] ; then - OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" - fi +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + # Now convert the arguments - kludge to limit ourselves to /bin/sh - i=0 - for arg in "$@" ; do - CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` - CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option - - if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition - eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` - else - eval `echo args$i`="\"$arg\"" + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) fi - i=`expr $i + 1` + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg done - case $i in - 0) set -- ;; - 1) set -- "$args0" ;; - 2) set -- "$args0" "$args1" ;; - 3) set -- "$args0" "$args1" "$args2" ;; - 4) set -- "$args0" "$args1" "$args2" "$args3" ;; - 5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; - 6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; - 7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; - 8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; - 9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; - esac fi -# Escape application args -save () { - for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done - echo " " -} -APP_ARGS=`save "$@"` +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# -# Collect all arguments for the java command, following the shell quoting and substitution rules -eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' exec "$JAVACMD" "$@" diff --git a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat index 6a68175eb70f..ea603b410240 100644 --- a/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat +++ b/modules/openapi-generator-gradle-plugin/samples/local-spec/gradlew.bat @@ -14,7 +14,7 @@ @rem limitations under the License. @rem -@if "%DEBUG%" == "" @echo off +@if "%DEBUG%"=="" @echo off @rem ########################################################################## @rem @rem Gradle startup script for Windows @@ -25,7 +25,8 @@ if "%OS%"=="Windows_NT" setlocal set DIRNAME=%~dp0 -if "%DIRNAME%" == "" set DIRNAME=. +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused set APP_BASE_NAME=%~n0 set APP_HOME=%DIRNAME% @@ -40,7 +41,7 @@ if defined JAVA_HOME goto findJavaFromJavaHome set JAVA_EXE=java.exe %JAVA_EXE% -version >NUL 2>&1 -if "%ERRORLEVEL%" == "0" goto execute +if %ERRORLEVEL% equ 0 goto execute echo. echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. @@ -75,13 +76,15 @@ set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar :end @rem End local scope for the variables with windows NT shell -if "%ERRORLEVEL%"=="0" goto mainEnd +if %ERRORLEVEL% equ 0 goto mainEnd :fail rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of rem the _cmd.exe /c_ return code! -if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 -exit /b 1 +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% :mainEnd if "%OS%"=="Windows_NT" endlocal diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt index 3947d3806ee4..cf3552d38fb5 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/OpenApiGeneratorPlugin.kt @@ -163,3 +163,5 @@ class OpenApiGeneratorPlugin : Plugin { } } + + diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt index 04e654942b6d..6270c8df6a3a 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/extensions/OpenApiGeneratorGenerateExtension.kt @@ -147,6 +147,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) { */ val languageSpecificPrimitives = project.objects.listProperty() + /** + * Specifies .openapi-generator-ignore list in the form of relative/path/to/file1,relative/path/to/file2. For example: README.md,pom.xml. + */ + val openapiGeneratorIgnoreList = project.objects.listProperty() + /** * Specifies mappings between a given class and the import that should be used for that class. */ @@ -182,6 +187,11 @@ open class OpenApiGeneratorGenerateExtension(project: Project) { */ val modelNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between an enum name and the new name + */ + val enumNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ diff --git a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt index 3eeb5955a74b..1d4cefb7ca19 100644 --- a/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt +++ b/modules/openapi-generator-gradle-plugin/src/main/kotlin/org/openapitools/generator/gradle/plugin/tasks/GenerateTask.kt @@ -244,6 +244,13 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac @Input val languageSpecificPrimitives = project.objects.listProperty() + /** + * Specifies .openapi-generator-ignore list in the form of relative/path/to/file1,relative/path/to/file2. For example: README.md,pom.xml. + */ + @Optional + @Input + val openapiGeneratorIgnoreList = project.objects.listProperty() + /** * Specifies mappings between a given class and the import that should be used for that class. */ @@ -293,6 +300,13 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac @Input val modelNameMappings = project.objects.mapProperty() + /** + * Specifies mappings between the enum name and the new name + */ + @Optional + @Input + val enumNameMappings = project.objects.mapProperty() + /** * Specifies mappings (rules) in OpenAPI normalizer */ @@ -852,6 +866,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac } } + if (enumNameMappings.isPresent) { + enumNameMappings.get().forEach { entry -> + configurator.addEnumNameMapping(entry.key, entry.value) + } + } + if (openapiNormalizer.isPresent) { openapiNormalizer.get().forEach { entry -> configurator.addOpenAPINormalizer(entry.key, entry.value) @@ -882,6 +902,12 @@ open class GenerateTask @Inject constructor(private val objectFactory: ObjectFac } } + if (openapiGeneratorIgnoreList.isPresent) { + openapiGeneratorIgnoreList.get().forEach { + configurator.addOpenAPIGeneratorIgnoreList(it) + } + } + if (reservedWordsMappings.isPresent) { reservedWordsMappings.get().forEach { entry -> configurator.addAdditionalReservedWordMapping(entry.key, entry.value) diff --git a/modules/openapi-generator-maven-plugin/README.md b/modules/openapi-generator-maven-plugin/README.md index 15b47ba991fa..38877d8dee4c 100644 --- a/modules/openapi-generator-maven-plugin/README.md +++ b/modules/openapi-generator-maven-plugin/README.md @@ -12,7 +12,7 @@ Add to your `build->plugins` section (default phase is `generate-sources` phase) org.openapitools openapi-generator-maven-plugin - 6.3.0 + 7.2.0 diff --git a/modules/openapi-generator-maven-plugin/examples/java-client.xml b/modules/openapi-generator-maven-plugin/examples/java-client.xml index 96bcc4607cd4..858fa213898b 100644 --- a/modules/openapi-generator-maven-plugin/examples/java-client.xml +++ b/modules/openapi-generator-maven-plugin/examples/java-client.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/kotlin.xml b/modules/openapi-generator-maven-plugin/examples/kotlin.xml index 21ce29311af0..cf872050026f 100644 --- a/modules/openapi-generator-maven-plugin/examples/kotlin.xml +++ b/modules/openapi-generator-maven-plugin/examples/kotlin.xml @@ -15,7 +15,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml b/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml index 6c40c71be00c..09e4507e98a8 100644 --- a/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml +++ b/modules/openapi-generator-maven-plugin/examples/multi-module/java-client/pom.xml @@ -19,7 +19,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml index acdfe54dfdd5..fab8ba5eeef5 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java-invalid-spec.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/non-java.xml b/modules/openapi-generator-maven-plugin/examples/non-java.xml index 7d3617d18d13..2bd480be7ef7 100644 --- a/modules/openapi-generator-maven-plugin/examples/non-java.xml +++ b/modules/openapi-generator-maven-plugin/examples/non-java.xml @@ -13,7 +13,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/examples/spring.xml b/modules/openapi-generator-maven-plugin/examples/spring.xml index 02d44313e189..1d1b07f1814e 100644 --- a/modules/openapi-generator-maven-plugin/examples/spring.xml +++ b/modules/openapi-generator-maven-plugin/examples/spring.xml @@ -20,7 +20,7 @@ org.openapitools openapi-generator-maven-plugin - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT diff --git a/modules/openapi-generator-maven-plugin/pom.xml b/modules/openapi-generator-maven-plugin/pom.xml index c8598352669d..68b263d7bf4b 100644 --- a/modules/openapi-generator-maven-plugin/pom.xml +++ b/modules/openapi-generator-maven-plugin/pom.xml @@ -5,7 +5,7 @@ org.openapitools openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java index 40de961a11e7..b06aface93e7 100644 --- a/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java +++ b/modules/openapi-generator-maven-plugin/src/main/java/org/openapitools/codegen/plugin/CodeGenMojo.java @@ -350,6 +350,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "modelNameMappings", property = "openapi.generator.maven.plugin.modelNameMappings") private List modelNameMappings; + /** + * A map of enum names and the new names + */ + @Parameter(name = "enumNameMappings", property = "openapi.generator.maven.plugin.enumNameMappings") + private List enumNameMappings; + /** * A set of rules for OpenAPI normalizer */ @@ -368,6 +374,12 @@ public class CodeGenMojo extends AbstractMojo { @Parameter(name = "languageSpecificPrimitives", property = "openapi.generator.maven.plugin.languageSpecificPrimitives") private List languageSpecificPrimitives; + /** + * A list of openapi-generator-ignore entries + */ + @Parameter(name = "openapiGeneratorIgnoreList", property = "openapi.generator.maven.plugin.openapiGeneratorIgnoreList") + private List openapiGeneratorIgnoreList; + /** * A map of additional properties that can be referenced by the mustache templates */ @@ -777,6 +789,12 @@ public void execute() throws MojoExecutionException { .get("language-specific-primitives").toString(), configurator); } + // Retained for backwards-compatibility with configOptions -> openapi-generator-ignore-list + if (openapiGeneratorIgnoreList == null && configOptions.containsKey("openapi-generator-ignore-list")) { + applyOpenAPIGeneratorIgnoreListCsv(configOptions + .get("openapi-generator-ignore-list").toString(), configurator); + } + // Retained for backwards-compatibility with configOptions -> additional-properties if (additionalProperties == null && configOptions.containsKey("additional-properties")) { applyAdditionalPropertiesKvp(configOptions.get("additional-properties").toString(), @@ -834,6 +852,11 @@ public void execute() throws MojoExecutionException { applyModelNameMappingsKvpList(modelNameMappings, configurator); } + // Apply Enum Name Mappings + if (enumNameMappings != null && (configOptions == null || !configOptions.containsKey("enum-name-mappings"))) { + applyEnumNameMappingsKvpList(enumNameMappings, configurator); + } + // Apply OpenAPI normalizer rules if (openapiNormalizer != null && (configOptions == null || !configOptions.containsKey("openapi-normalizer"))) { applyOpenAPINormalizerKvpList(openapiNormalizer, configurator); @@ -850,6 +873,12 @@ public void execute() throws MojoExecutionException { applyLanguageSpecificPrimitivesCsvList(languageSpecificPrimitives, configurator); } + // Apply Language Specific Primitives + if (openapiGeneratorIgnoreList != null + && (configOptions == null || !configOptions.containsKey("openapi-generator-ignore-list"))) { + applyOpenAPIGeneratorIgnoreListCsvList(openapiGeneratorIgnoreList, configurator); + } + // Apply Additional Properties if (additionalProperties != null && (configOptions == null || !configOptions.containsKey("additional-properties"))) { applyAdditionalPropertiesKvpList(additionalProperties, configurator); @@ -903,6 +932,7 @@ public void execute() throws MojoExecutionException { return; } adjustAdditionalProperties(config); + GlobalSettings.log(); new DefaultGenerator(dryRun).opts(input).generate(); if (buildContext != null) { diff --git a/modules/openapi-generator-online/Dockerfile b/modules/openapi-generator-online/Dockerfile index 74ac8c6f9801..806129c5ff57 100644 --- a/modules/openapi-generator-online/Dockerfile +++ b/modules/openapi-generator-online/Dockerfile @@ -1,4 +1,4 @@ -FROM openjdk:11 +FROM eclipse-temurin:17.0.9_9-jre-focal WORKDIR /generator diff --git a/modules/openapi-generator-online/pom.xml b/modules/openapi-generator-online/pom.xml index 3ef2e372a8d7..7c1a8dda27e9 100644 --- a/modules/openapi-generator-online/pom.xml +++ b/modules/openapi-generator-online/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. diff --git a/modules/openapi-generator-online/src/test/java/org/openapitools/codegen/online/api/GenApiControllerTest.java b/modules/openapi-generator-online/src/test/java/org/openapitools/codegen/online/api/GenApiControllerTest.java index 262e0eba6603..8df33829c926 100644 --- a/modules/openapi-generator-online/src/test/java/org/openapitools/codegen/online/api/GenApiControllerTest.java +++ b/modules/openapi-generator-online/src/test/java/org/openapitools/codegen/online/api/GenApiControllerTest.java @@ -124,5 +124,12 @@ public void generateWIthForwardedHeaders() throws Exception { .andExpect(status().isOk()) .andExpect(header().string(HttpHeaders.CONTENT_LENGTH, not(0))); } - + @Test + public void generateClientWithInvalidOpenAPIUrl() throws Exception { + String invalidOpenAPIUrl = "https://test.com:1234/invalid_openapi.json"; + mockMvc.perform(post("http://test.com:1234/api/gen/clients/java") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"openAPIUrl\": \"" + invalidOpenAPIUrl + "\"}")) + .andExpect(status().isBadRequest()); + } } diff --git a/modules/openapi-generator/pom.xml b/modules/openapi-generator/pom.xml index f55c4d55abe6..0b7c4ce16590 100644 --- a/modules/openapi-generator/pom.xml +++ b/modules/openapi-generator/pom.xml @@ -4,7 +4,7 @@ org.openapitools openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT ../.. @@ -271,7 +271,7 @@ ch.qos.logback logback-classic - 1.2.11 + 1.2.13 test diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java index 59651d41e40c..ccb63c22e556 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConfig.java @@ -30,6 +30,7 @@ import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.model.WebhooksMap; import java.io.File; import java.util.List; @@ -155,6 +156,8 @@ public interface CodegenConfig { Map modelNameMapping(); + Map enumNameMapping(); + Map openapiNormalizer(); Map apiTemplateFiles(); @@ -171,6 +174,8 @@ public interface CodegenConfig { Set languageSpecificPrimitives(); + Set openapiGeneratorIgnoreList(); + Map reservedWordsMappings(); void preprocessOpenAPI(OpenAPI openAPI); @@ -213,10 +218,14 @@ public interface CodegenConfig { OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels); + WebhooksMap postProcessWebhooksWithModels(WebhooksMap objs, List allModels); + Map postProcessSupportingFileData(Map objs); void postProcessModelProperty(CodegenModel model, CodegenProperty property); + void postProcessResponseWithProperty(CodegenResponse response, CodegenProperty property); + void postProcessParameter(CodegenParameter parameter); String modelFilename(String templateName, String modelName); @@ -347,4 +356,6 @@ public interface CodegenConfig { boolean getUseOpenAPINormalizer(); + Set getOpenAPIGeneratorIgnoreList(); + } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java index edc2ef10c096..39a22bb458a7 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenConstants.java @@ -28,6 +28,7 @@ public class CodegenConstants { public static final String SUPPORTING_FILES = "supportingFiles"; public static final String MODEL_TESTS = "modelTests"; public static final String MODEL_DOCS = "modelDocs"; + public static final String WEBHOOKS = "webhooks"; public static final String API_TESTS = "apiTests"; public static final String API_DOCS = "apiDocs"; @@ -43,6 +44,8 @@ public class CodegenConstants { public static final String API_SUFFIX = "apiSuffix"; public static final String API_SUFFIX_DESC = "suffix for api classes"; + public static final String AUTOSET_CONSTANTS = "autosetConstants"; + public static final String MODEL_PACKAGE = "modelPackage"; public static final String MODEL_PACKAGE_DESC = "package for generated models"; @@ -153,6 +156,9 @@ public class CodegenConstants { public static final String USE_DATETIME_OFFSET = "useDateTimeOffset"; public static final String USE_DATETIME_OFFSET_DESC = "Use DateTimeOffset to model date-time properties"; + public static final String USE_DATETIME_FOR_DATE = "useDateTimeForDate"; + public static final String USE_DATETIME_FOR_DATE_DESC = "Use DateTime to model date properties even if DateOnly supported. (.net 6.0+ only)"; + public static final String ENSURE_UNIQUE_PARAMS = "ensureUniqueParams"; public static final String ENSURE_UNIQUE_PARAMS_DESC = "Whether to ensure parameter names are unique in an operation (rename parameters that are not)."; @@ -294,6 +300,7 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, public static final String GENERATE_APIS = "generateApis"; public static final String GENERATE_API_DOCS = "generateApiDocs"; + public static final String GENERATE_WEBHOOKS = "generateWebhooks"; public static final String GENERATE_API_TESTS = "generateApiTests"; public static final String GENERATE_API_TESTS_DESC = "Specifies that api tests are to be generated."; @@ -429,4 +436,13 @@ public static enum ENUM_PROPERTY_NAMING_TYPE {camelCase, PascalCase, snake_case, "

            • setting additionalProperties: false in your schemas
            "; public static final String FASTAPI_IMPLEMENTATION_PACKAGE = "fastapiImplementationPackage"; + + public static final String WITH_GO_MOD = "withGoMod"; + + public static final String GENERATE_MARSHAL_JSON = "generateMarshalJSON"; + public static final String GENERATE_MARSHAL_JSON_DESC = "Generate MarshalJSON method"; + + public static final String MAX_ATTEMPTS_FOR_RETRY = "maxAttemptsForRetry"; + + public static final String WAIT_TIME_OF_THREAD = "waitTimeMillis"; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java index 4c2d8bc5b170..a09d7a84599b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenModel.java @@ -177,6 +177,7 @@ public class CodegenModel implements IJsonSchemaValidationProperties { private boolean hasDiscriminatorWithNonEmptyMapping; private boolean isAnyType; private boolean isUuid; + private boolean isUri; private Map requiredVarsMap; private String ref; @@ -979,6 +980,10 @@ public void setIsFreeFormObject(boolean isFreeFormObject) { public void setIsUuid(boolean isUuid) { this.isUuid = isUuid; } + public boolean getIsUri() { return isUri; } + + public void setIsUri(boolean isUri) { this.isUri = isUri; } + @Override public void setComposedSchemas(CodegenComposedSchemas composedSchemas) { this.composedSchemas = composedSchemas; @@ -1112,6 +1117,7 @@ public boolean equals(Object o) { hasMultipleTypes == that.getHasMultipleTypes() && hasDiscriminatorWithNonEmptyMapping == that.getHasDiscriminatorWithNonEmptyMapping() && isUuid == that.getIsUuid() && + isUri == that.getIsUri() && isBooleanSchemaTrue == that.getIsBooleanSchemaTrue() && isBooleanSchemaFalse == that.getIsBooleanSchemaFalse() && getSchemaIsFromAdditionalProperties() == that.getSchemaIsFromAdditionalProperties() && @@ -1199,7 +1205,7 @@ hasChildren, isMap, isDeprecated, hasOnlyReadOnly, getExternalDocumentation(), g getMinItems(), getMaxLength(), getMinLength(), getExclusiveMinimum(), getExclusiveMaximum(), getMinimum(), getMaximum(), getPattern(), getMultipleOf(), getItems(), getAdditionalProperties(), getIsModel(), getAdditionalPropertiesIsAnyType(), hasDiscriminatorWithNonEmptyMapping, - isAnyType, getComposedSchemas(), hasMultipleTypes, isDecimal, isUuid, requiredVarsMap, ref, + isAnyType, getComposedSchemas(), hasMultipleTypes, isDecimal, isUuid, isUri, requiredVarsMap, ref, uniqueItemsBoolean, schemaIsFromAdditionalProperties, isBooleanSchemaTrue, isBooleanSchemaFalse, format, dependentRequired, contains); } @@ -1300,6 +1306,7 @@ public String toString() { sb.append(", hasMultipleTypes=").append(hasMultipleTypes); sb.append(", isDecimal=").append(isDecimal); sb.append(", isUUID=").append(isUuid); + sb.append(", isURI=").append(isUri); sb.append(", requiredVarsMap=").append(requiredVarsMap); sb.append(", ref=").append(ref); sb.append(", schemaIsFromAdditionalProperties=").append(schemaIsFromAdditionalProperties); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java index ab9382911872..76b98ac0d77d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenOperation.java @@ -152,6 +152,15 @@ public boolean getHasCookieParams() { return nonEmpty(cookieParams); } + /** + * Check if there's at least one parameter which is not a body parameter + * + * @return true if any non body parameter exists, false otherwise + */ + public boolean getHasNonBodyParams() { + return nonEmpty(queryParams) || nonEmpty(headerParams) || nonEmpty(pathParams) || nonEmpty(cookieParams) || nonEmpty(formParams); + } + /** * Check if there's at least one optional parameter * diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java index 72587604a53c..671585bc70b6 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/CodegenSecurity.java @@ -22,6 +22,7 @@ import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.stream.Collectors; public class CodegenSecurity { public String name; @@ -89,6 +90,16 @@ public CodegenSecurity (CodegenSecurity original) { public CodegenSecurity filterByScopeNames(List filterScopes) { CodegenSecurity filteredSecurity = new CodegenSecurity(this); + // Since OAS 3.1.0, security scheme types other than "oauth2" and "openIdConnect" may have a list of role names + // which are required for the execution, but are not otherwise defined or exchanged in-band. + // In such cases, no filtering is performed. + if (!(Boolean.TRUE.equals(isOAuth) || Boolean.TRUE.equals(isOpenId))) { + filteredSecurity.scopes = filterScopes.stream() + .map(s -> new HashMap(Map.of("scope", s))) + .collect(Collectors.toList()); + return filteredSecurity; + } + if (scopes == null) { return filteredSecurity; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java index b37bf23837d6..f2bc4bbd8eaf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultCodegen.java @@ -26,6 +26,7 @@ import com.samskivert.mustache.Mustache; import com.samskivert.mustache.Mustache.Compiler; import com.samskivert.mustache.Mustache.Lambda; +import io.swagger.v3.core.util.AnnotationsUtils; import io.swagger.v3.core.util.Json; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; @@ -59,6 +60,7 @@ import org.openapitools.codegen.model.ModelMap; import org.openapitools.codegen.model.ModelsMap; import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.model.WebhooksMap; import org.openapitools.codegen.serializer.SerializerUtils; import org.openapitools.codegen.templating.MustacheEngineAdapter; import org.openapitools.codegen.templating.mustache.*; @@ -131,7 +133,7 @@ public class DefaultCodegen implements CodegenConfig { SecurityFeature.BasicAuth, SecurityFeature.ApiKey, SecurityFeature.BearerToken, SecurityFeature.OAuth2_Implicit, SecurityFeature.OAuth2_Password, SecurityFeature.OAuth2_ClientCredentials, SecurityFeature.OAuth2_AuthorizationCode - // OpenIdConnect and SignatureAuth are not yet 100% supported + // OpenIdConnect and SignatureAuth and AW4Signature are not yet 100% supported ) .includeWireFormatFeatures( WireFormatFeature.JSON, WireFormatFeature.XML @@ -159,6 +161,7 @@ public class DefaultCodegen implements CodegenConfig { protected Map instantiationTypes; protected Set reservedWords; protected Set languageSpecificPrimitives = new HashSet<>(); + protected Set openapiGeneratorIgnoreList = new HashSet<>(); protected Map importMapping = new HashMap<>(); // a map to store the mapping between a schema and the new one protected Map schemaMapping = new HashMap<>(); @@ -172,6 +175,8 @@ public class DefaultCodegen implements CodegenConfig { protected Map parameterNameMapping = new HashMap<>(); // a map to store the mapping between model name and the name provided by the user protected Map modelNameMapping = new HashMap<>(); + // a map to store the mapping between enum name and the name provided by the user + protected Map enumNameMapping = new HashMap<>(); // a map to store the rules in OpenAPI Normalizer protected Map openapiNormalizer = new HashMap<>(); protected String modelPackage = "", apiPackage = "", fileSuffix; @@ -304,6 +309,9 @@ apiTemplateFiles are for API outputs only (controllers/handlers). protected boolean addSuffixToDuplicateOperationNicknames = true; + // Whether to automatically hardcode params that are considered Constants by OpenAPI Spec + protected boolean autosetConstants = false; + public boolean getAddSuffixToDuplicateOperationNicknames() { return addSuffixToDuplicateOperationNicknames; } @@ -427,6 +435,10 @@ public void processOpts() { this.setEnumUnknownDefaultCase(Boolean.parseBoolean(additionalProperties .get(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE).toString())); } + if (additionalProperties.containsKey(CodegenConstants.AUTOSET_CONSTANTS)) { + this.setAutosetConstants( + Boolean.parseBoolean(additionalProperties.get(CodegenConstants.AUTOSET_CONSTANTS).toString())); + } } /*** @@ -493,28 +505,28 @@ public Map postProcessAllModels(Map objs) } } - for (CodegenProperty property : model.allVars){ + for (CodegenProperty property : model.allVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.vars){ + for (CodegenProperty property : model.vars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.readWriteVars){ + for (CodegenProperty property : model.readWriteVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.optionalVars){ + for (CodegenProperty property : model.optionalVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.parentVars){ + for (CodegenProperty property : model.parentVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.requiredVars){ + for (CodegenProperty property : model.requiredVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.readOnlyVars){ + for (CodegenProperty property : model.readOnlyVars) { property.isNew = codegenPropertyIsNew(model, property); } - for (CodegenProperty property : model.nonNullableVars){ + for (CodegenProperty property : model.nonNullableVars) { property.isNew = codegenPropertyIsNew(model, property); } } @@ -575,8 +587,8 @@ public Map postProcessAllModels(Map objs) private boolean codegenPropertyIsNew(CodegenModel model, CodegenProperty property) { return model.parentModel == null - ? false - : model.parentModel.allVars.stream().anyMatch(p -> p.name.equals(property.name) && (p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false)); + ? false + : model.parentModel.allVars.stream().anyMatch(p -> p.name.equals(property.name) && (p.dataType.equals(property.dataType) == false || p.datatypeWithEnum.equals(property.datatypeWithEnum) == false)); } /** @@ -738,7 +750,7 @@ public void setCircularReferences(Map models) { models.keySet().forEach(name -> setCircularReferencesOnProperties(name, oneOfDependencyMap)); } - private List getModelDependencies( List vars) { + private List getModelDependencies(List vars) { return vars.stream() .map(prop -> { if (prop.isContainer) { @@ -917,12 +929,7 @@ public String toEnumVarName(String value, String datatype) { } } - /** - * Set the OpenAPI document. - * This method is invoked when the input OpenAPI document has been parsed and validated. - */ - @Override - public void setOpenAPI(OpenAPI openAPI) { + public boolean specVersionGreaterThanOrEqualTo310(OpenAPI openAPI) { String originalSpecVersion; String xOriginalSwaggerVersion = "x-original-swagger-version"; if (openAPI.getExtensions() != null && !openAPI.getExtensions().isEmpty() && openAPI.getExtensions().containsValue(xOriginalSwaggerVersion)) { @@ -932,8 +939,16 @@ public void setOpenAPI(OpenAPI openAPI) { } Integer specMajorVersion = Integer.parseInt(originalSpecVersion.substring(0, 1)); Integer specMinorVersion = Integer.parseInt(originalSpecVersion.substring(2, 3)); - boolean specVersionGreaterThanOrEqualTo310 = (specMajorVersion == 3 && specMinorVersion >= 1); - if (specVersionGreaterThanOrEqualTo310) { + return specMajorVersion == 3 && specMinorVersion >= 1; + } + + /** + * Set the OpenAPI document. + * This method is invoked when the input OpenAPI document has been parsed and validated. + */ + @Override + public void setOpenAPI(OpenAPI openAPI) { + if (specVersionGreaterThanOrEqualTo310(openAPI)) { LOGGER.warn(UNSUPPORTED_V310_SPEC_MSG); } this.openAPI = openAPI; @@ -963,6 +978,13 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + return objs; + } + // override with any special post-processing @Override @SuppressWarnings("static-method") @@ -976,6 +998,12 @@ public Map postProcessSupportingFileData(Map obj public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { } + // override to post-process any response + @Override + @SuppressWarnings("unused") + public void postProcessResponseWithProperty(CodegenResponse response, CodegenProperty property) { + } + // override to post-process any parameters @Override @SuppressWarnings("unused") @@ -1012,7 +1040,7 @@ public void preprocessOpenAPI(OpenAPI openAPI) { if (op.getValue().getResponses() != null) { for (Map.Entry ar : op.getValue().getResponses().entrySet()) { ApiResponse a = ModelUtils.getReferencedApiResponse(openAPI, ar.getValue()); - Schema responseSchema = ModelUtils.getSchemaFromResponse(a); + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, a)); if (responseSchema != null) { schemas.put(opId + ar.getKey(), responseSchema); } @@ -1198,6 +1226,11 @@ public Set languageSpecificPrimitives() { return languageSpecificPrimitives; } + @Override + public Set openapiGeneratorIgnoreList() { + return openapiGeneratorIgnoreList; + } + @Override public Map importMapping() { return importMapping; @@ -1233,6 +1266,11 @@ public Map modelNameMapping() { return modelNameMapping; } + @Override + public Map enumNameMapping() { + return enumNameMapping; + } + @Override public Map openapiNormalizer() { return openapiNormalizer; @@ -2672,7 +2710,7 @@ public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; NamedSchema that = (NamedSchema) o; - return Objects.equals(required, that.required) && + return Objects.equals(required, that.required) && Objects.equals(name, that.name) && Objects.equals(schema, that.schema) && Objects.equals(schemaIsFromAdditionalProperties, that.schemaIsFromAdditionalProperties); @@ -2887,7 +2925,11 @@ private void mergeProperties(Map existingProperties, Map + existingProperties.put( + key, + AnnotationsUtils.clone(value, specVersionGreaterThanOrEqualTo310(openAPI)) + )); if (null != existingType && null != newType && null != newType.getEnum() && !newType.getEnum().isEmpty()) { for (Object e : newType.getEnum()) { // ensure all interface enum types are added to schema @@ -2961,7 +3003,7 @@ protected Object processTestExampleData(Object data) { private HashMap extractSchemaTestCases(String refToTestCases) { // schemaName to a map of test case name to test case HashMap vendorExtensions = (HashMap) openAPI.getComponents().getExtensions(); - if (vendorExtensions == null || !vendorExtensions.containsKey(xSchemaTestExamplesKey)) { + if (vendorExtensions == null || !vendorExtensions.containsKey(xSchemaTestExamplesKey)) { return null; } if (!refToTestCases.startsWith(xSchemaTestExamplesRefPrefix)) { @@ -2975,7 +3017,7 @@ private HashMap extractSchemaTestCases(String refToTestC return null; } LinkedHashMap> testNameToTesCase = (LinkedHashMap>) schemaNameToTestCases.get(schemaName); - for (Entry> entry: testNameToTesCase.entrySet()) { + for (Entry> entry : testNameToTesCase.entrySet()) { LinkedHashMap testExample = (LinkedHashMap) entry.getValue(); String nameInSnakeCase = toTestCaseName(entry.getKey()); Object data = processTestExampleData(testExample.get("data")); @@ -3009,6 +3051,9 @@ protected void updateModelForString(CodegenModel model, Schema schema) { // NOTE: UUID schemas as CodegenModel is a rare use case and may be removed at a later date. model.setIsString(false); model.setIsUuid(true); + } else if (ModelUtils.isURISchema(schema)) { + model.setIsString(false); + model.setIsUri(true); } } @@ -3552,10 +3597,10 @@ protected List getAllOfDescendants(String thisSchemaName) { Schema cs = schemas.get(currentSchemaName); Map vendorExtensions = cs.getExtensions(); String mappingName = - Optional.ofNullable(vendorExtensions) - .map(ve -> ve.get("x-discriminator-value")) - .map(discriminatorValue -> (String) discriminatorValue) - .orElse(currentSchemaName); + Optional.ofNullable(vendorExtensions) + .map(ve -> ve.get("x-discriminator-value")) + .map(discriminatorValue -> (String) discriminatorValue) + .orElse(currentSchemaName); MappedModel mm = new MappedModel(mappingName, toModelName(currentSchemaName), !mappingName.equals(currentSchemaName)); descendentSchemas.add(mm); } @@ -3581,12 +3626,12 @@ protected CodegenDiscriminator createDiscriminator(String schemaName, Schema sch // for example). Handling those scenarios is too complicated for me, I'm leaving it for // the future.. String propertyType = - Optional.ofNullable(schema.getProperties()) - .map(p -> (Schema) p.get(discriminatorPropertyName)) - .map(Schema::get$ref) - .map(ModelUtils::getSimpleRef) - .map(this::toModelName) - .orElseGet(() -> typeMapping.get("string")); + Optional.ofNullable(schema.getProperties()) + .map(p -> (Schema) p.get(discriminatorPropertyName)) + .map(Schema::get$ref) + .map(ModelUtils::getSimpleRef) + .map(this::toModelName) + .orElseGet(() -> typeMapping.get("string")); discriminator.setPropertyType(propertyType); // check to see if the discriminator property is an enum string @@ -3624,7 +3669,7 @@ protected CodegenDiscriminator createDiscriminator(String schemaName, Schema sch boolean matched = false; for (MappedModel uniqueDescendant : uniqueDescendants) { if (uniqueDescendant.getMappingName().equals(otherDescendant.getMappingName()) - || (uniqueDescendant.getModelName().equals(otherDescendant.getModelName()))) { + || (uniqueDescendant.getModelName().equals(otherDescendant.getModelName()))) { matched = true; break; } @@ -3679,6 +3724,10 @@ protected void addProperties(Map properties, List requir return; } if (ModelUtils.isComposedSchema(schema)) { + // fix issue #16797 and #15796, constructor fail by missing parent required params + if (schema.getProperties() != null && !schema.getProperties().isEmpty()) { + properties.putAll(schema.getProperties()); + } if (schema.getAllOf() != null) { for (Object component : schema.getAllOf()) { @@ -3702,6 +3751,11 @@ protected void addProperties(Map properties, List requir } } + for (String r : required) { + if (!properties.containsKey(r)) { + LOGGER.error("Required var %s not in properties", r); + } + } return; } @@ -4144,6 +4198,12 @@ public CodegenProperty fromProperty(String name, Schema p, boolean required, boo if (original.getExtensions() != null) { property.getVendorExtensions().putAll(original.getExtensions()); } + if (original.getDeprecated() != null) { + property.deprecated = p.getDeprecated(); + } + if (original.getDescription() != null) { + property.description = p.getDescription(); + } } // set the default value @@ -4372,7 +4432,7 @@ protected void handleMethodResponse(Operation operation, CodegenOperation op, ApiResponse methodResponse, Map schemaMappings) { - Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(methodResponse)); + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, methodResponse)); if (responseSchema != null) { CodegenProperty cm = fromProperty("response", responseSchema, false); @@ -4634,18 +4694,19 @@ public CodegenOperation fromOperation(String path, bodyParameterName = (String) op.vendorExtensions.get("x-codegen-request-body-name"); } bodyParam = fromRequestBody(requestBody, imports, bodyParameterName); - bodyParam.description = escapeText(requestBody.getDescription()); - postProcessParameter(bodyParam); - - bodyParams.add(bodyParam); - if (prependFormOrBodyParameters) { - allParams.add(bodyParam); - } + if (bodyParam != null) { + bodyParam.description = escapeText(requestBody.getDescription()); + postProcessParameter(bodyParam); + bodyParams.add(bodyParam); + if (prependFormOrBodyParameters) { + allParams.add(bodyParam); + } - // add example - if (schemas != null && !isSkipOperationExample()) { - op.requestBodyExamples = new ExampleGenerator(schemas, this.openAPI).generate(null, new ArrayList<>(getConsumesInfo(this.openAPI, operation)), bodyParam.baseType); + // add example + if (schemas != null && !isSkipOperationExample()) { + op.requestBodyExamples = new ExampleGenerator(schemas, this.openAPI).generate(null, new ArrayList<>(getConsumesInfo(this.openAPI, operation)), bodyParam.baseType); + } } } } @@ -4806,6 +4867,7 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { } else { r.code = responseCode; switch (r.code.charAt(0)) { + case '1': r.is1xx = true; break; @@ -4828,12 +4890,11 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { Schema responseSchema; if (this.openAPI != null && this.openAPI.getComponents() != null) { - responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(response)); + responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, response)); } else { // no model/alias defined - responseSchema = ModelUtils.getSchemaFromResponse(response); + responseSchema = ModelUtils.getSchemaFromResponse(openAPI, response); } r.schema = responseSchema; - r.message = escapeText(response.getDescription()); // TODO need to revise and test examples in responses // ApiResponse does not support examples at the moment @@ -4959,6 +5020,7 @@ public CodegenResponse fromResponse(String responseCode, ApiResponse response) { r.simpleType = true; } + postProcessResponseWithProperty(r, cp); return r; } @@ -5682,6 +5744,10 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera co.baseName = tag; } + protected void addParentFromContainer(CodegenModel model, Schema schema) { + model.parent = toInstantiationType(schema); + } + /** * Sets the value of the 'model.parent' property in CodegenModel, based on the value * of the 'additionalProperties' keyword. Some language generator use class inheritance @@ -5701,7 +5767,7 @@ public void addOperationToGroup(String tag, String resourcePath, Operation opera protected void addParentContainer(CodegenModel model, String name, Schema schema) { final CodegenProperty property = fromProperty(name, schema, false); addImport(model, property.complexType); - model.parent = toInstantiationType(schema); + addParentFromContainer(model, schema); final String instantiationType = instantiationTypes.get(property.containerType); if (instantiationType != null) { addImport(model, instantiationType); @@ -5764,7 +5830,7 @@ protected void addImport(Set importsToBeAddedTo, String type) { * @param model codegen model * @param modelName model name */ - protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName ) { + protected void addImport(Schema composed, Schema childSchema, CodegenModel model, String modelName) { if (composed == null || childSchema == null) { return; } @@ -5932,7 +5998,7 @@ protected void addVars(IJsonSchemaValidationProperties m, List cm.readWriteVars.add(cp); } - if (Boolean.FALSE.equals(cp.isNullable)){ + if (Boolean.FALSE.equals(cp.isNullable)) { cm.nonNullableVars.add(cp); } } @@ -5980,21 +6046,31 @@ Map getAllAliases(Map schemas) { for (Map.Entry entry : schemas.entrySet()) { Schema schema = entry.getValue(); if (isAliasOfSimpleTypes(schema)) { - String oasName = entry.getKey(); - String schemaType = getPrimitiveType(schema); - aliases.put(oasName, schemaType); + if (schema.getAllOf() != null && schema.getAllOf().size() == 1) { // allOf with a single item + Schema unaliasSchema = unaliasSchema(schema); + unaliasSchema = ModelUtils.getReferencedSchema(this.openAPI, unaliasSchema); + aliases.put(entry.getKey() /* schema name, e.g. Pet */, getPrimitiveType(unaliasSchema)); + } else { + aliases.put(entry.getKey() /* schema name, e.g. Pet */, getPrimitiveType(schema)); + } } - } return aliases; } - private static Boolean isAliasOfSimpleTypes(Schema schema) { + private Boolean isAliasOfSimpleTypes(Schema schema) { if (schema == null) { return false; } + // allOf with a single item + if (schema.getAllOf() != null && schema.getAllOf().size() == 1 + && schema.getAllOf().get(0) instanceof Schema) { + schema = unaliasSchema((Schema) schema.getAllOf().get(0)); + schema = ModelUtils.getReferencedSchema(this.openAPI, schema); + } + return (!ModelUtils.isObjectSchema(schema) && !ModelUtils.isArraySchema(schema) && !ModelUtils.isMapSchema(schema) @@ -6630,14 +6706,14 @@ protected List> buildEnumVars(List values, String da String enumName = enumUnknownDefaultCaseName; String enumValue = isDataTypeString(dataType) - ? enumUnknownDefaultCaseName - : // This is a dummy value that attempts to avoid collisions with previously specified cases. - // Int.max / 192 - // The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums. - // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) - // Since this functionality was born in the Swift 5 generator and latter on broth to all generators - // https://github.com/OpenAPITools/openapi-generator/pull/11013 - String.valueOf(11184809); + ? enumUnknownDefaultCaseName + : // This is a dummy value that attempts to avoid collisions with previously specified cases. + // Int.max / 192 + // The number 192 that is used to calculate this random value, is the Swift Evolution proposal for frozen/non-frozen enums. + // [SE-0192](https://github.com/apple/swift-evolution/blob/master/proposals/0192-non-exhaustive-enums.md) + // Since this functionality was born in the Swift 5 generator and latter on broth to all generators + // https://github.com/OpenAPITools/openapi-generator/pull/11013 + String.valueOf(11184809); enumVar.put("name", toEnumVarName(enumName, dataType)); enumVar.put("value", toEnumValue(enumValue, dataType)); @@ -6665,8 +6741,8 @@ protected void postProcessEnumVars(List> enumVars) { private String getUniqueEnumName(String name, List> enumVars) { long count = enumVars.stream().filter(v -> v.get("name").equals(name)).count(); return count > 1 - ? getUniqueEnumName(name + count, enumVars) - : name; + ? getUniqueEnumName(name + count, enumVars) + : name; } protected void updateEnumVarsWithExtensions(List> enumVars, Map vendorExtensions, String dataType) { @@ -6959,10 +7035,10 @@ public List fromRequestBodyToFormParameters(RequestBody body, LOGGER.debug("debugging fromRequestBodyToFormParameters= {}", body); Schema schema = ModelUtils.getSchemaFromRequestBody(body); schema = ModelUtils.getReferencedSchema(this.openAPI, schema); - if(ModelUtils.isMapSchema(schema)) { + if (ModelUtils.isMapSchema(schema)) { LOGGER.error("Form parameters with additionalProperties are not supported by OpenAPI Generator. Please report the issue to https://github.com/openapitools/openapi-generator if you need help."); } - if(ModelUtils.isArraySchema(schema)) { + if (ModelUtils.isArraySchema(schema)) { LOGGER.error("Array form parameters are not supported by OpenAPI Generator. Please report the issue to https://github.com/openapitools/openapi-generator if you need help."); } @@ -7201,7 +7277,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name codegenParameter.description = codegenModel.description; codegenParameter.isNullable = codegenModel.isNullable; imports.add(codegenParameter.baseType); - } else { + } else { CodegenProperty codegenProperty = fromProperty("property", schema, false); if (codegenProperty != null && codegenProperty.getComplexType() != null && codegenProperty.getComplexType().contains(" | ")) { @@ -7248,7 +7324,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name codegenParameter.description = codegenModelDescription; imports.add(codegenParameter.baseType); - if (codegenProperty.complexType != null) { + if (codegenProperty.complexType != null && codegenProperty.getComposedSchemas() == null) { imports.add(codegenProperty.complexType); } } @@ -7260,7 +7336,7 @@ protected void addBodyModelSchema(CodegenParameter codegenParameter, String name } protected void updateRequestBodyForMap(CodegenParameter codegenParameter, Schema schema, String name, Set imports, String bodyParameterName) { - if (StringUtils.isNotBlank(name)) { + if (StringUtils.isNotBlank(name) && !(ModelUtils.isFreeFormObject(schema) && !ModelUtils.shouldGenerateFreeFormObjectModel(name, this))) { this.addBodyModelSchema(codegenParameter, name, schema, imports, bodyParameterName, true); } else { Schema inner = ModelUtils.getAdditionalProperties(schema); @@ -7526,9 +7602,9 @@ protected LinkedHashMap getContent(Content content, Se } CodegenMediaType codegenMt; - if(mt.getExamples() != null) { + if (mt.getExamples() != null) { codegenMt = new CodegenMediaType(schemaProp, ceMap, schemaTestCases, mt.getExamples()); - } else if(mt.getExample() != null) { + } else if (mt.getExample() != null) { codegenMt = new CodegenMediaType(schemaProp, ceMap, schemaTestCases, mt.getExample()); } else { codegenMt = new CodegenMediaType(schemaProp, ceMap, schemaTestCases); @@ -7564,8 +7640,23 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S String name = null; LOGGER.debug("Request body = {}", body); Schema schema = ModelUtils.getSchemaFromRequestBody(body); - codegenParameter.setContent(getContent(body.getContent(), imports, "RequestBody")); + if (schema == null) { + LOGGER.error("Schema cannot be null in the request body: {}", body); + return null; + } + Schema original = null; + // check if it's allOf (only 1 sub schema) with or without default/nullable/etc set in the top level + if (ModelUtils.isAllOf(schema) && schema.getAllOf().size() == 1 && + schema.getType() == null && schema.getTypes() == null) { + if (schema.getAllOf().get(0) instanceof Schema) { + original = schema; + schema = (Schema) schema.getAllOf().get(0); + } else { + LOGGER.error("Unknown type in allOf schema. Please report the issue via openapi-generator's Github issue tracker."); + } + } + codegenParameter.setContent(getContent(body.getContent(), imports, "RequestBody")); if (StringUtils.isNotBlank(schema.get$ref())) { name = ModelUtils.getSimpleRef(schema.get$ref()); } @@ -7634,6 +7725,24 @@ public CodegenParameter fromRequestBody(RequestBody body, Set imports, S // should be overridden by lang codegen setParameterExampleValue(codegenParameter, body); + // restore original schema with description, extensions etc + if (original != null) { + schema = original; + // evaluate common attributes such as description if defined in the top level + if (schema.getDescription() != null) { + codegenParameter.description = escapeText(schema.getDescription()); + codegenParameter.unescapedDescription = schema.getDescription(); + } + + if (original.getExtensions() != null) { + codegenParameter.vendorExtensions.putAll(original.getExtensions()); + } + + if (original.getDeprecated() != null) { + codegenParameter.isDeprecated = original.getDeprecated(); + } + } + return codegenParameter; } @@ -7651,13 +7760,13 @@ protected void addRequiredVarsMap(Schema schema, IJsonSchemaValidationProperties if (requiredPropertyNames == null) { return; } - for (String requiredPropertyName: requiredPropertyNames) { + for (String requiredPropertyName : requiredPropertyNames) { // required property is defined in properties, value is that CodegenProperty String usedRequiredPropertyName = handleSpecialCharacters(requiredPropertyName); if (properties != null && properties.containsKey(requiredPropertyName)) { // get cp from property boolean found = false; - for (CodegenProperty cp: property.getVars()) { + for (CodegenProperty cp : property.getVars()) { if (cp.baseName.equals(requiredPropertyName)) { found = true; requiredVarsMap.put(requiredPropertyName, cp); @@ -7665,7 +7774,8 @@ protected void addRequiredVarsMap(Schema schema, IJsonSchemaValidationProperties } } if (found == false) { - throw new RuntimeException("Property " + requiredPropertyName + " is missing from getVars"); + LOGGER.warn("Property {} is not processed correctly (missing from getVars). Maybe it's a const (not yet supported) in openapi v3.1 spec.", requiredPropertyName); + continue; } } else if (schema.getAdditionalProperties() instanceof Boolean && Boolean.FALSE.equals(schema.getAdditionalProperties())) { // TODO add processing for requiredPropertyName @@ -8247,6 +8357,11 @@ public List getSupportedVendorExtensions() { @Override public boolean getUseOpenAPINormalizer() { return true; } + @Override + public Set getOpenAPIGeneratorIgnoreList() { + return openapiGeneratorIgnoreList; + } + /* A function to convert yaml or json ingested strings like property names And convert special characters like newline, tab, carriage return @@ -8281,4 +8396,47 @@ protected Schema getSchemaFromBooleanOrSchema(Object schema) { throw new IllegalArgumentException("Invalid schema type; type must be Boolean or Schema"); } } + + public void setAutosetConstants(boolean autosetConstants) { + this.autosetConstants = autosetConstants; + } + + /** + * This method removes all constant Query, Header and Cookie Params from allParams and sets them as constantParams in the CodegenOperation. + * The definition of constant is single valued required enum params. + * The constantParams in the the generated code should be hardcoded to the constantValue if autosetConstants feature is enabled. + * + * @param operation - operation to be processed + */ + protected void handleConstantParams(CodegenOperation operation) { + if (!autosetConstants || operation.allParams.isEmpty()) { + return; + } + final ArrayList copy = new ArrayList<>(operation.allParams); + // Remove all params from Params, Non constant params will be added back later. + operation.allParams.clear(); + + // Finds all constant params, removes them from allParams and adds them to constant params. + // Also, adds back non constant params to allParams. + for (CodegenParameter p : copy) { + if (p.isEnum && p.required && p._enum != null && p._enum.size() == 1) { + // Add to constantParams for use in the code generation templates. + operation.constantParams.add(p); + if (p.isQueryParam) { + operation.queryParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + if (p.isHeaderParam) { + operation.headerParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + if (p.isCookieParam) { + operation.cookieParams.removeIf(param -> param.baseName.equals(p.baseName)); + } + LOGGER.info("Update operation [{}]. Remove parameter [{}] because it can only have a fixed value of [{}]", operation.operationId, p.baseName, p._enum.get(0)); + } else { + // Add back to allParams as the param is not a constant. + operation.allParams.add(p); + } + } + operation.hasParams = !operation.allParams.isEmpty(); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java index 7d80a710940e..6af7f8cfb430 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/DefaultGenerator.java @@ -36,19 +36,13 @@ import org.openapitools.codegen.api.TemplateDefinition; import org.openapitools.codegen.api.TemplatePathLocator; import org.openapitools.codegen.api.TemplateProcessor; -import org.openapitools.codegen.config.GeneratorSettings; import org.openapitools.codegen.config.GlobalSettings; import org.openapitools.codegen.api.TemplatingEngineAdapter; import org.openapitools.codegen.api.TemplateFileType; import org.openapitools.codegen.ignore.CodegenIgnoreProcessor; -import org.openapitools.codegen.languages.CSharpClientCodegen; import org.openapitools.codegen.meta.GeneratorMetadata; import org.openapitools.codegen.meta.Stability; -import org.openapitools.codegen.model.ApiInfoMap; -import org.openapitools.codegen.model.ModelMap; -import org.openapitools.codegen.model.ModelsMap; -import org.openapitools.codegen.model.OperationMap; -import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.model.*; import org.openapitools.codegen.serializer.SerializerUtils; import org.openapitools.codegen.templating.CommonTemplateContentLocator; import org.openapitools.codegen.templating.GeneratorTemplateContentLocator; @@ -65,6 +59,7 @@ import java.io.*; import java.net.URL; import java.nio.charset.StandardCharsets; +import java.nio.file.Files; import java.nio.file.Path; import java.time.ZonedDateTime; import java.util.*; @@ -87,6 +82,7 @@ public class DefaultGenerator implements Generator { private Boolean generateApis = null; private Boolean generateModels = null; private Boolean generateSupportingFiles = null; + private Boolean generateWebhooks = null; private Boolean generateApiTests = null; private Boolean generateApiDocumentation = null; private Boolean generateModelTests = null; @@ -99,6 +95,8 @@ public class DefaultGenerator implements Generator { protected TemplateProcessor templateProcessor = null; private List userDefinedTemplates = new ArrayList<>(); + private String generatorCheck = "spring"; + private String templateCheck = "apiController.mustache"; public DefaultGenerator() { @@ -209,10 +207,11 @@ void configureGeneratorProperties() { generateApis = GlobalSettings.getProperty(CodegenConstants.APIS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.APIS, null); generateModels = GlobalSettings.getProperty(CodegenConstants.MODELS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.MODELS, null); generateSupportingFiles = GlobalSettings.getProperty(CodegenConstants.SUPPORTING_FILES) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.SUPPORTING_FILES, null); + generateWebhooks = GlobalSettings.getProperty(CodegenConstants.WEBHOOKS) != null ? Boolean.TRUE : getGeneratorPropertyDefaultSwitch(CodegenConstants.WEBHOOKS, null); - if (generateApis == null && generateModels == null && generateSupportingFiles == null) { + if (generateApis == null && generateModels == null && generateSupportingFiles == null && generateWebhooks == null) { // no specifics are set, generate everything - generateApis = generateModels = generateSupportingFiles = true; + generateApis = generateModels = generateSupportingFiles = generateWebhooks = true; } else { if (generateApis == null) { generateApis = false; @@ -223,6 +222,9 @@ void configureGeneratorProperties() { if (generateSupportingFiles == null) { generateSupportingFiles = false; } + if (generateWebhooks == null) { + generateWebhooks = false; + } } // model/api tests and documentation options rely on parent generate options (api or model) and no other options. // They default to true in all scenarios and can only be marked false explicitly @@ -240,6 +242,7 @@ void configureGeneratorProperties() { config.additionalProperties().put(CodegenConstants.GENERATE_APIS, generateApis); config.additionalProperties().put(CodegenConstants.GENERATE_MODELS, generateModels); + config.additionalProperties().put(CodegenConstants.GENERATE_WEBHOOKS, generateWebhooks); if (!generateApiTests && !generateModelTests) { config.additionalProperties().put(CodegenConstants.EXCLUDE_TESTS, true); @@ -506,16 +509,7 @@ void generateModels(List files, List allModels, List unu Schema schema = schemas.get(name); if (ModelUtils.isFreeFormObject(schema)) { // check to see if it's a free-form object - // there are 3 free form use cases - // 1. free form with no validation that is not allOf included in any composed schemas - // 2. free form with validation - // 3. free form that is allOf included in any composed schemas - // this use case arises when using interface schemas - // generators may choose to make models for use case 2 + 3 - Schema refSchema = new Schema(); - refSchema.set$ref("#/components/schemas/" + name); - Schema unaliasedSchema = config.unaliasSchema(refSchema); - if (unaliasedSchema.get$ref() == null) { + if (!ModelUtils.shouldGenerateFreeFormObjectModel(name, config)) { LOGGER.info("Model {} not generated since it's a free-form object", name); continue; } @@ -606,7 +600,7 @@ void generateApis(List files, List allOperations, List> paths = processPaths(this.openAPI.getPaths()); Set apisToGenerate = null; - String apiNames = GlobalSettings.getProperty("apis"); + String apiNames = GlobalSettings.getProperty(CodegenConstants.APIS); if (apiNames != null && !apiNames.isEmpty()) { apisToGenerate = new HashSet<>(Arrays.asList(apiNames.split(","))); } @@ -694,14 +688,23 @@ void generateApis(List files, List allOperations, List files, List allOperations, List files, List allWebhooks, List allModels) { + if (!generateWebhooks) { + // TODO: Process these anyway and present info via dryRun? + LOGGER.info("Skipping generation of Webhooks."); + return; + } + Map> webhooks = processWebhooks(this.openAPI.getWebhooks()); + Set webhooksToGenerate = null; + String webhookNames = GlobalSettings.getProperty(CodegenConstants.WEBHOOKS); + if (webhookNames != null && !webhookNames.isEmpty()) { + webhooksToGenerate = new HashSet<>(Arrays.asList(webhookNames.split(","))); + } + if (webhooksToGenerate != null && !webhooksToGenerate.isEmpty()) { + Map> Webhooks = new TreeMap<>(); + for (String m : webhooks.keySet()) { + if (webhooksToGenerate.contains(m)) { + Webhooks.put(m, webhooks.get(m)); + } + } + webhooks = Webhooks; + } + for (String tag : webhooks.keySet()) { + try { + List wks = webhooks.get(tag); + wks.sort((one, another) -> ObjectUtils.compare(one.operationId, another.operationId)); + WebhooksMap operation = processWebhooks(config, tag, wks, allModels); + URL url = URLPathUtils.getServerURL(openAPI, config.serverVariableOverrides()); + operation.put("basePath", basePath); + operation.put("basePathWithoutHost", removeTrailingSlash(config.encodePath(url.getPath()))); + operation.put("contextPath", contextPath); + operation.put("baseName", tag); + Optional.ofNullable(openAPI.getTags()).orElseGet(Collections::emptyList).stream() + .map(Tag::getName) + .filter(Objects::nonNull) + .filter(tag::equalsIgnoreCase) + .findFirst() + .ifPresent(tagName -> operation.put("operationTagName", config.escapeText(tagName))); + operation.put("operationTagDescription", ""); + Optional.ofNullable(openAPI.getTags()).orElseGet(Collections::emptyList).stream() + .filter(t -> tag.equalsIgnoreCase(t.getName())) + .map(Tag::getDescription) + .filter(Objects::nonNull) + .findFirst() + .ifPresent(description -> operation.put("operationTagDescription", config.escapeText(description))); + Optional.ofNullable(config.additionalProperties().get("appVersion")).ifPresent(version -> operation.put("version", version)); + operation.put("apiPackage", config.apiPackage()); + operation.put("modelPackage", config.modelPackage()); + operation.putAll(config.additionalProperties()); + operation.put("classname", config.toApiName(tag)); + operation.put("classVarName", config.toApiVarName(tag)); + operation.put("importPath", config.toApiImport(tag)); + operation.put("classFilename", config.toApiFilename(tag)); + operation.put("strictSpecBehavior", config.isStrictSpecBehavior()); + Optional.ofNullable(openAPI.getInfo()).map(Info::getLicense).ifPresent(license -> operation.put("license", license)); + Optional.ofNullable(openAPI.getInfo()).map(Info::getContact).ifPresent(contact -> operation.put("contact", contact)); + + if (allModels == null || allModels.isEmpty()) { + operation.put("hasModel", false); + } else { + operation.put("hasModel", true); + } + + if (!config.vendorExtensions().isEmpty()) { + operation.put("vendorExtensions", config.vendorExtensions()); + } + + // process top-level x-group-parameters + if (config.vendorExtensions().containsKey("x-group-parameters")) { + boolean isGroupParameters = Boolean.parseBoolean(config.vendorExtensions().get("x-group-parameters").toString()); + + OperationMap objectMap = operation.getWebhooks(); + List operations = objectMap.getOperation(); + for (CodegenOperation op : operations) { + if (isGroupParameters && !op.vendorExtensions.containsKey("x-group-parameters")) { + op.vendorExtensions.put("x-group-parameters", Boolean.TRUE); + } + } + } + + // Pass sortParamsByRequiredFlag through to the Mustache template... + boolean sortParamsByRequiredFlag = true; + if (this.config.additionalProperties().containsKey(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG)) { + sortParamsByRequiredFlag = Boolean.parseBoolean(this.config.additionalProperties().get(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG).toString()); + } + operation.put("sortParamsByRequiredFlag", sortParamsByRequiredFlag); + + /* consumes, produces are no longer defined in OAS3.0 + processMimeTypes(swagger.getConsumes(), operation, "consumes"); + processMimeTypes(swagger.getProduces(), operation, "produces"); + */ + + allWebhooks.add(operation); + + addAuthenticationSwitches(operation); + + for (String templateName : config.apiTemplateFiles().keySet()) { + File written = null; + if (config.templateOutputDirs().containsKey(templateName)) { + String outputDir = config.getOutputDir() + File.separator + config.templateOutputDirs().get(templateName); + String filename = config.apiFilename(templateName, tag, outputDir); + // do not overwrite apiController file for spring server + if (apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){ + written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS, outputDir); + } else { + LOGGER.info("Implementation file {} is not overwritten",filename); + } + } else { + String filename = config.apiFilename(templateName, tag); + if(apiFilePreCheck(filename, generatorCheck, templateName, templateCheck)){ + written = processTemplateToFile(operation, templateName, filename, generateWebhooks, CodegenConstants.WEBHOOKS); + } else { + LOGGER.info("Implementation file {} is not overwritten",filename); + } + } + if (written != null) { + files.add(written); + if (config.isEnablePostProcessFile() && !dryRun) { + config.postProcessFile(written, "api"); + } + } + } + + // to generate api test files + for (String templateName : config.apiTestTemplateFiles().keySet()) { + String filename = config.apiTestFilename(templateName, tag); + File apiTestFile = new File(filename); + // do not overwrite test file that already exists + if (apiTestFile.exists()) { + this.templateProcessor.skip(apiTestFile.toPath(), "Test files never overwrite an existing file of the same name."); + } else { + File written = processTemplateToFile(operation, templateName, filename, generateApiTests, CodegenConstants.API_TESTS, config.apiTestFileFolder()); + if (written != null) { + files.add(written); + if (config.isEnablePostProcessFile() && !dryRun) { + config.postProcessFile(written, "api-test"); + } + } + } + } + + // to generate api documentation files + for (String templateName : config.apiDocTemplateFiles().keySet()) { + String filename = config.apiDocFilename(templateName, tag); + File written = processTemplateToFile(operation, templateName, filename, generateApiDocumentation, CodegenConstants.API_DOCS); + if (written != null) { + files.add(written); + if (config.isEnablePostProcessFile() && !dryRun) { + config.postProcessFile(written, "api-doc"); + } + } + } + + } catch (Exception e) { + throw new RuntimeException("Could not generate api file for '" + tag + "'", e); + } + } + if (GlobalSettings.getProperty("debugOperations") != null) { + LOGGER.info("############ Operation info ############"); + Json.prettyPrint(allWebhooks); + } + + } + + // checking if apiController file is already existed for spring generator + private boolean apiFilePreCheck(String filename, String generator, String templateName, String apiControllerTemplate) { + File apiFile = new File(filename); + return !(apiFile.exists() && config.getName().equals(generator) && templateName.equals(apiControllerTemplate)); + } + + /* + * Generate .openapi-generator-ignore if the option openapiGeneratorIgnoreFile is enabled. + */ + private void generateOpenAPIGeneratorIgnoreFile() { + if (config.getOpenAPIGeneratorIgnoreList() == null || config.getOpenAPIGeneratorIgnoreList().isEmpty()) { + return; + } + + final String openapiGeneratorIgnore = ".openapi-generator-ignore"; + String ignoreFileNameTarget = config.outputFolder() + File.separator + openapiGeneratorIgnore; + File ignoreFile = new File(ignoreFileNameTarget); + // use the entries provided by the users to pre-populate .openapi-generator-ignore + try { + LOGGER.info("Writing file " + ignoreFileNameTarget + " (which is always overwritten when the option `openapiGeneratorIgnoreFile` is enabled.)"); + new File(config.outputFolder()).mkdirs(); + if (!ignoreFile.createNewFile()) { + // file may already exist, do nothing + } + + String header = String.join("\n", + "# IMPORTANT: this file is generated with the option `openapiGeneratorIgnoreList` enabled", + "# (--openapi-generator-ignore-list in CLI for example) so the entries below are pre-populated based", + "# on the input provided by the users and this file will be overwritten every time when the option is", + "# enabled (which is the exact opposite of the default behaviour to not overwrite", + "# .openapi-generator-ignore if the file exists).", + "", + "# OpenAPI Generator Ignore", + "# Generated by openapi-generator https://github.com/openapitools/openapi-generator", + "", + "# Use this file to prevent files from being overwritten by the generator.", + "# The patterns follow closely to .gitignore or .dockerignore.", + "", + "# As an example, the C# client generator defines ApiClient.cs.", + "# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line:", + "#ApiClient.cs", + "", + "# You can match any string of characters against a directory, file or extension with a single asterisk (*):", + "#foo/*/qux", + "# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux", + "", + "# You can recursively match patterns against a directory, file or extension with a double asterisk (**):", + "#foo/**/qux", + "# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux", + "", + "# You can also negate patterns with an exclamation (!).", + "# For example, you can ignore all files in a docs folder with the file extension .md:", + "#docs/*.md", + "# Then explicitly reverse the ignore rule for a single file:", + "#!docs/README.md", + "", + "# The following entries are pre-populated based on the input obtained via", + "# the option `openapiGeneratorIgnoreList` (--openapi-generator-ignore-list in CLI for example).", + ""); + Writer fileWriter = Files.newBufferedWriter(ignoreFile.toPath(), StandardCharsets.UTF_8); + fileWriter.write(header); + // add entries provided by the users + for (String entry : config.getOpenAPIGeneratorIgnoreList()) { + fileWriter.write(entry); + fileWriter.write("\n"); + } + fileWriter.close(); + // re-create ignore processor based on the newly-created .openapi-generator-ignore + this.ignoreProcessor = new CodegenIgnoreProcessor(ignoreFile); + } catch (IOException e) { + throw new RuntimeException("Failed to generate .openapi-generator-ignore when the option `openapiGeneratorIgnoreList` is enabled: ", e); + } + } + private void generateSupportingFiles(List files, Map bundle) { if (!generateSupportingFiles) { // TODO: process these anyway and report via dryRun? LOGGER.info("Skipping generation of supporting files."); return; } + Set supportingFilesToGenerate = null; String supportingFiles = GlobalSettings.getProperty(CodegenConstants.SUPPORTING_FILES); if (supportingFiles != null && !supportingFiles.isEmpty()) { @@ -802,33 +1043,40 @@ private void generateSupportingFiles(List files, Map bundl // Consider .openapi-generator-ignore a supporting file // Output .openapi-generator-ignore if it doesn't exist and wasn't explicitly created by a generator - final String openapiGeneratorIgnore = ".openapi-generator-ignore"; - String ignoreFileNameTarget = config.outputFolder() + File.separator + openapiGeneratorIgnore; - File ignoreFile = new File(ignoreFileNameTarget); - if (generateMetadata) { - try { - boolean shouldGenerate = !ignoreFile.exists(); - if (shouldGenerate && supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) { - shouldGenerate = supportingFilesToGenerate.contains(openapiGeneratorIgnore); - } - File written = processTemplateToFile(bundle, openapiGeneratorIgnore, ignoreFileNameTarget, shouldGenerate, CodegenConstants.SUPPORTING_FILES); - if (written != null) { - files.add(written); - if (config.isEnablePostProcessFile() && !dryRun) { - config.postProcessFile(written, "openapi-generator-ignore"); + // and the option openapiGeneratorIgnoreList is not set + if (config.openapiGeneratorIgnoreList() == null || config.openapiGeneratorIgnoreList().isEmpty()) { + final String openapiGeneratorIgnore = ".openapi-generator-ignore"; + String ignoreFileNameTarget = config.outputFolder() + File.separator + openapiGeneratorIgnore; + File ignoreFile = new File(ignoreFileNameTarget); + if (generateMetadata) { + try { + boolean shouldGenerate = !ignoreFile.exists(); + if (shouldGenerate && supportingFilesToGenerate != null && !supportingFilesToGenerate.isEmpty()) { + shouldGenerate = supportingFilesToGenerate.contains(openapiGeneratorIgnore); } + File written = processTemplateToFile(bundle, openapiGeneratorIgnore, ignoreFileNameTarget, shouldGenerate, CodegenConstants.SUPPORTING_FILES); + if (written != null) { + files.add(written); + if (config.isEnablePostProcessFile() && !dryRun) { + config.postProcessFile(written, "openapi-generator-ignore"); + } + } + } catch (Exception e) { + throw new RuntimeException("Could not generate supporting file '" + ignoreFileNameTarget + "'", e); } - } catch (Exception e) { - throw new RuntimeException("Could not generate supporting file '" + ignoreFileNameTarget + "'", e); + } else { + this.templateProcessor.skip(ignoreFile.toPath(), "Skipped by generateMetadata option supplied by user."); } - } else { - this.templateProcessor.skip(ignoreFile.toPath(), "Skipped by generateMetadata option supplied by user."); } generateVersionMetadata(files); } Map buildSupportFileBundle(List allOperations, List allModels) { + return this.buildSupportFileBundle(allOperations, allModels, null); + } + + Map buildSupportFileBundle(List allOperations, List allModels, List allWebhooks) { Map bundle = new HashMap<>(config.additionalProperties()); bundle.put("apiPackage", config.apiPackage()); @@ -848,6 +1096,7 @@ Map buildSupportFileBundle(List allOperations, Li } bundle.put("contextPath", contextPath); bundle.put("apiInfo", apis); + bundle.put("webhooks", allWebhooks); bundle.put("models", allModels); bundle.put("apiFolder", config.apiPackage().replace('.', File.separatorChar)); bundle.put("modelPackage", config.modelPackage()); @@ -967,6 +1216,9 @@ public List generate() { processUserDefinedTemplates(); + // generate .openapi-generator-ignore if the option openapiGeneratorIgnoreFile is enabled + generateOpenAPIGeneratorIgnoreFile(); + List files = new ArrayList<>(); // models List filteredSchemas = ModelUtils.getSchemasUsedOnlyInFormParam(openAPI); @@ -975,9 +1227,11 @@ public List generate() { // apis List allOperations = new ArrayList<>(); generateApis(files, allOperations, allModels); - + // webhooks + List allWebhooks = new ArrayList<>(); + generateWebhooks(files, allWebhooks, allModels); // supporting files - Map bundle = buildSupportFileBundle(allOperations, allModels); + Map bundle = buildSupportFileBundle(allOperations, allModels, allWebhooks); generateSupportingFiles(files, bundle); if (dryRun) { @@ -1152,6 +1406,27 @@ public Map> processPaths(Paths paths) { return ops; } + public Map> processWebhooks(Map webhooks) { + Map> ops = new TreeMap<>(); + // when input file is not valid and doesn't contain any paths + if (webhooks == null) { + return ops; + } + for (Map.Entry webhooksEntry : webhooks.entrySet()) { + String resourceKey = webhooksEntry.getKey(); + PathItem path = webhooksEntry.getValue(); + processOperation(resourceKey, "get", path.getGet(), ops, path); + processOperation(resourceKey, "head", path.getHead(), ops, path); + processOperation(resourceKey, "put", path.getPut(), ops, path); + processOperation(resourceKey, "post", path.getPost(), ops, path); + processOperation(resourceKey, "delete", path.getDelete(), ops, path); + processOperation(resourceKey, "patch", path.getPatch(), ops, path); + processOperation(resourceKey, "options", path.getOptions(), ops, path); + processOperation(resourceKey, "trace", path.getTrace(), ops, path); + } + return ops; + } + private void processOperation(String resourcePath, String httpMethod, Operation operation, Map> operations, PathItem path) { if (operation == null) { return; @@ -1303,6 +1578,50 @@ private OperationsMap processOperations(CodegenConfig config, String tag, List wks, List allModels) { + WebhooksMap operations = new WebhooksMap(); + OperationMap objs = new OperationMap(); + objs.setClassname(config.toApiName(tag)); + objs.setPathPrefix(config.toApiVarName(tag)); + + // check for nickname uniqueness + if (config.getAddSuffixToDuplicateOperationNicknames()) { + Set opIds = new HashSet<>(); + int counter = 0; + for (CodegenOperation op : wks) { + String opId = op.nickname; + if (opIds.contains(opId)) { + counter++; + op.nickname += "_" + counter; + } + opIds.add(opId); + } + } + objs.setOperation(wks); + + operations.setWebhooks(objs); + operations.put("package", config.apiPackage()); + + Set allImports = new ConcurrentSkipListSet<>(); + for (CodegenOperation op : wks) { + allImports.addAll(op.imports); + } + + Map mappings = getAllImportsMappings(allImports); + Set> imports = toImportsObjects(mappings); + + //Some codegen implementations rely on a list interface for the imports + operations.setImports(new ArrayList<>(imports)); + + // add a flag to indicate whether there's any {{import}} + if (!imports.isEmpty()) { + operations.put("hasImport", true); + } + + config.postProcessWebhooksWithModels(operations, allModels); + return operations; + } + /** * Transforms a set of imports to a map with key config.toModelImport(import) and value the import string. * @@ -1506,7 +1825,7 @@ private List filterAuthMethods(List authMethod for (CodegenSecurity security : authMethods) { boolean filtered = false; - if (security != null && security.scopes != null) { + if (security != null) { for (SecurityRequirement requirement : securities) { List opScopes = requirement.get(security.name); if (opScopes != null) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java index 20ce9f3ad403..45c883722b73 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/InlineModelResolver.java @@ -811,9 +811,17 @@ private void flattenProperties(OpenAPI openAPI, Map properties, ap.setItems(schema); } } + } else if (ModelUtils.isComposedSchema(inner)) { + String innerModelName = resolveModelName(inner.getTitle(), path + "_" + key); + gatherInlineModels(inner, innerModelName); + innerModelName = addSchemas(innerModelName, inner); + Schema schema = new Schema().$ref(innerModelName); + schema.setRequired(inner.getRequired()); + ap.setItems(schema); + } else { + LOGGER.debug("Schema not yet handled in model resolver: {}", inner); } - } - if (ModelUtils.isMapSchema(property)) { + } else if (ModelUtils.isMapSchema(property)) { Schema inner = ModelUtils.getAdditionalProperties(property); if (inner instanceof ObjectSchema) { ObjectSchema op = (ObjectSchema) inner; @@ -833,7 +841,25 @@ private void flattenProperties(OpenAPI openAPI, Map properties, property.setAdditionalProperties(schema); } } + } else if (ModelUtils.isComposedSchema(inner)) { + String innerModelName = resolveModelName(inner.getTitle(), path + "_" + key); + gatherInlineModels(inner, innerModelName); + innerModelName = addSchemas(innerModelName, inner); + Schema schema = new Schema().$ref(innerModelName); + schema.setRequired(inner.getRequired()); + property.setAdditionalProperties(schema); + } else { + LOGGER.debug("Schema not yet handled in model resolver: {}", inner); } + } else if (ModelUtils.isComposedSchema(property)) { // oneOf, anyOf, etc + String propertyModelName = resolveModelName(property.getTitle(), path + "_" + key); + gatherInlineModels(property, propertyModelName); + propertyModelName = addSchemas(propertyModelName, property); + Schema schema = new Schema().$ref(propertyModelName); + schema.setRequired(property.getRequired()); + propsToUpdate.put(key, schema); + } else { + LOGGER.debug("Schema not yet handled in model resolver: {}", property); } } if (propsToUpdate.size() > 0) { @@ -867,8 +893,10 @@ private Schema modelFromProperty(OpenAPI openAPI, Schema object, String path) { // including object types. model.setFormat(object.getFormat()); + if (object.getExample() != null) { + model.setExample(example); + } model.setDescription(description); - model.setExample(example); model.setName(object.getName()); model.setXml(xml); model.setRequired(object.getRequired()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java index ebe004e8fe58..3f5465a3c668 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/OpenAPINormalizer.java @@ -80,6 +80,11 @@ public class OpenAPINormalizer { final String SET_TAGS_FOR_ALL_OPERATIONS = "SET_TAGS_FOR_ALL_OPERATIONS"; String setTagsForAllOperations; + // when set to true, tags in all operations will be set to operationId or "default" if operationId + // is empty + final String SET_TAGS_TO_OPERATIONID = "SET_TAGS_TO_OPERATIONID"; + String setTagsToOperationId; + // when set to true, auto fix integer with maximum value 4294967295 (2^32-1) or long with 18446744073709551615 (2^64-1) // by adding x-unsigned to the schema final String ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE = "ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE"; @@ -104,7 +109,6 @@ public OpenAPINormalizer(OpenAPI openAPI, Map inputRules) { this.inputRules = inputRules; if (Boolean.parseBoolean(inputRules.get(DISABLE_ALL))) { - LOGGER.info("Disabled all rules in OpenAPI Normalizer (DISABLE_ALL=true)"); this.disableAll = true; return; // skip the rest } @@ -117,6 +121,7 @@ public OpenAPINormalizer(OpenAPI openAPI, Map inputRules) { ruleNames.add(SIMPLIFY_BOOLEAN_ENUM); ruleNames.add(KEEP_ONLY_FIRST_TAG_IN_OPERATION); ruleNames.add(SET_TAGS_FOR_ALL_OPERATIONS); + ruleNames.add(SET_TAGS_TO_OPERATIONID); ruleNames.add(ADD_UNSIGNED_TO_INTEGER_WITH_INVALID_MAX_VALUE); ruleNames.add(REFACTOR_ALLOF_WITH_PROPERTIES_ONLY); ruleNames.add(NORMALIZE_31SPEC); @@ -188,7 +193,7 @@ void normalize() { } normalizePaths(); - normalizeComponents(); + normalizeComponentsSchemas(); } /** @@ -215,10 +220,14 @@ private void normalizePaths() { } } + // normalize PathItem common parameters + normalizeParameters(path.getParameters()); + for (Operation operation : operations) { + normalizeOperation(operation); normalizeRequestBody(operation); - normalizeParameters(operation); + normalizeParameters(operation.getParameters()); normalizeResponses(operation); } } @@ -233,6 +242,8 @@ private void normalizeOperation(Operation operation) { processKeepOnlyFirstTagInOperation(operation); processSetTagsForAllOperations(operation); + + processSetTagsToOperationId(operation); } /** @@ -286,15 +297,19 @@ private void normalizeRequestBody(Operation operation) { /** * Normalizes schemas in parameters * - * @param operation target operation + * @param parameters List parameters */ - private void normalizeParameters(Operation operation) { - List parameters = operation.getParameters(); + private void normalizeParameters(List parameters) { if (parameters == null) { return; } for (Parameter parameter : parameters) { + // dereference parameter + if (StringUtils.isNotEmpty(parameter.get$ref())) { + parameter = ModelUtils.getReferencedParameter(openAPI, parameter); + } + if (parameter.getSchema() == null) { continue; } else { @@ -319,9 +334,8 @@ private void normalizeResponses(Operation operation) { if (responsesEntry.getValue() == null) { continue; } else { - normalizeContent(responsesEntry.getValue().getContent()); - normalizeHeaders(responsesEntry.getValue().getHeaders()); - + normalizeContent(ModelUtils.getReferencedApiResponse(openAPI, responsesEntry.getValue()).getContent()); + normalizeHeaders(ModelUtils.getReferencedApiResponse(openAPI, responsesEntry.getValue()).getHeaders()); } } } @@ -346,7 +360,7 @@ private void normalizeHeaders(Map headers) { /** * Normalizes schemas in components */ - private void normalizeComponents() { + private void normalizeComponentsSchemas() { Map schemas = openAPI.getComponents().getSchemas(); if (schemas == null) { return; @@ -559,6 +573,10 @@ private void processUseAllOfRefAsParent(Schema schema) { return; } + if (schema.getAllOf().size() == 1) { + return; + } + for (Object item : schema.getAllOf()) { if (!(item instanceof Schema)) { throw new RuntimeException("Error! allOf schema is not of the type Schema: " + item); @@ -620,6 +638,24 @@ private void processSetTagsForAllOperations(Operation operation) { operation.addTagsItem(setTagsForAllOperations); } + /** + * Set the tag name to operationId (or "default" if operationId is empty) + * + * @param operation Operation + */ + private void processSetTagsToOperationId(Operation operation) { + if (!getRule(SET_TAGS_TO_OPERATIONID)) { + return; + } + + operation.setTags(null); + if (StringUtils.isNotEmpty(operation.getOperationId())) { + operation.addTagsItem(operation.getOperationId()); + } else { // default to "default" if operationId is empty + operation.addTagsItem("default"); + } + } + /** * If the schema contains anyOf/oneOf and properties, remove oneOf/anyOf as these serve as rules to * ensure inter-dependency between properties. It's a workaround as such validation is not supported at the moment. @@ -883,10 +919,20 @@ private Schema processNormalize31Spec(Schema schema, Set visitedSchemas) return schema; } - if (schema == null || schema.getTypes() == null) { + if (schema == null) { return null; } + if (schema instanceof JsonSchema && + schema.get$schema() == null && + schema.getTypes() == null && schema.getType() == null) { + // convert any type in v3.1 to empty schema (any type in v3.0 spec), any type example: + // components: + // schemas: + // any_type: {} + return new Schema(); + } + // process null if (schema.getTypes().contains("null")) { schema.setNullable(true); @@ -898,6 +944,17 @@ private Schema processNormalize31Spec(Schema schema, Set visitedSchemas) String type = String.valueOf(schema.getTypes().iterator().next()); if ("array".equals(type)) { ArraySchema as = new ArraySchema(); + as.setDescription(schema.getDescription()); + as.setDefault(schema.getDefault()); + if (schema.getExample() != null) { + as.setExample(schema.getExample()); + } + if (schema.getExamples() != null) { + as.setExamples(schema.getExamples()); + } + as.setMinItems(schema.getMinItems()); + as.setMaxItems(schema.getMaxItems()); + as.setExtensions(schema.getExtensions()); as.setXml(schema.getXml()); // `items` is also a json schema if (StringUtils.isNotEmpty(schema.getItems().get$ref())) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java index c81cd523fe35..dd9bdc161224 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfigurator.java @@ -74,8 +74,10 @@ public class CodegenConfigurator { private Map nameMappings = new HashMap<>(); private Map parameterNameMappings = new HashMap<>(); private Map modelNameMappings = new HashMap<>(); + private Map enumNameMappings = new HashMap<>(); private Map openapiNormalizer = new HashMap<>(); private Set languageSpecificPrimitives = new HashSet<>(); + private Set openapiGeneratorIgnoreList = new HashSet<>(); private Map reservedWordsMappings = new HashMap<>(); private Map serverVariables = new HashMap<>(); private String auth; @@ -136,12 +138,18 @@ public static CodegenConfigurator fromFile(String configFile, Module... modules) if(generatorSettings.getModelNameMappings() != null) { configurator.modelNameMappings.putAll(generatorSettings.getModelNameMappings()); } + if(generatorSettings.getEnumNameMappings() != null) { + configurator.enumNameMappings.putAll(generatorSettings.getEnumNameMappings()); + } if(generatorSettings.getOpenAPINormalizer() != null) { configurator.openapiNormalizer.putAll(generatorSettings.getOpenAPINormalizer()); } if(generatorSettings.getLanguageSpecificPrimitives() != null) { configurator.languageSpecificPrimitives.addAll(generatorSettings.getLanguageSpecificPrimitives()); } + if(generatorSettings.getOpenAPIGeneratorIgnoreList() != null) { + configurator.openapiGeneratorIgnoreList.addAll(generatorSettings.getOpenAPIGeneratorIgnoreList()); + } if(generatorSettings.getReservedWordsMappings() != null) { configurator.reservedWordsMappings.putAll(generatorSettings.getReservedWordsMappings()); } @@ -244,6 +252,12 @@ public CodegenConfigurator addModelNameMapping(String key, String value) { return this; } + public CodegenConfigurator addEnumNameMapping(String key, String value) { + this.enumNameMappings.put(key, value); + generatorSettingsBuilder.withEnumNameMapping(key, value); + return this; + } + public CodegenConfigurator addOpenAPINormalizer(String key, String value) { this.openapiNormalizer.put(key, value); generatorSettingsBuilder.withOpenAPINormalizer(key, value); @@ -262,6 +276,12 @@ public CodegenConfigurator addLanguageSpecificPrimitive(String value) { return this; } + public CodegenConfigurator addOpenAPIGeneratorIgnoreList(String value) { + this.openapiGeneratorIgnoreList.add(value); + generatorSettingsBuilder.withOpenAPIGeneratorIgnoreList(value); + return this; + } + public CodegenConfigurator addGlobalProperty(String key, String value) { this.globalProperties.put(key, value); workflowSettingsBuilder.withGlobalProperty(key, value); @@ -440,6 +460,12 @@ public CodegenConfigurator setModelNameMappings(Map modelNameMap return this; } + public CodegenConfigurator setEnumNameMappings(Map enumNameMappings) { + this.enumNameMappings = enumNameMappings; + generatorSettingsBuilder.withEnumNameMappings(enumNameMappings); + return this; + } + public CodegenConfigurator setOpenAPINormalizer(Map openapiNormalizer) { this.openapiNormalizer = openapiNormalizer; generatorSettingsBuilder.withOpenAPINormalizer(openapiNormalizer); @@ -473,6 +499,13 @@ public CodegenConfigurator setLanguageSpecificPrimitives( return this; } + public CodegenConfigurator setOpenAPIGeneratorIgnoreList( + Set openapiGeneratorIgnoreList) { + this.openapiGeneratorIgnoreList = openapiGeneratorIgnoreList; + generatorSettingsBuilder.withOpenAPIGeneratorIgnoreList(openapiGeneratorIgnoreList); + return this; + } + public CodegenConfigurator setLibrary(String library) { generatorSettingsBuilder.withLibrary(library); return this; @@ -728,8 +761,10 @@ public ClientOptInput toClientOptInput() { config.nameMapping().putAll(generatorSettings.getNameMappings()); config.parameterNameMapping().putAll(generatorSettings.getParameterNameMappings()); config.modelNameMapping().putAll(generatorSettings.getModelNameMappings()); + config.enumNameMapping().putAll(generatorSettings.getEnumNameMappings()); config.openapiNormalizer().putAll(generatorSettings.getOpenAPINormalizer()); config.languageSpecificPrimitives().addAll(generatorSettings.getLanguageSpecificPrimitives()); + config.openapiGeneratorIgnoreList().addAll(generatorSettings.getOpenAPIGeneratorIgnoreList()); config.reservedWordsMappings().putAll(generatorSettings.getReservedWordsMappings()); config.additionalProperties().putAll(generatorSettings.getAdditionalProperties()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java index c6a871b7c42e..21cbde34c9a2 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/CodegenConfiguratorUtils.java @@ -159,6 +159,19 @@ public static void applyModelNameMappingsKvp(String modelNameMappings, CodegenCo } } + public static void applyEnumNameMappingsKvpList(List enumNameMappings, CodegenConfigurator configurator) { + for (String propString : enumNameMappings) { + applyEnumNameMappingsKvp(propString, configurator); + } + } + + public static void applyEnumNameMappingsKvp(String enumNameMappings, CodegenConfigurator configurator) { + final Map map = createMapFromKeyValuePairs(enumNameMappings); + for (Map.Entry entry : map.entrySet()) { + configurator.addEnumNameMapping(entry.getKey().trim(), entry.getValue().trim()); + } + } + public static void applyOpenAPINormalizerKvpList(List openapiNormalizer, CodegenConfigurator configurator) { for (String propString : openapiNormalizer) { applyOpenAPINormalizerKvp(propString, configurator); @@ -224,6 +237,19 @@ public static void applyLanguageSpecificPrimitivesCsv(String languageSpecificPri } } + public static void applyOpenAPIGeneratorIgnoreListCsvList(List openapiGeneratorIgnoreList, CodegenConfigurator configurator) { + for (String propString : openapiGeneratorIgnoreList) { + applyOpenAPIGeneratorIgnoreListCsv(propString, configurator); + } + } + + public static void applyOpenAPIGeneratorIgnoreListCsv(String openapiGeneratorIgnoreList, CodegenConfigurator configurator) { + final Set set = createSetFromCsvList(openapiGeneratorIgnoreList); + for (String item : set) { + configurator.addOpenAPIGeneratorIgnoreList(item); + } + } + public static void applyReservedWordsMappingsKvpList(List reservedWordsMappings, CodegenConfigurator configurator) { for (String propString : reservedWordsMappings) { applyReservedWordsMappingsKvp(propString, configurator); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/GlobalSettings.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/GlobalSettings.java index 1bf89faabbbf..fae47e37f8ec 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/GlobalSettings.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/config/GlobalSettings.java @@ -16,6 +16,11 @@ package org.openapitools.codegen.config; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.PrintWriter; +import java.io.StringWriter; import java.util.Properties; /** @@ -31,6 +36,8 @@ */ public class GlobalSettings { + private static final Logger LOGGER = LoggerFactory.getLogger(GlobalSettings.class); + private static ThreadLocal properties = new InheritableThreadLocal() { @Override protected Properties initialValue() { @@ -60,4 +67,10 @@ public static void clearProperty(String key) { public static void reset() { properties.remove(); } + + public static void log() { + StringWriter stringWriter = new StringWriter(); + properties.get().list(new PrintWriter(stringWriter)); + LOGGER.debug("GlobalSettings: {}", stringWriter); + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java index ac14f2b9e6bf..09ef2bfb4461 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/examples/ExampleGenerator.java @@ -27,6 +27,7 @@ import org.slf4j.LoggerFactory; import java.math.BigDecimal; +import java.text.SimpleDateFormat; import java.util.*; public class ExampleGenerator { @@ -36,6 +37,8 @@ public class ExampleGenerator { private static final String MIME_TYPE_JSON = "application/json"; private static final String MIME_TYPE_XML = "application/xml"; + protected final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd", Locale.ROOT); + private static final String EXAMPLE = "example"; private static final String CONTENT_TYPE = "contentType"; private static final String GENERATED_CONTENT_TYPE = "generatedContentType"; @@ -54,6 +57,7 @@ public ExampleGenerator(Map examples, OpenAPI openAPI) { this.openAPI = openAPI; // use a fixed seed to make the "random" numbers reproducible. this.random = new Random("ExampleGenerator".hashCode()); + DATE_FORMAT.setTimeZone(TimeZone.getTimeZone("UTC")); } public List> generateFromResponseSchema(String statusCode, Schema responseSchema, Set producesInfo) { @@ -224,9 +228,18 @@ private List> generate(Object example, List mediaTyp } private Object resolvePropertyToExample(String propertyName, String mediaType, Schema property, Set processedModels) { + if (property == null) { + LOGGER.error("Property schema shouldn't be null. Please report the issue to the openapi-generator team."); + return ""; + } LOGGER.debug("Resolving example for property {}...", property); if (property.getExample() != null) { LOGGER.debug("Example set in openapi spec, returning example: '{}'", property.getExample().toString()); + // When a property is of type Date, we want to ensure that we're returning a formatted Date. + // And not returning the Date object directly. + if (property.getExample() instanceof Date) { + return DATE_FORMAT.format(property.getExample()); + } return property.getExample(); } else if (ModelUtils.isBooleanSchema(property)) { Object defaultValue = property.getDefault(); @@ -347,15 +360,57 @@ private Object resolveModelToExample(String name, String mediaType, Schema schem return schema.getExample(); } else if (schema.getProperties() != null) { LOGGER.debug("Creating example from model values"); - for (Object propertyName : schema.getProperties().keySet()) { - Schema property = (Schema) schema.getProperties().get(propertyName.toString()); - values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, property, processedModels)); + traverseSchemaProperties(mediaType, schema, processedModels, values); + schema.setExample(values); + return schema.getExample(); + } else if (ModelUtils.isAllOf(schema) || ModelUtils.isAllOfWithProperties(schema)) { + LOGGER.debug("Resolving allOf model '{}' to example", name); + List interfaces = schema.getAllOf(); + for (Schema composed : interfaces) { + traverseSchemaProperties(mediaType, composed, processedModels, values); + if (composed.get$ref() != null) { + String ref = ModelUtils.getSimpleRef(composed.get$ref()); + Schema resolved = ModelUtils.getSchema(openAPI, ref); + if (resolved != null) { + traverseSchemaProperties(mediaType, resolved, processedModels, values); + } + } } schema.setExample(values); return schema.getExample(); + } else if (ModelUtils.isAnyOf(schema) || ModelUtils.isOneOf(schema)) { + LOGGER.debug("Resolving anyOf/oneOf model '{}' using the first schema to example", name); + Optional found = ModelUtils.getInterfaces(schema) + .stream() + .filter(this::hasValidRef) + .findFirst(); + + if (found.isEmpty()) { + return null; + } + return resolvePropertyToExample(name, mediaType, found.get(), processedModels); } else { // TODO log an error message as the model does not have any properties return null; } } + + private void traverseSchemaProperties(String mediaType, Schema schema, Set processedModels, Map values) { + if (schema.getProperties() != null) { + for (Object propertyName : schema.getProperties().keySet()) { + Schema property = (Schema) schema.getProperties().get(propertyName.toString()); + values.put(propertyName.toString(), resolvePropertyToExample(propertyName.toString(), mediaType, property, processedModels)); + } + } + } + + private boolean hasValidRef(Schema schema) { + if (schema.get$ref() != null) { + String ref = ModelUtils.getSimpleRef(schema.get$ref()); + Schema resolved = ModelUtils.getSchema(openAPI, ref); + return resolved != null; + } + + return true; + } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java index 6411726d8c36..5087cf7240de 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractAdaCodegen.java @@ -428,6 +428,10 @@ public String toModelName(final String name) { @Override public String toEnumVarName(String value, String datatype) { + if (enumNameMapping.containsKey(value)) { + return enumNameMapping.get(value); + } + String var; if (value.isEmpty()) { var = "EMPTY"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java index 97616dcaf3ca..92bdcfcba52b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractApexCodegen.java @@ -573,7 +573,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation if (op.getHasExamples()) { // prepare examples for Apex test classes ApiResponse apiResponse = findMethodResponse(operation.getResponses()); - final Schema responseSchema = ModelUtils.getSchemaFromResponse(apiResponse); + final Schema responseSchema = ModelUtils.getSchemaFromResponse(openAPI, apiResponse); String deserializedExample = toExampleValue(responseSchema); for (Map example : op.examples) { example.put("example", escapeText(example.get("example"))); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java index e9a7a50b8a09..59584728003e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractCSharpCodegen.java @@ -45,6 +45,7 @@ import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER; import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; public abstract class AbstractCSharpCodegen extends DefaultCodegen implements CodegenConfig { @@ -54,6 +55,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected boolean optionalProjectFileFlag = true; protected boolean optionalMethodArgumentFlag = true; protected boolean useDateTimeOffsetFlag = false; + protected boolean useDateTimeForDateFlag = false; protected boolean useCollection = false; protected boolean returnICollection = false; protected boolean netCoreProjectFileFlag = false; @@ -84,6 +86,7 @@ public abstract class AbstractCSharpCodegen extends DefaultCodegen implements Co protected String sourceFolder = "src"; protected String invalidNamePrefix = "var"; + protected CodegenConstants.ENUM_PROPERTY_NAMING_TYPE enumPropertyNaming = CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.PascalCase; // TODO: Add option for test folder output location. Nice to allow e.g. ./test instead of ./src. // This would require updating relative paths (e.g. path to main project file in test project file) @@ -134,7 +137,8 @@ public AbstractCSharpCodegen() { // set "client" as a reserved word to avoid conflicts with Org.OpenAPITools.Client // this is a workaround and can be removed if c# api client is updated to use // fully qualified name - "Client", "client", "parameter", "Configuration", "Version", + "Client", "client", "parameter", "Configuration", "Version", "Environment", + "TimeZone", "OperatingSystem", // local variable names in API methods (endpoints) "localVarPath", "localVarPathParams", "localVarQueryParams", "localVarHeaderParams", "localVarFormParams", "localVarFileParams", "localVarStatusCode", "localVarResponse", @@ -183,6 +187,8 @@ public AbstractCSharpCodegen() { "DateTime", "DateTimeOffset?", "DateTimeOffset", + "DateOnly?", + "DateOnly", "Boolean", "Double", "Decimal", @@ -231,6 +237,16 @@ public void useDateTimeOffset(boolean flag) { this.setTypeMapping(); } + public void useDateTimeForDate(boolean flag) { + this.useDateTimeForDateFlag = flag; + this.setTypeMapping(); + } + + @Override + protected void addParentFromContainer(CodegenModel model, Schema schema) { + // we do not want to inherit simply because additionalProperties is true + // do nothing here + } @Override public void processOpts() { @@ -346,6 +362,13 @@ public void processOpts() { additionalProperties.put(CodegenConstants.USE_DATETIME_OFFSET, useDateTimeOffsetFlag); } + // {{useDateTimeForDate}} + if (additionalProperties.containsKey(CodegenConstants.USE_DATETIME_FOR_DATE)) { + useDateTimeForDate(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_DATETIME_FOR_DATE)); + } else { + additionalProperties.put(CodegenConstants.USE_DATETIME_FOR_DATE, useDateTimeForDateFlag); + } + if (additionalProperties.containsKey(CodegenConstants.USE_COLLECTION)) { setUseCollection(convertPropertyToBooleanAndWriteBack(CodegenConstants.USE_COLLECTION)); } else { @@ -391,6 +414,10 @@ public void processOpts() { setEnumValueSuffix(additionalProperties.get(CodegenConstants.ENUM_VALUE_SUFFIX).toString()); } + if (additionalProperties.containsKey(CodegenConstants.ENUM_PROPERTY_NAMING)) { + setEnumPropertyNaming((String) additionalProperties.get(CodegenConstants.ENUM_PROPERTY_NAMING)); + } + // This either updates additionalProperties with the above fixes, or sets the default if the option was not specified. additionalProperties.put(CodegenConstants.INTERFACE_PREFIX, interfacePrefix); @@ -411,11 +438,14 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio @Override protected ImmutableMap.Builder addMustacheLambdas() { + CopyLambda copyLambda = new CopyLambda(); + return super.addMustacheLambdas() .put("camelcase_param", new CamelCaseLambda().generator(this).escapeAsParamName(true)) .put("required", new RequiredParameterLambda()) .put("optional", new OptionalParameterLambda().generator(this)) .put("joinWithComma", new JoinWithCommaLambda()) + .put("joinWithAmpersand", new JoinWithCommaLambda(true, " ", " && ")) .put("joinLinesWithComma", new JoinWithCommaLambda(false, "\n", ",\n")) .put("joinConditions", new JoinWithCommaLambda(true, " ", " && ")) .put("trimLineBreaks", new TrimLineBreaksLambda()) @@ -423,9 +453,15 @@ protected ImmutableMap.Builder addMustacheLambdas() { .put("trimTrailing", new TrimTrailingWhiteSpaceLambda(false)) .put("first", new FirstLambda(" ")) .put("firstDot", new FirstLambda("\\.")) + .put("indent1", new IndentedLambda(4, " ", false, true)) .put("indent3", new IndentedLambda(12, " ", false, true)) .put("indent4", new IndentedLambda(16, " ", false, true)) - .put("uniqueLinesWithNewLine", new UniqueLambda("\n", true)); + .put("copy", copyLambda) + .put("paste", new PasteLambda(copyLambda, true, true, true, false)) + .put("pasteOnce", new PasteLambda(copyLambda, true, true, true, true)) + .put("pasteLine", new PasteLambda(copyLambda, true, true, false, false)) + .put("uniqueLines", new UniqueLambda("\n", false)) + .put("unique", new UniqueLambda("\n", true)); } @Override @@ -772,6 +808,11 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List h.baseName.equals("Set-Cookie"))) { + response.vendorExtensions.put("x-set-cookie", true); + operation.vendorExtensions.put("x-set-cookie", true); + } + String code = response.code.toLowerCase(Locale.ROOT); switch(code) { case "default": @@ -960,7 +1001,7 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List getNullableTypes() { } protected Set getValueTypes() { - return new HashSet<>(Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double", "DateTime", "DateTimeOffset", "Guid")); + return new HashSet<>(Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double", "DateTime", "DateOnly", "DateTimeOffset", "Guid")); } protected void setTypeMapping() { @@ -1939,7 +2035,7 @@ protected void setTypeMapping() { typeMapping.put("decimal", "decimal"); typeMapping.put("BigDecimal", "decimal"); typeMapping.put("DateTime", this.useDateTimeOffsetFlag ? "DateTimeOffset" : "DateTime"); - typeMapping.put("date", "DateTime"); + typeMapping.put("date", this.useDateOnly() ? "DateOnly" : "DateTime"); typeMapping.put("file", "System.IO.Stream"); typeMapping.put("array", "List"); typeMapping.put("list", "List"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java index 1e1dc710026e..62c55f904d80 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractDartCodegen.java @@ -712,6 +712,10 @@ protected void updateEnumVarsWithExtensions(List> enumVars, @Override public String toEnumVarName(String value, String datatype) { + if (enumNameMapping.containsKey(value)) { + return enumNameMapping.get(value); + } + if (value.length() == 0) { return "empty"; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java index 99df1b1c3252..b88d98086f80 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractGoCodegen.java @@ -22,10 +22,7 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.StringUtils; import org.openapitools.codegen.*; -import org.openapitools.codegen.model.ModelMap; -import org.openapitools.codegen.model.ModelsMap; -import org.openapitools.codegen.model.OperationMap; -import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.model.*; import org.openapitools.codegen.utils.ModelUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -49,6 +46,8 @@ public abstract class AbstractGoCodegen extends DefaultCodegen implements Codege protected boolean enumClassPrefix = false; protected boolean structPrefix = false; protected boolean generateInterfaces = false; + protected boolean withGoMod = false; + protected boolean generateMarshalJSON = true; protected String packageName = "openapi"; protected Set numberTypes; @@ -278,6 +277,10 @@ protected boolean isReservedFilename(String name) { @Override public String toModelFilename(String name) { + // Obtain the model name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + name = modelNameMapping.get(name); + } name = toModel("model_" + name); if (isReservedFilename(name)) { @@ -293,6 +296,11 @@ public String toModel(String name) { } public String toModel(String name, boolean doUnderscore) { + // obtain the name from modelNameMapping directly if provided + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + if (!StringUtils.isEmpty(modelNamePrefix)) { name = modelNamePrefix + "_" + name; } @@ -575,6 +583,105 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + OperationMap objectMap = objs.getWebhooks(); + List operations = objectMap.getOperation(); + + for (CodegenOperation operation : operations) { + // http method verb conversion (e.g. PUT => Put) + operation.httpMethod = camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + } + + // remove model imports to avoid error + List> imports = objs.getImports(); + if (imports == null) + return objs; + + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(apiPackage())) + iterator.remove(); + } + + // this will only import "fmt" and "strings" if there are items in pathParams + for (CodegenOperation operation : operations) { + if (operation.pathParams != null && operation.pathParams.size() > 0) { + imports.add(createMapping("import", "strings")); + break; //just need to import once + } + } + + boolean addedTimeImport = false; + boolean addedOSImport = false; + boolean addedReflectImport = false; + for (CodegenOperation operation : operations) { + // import "os" if the operation uses files + if (!addedOSImport && "*os.File".equals(operation.returnType)) { + imports.add(createMapping("import", "os")); + addedOSImport = true; + } + for (CodegenParameter param : operation.allParams) { + // import "os" if the operation uses files + if (!addedOSImport && "*os.File".equals(param.dataType)) { + imports.add(createMapping("import", "os")); + addedOSImport = true; + } + + // import "time" if the operation has a time parameter. + if (!addedTimeImport && "time.Time".equals(param.dataType)) { + imports.add(createMapping("import", "time")); + addedTimeImport = true; + } + + // import "reflect" package if the parameter is collectionFormat=multi + if (!addedReflectImport && param.isCollectionFormatMulti) { + imports.add(createMapping("import", "reflect")); + addedReflectImport = true; + } + + // set x-exportParamName + char nameFirstChar = param.paramName.charAt(0); + if (Character.isUpperCase(nameFirstChar)) { + // First char is already uppercase, just use paramName. + param.vendorExtensions.put("x-export-param-name", param.paramName); + } else { + // It's a lowercase first char, let's convert it to uppercase + StringBuilder sb = new StringBuilder(param.paramName); + sb.setCharAt(0, Character.toUpperCase(nameFirstChar)); + param.vendorExtensions.put("x-export-param-name", sb.toString()); + } + } + + setExportParameterName(operation.queryParams); + setExportParameterName(operation.formParams); + setExportParameterName(operation.headerParams); + setExportParameterName(operation.bodyParams); + setExportParameterName(operation.cookieParams); + setExportParameterName(operation.optionalParams); + setExportParameterName(operation.requiredParams); + + } + + // recursively add import for mapping one type to multiple imports + List> recursiveImports = objs.getImports(); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = imports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + listIterator.add(createMapping("import", importMapping.get(_import))); + } + } + + return objs; + } + private void setExportParameterName(List codegenParameters) { for (CodegenParameter param : codegenParameters) { char nameFirstChar = param.paramName.charAt(0); @@ -666,7 +773,12 @@ public ModelsMap postProcessModels(ModelsMap objs) { model.isNullable = true; model.anyOf.remove("nil"); } + + if (generateMarshalJSON) { + model.vendorExtensions.put("x-go-generate-marshal-json", true); + } } + // recursively add import for mapping one type to multiple imports List> recursiveImports = objs.getImports(); if (recursiveImports == null) @@ -734,6 +846,10 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + if (name.length() == 0) { return "EMPTY"; } @@ -768,6 +884,10 @@ public String toEnumVarName(String name, String datatype) { @Override public String toEnumName(CodegenProperty property) { + if (enumNameMapping.containsKey(property.name)) { + return enumNameMapping.get(property.name); + } + String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum @@ -804,6 +924,14 @@ public void setGenerateInterfaces(boolean generateInterfaces) { this.generateInterfaces = generateInterfaces; } + public void setWithGoMod(boolean withGoMod) { + this.withGoMod = withGoMod; + } + + public void setGenerateMarshalJSON(boolean generateMarshalJSON) { + this.generateMarshalJSON = generateMarshalJSON; + } + @Override public String toDefaultValue(Schema schema) { schema = unaliasSchema(schema); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java index b389a550b01a..e43242f3c7bf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractJavaCodegen.java @@ -21,7 +21,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode; import com.google.common.base.Strings; import com.google.common.collect.Sets; -import io.swagger.models.Model; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.Operation; import io.swagger.v3.oas.models.PathItem; @@ -34,7 +33,9 @@ import org.apache.commons.io.FilenameUtils; import org.apache.commons.lang3.BooleanUtils; import org.apache.commons.lang3.StringUtils; +import org.apache.commons.text.StringEscapeUtils; import org.openapitools.codegen.*; +import org.openapitools.codegen.languages.features.BeanValidationFeatures; import org.openapitools.codegen.languages.features.DocumentationProviderFeatures; import org.openapitools.codegen.meta.features.*; import org.openapitools.codegen.model.ModelMap; @@ -82,7 +83,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code public static final String TEST_OUTPUT = "testOutput"; public static final String IMPLICIT_HEADERS = "implicitHeaders"; public static final String IMPLICIT_HEADERS_REGEX = "implicitHeadersRegex"; - public static final String AUTOSET_CONSTANTS = "autosetConstants"; public static final String JAVAX_PACKAGE = "javaxPackage"; public static final String USE_JAKARTA_EE = "useJakartaEe"; public static final String CONTAINER_DEFAULT_TO_NULL = "containerDefaultToNull"; @@ -136,7 +136,6 @@ public abstract class AbstractJavaCodegen extends DefaultCodegen implements Code protected AnnotationLibrary annotationLibrary; protected boolean implicitHeaders = false; protected String implicitHeadersRegex = null; - protected boolean autosetConstants = false; protected boolean camelCaseDollarSign = false; protected boolean useJakartaEe = false; protected boolean containerDefaultToNull = false; @@ -558,10 +557,6 @@ public void processOpts() { this.setImplicitHeadersRegex(additionalProperties.get(IMPLICIT_HEADERS_REGEX).toString()); } - if (additionalProperties.containsKey(AUTOSET_CONSTANTS)) { - this.setAutosetConstants(Boolean.parseBoolean(additionalProperties.get(AUTOSET_CONSTANTS).toString())); - } - if (additionalProperties.containsKey(CAMEL_CASE_DOLLAR_SIGN)) { this.setCamelCaseDollarSign(Boolean.parseBoolean(additionalProperties.get(CAMEL_CASE_DOLLAR_SIGN).toString())); } @@ -936,7 +931,7 @@ public String getTypeDeclaration(Schema p) { Schema target = ModelUtils.isGenerateAliasAsModel() ? p : schema; if (ModelUtils.isArraySchema(target)) { Schema items = getSchemaItems((ArraySchema) schema); - return getSchemaType(target) + "<" + getTypeDeclaration(items) + ">"; + return getSchemaType(target) + "<" + getBeanValidation(items) + getTypeDeclaration(items) + ">"; } else if (ModelUtils.isMapSchema(target)) { // Note: ModelUtils.isMapSchema(p) returns true when p is a composed schema that also defines // additionalproperties: true @@ -951,6 +946,128 @@ public String getTypeDeclaration(Schema p) { return super.getTypeDeclaration(target); } + /** + * This method stand for resolve bean validation for container(array, set). + * Return empty if there's no bean validation for requested type or prop useBeanValidation false or missed. + * + * @param items type + * @return BeanValidation for declared type in container(array, set) + */ + private String getBeanValidation(Schema items) { + if (Boolean.FALSE.equals(additionalProperties.getOrDefault(BeanValidationFeatures.USE_BEANVALIDATION, Boolean.FALSE))) { + return ""; + } + + if (ModelUtils.isTypeObjectSchema(items)) { + // prevents generation '@Valid' for Object + return ""; + } + + if (items.get$ref() != null) { + return "@Valid "; + } + + if (ModelUtils.isStringSchema(items)) { + return getStringBeanValidation(items); + } + + if (ModelUtils.isNumberSchema(items)) { + return getNumberBeanValidation(items); + } + + if (ModelUtils.isIntegerSchema(items)) { + return getIntegerBeanValidation(items); + } + + return ""; + } + + private String getIntegerBeanValidation(Schema items) { + if (items.getMinimum() != null && items.getMaximum() != null) { + return String.format(Locale.ROOT, "@Min(%s) @Max(%s)", items.getMinimum(), items.getMaximum()); + } + + if (items.getMinimum() != null) { + return String.format(Locale.ROOT, "@Min(%s)", items.getMinimum()); + } + + if (items.getMaximum() != null) { + return String.format(Locale.ROOT, "@Max(%s)", items.getMaximum()); + } + return ""; + } + + private String getNumberBeanValidation(Schema items) { + if (items.getMinimum() != null && items.getMaximum() != null) { + return String.format(Locale.ROOT, "@DecimalMin(value = \"%s\", inclusive = %s) @DecimalMax(value = \"%s\", inclusive = %s)", + items.getMinimum(), + Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE), + items.getMaximum(), + Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE)); + } + + if (items.getMinimum() != null) { + return String.format(Locale.ROOT, "@DecimalMin( value = \"%s\", inclusive = %s)", + items.getMinimum(), + Optional.ofNullable(items.getExclusiveMinimum()).orElse(Boolean.FALSE)); + } + + if (items.getMaximum() != null) { + return String.format(Locale.ROOT, "@DecimalMax( value = \"%s\", inclusive = %s)", + items.getMaximum(), + Optional.ofNullable(items.getExclusiveMaximum()).orElse(Boolean.FALSE)); + } + + return ""; + } + + private String getStringBeanValidation(Schema items) { + String validations = ""; + if (ModelUtils.isByteArraySchema(items) || ModelUtils.isBinarySchema(items)) { + return validations; + } + + if (StringUtils.isNotEmpty(items.getPattern())) { + final String pattern = escapeUnsafeCharacters( + StringEscapeUtils.unescapeJava( + StringEscapeUtils.escapeJava(items.getPattern()) + .replace("\\/", "/")) + .replaceAll("[\\t\\n\\r]", " ") + .replace("\\", "\\\\") + .replace("\"", "\\\"")); + + validations = String.format(Locale.ROOT, "@Pattern(regexp = \"%s\")", pattern); + } + + if (ModelUtils.isEmailSchema(items)) { + return String.join("", "@Email "); + } + + if (ModelUtils.isDecimalSchema(items)) { + return String.join("", validations, getNumberBeanValidation(items)); + } + + if (items.getMinLength() != null && items.getMaxLength() != null) { + return String.join("", + validations, + String.format(Locale.ROOT, "@Size(min = %d, max = %d)", items.getMinLength(), items.getMaxLength())); + } + + if (items.getMinLength() != null) { + return String.join("", + validations, + String.format(Locale.ROOT, "@Size(min = %d)", items.getMinLength())); + } + + if (items.getMaxLength() != null) { + return String.join("", + validations, + String.format(Locale.ROOT, "@Size(max = %d)", items.getMaxLength())); + } + + return validations; + } + @Override public String getAlias(String name) { if (typeAliases != null && typeAliases.containsKey(name)) { @@ -1517,6 +1634,21 @@ public void postProcessModelProperty(CodegenModel model, CodegenProperty propert } } + public void postProcessResponseWithProperty(CodegenResponse response, CodegenProperty property) { + if (response == null || property == null || response.dataType == null || property.dataType == null) { + return; + } + + // the response data types should not contains a bean validation annotation. + if (property.dataType.contains("@")) { + property.dataType = property.dataType.replaceAll("(?:(?i)@[a-z0-9]*+\\s*)*+", ""); + } + // the response data types should not contains a bean validation annotation. + if (response.dataType.contains("@")) { + response.dataType = response.dataType.replaceAll("(?:(?i)@[a-z0-9]*+\\s*)*+", ""); + } + } + @Override public ModelsMap postProcessModels(ModelsMap objs) { // recursively add import for mapping one type to multiple imports @@ -1695,6 +1827,10 @@ public String toEnumName(CodegenProperty property) { @Override public String toEnumVarName(String value, String datatype) { + if (enumNameMapping.containsKey(value)) { + return enumNameMapping.get(value); + } + if (value.length() == 0) { return "EMPTY"; } @@ -1740,6 +1876,8 @@ public String toEnumValue(String value, String datatype) { } else if ("BigDecimal".equals(datatype)) { // use BigDecimal String constructor return "new BigDecimal(\"" + value + "\")"; + } else if ("URI".equals(datatype)) { + return "URI.create(\"" + escapeText(value) + "\")"; } else { return "\"" + escapeText(value) + "\""; } @@ -2052,10 +2190,6 @@ public void setImplicitHeadersRegex(String implicitHeadersRegex) { this.implicitHeadersRegex = implicitHeadersRegex; } - public void setAutosetConstants(boolean autosetConstants) { - this.autosetConstants = autosetConstants; - } - public void setCamelCaseDollarSign(boolean camelCaseDollarSign) { this.camelCaseDollarSign = camelCaseDollarSign; } @@ -2294,45 +2428,6 @@ protected void handleImplicitHeaders(CodegenOperation operation) { operation.hasParams = !operation.allParams.isEmpty(); } - /** - * This method removes all constant Query, Header and Cookie Params from allParams and sets them as constantParams in the CodegenOperation. - * The definition of constant is single valued required enum params. - * The constantParams in the the generated code should be hardcoded to the constantValue if autosetConstants feature is enabled. - * - * @param operation - operation to be processed - */ - protected void handleConstantParams(CodegenOperation operation) { - if (!autosetConstants || operation.allParams.isEmpty()) { - return; - } - final ArrayList copy = new ArrayList<>(operation.allParams); - // Remove all params from Params, Non constant params will be added back later. - operation.allParams.clear(); - - // Finds all constant params, removes them from allParams and adds them to constant params. - // Also, adds back non constant params to allParams. - for (CodegenParameter p : copy) { - if (p.isEnum && p.required && p._enum != null && p._enum.size() == 1) { - // Add to constantParams for use in the code generation templates. - operation.constantParams.add(p); - if(p.isQueryParam) { - operation.queryParams.removeIf(param -> param.baseName.equals(p.baseName)); - } - if(p.isHeaderParam) { - operation.headerParams.removeIf(param -> param.baseName.equals(p.baseName)); - } - if(p.isCookieParam) { - operation.cookieParams.removeIf(param -> param.baseName.equals(p.baseName)); - } - LOGGER.info("Update operation [{}]. Remove parameter [{}] because it can only have a fixed value of [{}]", operation.operationId, p.baseName, p._enum.get(0)); - } else { - // Add back to allParams as the param is not a constant. - operation.allParams.add(p); - } - } - operation.hasParams = !operation.allParams.isEmpty(); - } - private boolean shouldBeImplicitHeader(CodegenParameter parameter) { return StringUtils.isNotBlank(implicitHeadersRegex) && parameter.baseName.matches(implicitHeadersRegex); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java index d3f7fd6dbab4..35e5e4a245aa 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractKotlinCodegen.java @@ -599,6 +599,10 @@ public void setNonPublicApi(boolean nonPublicApi) { */ @Override public String toEnumVarName(String value, String datatype) { + if (enumNameMapping.containsKey(value)) { + return enumNameMapping.get(value); + } + String modified; if (value.length() == 0) { modified = "EMPTY"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java index c4815a6557a0..19dddf4a3715 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPhpCodegen.java @@ -742,6 +742,10 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + if (name.length() == 0) { return "EMPTY"; } @@ -778,6 +782,10 @@ public String toEnumVarName(String name, String datatype) { @Override public String toEnumName(CodegenProperty property) { + if (enumNameMapping.containsKey(property.name)) { + return enumNameMapping.get(property.name); + } + String enumName = underscore(toGenericName(property.name)).toUpperCase(Locale.ROOT); // remove [] for array or map of enum diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java index ec63f2846203..63dcef5d8674 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonCodegen.java @@ -861,10 +861,7 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { // process enum in models objs = postProcessModelsEnum(objs); - // TODO: migrate almost (all?) everything to the `Imports` class. - TreeSet typingImports = new TreeSet<>(); - TreeSet pydanticImports = new TreeSet<>(); - TreeSet datetimeImports = new TreeSet<>(); + // TODO: migrate almost (all?) everything to the `PythonImports` class. TreeSet modelImports = new TreeSet<>(); TreeSet postponedModelImports = new TreeSet<>(); @@ -874,21 +871,16 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { List readOnlyFields = new ArrayList<>(); hasModelsToImport = false; int property_count = 1; - typingImports.clear(); - pydanticImports.clear(); - datetimeImports.clear(); - Imports otherImports = new Imports(); + PythonImports moduleImports = new PythonImports(); CodegenModel model = m.getModel(); + PydanticType pydantic = new PydanticType( - typingImports, - pydanticImports, - datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, - otherImports, + moduleImports, model.classname ); @@ -909,27 +901,27 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { List codegenProperties = null; if (!model.oneOf.isEmpty()) { // oneOfValidationError codegenProperties = model.getComposedSchemas().getOneOf(); - typingImports.add("Any"); - typingImports.add("List"); - pydanticImports.add("Field"); - pydanticImports.add("StrictStr"); - pydanticImports.add("ValidationError"); - pydanticImports.add("field_validator"); + moduleImports.add("typing", "Any"); + moduleImports.add("typing", "List"); + moduleImports.add("pydantic", "Field"); + moduleImports.add("pydantic", "StrictStr"); + moduleImports.add("pydantic", "ValidationError"); + moduleImports.add("pydantic", "field_validator"); } else if (!model.anyOf.isEmpty()) { // anyOF codegenProperties = model.getComposedSchemas().getAnyOf(); - pydanticImports.add("Field"); - pydanticImports.add("StrictStr"); - pydanticImports.add("ValidationError"); - pydanticImports.add("field_validator"); + moduleImports.add("pydantic", "Field"); + moduleImports.add("pydantic", "StrictStr"); + moduleImports.add("pydantic", "ValidationError"); + moduleImports.add("pydantic", "field_validator"); } else { // typical model codegenProperties = model.vars; // if super class if (model.getDiscriminator() != null && model.getDiscriminator().getMappedModels() != null) { - typingImports.add("Union"); + moduleImports.add("typing", "Union"); Set discriminator = model.getDiscriminator().getMappedModels(); for (CodegenDiscriminator.MappedModel mappedModel : discriminator) { - postponedModelImports.add(mappedModel.getMappingName()); + postponedModelImports.add(mappedModel.getModelName()); } } } @@ -946,16 +938,17 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { } } - // if model_generic.mustache is used and support additionalProperties - if (model.oneOf.isEmpty() && model.anyOf.isEmpty() - && !model.isEnum - && !this.disallowAdditionalPropertiesIfNotPresent) { - typingImports.add("Dict"); - typingImports.add("List"); - typingImports.add("Any"); - typingImports.add("ClassVar"); + // if model_generic.mustache is used + if (model.oneOf.isEmpty() && model.anyOf.isEmpty() && !model.isEnum) { + moduleImports.add("typing", "ClassVar"); + moduleImports.add("typing", "Dict"); + moduleImports.add("typing", "Any"); + if(this.disallowAdditionalPropertiesIfNotPresent || model.isAdditionalPropertiesTrue) { + moduleImports.add("typing", "List"); + } } + //loop through properties/schemas to set up typing, pydantic for (CodegenProperty cp : codegenProperties) { // is readOnly? @@ -978,7 +971,7 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { if (!StringUtils.isEmpty(model.parent)) { modelImports.add(model.parent); } else if (!model.isEnum) { - pydanticImports.add("BaseModel"); + moduleImports.add("pydantic", "BaseModel"); } // set enum type in extensions and update `name` in enumVars @@ -996,9 +989,6 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { } // set the extensions if the key is absent - model.getVendorExtensions().putIfAbsent("x-py-typing-imports", typingImports); - model.getVendorExtensions().putIfAbsent("x-py-pydantic-imports", pydanticImports); - model.getVendorExtensions().putIfAbsent("x-py-datetime-imports", datetimeImports); model.getVendorExtensions().putIfAbsent("x-py-readonly", readOnlyFields); // import models one by one @@ -1010,7 +1000,6 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { continue; } modelsToImport.add("from " + packageName + ".models." + underscore(modelImport) + " import " + modelImport); - } if (!modelsToImport.isEmpty()) { @@ -1018,8 +1007,8 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { } } - if (!otherImports.isEmpty()) { - model.getVendorExtensions().putIfAbsent("x-py-other-imports", otherImports.exports()); + if (!moduleImports.isEmpty()) { + model.getVendorExtensions().putIfAbsent("x-py-other-imports", moduleImports.exports()); } @@ -1045,9 +1034,6 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { * Gets the pydantic type given a Codegen Property * * @param cp codegen property - * @param typingImports typing imports - * @param pydantic pydantic imports - * @param datetimeImports datetime imports * @param modelImports model imports * @param exampleImports example imports * @param postponedModelImports postponed model imports @@ -1057,24 +1043,18 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { * */ private PythonType getPydanticType(CodegenProperty cp, - Set typingImports, - Set pydanticImports, - Set datetimeImports, Set modelImports, Set exampleImports, Set postponedModelImports, Set postponedExampleImports, String classname) { - Imports otherImports = new Imports(); + PythonImports moduleImports = new PythonImports(); PydanticType pt = new PydanticType( - typingImports, - pydanticImports, - datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, - otherImports, + moduleImports, classname ); @@ -1087,7 +1067,7 @@ public void setMapNumberTo(String mapNumberTo) { || "float".equals(mapNumberTo)) { this.mapNumberTo = mapNumberTo; } else { - throw new IllegalArgumentException("mapNumberTo value must be Union[StrictFloat, StrictInt], StrictStr or float"); + throw new IllegalArgumentException("mapNumberTo value must be Union[StrictFloat, StrictInt], StrictFloat or float"); } } @@ -1227,31 +1207,27 @@ public void updateImportsFromCodegenModel(String modelName, CodegenModel cm, Set public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { hasModelsToImport = false; - // TODO: migrate almost (all?) everything to the `Imports` class. - TreeSet typingImports = new TreeSet<>(); - TreeSet pydanticImports = new TreeSet<>(); - TreeSet datetimeImports = new TreeSet<>(); TreeSet modelImports = new TreeSet<>(); TreeSet postponedModelImports = new TreeSet<>(); + PythonImports moduleImports = new PythonImports(); OperationMap objectMap = objs.getOperations(); List operations = objectMap.getOperation(); - Imports otherImports = new Imports(); - for (CodegenOperation operation : operations) { TreeSet exampleImports = new TreeSet<>(); // import for each operation to be show in sample code TreeSet postponedExampleImports = new TreeSet<>(); // import for each operation to be show in sample code List params = operation.allParams; - for (CodegenParameter cp : params) { PydanticType pydantic = new PydanticType( - typingImports, pydanticImports, datetimeImports, - modelImports, exampleImports, - postponedModelImports, postponedExampleImports, - otherImports, - null); + modelImports, + exampleImports, + postponedModelImports, + postponedExampleImports, + moduleImports, + null + ); String typing = pydantic.generatePythonType(cp); cp.vendorExtensions.put("x-py-typing", typing); } @@ -1259,8 +1235,14 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List() /* skip pydantic import for return type */, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, null); + getPydanticType( + operation.returnProperty, + modelImports, + exampleImports, + postponedModelImports, + postponedExampleImports, + null + ); } // add import for code samples @@ -1281,37 +1263,19 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List> newImports = new ArrayList<>(); - for (String importLine : otherImports.exports()) { + for (String importLine : moduleImports.exports()) { Map item = new HashMap<>(); item.put("import", importLine); newImports.add(item); } - // need datetime import - if (!datetimeImports.isEmpty()) { - Map item = new HashMap<>(); - item.put("import", String.format(Locale.ROOT, "from datetime import %s\n", StringUtils.join(datetimeImports, ", "))); - newImports.add(item); - } - - // need pydantic imports - if (!pydanticImports.isEmpty()) { - Map item = new HashMap<>(); - item.put("import", String.format(Locale.ROOT, "from pydantic import %s\n", StringUtils.join(pydanticImports, ", "))); - newImports.add(item); - } - - // need typing imports - if (!typingImports.isEmpty()) { - Map item = new HashMap<>(); - item.put("import", String.format(Locale.ROOT, "from typing import %s\n", StringUtils.join(typingImports, ", "))); - newImports.add(item); - } - // import models one by one if (!modelImports.isEmpty()) { for (String modelImport : modelImports) { @@ -1580,7 +1544,7 @@ public PythonType addTypeParam(PythonType typeParam) { * the field / variable being defined are *not* part of the * constraints but part of the "type value". */ - public String asTypeConstraint(Imports imports) { + public String asTypeConstraint(PythonImports imports) { return asTypeConstraint(imports, false); } @@ -1595,11 +1559,11 @@ public String asTypeConstraint(Imports imports) { * Note that the default value is not managed here, but directly in * the Mustache template. */ - public String asTypeConstraintWithAnnotations(Imports imports) { + public String asTypeConstraintWithAnnotations(PythonImports imports) { return asTypeConstraint(imports, true); } - private String asTypeConstraint(Imports imports, boolean withAnnotations) { + private String asTypeConstraint(PythonImports imports, boolean withAnnotations) { String typeParam = ""; if (this.typeParams.size() > 0) { List types = new ArrayList<>(); @@ -1653,7 +1617,7 @@ private String asTypeConstraint(Imports imports, boolean withAnnotations) { * Constraints on the type are *not* part of the "type value", but are part of the "type constraints". */ @Nullable - public String asTypeValue(Imports imports) { + public String asTypeValue(PythonImports imports) { String defaultValue = this.defaultValue; if (this.annotations.size() > 0) { @@ -1683,7 +1647,7 @@ public String asTypeValue(Imports imports) { /* Track the list of resources to imports from where. * - * Imports are tracked as a set of modules to import from, and actual + * PythonImports are tracked as a set of modules to import from, and actual * resources (classes, functions, etc.) to import. * * The same resource can be safely "imported" many times from the same @@ -1691,10 +1655,10 @@ public String asTypeValue(Imports imports) { * entries will be automatically removed. * * */ - class Imports { + class PythonImports { private Map> imports; - public Imports() { + public PythonImports() { imports = new HashMap<>(); } @@ -1738,35 +1702,26 @@ public boolean isEmpty() { } class PydanticType { - private Set typingImports; - private Set pydanticImports; - private Set datetimeImports; private Set modelImports; private Set exampleImports; private Set postponedModelImports; private Set postponedExampleImports; - private Imports otherImports; + private PythonImports moduleImports; private String classname; public PydanticType( - Set typingImports, - Set pydanticImports, - Set datetimeImports, Set modelImports, Set exampleImports, Set postponedModelImports, Set postponedExampleImports, - Imports otherImports, + PythonImports moduleImports, String classname ) { - this.typingImports = typingImports; - this.pydanticImports = pydanticImports; - this.datetimeImports = datetimeImports; this.modelImports = modelImports; this.exampleImports = exampleImports; this.postponedModelImports = postponedModelImports; this.postponedExampleImports = postponedExampleImports; - this.otherImports = otherImports; + this.moduleImports = moduleImports; this.classname = classname; } @@ -1786,12 +1741,12 @@ private PythonType arrayType(IJsonSchemaValidationProperties cp) { // random JSON serialization order, unable to easily serialize // to JSON, etc. //pt.setType("Set"); - //typingImports.add("Set"); + //moduleImports.add("typing", "Set"); pt.setType("List"); - typingImports.add("List"); + moduleImports.add("typing", "List"); } else { pt.setType("List"); - typingImports.add("List"); + moduleImports.add("typing", "List"); } pt.addTypeParam(getType(cp.getItems())); return pt; @@ -1812,24 +1767,24 @@ private PythonType stringType(IJsonSchemaValidationProperties cp) { } if (cp.getPattern() != null) { - pydanticImports.add("field_validator"); + moduleImports.add("pydantic", "field_validator"); // use validator instead as regex doesn't support flags, e.g. IGNORECASE //fieldCustomization.add(Locale.ROOT, String.format(Locale.ROOT, "regex=r'%s'", cp.getPattern())); } return pt; } else { if ("password".equals(cp.getFormat())) { // TDOO avoid using format, use `is` boolean flag instead - pydanticImports.add("SecretStr"); + moduleImports.add("pydantic", "SecretStr"); return new PythonType("SecretStr"); } else { - pydanticImports.add("StrictStr"); + moduleImports.add("pydantic", "StrictStr"); return new PythonType("StrictStr"); } } } private PythonType mapType(IJsonSchemaValidationProperties cp) { - typingImports.add("Dict"); + moduleImports.add("typing", "Dict"); PythonType pt = new PythonType("Dict"); pt.addTypeParam(new PythonType("str")); pt.addTypeParam(getType(cp.getItems())); @@ -1868,7 +1823,7 @@ private PythonType numberType(IJsonSchemaValidationProperties cp) { floatt.constrain("strict", true); intt.constrain("strict", true); - typingImports.add("Union"); + moduleImports.add("typing", "Union"); PythonType pt = new PythonType("Union"); pt.addTypeParam(floatt); pt.addTypeParam(intt); @@ -1881,15 +1836,15 @@ private PythonType numberType(IJsonSchemaValidationProperties cp) { } } else { if ("Union[StrictFloat, StrictInt]".equals(mapNumberTo)) { - typingImports.add("Union"); - pydanticImports.add("StrictFloat"); - pydanticImports.add("StrictInt"); + moduleImports.add("typing", "Union"); + moduleImports.add("pydantic", "StrictFloat"); + moduleImports.add("pydantic", "StrictInt"); PythonType pt = new PythonType("Union"); pt.addTypeParam(new PythonType("StrictFloat")); pt.addTypeParam(new PythonType("StrictInt")); return pt; } else if ("StrictFloat".equals(mapNumberTo)) { - pydanticImports.add("StrictFloat"); + moduleImports.add("pydantic", "StrictFloat"); return new PythonType("StrictFloat"); } else { return new PythonType("float"); @@ -1921,7 +1876,7 @@ private PythonType intType(IJsonSchemaValidationProperties cp) { } return pt; } else { - pydanticImports.add("StrictInt"); + moduleImports.add("pydantic", "StrictInt"); return new PythonType("StrictInt"); } } @@ -1943,21 +1898,21 @@ private PythonType binaryType(IJsonSchemaValidationProperties cp) { strt.constrain("min_length", cp.getMinLength()); } if (cp.getPattern() != null) { - pydanticImports.add("field_validator"); + moduleImports.add("pydantic", "field_validator"); // use validator instead as regex doesn't support flags, e.g. IGNORECASE //fieldCustomization.add(Locale.ROOT, String.format(Locale.ROOT, "regex=r'%s'", cp.getPattern())); } - typingImports.add("Union"); + moduleImports.add("typing", "Union"); PythonType pt = new PythonType("Union"); pt.addTypeParam(bytest); pt.addTypeParam(strt); return pt; } else { // same as above which has validation - pydanticImports.add("StrictBytes"); - pydanticImports.add("StrictStr"); - typingImports.add("Union"); + moduleImports.add("pydantic", "StrictBytes"); + moduleImports.add("pydantic", "StrictStr"); + moduleImports.add("typing", "Union"); PythonType pt = new PythonType("Union"); pt.addTypeParam(new PythonType("StrictBytes")); @@ -1967,13 +1922,13 @@ private PythonType binaryType(IJsonSchemaValidationProperties cp) { } private PythonType boolType(IJsonSchemaValidationProperties cp) { - pydanticImports.add("StrictBool"); + moduleImports.add("pydantic", "StrictBool"); return new PythonType("StrictBool"); } private PythonType decimalType(IJsonSchemaValidationProperties cp) { PythonType pt = new PythonType("Decimal"); - otherImports.add("decimal", "Decimal"); + moduleImports.add("decimal", "Decimal"); if (cp.getHasValidation()) { // e.g. condecimal(ge=10, le=100, strict=True) @@ -2001,16 +1956,16 @@ private PythonType decimalType(IJsonSchemaValidationProperties cp) { } private PythonType anyType(IJsonSchemaValidationProperties cp) { - typingImports.add("Any"); + moduleImports.add("typing", "Any"); return new PythonType("Any"); } private PythonType dateType(IJsonSchemaValidationProperties cp) { if (cp.getIsDate()) { - datetimeImports.add("date"); + moduleImports.add("datetime", "date"); } if (cp.getIsDateTime()) { - datetimeImports.add("datetime"); + moduleImports.add("datetime", "datetime"); } return new PythonType(cp.getDataType()); @@ -2020,16 +1975,6 @@ private PythonType uuidType(IJsonSchemaValidationProperties cp) { return new PythonType(cp.getDataType()); } - private PythonType freeFormType(IJsonSchemaValidationProperties cp) { - typingImports.add("Dict"); - typingImports.add("Any"); - typingImports.add("Union"); - PythonType pt = new PythonType("Union"); - pt.addTypeParam(new PythonType("str")); - pt.addTypeParam(new PythonType("Any")); - return pt; - } - private PythonType modelType(IJsonSchemaValidationProperties cp) { // add model prefix hasModelsToImport = true; @@ -2042,17 +1987,17 @@ private PythonType fromCommon(IJsonSchemaValidationProperties cp) { if (cp == null) { // if codegen property (e.g. map/dict of undefined type) is null, default to string LOGGER.warn("Codegen property is null (e.g. map/dict of undefined type). Default to typing.Any."); - typingImports.add("Any"); + moduleImports.add("typing", "Any"); return new PythonType("Any"); } if (cp.getIsEnum()) { - pydanticImports.add("field_validator"); + moduleImports.add("pydantic", "field_validator"); } if (cp.getIsArray()) { return arrayType(cp); - } else if (cp.getIsMap()) { + } else if (cp.getIsMap() || cp.getIsFreeFormObject()) { return mapType(cp); } else if (cp.getIsString()) { return stringType(cp); @@ -2072,8 +2017,6 @@ private PythonType fromCommon(IJsonSchemaValidationProperties cp) { return dateType(cp); } else if (cp.getIsUuid()) { return uuidType(cp); - } else if (cp.getIsFreeFormObject()) { // type: object - return freeFormType(cp); } return null; @@ -2091,7 +2034,7 @@ private PythonType getType(CodegenProperty cp) { also need to put cp.isEnum check after isArray, isMap check if (cp.isEnum) { // use Literal for inline enum - typingImports.add("Literal"); + moduleImports.add("typing", "Literal"); List values = new ArrayList<>(); List> enumVars = (List>) cp.allowableValues.get("enumVars"); if (enumVars != null) { @@ -2140,7 +2083,7 @@ private PythonType getType(CodegenProperty cp) { private String finalizeType(CodegenProperty cp, PythonType pt) { if (!cp.required || cp.isNullable) { - typingImports.add("Optional"); + moduleImports.add("typing", "Optional"); PythonType opt = new PythonType("Optional"); opt.addTypeParam(pt); pt = opt; @@ -2175,8 +2118,8 @@ private String finalizeType(CodegenProperty cp, PythonType pt) { } } - String typeConstraint = pt.asTypeConstraint(otherImports); - String typeValue = pt.asTypeValue(otherImports); + String typeConstraint = pt.asTypeConstraint(moduleImports); + String typeValue = pt.asTypeValue(moduleImports); if (typeValue == null) { return typeConstraint; @@ -2208,7 +2151,7 @@ private PythonType getType(CodegenParameter cp) { // TODO process the first one only at the moment if (cmt != null) // TODO: don't loop back to the deprecated getPydanticType method - result = getPydanticType(cmt.getSchema(), typingImports, pydanticImports, datetimeImports, modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname); + return getPydanticType(cmt.getSchema(), modelImports, exampleImports, postponedModelImports, postponedExampleImports, classname); } throw new RuntimeException("Error! Failed to process getPydanticType when getting the content: " + cp); } else { @@ -2221,7 +2164,7 @@ private PythonType getType(CodegenParameter cp) { private String finalizeType(CodegenParameter cp, PythonType pt) { if (!cp.required || cp.isNullable) { - typingImports.add("Optional"); + moduleImports.add("typing", "Optional"); PythonType opt = new PythonType("Optional"); opt.addTypeParam(pt); pt = opt; @@ -2236,8 +2179,8 @@ private String finalizeType(CodegenParameter cp, PythonType pt) { fields.add(String.format(Locale.ROOT, "example=%s", cp.getExample())); }*/ - //return pt.asTypeConstraint(otherImports); - return pt.asTypeConstraintWithAnnotations(otherImports); + //return pt.asTypeConstraint(moduleImports); + return pt.asTypeConstraintWithAnnotations(moduleImports); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonPydanticV1Codegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonPydanticV1Codegen.java index 5fc6023360f9..52a203e3c974 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonPydanticV1Codegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractPythonPydanticV1Codegen.java @@ -881,7 +881,7 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { typingImports.add("Union"); Set discriminator = model.getDiscriminator().getMappedModels(); for (CodegenDiscriminator.MappedModel mappedModel : discriminator) { - postponedModelImports.add(mappedModel.getMappingName()); + postponedModelImports.add(mappedModel.getModelName()); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java index df0c7df1dccc..107cf5dbdba4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractRustCodegen.java @@ -285,9 +285,12 @@ public String toModelDocFilename(String name) { } //// Enum naming //// - @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + // Empty strings need to be mapped to "Empty" // https://github.com/OpenAPITools/openapi-generator/issues/13453 if (Strings.isNullOrEmpty(name)) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java index 4b74d10686d9..10cfdd80cc10 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AbstractTypeScriptClientCodegen.java @@ -629,6 +629,9 @@ public String getTypeDeclaration(Schema p) { } else if (ModelUtils.isMapSchema(p)) { Schema inner = getSchemaAdditionalProperties(p); String nullSafeSuffix = getNullSafeAdditionalProps() ? " | undefined" : ""; + if (Boolean.TRUE.equals(inner.getNullable())) { + nullSafeSuffix += " | null"; + } return "{ [key: string]: " + getTypeDeclaration(unaliasSchema(inner)) + nullSafeSuffix + "; }"; } else if (ModelUtils.isFileSchema(p)) { return "File"; diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetServerCodegen.java index 9afd271def01..4248ad52050a 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/AspNetServerCodegen.java @@ -52,6 +52,7 @@ public class AspNetServerCodegen extends AbstractCSharpCodegen { public static final String BUILD_TARGET = "buildTarget"; public static final String MODEL_CLASS_MODIFIER = "modelClassModifier"; public static final String TARGET_FRAMEWORK = "targetFramework"; + public static final String NET_60_OR_LATER = "net60OrLater"; public static final String PROJECT_SDK = "projectSdk"; public static final String SDK_WEB = "Microsoft.NET.Sdk.Web"; @@ -209,6 +210,10 @@ public AspNetServerCodegen() { CodegenConstants.USE_DATETIME_OFFSET_DESC, useDateTimeOffsetFlag); + addSwitch(CodegenConstants.USE_DATETIME_FOR_DATE, + CodegenConstants.USE_DATETIME_FOR_DATE_DESC, + useDateTimeForDateFlag); + addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, useCollection); @@ -299,7 +304,7 @@ public AspNetServerCodegen() { @Override protected Set getNullableTypes() { return new HashSet<>(Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double", - "DateTime", "DateTimeOffset", "Guid")); + "DateTime", "DateOnly", "DateTimeOffset", "Guid")); } @Override @@ -462,6 +467,11 @@ public void processOpts() { this.setTypeMapping(); } + @Override + protected boolean useNet60OrLater() { + return additionalProperties.containsKey(NET_60_OR_LATER); + } + public void setPackageGuid(String packageGuid) { this.packageGuid = packageGuid; } @@ -775,6 +785,20 @@ private void setIsFramework() { useFrameworkReference = true; additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference); additionalProperties.put(TARGET_FRAMEWORK, "net6.0"); + } else if (aspnetCoreVersion.getOptValue().startsWith("7.")) { + LOGGER.warn( + "ASP.NET core version is {} so changing to use frameworkReference instead of packageReference ", + aspnetCoreVersion.getOptValue()); + useFrameworkReference = true; + additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference); + additionalProperties.put(TARGET_FRAMEWORK, "net7.0"); + } else if (aspnetCoreVersion.getOptValue().startsWith("8.")) { + LOGGER.warn( + "ASP.NET core version is {} so changing to use frameworkReference instead of packageReference ", + aspnetCoreVersion.getOptValue()); + useFrameworkReference = true; + additionalProperties.put(USE_FRAMEWORK_REFERENCE, useFrameworkReference); + additionalProperties.put(TARGET_FRAMEWORK, "net8.0"); } else { if (additionalProperties.containsKey(USE_FRAMEWORK_REFERENCE)) { useFrameworkReference = convertPropertyToBooleanAndWriteBack(USE_FRAMEWORK_REFERENCE); @@ -783,6 +807,17 @@ private void setIsFramework() { } additionalProperties.put(TARGET_FRAMEWORK, "netcoreapp" + aspnetCoreVersion); } + + setAddititonalPropertyForFramework(); + } + + private void setAddititonalPropertyForFramework() { + String targetFramework = ((String)additionalProperties.get(TARGET_FRAMEWORK)); + if (targetFramework.startsWith("net6.0") || + targetFramework.startsWith("net7.0") || + targetFramework.startsWith("net8.0")) { + additionalProperties.put(NET_60_OR_LATER, true); + } } private void setUseNewtonsoft() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java index bb27fe20f646..f084de1cc735 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpClientCodegen.java @@ -78,6 +78,7 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected static final String NET_48_OR_LATER = "net48OrLater"; protected static final String NET_60_OR_LATER = "net60OrLater"; protected static final String NET_70_OR_LATER = "net70OrLater"; + protected static final String NET_80_OR_LATER = "net80OrLater"; @SuppressWarnings("hiding") private final Logger LOGGER = LoggerFactory.getLogger(CSharpClientCodegen.class); @@ -91,7 +92,8 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { FrameworkStrategy.NETFRAMEWORK_4_7, FrameworkStrategy.NETFRAMEWORK_4_8, FrameworkStrategy.NET_6_0, - FrameworkStrategy.NET_7_0 + FrameworkStrategy.NET_7_0, + FrameworkStrategy.NET_8_0 ); private static FrameworkStrategy latestFramework = frameworkStrategies.get(frameworkStrategies.size() - 1); protected final Map frameworks; @@ -112,9 +114,10 @@ public class CSharpClientCodegen extends AbstractCSharpCodegen { protected boolean supportsAsync = Boolean.TRUE; protected boolean netStandard = Boolean.FALSE; protected boolean supportsFileParameters = Boolean.TRUE; + protected boolean supportsDateOnly = Boolean.FALSE; protected boolean validatable = Boolean.TRUE; - protected boolean equatable = Boolean.TRUE; + protected boolean equatable = Boolean.FALSE; // By default, generated code is considered public protected boolean nonPublicApi = Boolean.FALSE; @@ -262,6 +265,10 @@ public CSharpClientCodegen() { CodegenConstants.USE_DATETIME_OFFSET_DESC, this.useDateTimeOffsetFlag); + addSwitch(CodegenConstants.USE_DATETIME_FOR_DATE, + CodegenConstants.USE_DATETIME_FOR_DATE_DESC, + useDateTimeForDateFlag); + addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, this.useCollection); @@ -357,6 +364,11 @@ protected Set getValueTypes() { : new HashSet<>(Arrays.asList("decimal", "bool", "int", "uint", "long", "ulong", "float", "double")); } + @Override + protected boolean useNet60OrLater() { + return additionalProperties.containsKey(NET_60_OR_LATER); + } + @Override protected void setTypeMapping() { super.setTypeMapping(); @@ -454,14 +466,13 @@ public CodegenModel fromModel(String name, Schema model) { Collections.sort(codegenModel.readWriteVars, propertyComparatorByName); Collections.sort(codegenModel.parentVars, propertyComparatorByName); - Comparator comparator = propertyComparatorByNullable.thenComparing(propertyComparatorByDefaultValue); - Collections.sort(codegenModel.vars, comparator); - Collections.sort(codegenModel.allVars, comparator); - Collections.sort(codegenModel.requiredVars, comparator); - Collections.sort(codegenModel.optionalVars, comparator); - Collections.sort(codegenModel.readOnlyVars, comparator); - Collections.sort(codegenModel.readWriteVars, comparator); - Collections.sort(codegenModel.parentVars, comparator); + Collections.sort(codegenModel.vars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.allVars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.requiredVars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.optionalVars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.readOnlyVars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.readWriteVars, propertyComparatorByNotNullableRequiredNoDefault); + Collections.sort(codegenModel.parentVars, propertyComparatorByNotNullableRequiredNoDefault); } return codegenModel; @@ -474,24 +485,12 @@ public int compare(CodegenProperty one, CodegenProperty another) { } }; - public static Comparator propertyComparatorByDefaultValue = new Comparator() { - @Override - public int compare(CodegenProperty one, CodegenProperty another) { - if ((one.defaultValue == null) == (another.defaultValue == null)) - return 0; - else if (one.defaultValue == null) - return -1; - else - return 1; - } - }; - - public static Comparator propertyComparatorByNullable = new Comparator() { + public static Comparator propertyComparatorByNotNullableRequiredNoDefault = new Comparator() { @Override public int compare(CodegenProperty one, CodegenProperty another) { - if (one.isNullable == another.isNullable) + if (one.isNullable == another.isNullable && one.required == another.required && (one.defaultValue == null) == (another.defaultValue == null)) return 0; - else if (Boolean.FALSE.equals(one.isNullable)) + else if (!one.isNullable && one.required && one.defaultValue == null) return -1; else return 1; @@ -793,6 +792,7 @@ public void processOpts() { syncBooleanProperty(additionalProperties, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, this::setUseOneOfDiscriminatorLookup, this.useOneOfDiscriminatorLookup); syncBooleanProperty(additionalProperties, "supportsFileParameters", this::setSupportsFileParameters, this.supportsFileParameters); syncBooleanProperty(additionalProperties, "useSourceGeneration", this::setUseSourceGeneration, this.useSourceGeneration); + syncBooleanProperty(additionalProperties, "supportsDateOnly", this::setSupportsDateOnly, this.supportsDateOnly); final String testPackageName = testPackageName(); String packageFolder = sourceFolder + File.separator + packageName; @@ -854,6 +854,10 @@ public void processOpts() { } } + if (useDateOnly()) { + setSupportsDateOnly(true); + additionalProperties.put("supportsDateOnly", true); + } // include the spec in the output supportingFiles.add(new SupportingFile("openapi.mustache", "api", "openapi.yaml")); @@ -999,6 +1003,10 @@ public void addGenericHostSupportingFiles(final String clientPackageDir, final S supportingFiles.add(new SupportingFile("ApiFactory.mustache", clientPackageDir, "ApiFactory.cs")); supportingFiles.add(new SupportingFile("DateTimeJsonConverter.mustache", clientPackageDir, "DateTimeJsonConverter.cs")); supportingFiles.add(new SupportingFile("DateTimeNullableJsonConverter.mustache", clientPackageDir, "DateTimeNullableJsonConverter.cs")); + if (useDateOnly()) { + supportingFiles.add(new SupportingFile("DateOnlyJsonConverter.mustache", clientPackageDir, "DateOnlyJsonConverter.cs")); + supportingFiles.add(new SupportingFile("DateOnlyNullableJsonConverter.mustache", clientPackageDir, "DateOnlyNullableJsonConverter.cs")); + } supportingFiles.add(new SupportingFile("ApiResponseEventArgs`1.mustache", clientPackageDir, "ApiResponseEventArgs.cs")); supportingFiles.add(new SupportingFile("ExceptionEventArgs.mustache", clientPackageDir, "ExceptionEventArgs.cs")); supportingFiles.add(new SupportingFile("JsonSerializerOptionsProvider.mustache", clientPackageDir, "JsonSerializerOptionsProvider.cs")); @@ -1103,6 +1111,10 @@ public void setSupportsFileParameters(Boolean supportsFileParameters) { this.supportsFileParameters = supportsFileParameters; } + public void setSupportsDateOnly(Boolean supportsDateOnly) { + this.supportsDateOnly = supportsDateOnly; + } + public void setSupportsRetry(Boolean supportsRetry) { this.supportsRetry = supportsRetry; } @@ -1188,6 +1200,10 @@ public boolean getUseOneOfDiscriminatorLookup() { @Override public String toEnumVarName(String value, String datatype) { + if (enumNameMapping.containsKey(value)) { + return enumNameMapping.get(value); + } + if (value.length() == 0) { return "Empty"; } @@ -1341,6 +1357,8 @@ private static abstract class FrameworkStrategy { }; static FrameworkStrategy NET_7_0 = new FrameworkStrategy("net7.0", ".NET 7.0", "net7.0", Boolean.FALSE) { }; + static FrameworkStrategy NET_8_0 = new FrameworkStrategy("net8.0", ".NET 8.0", "net8.0", Boolean.FALSE) { + }; protected String name; protected String description; protected String testTargetFramework; @@ -1464,8 +1482,19 @@ protected void configureAdditionalPropertiesForFrameworks(final Map "net8.0".equals(p.name))) { + properties.put(NET_STANDARD_14_OR_LATER, true); + properties.put(NET_STANDARD_15_OR_LATER, true); + properties.put(NET_STANDARD_16_OR_LATER, true); + properties.put(NET_STANDARD_20_OR_LATER, true); + properties.put(NET_STANDARD_21_OR_LATER, true); + properties.put(NET_47_OR_LATER, true); + properties.put(NET_48_OR_LATER, true); + properties.put(NET_60_OR_LATER, true); + properties.put(NET_70_OR_LATER, true); + properties.put(NET_80_OR_LATER, true); } else { - throw new RuntimeException("Unhanlded case"); + throw new RuntimeException("Unhandled case"); } } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpFunctionsServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpFunctionsServerCodegen.java index 0052dbb04701..9aaffde2c104 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpFunctionsServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CSharpFunctionsServerCodegen.java @@ -53,6 +53,7 @@ public class CSharpFunctionsServerCodegen extends AbstractCSharpCodegen { public static final String COMPATIBILITY_VERSION = "compatibilityVersion"; public static final String USE_NEWTONSOFT = "useNewtonsoft"; public static final String NEWTONSOFT_VERSION = "newtonsoftVersion"; + public static final String NET_60_OR_LATER = "net60OrLater"; private String packageGuid = "{" + randomUUID().toString().toUpperCase(Locale.ROOT) + "}"; private String userSecretsGuid = randomUUID().toString(); @@ -188,6 +189,10 @@ public CSharpFunctionsServerCodegen() { CodegenConstants.USE_DATETIME_OFFSET_DESC, useDateTimeOffsetFlag); + addSwitch(CodegenConstants.USE_DATETIME_FOR_DATE, + CodegenConstants.USE_DATETIME_FOR_DATE_DESC, + useDateTimeForDateFlag); + addSwitch(CodegenConstants.USE_COLLECTION, CodegenConstants.USE_COLLECTION_DESC, useCollection); @@ -263,18 +268,8 @@ protected Set getValueTypes() { } @Override - protected void setTypeMapping() { - super.setTypeMapping(); - typeMapping.put("boolean", "bool"); - typeMapping.put("integer", "int"); - typeMapping.put("float", "float"); - typeMapping.put("long", "long"); - typeMapping.put("double", "double"); - typeMapping.put("number", "decimal"); - typeMapping.put("DateTime", "DateTime"); - typeMapping.put("date", "DateTime"); - typeMapping.put("UUID", "Guid"); - typeMapping.put("URI", "string"); + protected boolean useNet60OrLater() { + return additionalProperties.containsKey(NET_60_OR_LATER); } @Override @@ -607,6 +602,13 @@ private void setAzureFunctionsVersion() { //set .NET target version String targetFrameworkVersion = "net" + netCoreVersion.getOptValue(); additionalProperties.put(TARGET_FRAMEWORK, targetFrameworkVersion); + setAddititonalPropertyForFramework(); + } + + private void setAddititonalPropertyForFramework() { + if (((String)additionalProperties.get(TARGET_FRAMEWORK)).startsWith("net6.0")) { + additionalProperties.put(NET_60_OR_LATER, true); + } } private void setOperationIsAsync() { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java index 755cf3aac272..aceefd0f3c4b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppPistacheServerCodegen.java @@ -244,7 +244,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation ApiResponse apiResponse = findMethodResponse(operation.getResponses()); if (apiResponse != null) { - Schema response = ModelUtils.getSchemaFromResponse(apiResponse); + Schema response = ModelUtils.getSchemaFromResponse(openAPI, apiResponse); if (response != null) { CodegenProperty cm = fromProperty("response", response, false); op.vendorExtensions.put("x-codegen-response", cm); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java index 032f53f08a01..ca90e4b89560 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/CppRestSdkClientCodegen.java @@ -294,7 +294,7 @@ public CodegenOperation fromOperation(String path, String httpMethod, Operation ApiResponse methodResponse = findMethodResponse(operation.getResponses()); if (methodResponse != null) { - Schema response = ModelUtils.getSchemaFromResponse(methodResponse); + Schema response = ModelUtils.getSchemaFromResponse(openAPI, methodResponse); response = unaliasSchema(response); if (response != null) { CodegenProperty cm = fromProperty("response", response, false); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java index 47a9316b46d9..65b62e6b9d42 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoClientCodegen.java @@ -56,6 +56,7 @@ public class GoClientCodegen extends AbstractGoCodegen { public static final String WITH_AWSV4_SIGNATURE = "withAWSV4Signature"; public static final String GENERATE_INTERFACES = "generateInterfaces"; public static final String MODEL_FILE_FOLDER = "modelFileFolder"; + public static final String WITH_GO_MOD = "withGoMod"; protected String goImportAlias = "openapiclient"; protected boolean isGoSubmodule = false; protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup @@ -74,7 +75,8 @@ public GoClientCodegen() { SecurityFeature.BearerToken, SecurityFeature.ApiKey, SecurityFeature.OAuth2_Implicit, - SecurityFeature.SignatureAuth + SecurityFeature.SignatureAuth, + SecurityFeature.AWSV4Signature )) .includeGlobalFeatures( GlobalFeature.ParameterizedServer @@ -137,6 +139,9 @@ public GoClientCodegen() { disallowAdditionalPropertiesIfNotPresentOpt.setEnum(disallowAdditionalPropertiesIfNotPresentOpts); cliOptions.add(disallowAdditionalPropertiesIfNotPresentOpt); this.setDisallowAdditionalPropertiesIfNotPresent(true); + cliOptions.add(CliOption.newBoolean(WITH_GO_MOD, "Generate go.mod and go.sum", true)); + cliOptions.add(CliOption.newBoolean(CodegenConstants.GENERATE_MARSHAL_JSON, CodegenConstants.GENERATE_MARSHAL_JSON_DESC, true)); + this.setWithGoMod(true); } /** @@ -262,6 +267,17 @@ public void processOpts() { modelFileFolder = additionalProperties.get(MODEL_FILE_FOLDER).toString(); } + if (additionalProperties.containsKey(WITH_GO_MOD)) { + setWithGoMod(Boolean.parseBoolean(additionalProperties.get(WITH_GO_MOD).toString())); + additionalProperties.put(WITH_GO_MOD, withGoMod); + } else { + additionalProperties.put(WITH_GO_MOD, true); + } + + if (additionalProperties.containsKey(CodegenConstants.GENERATE_MARSHAL_JSON)) { + setGenerateMarshalJSON(Boolean.parseBoolean(additionalProperties.get(CodegenConstants.GENERATE_MARSHAL_JSON).toString())); + } + // add lambda for mustache templates to handle oneOf/anyOf naming // e.g. []string => ArrayOfString additionalProperties.put("lambda.type-to-name", (Mustache.Lambda) (fragment, writer) -> writer.write(typeToName(fragment.execute()))); @@ -273,8 +289,10 @@ public void processOpts() { supportingFiles.add(new SupportingFile("configuration.mustache", "", "configuration.go")); supportingFiles.add(new SupportingFile("client.mustache", "", "client.go")); supportingFiles.add(new SupportingFile("response.mustache", "", "response.go")); - supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod")); - supportingFiles.add(new SupportingFile("go.sum.mustache", "", "go.sum")); + if ((boolean)additionalProperties.get(WITH_GO_MOD)) { + supportingFiles.add(new SupportingFile("go.mod.mustache", "", "go.mod")); + supportingFiles.add(new SupportingFile("go.sum.mustache", "", "go.sum")); + } supportingFiles.add(new SupportingFile(".travis.yml", "", ".travis.yml")); supportingFiles.add(new SupportingFile("utils.mustache", "", "utils.go")); } @@ -467,14 +485,28 @@ public ModelsMap postProcessModels(ModelsMap objs) { } // additional import for different cases + boolean addedFmtImport = false; + // oneOf if (model.oneOf != null && !model.oneOf.isEmpty()) { imports.add(createMapping("import", "fmt")); + addedFmtImport = true; } // anyOf if (model.anyOf != null && !model.anyOf.isEmpty()) { imports.add(createMapping("import", "fmt")); + addedFmtImport = true; + } + + if (model.hasRequired) { + if (!model.isAdditionalPropertiesTrue) { + imports.add(createMapping("import", "bytes")); + } + + if (!addedFmtImport) { + imports.add(createMapping("import", "fmt")); + } } // additionalProperties: true and parent diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java index 97deeb584425..f2670ba25389 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/GoServerCodegen.java @@ -31,6 +31,8 @@ import java.io.File; import java.util.*; +import static org.openapitools.codegen.utils.StringUtils.camelize; + public class GoServerCodegen extends AbstractGoCodegen { /** @@ -301,6 +303,7 @@ public ModelsMap postProcessModels(ModelsMap objs) { CodegenModel model = m.getModel(); if (model.isEnum) { + imports.add(createMapping("import", "fmt")); continue; } @@ -321,34 +324,77 @@ public ModelsMap postProcessModels(ModelsMap objs) { @Override public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { - objs = super.postProcessOperationsWithModels(objs, allModels); + // TODO: refactor abstractGoCodegen, decouple go client only code and remove this OperationMap objectMap = objs.getOperations(); List operations = objectMap.getOperation(); + for (CodegenOperation operation : operations) { + // http method verb conversion (e.g. PUT => Put) + operation.httpMethod = camelize(operation.httpMethod.toLowerCase(Locale.ROOT)); + } + + // remove model imports to avoid error List> imports = objs.getImports(); if (imports == null) return objs; - // override imports to only include packages for interface parameters - imports.clear(); + Iterator> iterator = imports.iterator(); + while (iterator.hasNext()) { + String _import = iterator.next().get("import"); + if (_import.startsWith(apiPackage)) + iterator.remove(); + } boolean addedTimeImport = false; boolean addedOSImport = false; + boolean addedReflectImport = false; for (CodegenOperation operation : operations) { for (CodegenParameter param : operation.allParams) { // import "os" if the operation uses files - if (!addedOSImport && ("*os.File".equals(param.dataType) || ("[]*os.File".equals(param.dataType)))) { + if (!addedOSImport && ("*os.File".equals(param.dataType) || "[]*os.File".equals(param.dataType))) { imports.add(createMapping("import", "os")); addedOSImport = true; } - // import "time" if the operation has a required time parameter - if (param.required) { - if (!addedTimeImport && "time.Time".equals(param.dataType)) { - imports.add(createMapping("import", "time")); - addedTimeImport = true; - } + // import "time" if the operation has a time parameter. + if (!addedTimeImport && "time.Time".equals(param.dataType)) { + imports.add(createMapping("import", "time")); + addedTimeImport = true; + } + + // import "reflect" package if the parameter is collectionFormat=multi + if (!addedReflectImport && param.isCollectionFormatMulti) { + imports.add(createMapping("import", "reflect")); + addedReflectImport = true; } + + // set x-exportParamName + char nameFirstChar = param.paramName.charAt(0); + if (Character.isUpperCase(nameFirstChar)) { + // First char is already uppercase, just use paramName. + param.vendorExtensions.put("x-export-param-name", param.paramName); + } else { + // It's a lowercase first char, let's convert it to uppercase + StringBuilder sb = new StringBuilder(param.paramName); + sb.setCharAt(0, Character.toUpperCase(nameFirstChar)); + param.vendorExtensions.put("x-export-param-name", sb.toString()); + } + } + + } + + // recursively add import for mapping one type to multiple imports + List> recursiveImports = objs.getImports(); + if (recursiveImports == null) + return objs; + + ListIterator> listIterator = imports.listIterator(); + while (listIterator.hasNext()) { + String _import = listIterator.next().get("import"); + // if the import package happens to be found in the importMapping (key) + // add the corresponding import package to the list + if (importMapping.containsKey(_import)) { + listIterator.add(createMapping("import", importMapping.get(_import))); } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java index b8953d8f9845..5779f9631234 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JMeterClientCodegen.java @@ -163,6 +163,12 @@ public void preprocessOpenAPI(OpenAPI openAPI) { } } + @Override + public String toOperationId(String operationId) { + // replace $ with _ + return super.toOperationId(operationId.replace("$", "_")); + } + /** * Escapes a reserved word as defined in the `reservedWords` array. Handle escaping * those terms here. This logic is only called if a variable matches the reserved words diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java index 27561d94fa15..6c390a9b4768 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/JavaClientCodegen.java @@ -133,12 +133,15 @@ public class JavaClientCodegen extends AbstractJavaCodegen protected String serializationLibrary = null; protected boolean useOneOfDiscriminatorLookup = false; // use oneOf discriminator's mapping for model lookup protected String rootJavaEEPackage; - protected Map mpRestClientVersions = new HashMap<>(); + protected Map mpRestClientVersions = new LinkedHashMap<>(); protected boolean useSingleRequestParameter = false; protected boolean webclientBlockingOperations = false; protected boolean generateClientAsBean = false; protected boolean useEnumCaseInsensitive = false; + protected int maxAttemptsForRetry = 1; + protected long waitTimeMillis = 10l; + private static class MpRestClientVersion { public final String rootPackage; public final String pomTemplate; @@ -181,7 +184,8 @@ public JavaClientCodegen() { .includeSecurityFeatures(SecurityFeature.OAuth2_AuthorizationCode, SecurityFeature.OAuth2_ClientCredentials, SecurityFeature.OAuth2_Password, - SecurityFeature.SignatureAuth)//jersey only + SecurityFeature.SignatureAuth,//jersey only + SecurityFeature.AWSV4Signature)//okhttp-gson only ); outputFolder = "generated-code" + File.separator + "java"; @@ -222,7 +226,7 @@ public JavaClientCodegen() { cliOptions.add(CliOption.newString(CONFIG_KEY, "Config key in @RegisterRestClient. Default to none. Only `microprofile` supports this option.")); cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP_DESC + " Only jersey2, jersey3, native, okhttp-gson support this option.")); cliOptions.add(CliOption.newString(MICROPROFILE_REST_CLIENT_VERSION, "Version of MicroProfile Rest Client API.")); - cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter. ONLY jersey2, jersey3, okhttp-gson support this option.")); + cliOptions.add(CliOption.newBoolean(CodegenConstants.USE_SINGLE_REQUEST_PARAMETER, "Setting this property to true will generate functions with a single argument containing all API endpoint parameters instead of one argument per parameter. ONLY jersey2, jersey3, okhttp-gson, microprofile support this option.")); cliOptions.add(CliOption.newBoolean(WEBCLIENT_BLOCKING_OPERATIONS, "Making all WebClient operations blocking(sync). Note that if on operation 'x-webclient-blocking: false' then such operation won't be sync", this.webclientBlockingOperations)); cliOptions.add(CliOption.newBoolean(GENERATE_CLIENT_AS_BEAN, "For resttemplate, configure whether to create `ApiClient.java` and Apis clients as bean (with `@Component` annotation).", this.generateClientAsBean)); cliOptions.add(CliOption.newBoolean(SUPPORT_URL_QUERY, "Generate toUrlQueryString in POJO (default to true). Available on `native`, `apache-httpclient` libraries.")); @@ -465,6 +469,20 @@ public void processOpts() { if (additionalProperties.containsKey(USE_ENUM_CASE_INSENSITIVE)) { this.setUseEnumCaseInsensitive(Boolean.parseBoolean(additionalProperties.get(USE_ENUM_CASE_INSENSITIVE).toString())); } + + if (additionalProperties.containsKey(CodegenConstants.MAX_ATTEMPTS_FOR_RETRY)) { + this.setMaxAttemptsForRetry(Integer.parseInt(additionalProperties.get(CodegenConstants.MAX_ATTEMPTS_FOR_RETRY).toString())); + } + else { + additionalProperties.put(CodegenConstants.MAX_ATTEMPTS_FOR_RETRY, maxAttemptsForRetry); + } + + if (additionalProperties.containsKey(CodegenConstants.WAIT_TIME_OF_THREAD)) { + this.setWaitTimeMillis(Long.parseLong((additionalProperties.get(CodegenConstants.WAIT_TIME_OF_THREAD).toString()))); + } + else { + additionalProperties.put(CodegenConstants.WAIT_TIME_OF_THREAD, waitTimeMillis); + } writePropertyBack(USE_ENUM_CASE_INSENSITIVE, useEnumCaseInsensitive); final String invokerFolder = (sourceFolder + '/' + invokerPackage).replace(".", "/"); @@ -1240,6 +1258,14 @@ public void setUseEnumCaseInsensitive(boolean useEnumCaseInsensitive) { this.useEnumCaseInsensitive = useEnumCaseInsensitive; } + public void setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry= maxAttemptsForRetry; + } + + public void setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis= waitTimeMillis; + } + /** * Serialization library. * diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java index 704ae7c556fb..98afde69eb9d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinClientCodegen.java @@ -65,7 +65,9 @@ public class KotlinClientCodegen extends AbstractKotlinCodegen { protected static final String MULTIPLATFORM = "multiplatform"; protected static final String JVM_VOLLEY = "jvm-volley"; protected static final String JVM_VERTX = "jvm-vertx"; + protected static final String JVM_SPRING = "jvm-spring"; protected static final String JVM_SPRING_WEBCLIENT = "jvm-spring-webclient"; + protected static final String JVM_SPRING_RESTCLIENT = "jvm-spring-restclient"; public static final String USE_RX_JAVA3 = "useRxJava3"; public static final String USE_COROUTINES = "useCoroutines"; @@ -113,7 +115,8 @@ public enum DateLibrary { THREETENBP("threetenbp"), THREETENBP_LOCALDATETIME("threetenbp-localdatetime"), JAVA8("java8"), - JAVA8_LOCALDATETIME("java8-localdatetime"); + JAVA8_LOCALDATETIME("java8-localdatetime"), + KOTLINX_DATETIME("kotlinx-datetime"); public final String value; @@ -203,6 +206,7 @@ public KotlinClientCodegen() { dateOptions.put(DateLibrary.STRING.value, "String"); dateOptions.put(DateLibrary.JAVA8.value, "Java 8 native JSR310 (jvm only, preferred for jdk 1.8+)"); dateOptions.put(DateLibrary.JAVA8_LOCALDATETIME.value, "Java 8 native JSR310 (jvm only, for legacy app only)"); + dateOptions.put(DateLibrary.KOTLINX_DATETIME.value, "kotlinx-datetime (preferred for multiplatform)"); dateLibrary.setEnum(dateOptions); dateLibrary.setDefault(this.dateLibrary); cliOptions.add(dateLibrary); @@ -219,6 +223,7 @@ public KotlinClientCodegen() { supportedLibraries.put(JVM_OKHTTP4, "[DEFAULT] Platform: Java Virtual Machine. HTTP client: OkHttp 4.2.0 (Android 5.0+ and Java 8+). JSON processing: Moshi 1.8.0."); supportedLibraries.put(JVM_OKHTTP3, "Platform: Java Virtual Machine. HTTP client: OkHttp 3.12.4 (Android 2.3+ and Java 7+). JSON processing: Moshi 1.8.0. (DEPRECATED: this option will be remove in 7.x release)"); supportedLibraries.put(JVM_SPRING_WEBCLIENT, "Platform: Java Virtual Machine. HTTP: Spring 5 (or 6 with useSpringBoot3 enabled) WebClient. JSON processing: Jackson."); + supportedLibraries.put(JVM_SPRING_RESTCLIENT, "Platform: Java Virtual Machine. HTTP: Spring 6 RestClient. JSON processing: Jackson."); supportedLibraries.put(JVM_RETROFIT2, "Platform: Java Virtual Machine. HTTP client: Retrofit 2.6.2."); supportedLibraries.put(MULTIPLATFORM, "Platform: Kotlin multiplatform. HTTP client: Ktor 1.6.7. JSON processing: Kotlinx Serialization: 1.2.1."); supportedLibraries.put(JVM_VOLLEY, "Platform: JVM for Android. HTTP client: Volley 1.2.1. JSON processing: gson 2.8.9"); @@ -455,7 +460,10 @@ public void processOpts() { processJVMRetrofit2Library(infrastructureFolder); break; case JVM_SPRING_WEBCLIENT: - processJVMSpringWebClientLibrary(infrastructureFolder); + processJvmSpringWebClientLibrary(infrastructureFolder); + break; + case JVM_SPRING_RESTCLIENT: + processJvmSpringRestClientLibrary(infrastructureFolder); break; case MULTIPLATFORM: processMultiplatformLibrary(infrastructureFolder); @@ -515,6 +523,8 @@ private void processDateLibrary() { processStringDate(); } else if (DateLibrary.JAVA8.value.equals(dateLibrary) || DateLibrary.JAVA8_LOCALDATETIME.value.equals(dateLibrary)) { processJava8Date(dateLibrary); + } else if (DateLibrary.KOTLINX_DATETIME.value.equals(dateLibrary)) { + processKotlinxDate(); } } @@ -566,6 +576,14 @@ private void processJava8Date(String dateLibrary) { } } + private void processKotlinxDate() { + additionalProperties.put(DateLibrary.KOTLINX_DATETIME.value, true); + + typeMapping.put("date-time", "kotlinx.datetime.Instant"); + typeMapping.put("DateTime", "Instant"); + importMapping.put("Instant", "kotlinx.datetime.Instant"); + } + private void processJVMRetrofit2Library(String infrastructureFolder) { additionalProperties.put(JVM, true); additionalProperties.put(JVM_RETROFIT2, true); @@ -629,6 +647,7 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); + addKotlinxDateTimeInstantAdapter(infrastructureFolder); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigDecimalAdapter.kt.mustache", infrastructureFolder, "BigDecimalAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/BigIntegerAdapter.kt.mustache", infrastructureFolder, "BigIntegerAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/URIAdapter.kt.mustache", infrastructureFolder, "URIAdapter.kt")); @@ -639,6 +658,7 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateAdapter.kt.mustache", infrastructureFolder, "LocalDateAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/LocalDateTimeAdapter.kt.mustache", infrastructureFolder, "LocalDateTimeAdapter.kt")); supportingFiles.add(new SupportingFile("jvm-common/infrastructure/OffsetDateTimeAdapter.kt.mustache", infrastructureFolder, "OffsetDateTimeAdapter.kt")); + addKotlinxDateTimeInstantAdapter(infrastructureFolder); break; case jackson: @@ -662,6 +682,12 @@ private void addSupportingSerializerAdapters(final String infrastructureFolder) } } + private void addKotlinxDateTimeInstantAdapter(final String infrastructureFolder) { + if (DateLibrary.KOTLINX_DATETIME.value.equals(dateLibrary)) { + supportingFiles.add(new SupportingFile("jvm-common/infrastructure/InstantAdapter.kt.mustache", infrastructureFolder, "InstantAdapter.kt")); + } + } + private void processJVMKtorLibrary(final String infrastructureFolder) { // in future kotlinx.serialization may be added if (this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.gson && this.serializationLibrary != SERIALIZATION_LIBRARY_TYPE.jackson) { @@ -726,7 +752,7 @@ private void processJVMOkHttpLibrary(final String infrastructureFolder) { supportingFiles.add(new SupportingFile("infrastructure/ApiResponse.kt.mustache", infrastructureFolder, "ApiResponse.kt")); } - private void processJVMSpringWebClientLibrary(final String infrastructureFolder) { + private void proccessJvmSpring(final String infrastructureFolder) { if (getSerializationLibrary() != SERIALIZATION_LIBRARY_TYPE.jackson) { throw new RuntimeException("This library currently only supports jackson serialization. Try adding '--additional-properties serializationLibrary=jackson' to your command."); } @@ -734,14 +760,32 @@ private void processJVMSpringWebClientLibrary(final String infrastructureFolder) commonJvmMultiplatformSupportingFiles(infrastructureFolder); addSupportingSerializerAdapters(infrastructureFolder); + additionalProperties.put(JVM_SPRING, true); additionalProperties.put(JVM, true); + } + + private void processJvmSpringWebClientLibrary(final String infrastructureFolder) { + proccessJvmSpring(infrastructureFolder); additionalProperties.put(JVM_SPRING_WEBCLIENT, true); } + private void processJvmSpringRestClientLibrary(final String infrastructureFolder) { + if (additionalProperties.getOrDefault(USE_SPRING_BOOT3, false).equals(false)) { + throw new RuntimeException("This library muse use spring boot 3. Try adding '--additional-properties useSpringBoot3=true' to your command."); + } + + proccessJvmSpring(infrastructureFolder); + additionalProperties.put(JVM_SPRING_RESTCLIENT, true); + } + private void processMultiplatformLibrary(final String infrastructureFolder) { commonJvmMultiplatformSupportingFiles(infrastructureFolder); additionalProperties.put(MULTIPLATFORM, true); - setDateLibrary(DateLibrary.STRING.value); + + if (!DateLibrary.STRING.value.equals(dateLibrary) && !DateLibrary.KOTLINX_DATETIME.value.equals(dateLibrary)) { + throw new RuntimeException("Multiplatform only supports string and kotlinx-datetime. Try adding '--additional-properties dateLibrary=kotlinx-datetime' to your command."); + } + setRequestDateConverter(RequestDateConverter.TO_STRING.value); // multiplatform default includes diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java index d5e7eee753ed..ce14fe19a631 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/KotlinSpringServerCodegen.java @@ -101,6 +101,7 @@ public class KotlinSpringServerCodegen extends AbstractKotlinCodegen public static final String BEAN_QUALIFIERS = "beanQualifiers"; public static final String USE_SPRING_BOOT3 = "useSpringBoot3"; + public static final String APPEND_REQUEST_TO_HANDLER = "appendRequestToHandler"; private String basePackage; protected String configPackage; @@ -203,6 +204,7 @@ public KotlinSpringServerCodegen() { "@RestController annotations. May be used to prevent bean names clash if multiple generated libraries" + " (contexts) added to single project.", beanQualifiers); addSwitch(USE_SPRING_BOOT3, "Generate code and provide dependencies for use with Spring Boot 3.x. (Use jakarta instead of javax in imports). Enabling this option will also enable `useJakartaEe`.", useSpringBoot3); + addSwitch(APPEND_REQUEST_TO_HANDLER, "Append ServerHttpRequest to handler method for getting request stuff", false); supportedLibraries.put(SPRING_BOOT, "Spring-boot Server application."); supportedLibraries.put(SPRING_CLOUD_LIBRARY, "Spring-Cloud-Feign client with Spring-Boot auto-configured settings."); @@ -377,6 +379,10 @@ public void setUseTags(boolean useTags) { this.useTags = useTags; } + public boolean isAppendRequestToHandler() { + return Boolean.parseBoolean(additionalProperties.get(APPEND_REQUEST_TO_HANDLER).toString()); + } + public void setUseSpringBoot3(boolean isSpringBoot3) { this.useSpringBoot3 = isSpringBoot3; } @@ -744,8 +750,8 @@ public void processOpts() { additionalProperties.put("jackson", "true"); // add lambda for mustache templates - additionalProperties.put("lambdaEscapeDoubleQuote", - (Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("\"", Matcher.quoteReplacement("\\\"")))); + additionalProperties.put("lambdaEscapeInNormalString", + (Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("([$\"\\\\])", "\\\\$1"))); additionalProperties.put("lambdaRemoveLineBreak", (Mustache.Lambda) (fragment, writer) -> writer.write(fragment.execute().replaceAll("[\\r\\n]", ""))); } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/N4jsClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/N4jsClientCodegen.java index 290972ac9201..49a3166668ec 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/N4jsClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/N4jsClientCodegen.java @@ -229,11 +229,10 @@ private boolean processBooleanOpt(String OPT, boolean defaultValue) { @Override public String toModelFilename(String name) { - String modelFilename = super.toModelFilename(name); - if (typeMapping.containsKey(modelFilename) || defaultIncludes.contains(modelFilename)) { - return modelFilename; + if (typeMapping.containsKey(name) || defaultIncludes.contains(name)) { + return name; } - return modelFilename; + return super.toModelFilename(name); } public boolean checkRequiredBodyPropsNotNull() { @@ -485,10 +484,11 @@ private Map toN4jsImports(String className, Map(p.getEnum())); } } - return this.getTypeDeclaration(p); + String result = this.getTypeDeclaration(p); + if (result != null) { + result = toModelFilename(result); + } + return result; } @Override @@ -578,7 +582,11 @@ protected String getSingleSchemaType(@SuppressWarnings("rawtypes") Schema schema } } } - return super.getSingleSchemaType(unaliasSchema); + String result = super.getSingleSchemaType(unaliasSchema); + if (result != null) { + result = toModelFilename(result); + } + return result; } /** diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpNextgenClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpNextgenClientCodegen.java index 3be05eede2ad..3c57a89f4abf 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpNextgenClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpNextgenClientCodegen.java @@ -149,7 +149,7 @@ private ModelsMap postProcessModelsMap(ModelsMap objs) { propType = prop.dataType; } - if ((!prop.required || prop.isNullable)) { // optional or nullable + if ((!prop.required || prop.isNullable) && !propType.equals("mixed")) { // optional or nullable but not mixed propType = "?" + propType; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java index 177f8600e55d..9334bad5ab19 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PhpSymfonyServerCodegen.java @@ -407,13 +407,13 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List> codegenOperationsByTag = new HashMap<>(); + public Map> codegenOperationsByTag = new HashMap<>(); // list of operations - protected List codegenOperationsList = new ArrayList<>(); + public List codegenOperationsList = new ArrayList<>(); /** * Configures the type of generator. @@ -131,6 +131,7 @@ public PostmanCollectionCodegen() { @Override public void postProcessParameter(CodegenParameter parameter) { + // create Postman variable from every path parameter if(pathParamsAsVariables && parameter.isPathParam) { variables.add(new PostmanVariable() .addName(parameter.paramName) @@ -216,8 +217,14 @@ public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List obj.path)); } - void addToList(CodegenOperation codegenOperation) { + public void addToList(CodegenOperation codegenOperation) { + codegenOperationsList.add(codegenOperation); + + // sort requests by path + Collections.sort(codegenOperationsList, Comparator.comparing(obj -> obj.path)); } String getResponseBody(CodegenResponse codegenResponse) { @@ -492,15 +505,13 @@ public String escapeQuotationMark(String input) { return input.replace("\"", "\\\""); } - public String doubleCurlyBraces(String str) { + // convert path from /users/{id} to /users/:id + String replacesBracesInPath(String path) { - // remove doublebraces first - String s = str.replace("{{", "{").replace("}}", "}"); - // change all singlebraces to doublebraces - s = s.replace("{", "{{").replace("}", "}}"); + String s = path.replace("{", ":"); + s = s.replace("}", ""); return s; - } public String extractExampleByName(String ref) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPydanticV1ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPydanticV1ClientCodegen.java index 08db2c380ac3..0c7c0bbc78e4 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPydanticV1ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/PythonPydanticV1ClientCodegen.java @@ -120,7 +120,7 @@ public PythonPydanticV1ClientCodegen() { modelTestTemplateFiles.put("model_test.mustache", ".py"); apiTestTemplateFiles.put("api_test.mustache", ".py"); - embeddedTemplateDir = templateDir = "python"; + embeddedTemplateDir = templateDir = "python-pydantic-v1"; modelDocTemplateFiles.put("model_doc.mustache", ".md"); apiDocTemplateFiles.put("api_doc.mustache", ".md"); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java index 18127e4fa8b8..d3b90ce2eea5 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RubyClientCodegen.java @@ -48,6 +48,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { public static final String GEM_DESCRIPTION = "gemDescription"; public static final String GEM_AUTHOR = "gemAuthor"; public static final String GEM_AUTHOR_EMAIL = "gemAuthorEmail"; + public static final String GEM_METADATA = "gemMetadata"; public static final String FARADAY = "faraday"; public static final String HTTPX = "httpx"; public static final String TYPHOEUS = "typhoeus"; @@ -66,6 +67,7 @@ public class RubyClientCodegen extends AbstractRubyCodegen { protected String gemSummary = "A Ruby SDK for the REST API"; protected String gemDescription = "This gem maps to a REST API"; protected String gemAuthor = ""; + protected String gemMetadata = "{}"; protected String gemAuthorEmail = ""; protected String apiDocPath = "docs/"; protected String modelDocPath = "docs/"; @@ -170,6 +172,9 @@ public RubyClientCodegen() { cliOptions.add(new CliOption(GEM_AUTHOR_EMAIL, "gem author email (only one is supported).")); + cliOptions.add(new CliOption(GEM_METADATA, "gem metadata."). + defaultValue("{}")); + cliOptions.add(new CliOption(CodegenConstants.HIDE_GENERATION_TIMESTAMP, CodegenConstants.HIDE_GENERATION_TIMESTAMP_DESC). defaultValue(Boolean.TRUE.toString())); @@ -246,6 +251,10 @@ public void processOpts() { setGemAuthorEmail((String) additionalProperties.get(GEM_AUTHOR_EMAIL)); } + if (additionalProperties.containsKey(GEM_METADATA)) { + setGemMetadata((String) additionalProperties.get(GEM_METADATA)); + } + if (additionalProperties.containsKey(USE_AUTOLOAD)) { setUseAutoload(convertPropertyToBooleanAndWriteBack(USE_AUTOLOAD)); } @@ -292,10 +301,6 @@ public void processOpts() { .doNotOverwrite()); supportingFiles.add(new SupportingFile("spec_helper.mustache", specFolder, "spec_helper.rb") .doNotOverwrite()); - supportingFiles.add(new SupportingFile("configuration_spec.mustache", specFolder, "configuration_spec.rb") - .doNotOverwrite()); - supportingFiles.add(new SupportingFile("api_client_spec.mustache", specFolder, "api_client_spec.rb") - .doNotOverwrite()); // add lambda to convert a symbol to a string if an underscore is included (e.g. :'user_uuid' => 'user_uuid') additionalProperties.put("lambdaFixHeaderKey", new Mustache.Lambda() { @@ -405,6 +410,10 @@ public String toModelName(final String name) { return schemaMapping.get(name); } + if (modelNameMapping.containsKey(name)) { + return modelNameMapping.get(name); + } + // memoization String origName = name; if (schemaKeyToModelNameCache.containsKey(origName)) { @@ -499,6 +508,10 @@ public String toEnumValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + if (name.length() == 0) { return "EMPTY"; } @@ -526,6 +539,10 @@ public String toEnumVarName(String name, String datatype) { @Override public String toEnumName(CodegenProperty property) { + if (enumNameMapping.containsKey(property.name)) { + return enumNameMapping.get(property.name); + } + String enumName = underscore(toModelName(property.name)).toUpperCase(Locale.ROOT); enumName = enumName.replaceFirst("^_", ""); enumName = enumName.replaceFirst("_$", ""); @@ -613,6 +630,10 @@ public void setGemAuthorEmail(String gemAuthorEmail) { this.gemAuthorEmail = gemAuthorEmail; } + public void setGemMetadata(String gemMetadata) { + this.gemMetadata = gemMetadata; + } + public void setUseAutoload(boolean useAutoload) { this.useAutoload = useAutoload; } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java new file mode 100644 index 000000000000..3605dbc5fb54 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustAxumServerCodegen.java @@ -0,0 +1,1050 @@ +package org.openapitools.codegen.languages; + +import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.info.Info; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.FileSchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.parameters.RequestBody; +import io.swagger.v3.oas.models.responses.ApiResponse; +import io.swagger.v3.oas.models.servers.Server; +import joptsimple.internal.Strings; +import org.apache.commons.io.FilenameUtils; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.GeneratorMetadata; +import org.openapitools.codegen.meta.Stability; +import org.openapitools.codegen.meta.features.GlobalFeature; +import org.openapitools.codegen.meta.features.ParameterFeature; +import org.openapitools.codegen.meta.features.SchemaSupportFeature; +import org.openapitools.codegen.meta.features.WireFormatFeature; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.ModelsMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.utils.ModelUtils; +import org.openapitools.codegen.utils.URLPathUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.math.BigInteger; +import java.net.URL; +import java.util.*; +import java.util.stream.Collectors; + +import static org.openapitools.codegen.utils.StringUtils.camelize; +import static org.openapitools.codegen.utils.StringUtils.underscore; + +public class RustAxumServerCodegen extends AbstractRustCodegen implements CodegenConfig { + public static final String PROJECT_NAME = "openapi-server"; + // Types + private static final String uuidType = "uuid::Uuid"; + private static final String bytesType = "ByteArray"; + private static final String octetMimeType = "application/octet-stream"; + private static final String plainTextMimeType = "text/plain"; + + private static final String xmlMimeType = "application/xml"; + private static final String textXmlMimeType = "text/xml"; + + private static final String formUrlEncodedMimeType = "application/x-www-form-urlencoded"; + + private static final String jsonMimeType = "application/json"; + // RFC 7386 support + private static final String mergePatchJsonMimeType = "application/merge-patch+json"; + // RFC 7807 Support + private static final String problemJsonMimeType = "application/problem+json"; + private static final String problemXmlMimeType = "application/problem+xml"; + + private final Logger LOGGER = LoggerFactory.getLogger(RustAxumServerCodegen.class); + // Grouping (Method, Operation) by Path. + private final Map> pathMethodOpMap = new HashMap<>(); + + protected String apiVersion = "1.0.0"; + protected String apiPath = "rust-axum"; + protected String packageName; + protected String packageVersion; + protected Boolean disableValidator = false; + protected Boolean allowBlockingValidator = false; + protected Boolean allowBlockingResponseSerialize = false; + protected String externCrateName; + protected int serverPort = 8080; + + public RustAxumServerCodegen() { + super(); + + modifyFeatureSet(features -> features + .wireFormatFeatures(EnumSet.of( + WireFormatFeature.JSON, + WireFormatFeature.Custom + )) + .excludeGlobalFeatures( + GlobalFeature.Info, + GlobalFeature.ExternalDocumentation, + GlobalFeature.Examples, + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.MultiServer, + GlobalFeature.ParameterizedServer, + GlobalFeature.ParameterStyling, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + generatorMetadata = GeneratorMetadata.newBuilder(generatorMetadata) + .stability(Stability.BETA) + .build(); + + // Show the generation timestamp by default + hideGenerationTimestamp = Boolean.FALSE; + + // set the output folder here + outputFolder = "generated-code" + File.separator + "rust-axum"; + embeddedTemplateDir = templateDir = "rust-axum"; + + importMapping = new HashMap<>(); + modelTemplateFiles.clear(); + apiTemplateFiles.clear(); + + // types + defaultIncludes = new HashSet<>( + Arrays.asList( + "map", + "array") + ); + + languageSpecificPrimitives = new HashSet<>( + Arrays.asList( + "bool", + "char", + "i8", + "i16", + "i32", + "i64", + "u8", + "u16", + "u32", + "u64", + "isize", + "usize", + "f32", + "f64", + "str", + "String") + ); + + instantiationTypes.clear(); + instantiationTypes.put("array", "Vec"); + instantiationTypes.put("map", "std::collections::HashMap"); + + typeMapping.clear(); + typeMapping.put("number", "f64"); + typeMapping.put("integer", "i32"); + typeMapping.put("long", "i64"); + typeMapping.put("float", "f32"); + typeMapping.put("double", "f64"); + typeMapping.put("string", "String"); + typeMapping.put("UUID", uuidType); + typeMapping.put("URI", "String"); + typeMapping.put("byte", "u8"); + typeMapping.put("ByteArray", bytesType); + typeMapping.put("binary", bytesType); + typeMapping.put("boolean", "bool"); + typeMapping.put("date", "chrono::naive::NaiveDate"); + typeMapping.put("DateTime", "chrono::DateTime::"); + typeMapping.put("password", "String"); + typeMapping.put("File", "ByteArray"); + typeMapping.put("file", "ByteArray"); + typeMapping.put("array", "Vec"); + typeMapping.put("map", "std::collections::HashMap"); + typeMapping.put("object", "crate::types::Object"); + typeMapping.put("AnyType", "crate::types::Object"); + + // cli options + cliOptions.clear(); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_NAME, + "Rust crate name (convention: snake_case).") + .defaultValue("openapi")); + cliOptions.add(new CliOption(CodegenConstants.PACKAGE_VERSION, + "Rust crate version.")); + + CliOption optDisableValidator = new CliOption("disableValidator", "Disable validating request-data (header, path, query, body) " + + "against OpenAPI Schema Specification."); + optDisableValidator.setType("bool"); + optDisableValidator.defaultValue(disableValidator.toString()); + cliOptions.add(optDisableValidator); + + CliOption optAllowBlockingValidator = new CliOption("allowBlockingValidator", + String.join("", + "By default, validation process, which might perform a lot of compute in a ", + "future without yielding, is executed on a blocking thread via tokio::task::spawn_blocking. ", + "Set this option to true will override this behaviour and allow blocking call to happen. ", + "It helps to improve the performance when validating request-data (header, path, query, body) ", + "is low cost.")); + optAllowBlockingValidator.setType("bool"); + optAllowBlockingValidator.defaultValue(allowBlockingValidator.toString()); + cliOptions.add(optAllowBlockingValidator); + + CliOption optAllowBlockingResponseSerialize = new CliOption("allowBlockingResponseSerialize", + String.join("", "By default, json/form-urlencoded response serialization, which might ", + "perform a lot of compute in a future without yielding, is executed on a blocking thread ", + "via tokio::task::spawn_blocking. Set this option to true will override this behaviour and ", + "allow blocking call to happen. It helps to improve the performance when response ", + "serialization (e.g. returns tiny data) is low cost.")); + optAllowBlockingResponseSerialize.setType("bool"); + optAllowBlockingResponseSerialize.defaultValue(allowBlockingResponseSerialize.toString()); + cliOptions.add(optAllowBlockingResponseSerialize); + + additionalProperties.put("apiVersion", apiVersion); + additionalProperties.put("apiPath", apiPath); + + supportingFiles.add(new SupportingFile("Cargo.mustache", "", "Cargo.toml")); + supportingFiles.add(new SupportingFile("gitignore", "", ".gitignore")); + supportingFiles.add(new SupportingFile("lib.mustache", "src", "lib.rs")); + supportingFiles.add(new SupportingFile("models.mustache", "src", "models.rs")); + supportingFiles.add(new SupportingFile("types.mustache", "src", "types.rs")); + supportingFiles.add(new SupportingFile("header.mustache", "src", "header.rs")); + supportingFiles.add(new SupportingFile("server-mod.mustache", "src/server", "mod.rs")); + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md") + .doNotOverwrite()); + } + + public CodegenType getTag() { + return CodegenType.SERVER; + } + + public String getName() { + return "rust-axum"; + } + + public String getHelp() { + return "Generates a Rust server library which bases on Axum."; + } + + @Override + public Mustache.Compiler processCompiler(Mustache.Compiler compiler) { + return compiler + .emptyStringIsFalse(true) + .zeroIsFalse(true); + } + + @Override + public void processOpts() { + super.processOpts(); + + if (StringUtils.isEmpty(System.getenv("RUST_POST_PROCESS_FILE"))) { + LOGGER.info("Environment variable RUST_POST_PROCESS_FILE not defined. rustfmt will be used" + + " by default. To choose a different tool, try" + + " 'export RUST_POST_PROCESS_FILE=\"/usr/local/bin/rustfmt\"' (Linux/Mac)"); + LOGGER.info("NOTE: To enable file post-processing, 'enablePostProcessFile' must be set to `true` " + + " (--enable-post-process-file for CLI)."); + } + + if (!Boolean.TRUE.equals(ModelUtils.isGenerateAliasAsModel())) { + LOGGER.warn("generateAliasAsModel is set to false, which means array/map will be generated as model instead and the resulting code may have issues. Please enable `generateAliasAsModel` to address the issue."); + } + + setPackageName((String) additionalProperties.getOrDefault(CodegenConstants.PACKAGE_NAME, "openapi")); + + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_VERSION)) { + setPackageVersion((String) additionalProperties.get(CodegenConstants.PACKAGE_VERSION)); + } + + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + additionalProperties.put("externCrateName", externCrateName); + + if (additionalProperties.containsKey("disableValidator")) { + disableValidator = convertPropertyToBooleanAndWriteBack("disableValidator"); + } else { + additionalProperties.put("disableValidator", disableValidator); + } + + if (additionalProperties.containsKey("allowBlockingValidator")) { + allowBlockingValidator = convertPropertyToBooleanAndWriteBack("allowBlockingValidator"); + } else { + additionalProperties.put("allowBlockingValidator", allowBlockingValidator); + } + + if (additionalProperties.containsKey("allowBlockingResponseSerialize")) { + allowBlockingValidator = convertPropertyToBooleanAndWriteBack("allowBlockingResponseSerialize"); + } else { + additionalProperties.put("allowBlockingResponseSerialize", allowBlockingResponseSerialize); + } + } + + private void setPackageName(String packageName) { + this.packageName = packageName; + + // Also set the extern crate name, which has any '-' replace with a '_'. + this.externCrateName = packageName.replace('-', '_'); + } + + private void setPackageVersion(String packageVersion) { + this.packageVersion = packageVersion; + } + + @Override + public String apiPackage() { + return apiPath; + } + + @Override + public void preprocessOpenAPI(OpenAPI openAPI) { + Info info = openAPI.getInfo(); + + URL url = URLPathUtils.getServerURL(openAPI, serverVariableOverrides()); + additionalProperties.put("serverHost", url.getHost()); + additionalProperties.put("serverPort", URLPathUtils.getPort(url, serverPort)); + + if (packageVersion == null || packageVersion.isEmpty()) { + List versionComponents = new ArrayList<>(Arrays.asList(info.getVersion().split("[.]"))); + if (versionComponents.isEmpty()) { + versionComponents.add("1"); + } + while (versionComponents.size() < 3) { + versionComponents.add("0"); + } + + setPackageVersion(String.join(".", versionComponents)); + } + + additionalProperties.put(CodegenConstants.PACKAGE_VERSION, packageVersion); + } + + @Override + public String toApiName(String name) { + if (name.isEmpty()) { + return "default"; + } + return sanitizeIdentifier(name, CasingType.SNAKE_CASE, "api", "API", true); + } + + /** + * Location to write api files. You can use the apiPackage() as defined when the class is + * instantiated + */ + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String toOperationId(String operationId) { + return sanitizeIdentifier(operationId, CasingType.CAMEL_CASE, "call", "method", true); + } + + @Override + public String toEnumValue(String value, String datatype) { + return "\"" + super.toEnumValue(value, datatype) + "\""; + } + + private boolean isMimetypeXml(String mimetype) { + return mimetype.toLowerCase(Locale.ROOT).startsWith(xmlMimeType) || + mimetype.toLowerCase(Locale.ROOT).startsWith(problemXmlMimeType) || + mimetype.toLowerCase(Locale.ROOT).startsWith(textXmlMimeType); + } + + private boolean isMimetypeJson(String mimetype) { + return mimetype.toLowerCase(Locale.ROOT).startsWith(jsonMimeType) || + mimetype.toLowerCase(Locale.ROOT).startsWith(mergePatchJsonMimeType) || + mimetype.toLowerCase(Locale.ROOT).startsWith(problemJsonMimeType); + } + + private boolean isMimetypeWwwFormUrlEncoded(String mimetype) { + return mimetype.toLowerCase(Locale.ROOT).startsWith(formUrlEncodedMimeType); + } + + private boolean isMimetypeMultipartFormData(String mimetype) { + return mimetype.toLowerCase(Locale.ROOT).startsWith("multipart/form-data"); + } + + private boolean isMimetypeMultipartRelated(String mimetype) { + return mimetype.toLowerCase(Locale.ROOT).startsWith("multipart/related"); + } + + private boolean isMimetypeUnknown(String mimetype) { + return "*/*".equals(mimetype); + } + + boolean isMimetypePlain(String mimetype) { + return !(isMimetypeUnknown(mimetype) || + isMimetypeJson(mimetype) || + isMimetypeWwwFormUrlEncoded(mimetype) || + isMimetypeMultipartFormData(mimetype) || + isMimetypeMultipartRelated(mimetype)); + } + + @Override + public CodegenOperation fromOperation(String path, String httpMethod, Operation operation, List servers) { + CodegenOperation op = super.fromOperation(path, httpMethod, operation, servers); + + String underscoredOperationId = underscore(op.operationId); + op.vendorExtensions.put("x-operation-id", underscoredOperationId); + op.vendorExtensions.put("x-uppercase-operation-id", underscoredOperationId.toUpperCase(Locale.ROOT)); + + if (!op.isCallbackRequest) { + // group route by path + String axumPath = op.path; + for (CodegenParameter param : op.pathParams) { + // Replace {baseName} with {paramName} for format string + String paramSearch = "{" + param.baseName + "}"; + String paramReplace = ":" + param.paramName; + + axumPath = axumPath.replace(paramSearch, paramReplace); + } + pathMethodOpMap + .computeIfAbsent(axumPath, (key) -> new ArrayList<>()) + .add(new MethodOperation(op.httpMethod.toLowerCase(Locale.ROOT), underscoredOperationId)); + } + + // Determine the types that this operation produces. `getProducesInfo` + // simply lists all the types, and then we add the correct imports to + // the generated library. + Set producesInfo = getProducesInfo(openAPI, operation); + boolean producesPlainText = false; + boolean producesFormUrlEncoded = false; + if (producesInfo != null && !producesInfo.isEmpty()) { + List> produces = new ArrayList<>(producesInfo.size()); + + for (String mimeType : producesInfo) { + if (isMimetypeWwwFormUrlEncoded(mimeType)) { + producesFormUrlEncoded = true; + } else if (isMimetypePlain(mimeType)) { + producesPlainText = true; + } + + Map mediaType = new HashMap<>(); + mediaType.put("mediaType", mimeType); + + produces.add(mediaType); + } + + op.produces = produces; + op.hasProduces = true; + } + + // Set for deduplication of response IDs + for (CodegenResponse rsp : op.responses) { + // Get the original API response, so we get process the schema + // directly. + ApiResponse original; + if ("0".equals(rsp.code)) { + original = operation.getResponses().get("default"); + } else { + original = operation.getResponses().get(rsp.code); + } + + // Create a unique responseID for this response. + String[] words = rsp.message.split("[^A-Za-z ]"); + + // build responseId from both status code and description + String responseId = "Status" + rsp.code + ( + ((words.length != 0) && (!words[0].trim().isEmpty())) ? + "_" + camelize(words[0].replace(" ", "_")) : "" + ); + + rsp.vendorExtensions.put("x-response-id", responseId); + if (rsp.dataType != null) { + // Get the mimetype which is produced by this response. Note + // that although in general responses produces a set of + // different mimetypes currently we only support 1 per + // response. + String firstProduces = null; + + if (original.getContent() != null) { + firstProduces = original.getContent().keySet().stream().findFirst().orElse(null); + } + + // The output mime type. This allows us to do sensible fallback + // to JSON rather than using only the default operation + // mimetype. + String outputMime; + + if (firstProduces == null) { + if (producesFormUrlEncoded) { + outputMime = formUrlEncodedMimeType; + } else if (producesPlainText) { + if (bytesType.equals(rsp.dataType)) { + outputMime = octetMimeType; + } else { + outputMime = plainTextMimeType; + } + } else { + outputMime = jsonMimeType; + } + } else { + // If we know exactly what mimetype this response is + // going to produce, then use that. If we have not found + // anything, then we'll fall back to the 'producesXXX' + // definitions we worked out above for the operation as a + // whole. + if (isMimetypeWwwFormUrlEncoded(firstProduces)) { + producesFormUrlEncoded = true; + producesPlainText = false; + } else if (isMimetypePlain(firstProduces)) { + producesFormUrlEncoded = false; + producesPlainText = true; + } else { + producesFormUrlEncoded = false; + producesPlainText = false; + } + + outputMime = firstProduces; + + // As we don't support XML, fallback to plain text + if (isMimetypeXml(outputMime)) { + outputMime = plainTextMimeType; + } + } + + rsp.vendorExtensions.put("x-mime-type", outputMime); + + // Write out the type of data we actually expect this response + // to make. + if (producesFormUrlEncoded) { + rsp.vendorExtensions.put("x-produces-form-urlencoded", true); + } else if (producesPlainText) { + // Plain text means that there is not structured data in + // this response. So it'll either be a UTF-8 encoded string + // 'plainText' or some generic 'bytes'. + // + // Note that we don't yet distinguish between string/binary + // and string/bytes - that is we don't auto-detect whether + // base64 encoding should be done. They both look like + // 'producesBytes'. + if (bytesType.equals(rsp.dataType)) { + rsp.vendorExtensions.put("x-produces-bytes", true); + } else { + rsp.vendorExtensions.put("x-produces-plain-text", true); + } + } else { + rsp.vendorExtensions.put("x-produces-json", true); + // If the data type is just "object", then ensure that the + // Rust data type is "crate::types::Object". This allows us + // to define APIs that can return arbitrary JSON bodies. + if ("object".equals(rsp.dataType)) { + rsp.dataType = "crate::types::Object"; + } + } + } + + for (CodegenProperty header : rsp.headers) { + header.nameInCamelCase = toModelName(header.baseName); + header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); + } + } + + for (CodegenParameter header : op.headerParams) { + header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); + } + + for (CodegenProperty header : op.responseHeaders) { + header.nameInCamelCase = toModelName(header.baseName); + header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); + } + + return op; + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + OperationMap operations = objs.getOperations(); + List operationList = operations.getOperation(); + + for (CodegenOperation op : operationList) { + postProcessOperationWithModels(op); + } + + return objs; + } + + private void postProcessOperationWithModels(CodegenOperation op) { + boolean consumesJson = false; + boolean consumesPlainText = false; + boolean consumesFormUrlEncoded = false; + + if (op.consumes != null) { + for (Map consume : op.consumes) { + final String mediaType = consume.get("mediaType"); + if (mediaType != null) { + if (isMimetypeJson(mediaType)) { + consumesJson = true; + } else if (isMimetypeWwwFormUrlEncoded(mediaType)) { + consumesFormUrlEncoded = true; + } else if (isMimetypePlain(mediaType)) { + consumesPlainText = true; + } else if (isMimetypeMultipartFormData(mediaType)) { + op.vendorExtensions.put("x-consumes-multipart", true); + } else if (isMimetypeMultipartRelated(mediaType)) { + op.vendorExtensions.put("x-consumes-multipart-related", true); + } + } + } + } + + if (op.bodyParam != null) { + if (consumesJson) { + op.bodyParam.vendorExtensions.put("x-consumes-json", true); + } else if (consumesFormUrlEncoded) { + op.bodyParam.vendorExtensions.put("x-consumes-form-urlencoded", true); + } else if (consumesPlainText) { + op.bodyParam.vendorExtensions.put("x-consumes-plain-text", true); + } else { + op.bodyParam.vendorExtensions.put("x-consumes-json", true); + } + } + + for (CodegenParameter param : op.bodyParams) { + // Default to producing json if nothing else is specified + if (consumesJson) { + param.vendorExtensions.put("x-consumes-json", true); + } else if (consumesFormUrlEncoded) { + param.vendorExtensions.put("x-consumes-form-urlencoded", true); + } else if (consumesPlainText) { + param.vendorExtensions.put("x-consumes-plain-text", true); + } else { + param.vendorExtensions.put("x-consumes-json", true); + } + } + + for (CodegenParameter param : op.queryParams) { + // If the MIME type is JSON, mark it. We don't currently support any other MIME types. + if (param.contentType != null && isMimetypeJson(param.contentType)) { + param.vendorExtensions.put("x-consumes-json", true); + } + } + + for (CodegenParameter header : op.headerParams) { + header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); + } + + for (CodegenProperty header : op.responseHeaders) { + header.nameInCamelCase = toModelName(header.baseName); + header.nameInLowerCase = header.baseName.toLowerCase(Locale.ROOT); + } + } + + @Override + public boolean isDataTypeFile(final String dataType) { + return dataType != null && dataType.equals(typeMapping.get("File")); + } + + /** + * Add operation to group + * + * @param tag name of the tag + * @param resourcePath path of the resource + * @param operation OAS Operation object + * @param op Codegen Operation object + * @param operations map of Codegen operations + */ + @SuppressWarnings("static-method") + @Override + public void addOperationToGroup(String tag, String resourcePath, Operation operation, CodegenOperation + op, Map> operations) { + // only generate operation for the first tag of the tags + if (tag != null && op.tags.size() > 1) { + String expectedTag = sanitizeTag(op.tags.get(0).getName()); + if (!tag.equals(expectedTag)) { + LOGGER.info("generated skip additional tag `{}` with operationId={}", tag, op.operationId); + return; + } + } + super.addOperationToGroup(tag, resourcePath, operation, op, operations); + } + + // This is a really terrible hack. We're working around the fact that the + // base version of `fromRequestBody` checks to see whether the body is a + // ref. If so, it unwraps the reference and replaces it with its inner + // type. This causes problems in rust-axum, as it means that we use inner + // types in the API, rather than the correct outer type. + // + // Thus, we grab the inner schema beforehand, and then tinker afterward to + // restore things to sensible values. + @Override + public CodegenParameter fromRequestBody(RequestBody body, Set imports, String bodyParameterName) { + Schema original_schema = ModelUtils.getSchemaFromRequestBody(body); + CodegenParameter codegenParameter = super.fromRequestBody(body, imports, bodyParameterName); + + if (StringUtils.isNotBlank(original_schema.get$ref())) { + // Undo the mess `super.fromRequestBody` made - re-wrap the inner + // type. + codegenParameter.dataType = getTypeDeclaration(original_schema); + codegenParameter.isPrimitiveType = false; + codegenParameter.isArray = false; + codegenParameter.isString = false; + codegenParameter.isByteArray = ModelUtils.isByteArraySchema(original_schema); + } + + return codegenParameter; + } + + @Override + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + String innerType = getTypeDeclaration(inner); + return typeMapping.get("array") + "<" + innerType + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = ModelUtils.getAdditionalProperties(p); + String innerType = getTypeDeclaration(inner); + StringBuilder typeDeclaration = new StringBuilder(typeMapping.get("map")).append("<").append(typeMapping.get("string")).append(", "); + typeDeclaration.append(innerType).append(">"); + return typeDeclaration.toString(); + } else if (!StringUtils.isEmpty(p.get$ref())) { + String datatype; + try { + datatype = p.get$ref(); + + if (datatype.indexOf("#/components/schemas/") == 0) { + datatype = toModelName(datatype.substring("#/components/schemas/".length())); + datatype = "models::" + datatype; + } + } catch (Exception e) { + LOGGER.warn("Error obtaining the datatype from schema (model):{}. Datatype default to Object", p); + datatype = "Object"; + LOGGER.error(e.getMessage(), e); + } + return datatype; + } else if (p instanceof FileSchema) { + return typeMapping.get("File"); + } + + return super.getTypeDeclaration(p); + } + + @Override + public String toInstantiationType(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return instantiationTypes.get("array") + "<" + getSchemaType(inner) + ">"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = ModelUtils.getAdditionalProperties(p); + return instantiationTypes.get("map") + "<" + typeMapping.get("string") + ", " + getSchemaType(inner) + ">"; + } else { + return null; + } + } + + @Override + public CodegenModel fromModel(String name, Schema model) { + LOGGER.trace("Creating model from schema: {}", model); + + Map allDefinitions = ModelUtils.getSchemas(this.openAPI); + CodegenModel mdl = super.fromModel(name, model); + + mdl.vendorExtensions.put("x-upper-case-name", name.toUpperCase(Locale.ROOT)); + if (!StringUtils.isEmpty(model.get$ref())) { + Schema schema = allDefinitions.get(ModelUtils.getSimpleRef(model.get$ref())); + mdl.dataType = typeMapping.get(schema.getType()); + } + if (ModelUtils.isArraySchema(model)) { + if (typeMapping.containsKey(mdl.arrayModelType)) { + mdl.arrayModelType = typeMapping.get(mdl.arrayModelType); + } else { + mdl.arrayModelType = toModelName(mdl.arrayModelType); + } + } else if ((!mdl.anyOf.isEmpty()) || (!mdl.oneOf.isEmpty())) { + mdl.dataType = getSchemaType(model); + } + + Schema additionalProperties = ModelUtils.getAdditionalProperties(model); + + if (additionalProperties != null) { + mdl.additionalPropertiesType = getTypeDeclaration(additionalProperties); + } + + LOGGER.trace("Created model: {}", mdl); + + return mdl; + } + + @Override + public Map postProcessSupportingFileData(Map bundle) { + generateYAMLSpecFile(bundle); + + final List pathMethodOps = pathMethodOpMap.entrySet().stream() + .map(entry -> { + ArrayList methodOps = entry.getValue(); + methodOps.sort(Comparator.comparing(a -> a.method)); + return new PathMethodOperations(entry.getKey(), methodOps); + }) + .sorted(Comparator.comparing(a -> a.path)) + .collect(Collectors.toList()); + bundle.put("pathMethodOps", pathMethodOps); + + return super.postProcessSupportingFileData(bundle); + } + + @Override + public String toDefaultValue(Schema p) { + String defaultValue = null; + if ((ModelUtils.isNullable(p)) && (p.getDefault() != null) && ("null".equalsIgnoreCase(p.getDefault().toString()))) + return "Nullable::Null"; + else if (ModelUtils.isBooleanSchema(p)) { + if (p.getDefault() != null) { + if ("false".equalsIgnoreCase(p.getDefault().toString())) + defaultValue = "false"; + else + defaultValue = "true"; + } + } else if (ModelUtils.isNumberSchema(p)) { + if (p.getDefault() != null) { + defaultValue = p.getDefault().toString(); + } + } else if (ModelUtils.isIntegerSchema(p)) { + if (p.getDefault() != null) { + defaultValue = p.getDefault().toString(); + } + } else if (ModelUtils.isStringSchema(p)) { + if (p.getDefault() != null) { + defaultValue = "\"" + p.getDefault() + "\".to_string()"; + } + } + if ((defaultValue != null) && (ModelUtils.isNullable(p))) + defaultValue = "Nullable::Present(" + defaultValue + ")"; + return defaultValue; + } + + @Override + public void postProcessModelProperty(CodegenModel model, CodegenProperty property) { + super.postProcessModelProperty(model, property); + if (!languageSpecificPrimitives.contains(property.dataType)) { + // If we use a more qualified model name, then only camelize the actual type, not the qualifier. + if (property.dataType.contains(":")) { + int position = property.dataType.lastIndexOf(":"); + property.dataType = property.dataType.substring(0, position) + camelize(property.dataType.substring(position)); + } else { + property.dataType = camelize(property.dataType); + } + property.isPrimitiveType = property.isContainer && languageSpecificPrimitives.contains(typeMapping.get(property.complexType)); + } else { + property.isPrimitiveType = true; + } + + // Integer type fitting + if (Objects.equals(property.baseType, "integer")) { + + BigInteger minimum = Optional.ofNullable(property.getMinimum()).map(BigInteger::new).orElse(null); + BigInteger maximum = Optional.ofNullable(property.getMaximum()).map(BigInteger::new).orElse(null); + + boolean unsigned = canFitIntoUnsigned(minimum, property.getExclusiveMinimum()); + + if (Strings.isNullOrEmpty(property.dataFormat)) { + property.dataType = bestFittingIntegerType(minimum, + property.getExclusiveMinimum(), + maximum, + property.getExclusiveMaximum(), + true); + } else { + switch (property.dataFormat) { + // custom integer formats (legacy) + case "uint32": + property.dataType = "u32"; + break; + case "uint64": + property.dataType = "u64"; + break; + case "int32": + property.dataType = unsigned ? "u32" : "i32"; + break; + case "int64": + property.dataType = unsigned ? "u64" : "i64"; + break; + default: + LOGGER.warn("The integer format '{}' is not recognized and will be ignored.", property.dataFormat); + property.dataType = bestFittingIntegerType(minimum, + property.getExclusiveMinimum(), + maximum, + property.getExclusiveMaximum(), + true); + } + } + } + + property.name = underscore(property.name); + + if (!property.required) { + property.defaultValue = (property.defaultValue != null) ? "Some(" + property.defaultValue + ")" : "None"; + } + + // If a property has no type defined in the schema, it can take values of any type. + // This clashes with Rust being statically typed. Hence, assume it's sent as a json + // blob and return the json value to the user of the API and let the user determine + // the type from the value. If the property has no type, at this point it will have + // baseType "object" allowing us to identify such properties. Moreover, set to not + // nullable, we can use the crate::types::Object::Null enum variant. + if ("object".equals(property.baseType)) { + property.dataType = "crate::types::Object"; + property.isNullable = false; + } + } + + @Override + public ModelsMap postProcessModels(ModelsMap objs) { + for (ModelMap mo : objs.getModels()) { + CodegenModel cm = mo.getModel(); + + LOGGER.trace("Post processing model: {}", cm); + + if ("object".equals(cm.dataType)) { + // Object isn't a sensible default. Instead, we set it to + // 'null'. This ensures that we treat this model as a struct + // with multiple parameters. + cm.dataType = null; + } else if ("map".equals(cm.dataType)) { + if (!cm.allVars.isEmpty() || cm.additionalPropertiesType == null) { + // We don't yet support `additionalProperties` that also have + // properties. If we see variables, we ignore the + // `additionalProperties` type ('map') and warn the user. This + // will produce code that compiles, but won't feature the + // `additionalProperties` - but that's likely more useful to + // the user than the alternative. + LOGGER.warn("Ignoring additionalProperties (see https://github.com/OpenAPITools/openapi-generator/issues/318) alongside defined properties"); + cm.dataType = null; + } else { + cm.dataType = "std::collections::HashMap"; + } + } else if (cm.dataType != null) { + // We need to hack about with single-parameter models to + // get them recognised correctly. + cm.isAlias = false; + cm.dataType = typeMapping.get(cm.dataType); + + if (uuidType.equals(cm.dataType)) { + additionalProperties.put("apiUsesUuid", true); + } + } + + cm.vendorExtensions.put("x-is-string", "String".equals(cm.dataType)); + } + return super.postProcessModelsEnum(objs); + } + + @Override + public void postProcessFile(File file, String fileType) { + if (file == null) { + return; + } + + String commandPrefix = System.getenv("RUST_POST_PROCESS_FILE"); + if (StringUtils.isEmpty(commandPrefix)) { + commandPrefix = "rustfmt"; + } + + // only process files with .rs extension + if ("rs".equals(FilenameUtils.getExtension(file.toString()))) { + try { + Process p = Runtime.getRuntime().exec(new String[]{commandPrefix, "--edition", "2021", file.toString()}); + int exitValue = p.waitFor(); + if (exitValue != 0) { + LOGGER.error("Error running the command ({} {}). Exit code: {}", commandPrefix, file, exitValue); + } else { + LOGGER.info("Successfully executed: {} {}", commandPrefix, file); + } + } catch (InterruptedException | IOException e) { + LOGGER.error("Error running the command ({} {}). Exception: {}", commandPrefix, file, e.getMessage()); + // Restore interrupted state + Thread.currentThread().interrupt(); + } + } + } + + @Override + protected void updateParameterForString(CodegenParameter codegenParameter, Schema parameterSchema) { + /* + we have a custom version of this function to set isString to false for uuid + */ + if (ModelUtils.isEmailSchema(parameterSchema)) { + codegenParameter.isEmail = true; + } else if (ModelUtils.isUUIDSchema(parameterSchema)) { + codegenParameter.setIsString(false); + codegenParameter.isUuid = true; + } else if (ModelUtils.isByteArraySchema(parameterSchema)) { + codegenParameter.setIsString(false); + codegenParameter.isByteArray = true; + codegenParameter.isPrimitiveType = true; + } else if (ModelUtils.isBinarySchema(parameterSchema)) { + codegenParameter.isBinary = true; + codegenParameter.isFile = true; // file = binary in OAS3 + codegenParameter.isPrimitiveType = true; + } else if (ModelUtils.isDateSchema(parameterSchema)) { + codegenParameter.setIsString(false); // for backward compatibility with 2.x + codegenParameter.isDate = true; + codegenParameter.isPrimitiveType = true; + } else if (ModelUtils.isDateTimeSchema(parameterSchema)) { + codegenParameter.setIsString(false); // for backward compatibility with 2.x + codegenParameter.isDateTime = true; + codegenParameter.isPrimitiveType = true; + } else if (ModelUtils.isDecimalSchema(parameterSchema)) { // type: string, format: number + codegenParameter.setIsString(false); + codegenParameter.isDecimal = true; + codegenParameter.isPrimitiveType = true; + } + if (Boolean.TRUE.equals(codegenParameter.isString)) { + codegenParameter.isPrimitiveType = true; + } + } + + @Override + protected void updatePropertyForAnyType(CodegenProperty property, Schema p) { + /* + * we have a custom version of this function to not set isNullable to true + */ + // The 'null' value is allowed when the OAS schema is 'any type'. + // See https://github.com/OAI/OpenAPI-Specification/issues/1389 + if (Boolean.FALSE.equals(p.getNullable())) { + LOGGER.warn("Schema '{}' is any type, which includes the 'null' value. 'nullable' cannot be set to 'false'", p.getName()); + } + if (languageSpecificPrimitives.contains(property.dataType)) { + property.isPrimitiveType = true; + } + if (ModelUtils.isMapSchema(p)) { + // an object or anyType composed schema that has additionalProperties set + // some of our code assumes that any type schema with properties defined will be a map + // even though it should allow in any type and have map constraints for properties + updatePropertyForMap(property, p); + } + } + + @Override + protected String getParameterDataType(Parameter parameter, Schema schema) { + if (parameter.get$ref() != null) { + String refName = ModelUtils.getSimpleRef(parameter.get$ref()); + return toModelName(refName); + } + return null; + } + + static class PathMethodOperations { + public String path; + public ArrayList methodOperations; + + PathMethodOperations(String path, ArrayList methodOperations) { + this.path = path; + this.methodOperations = methodOperations; + } + } + + static class MethodOperation { + public String method; + public String operationID; + + MethodOperation(String method, String operationID) { + this.method = method; + this.operationID = operationID; + } + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java index 922249a0cee8..392e2b94bb8b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustClientCodegen.java @@ -93,7 +93,8 @@ public RustClientCodegen() { SecurityFeature.BasicAuth, SecurityFeature.BearerToken, SecurityFeature.ApiKey, - SecurityFeature.OAuth2_Implicit + SecurityFeature.OAuth2_Implicit, + SecurityFeature.AWSV4Signature )) .excludeGlobalFeatures( GlobalFeature.XMLStructureDefinitions, diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java index 5b7503c99622..2f34214da04e 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/RustServerCodegen.java @@ -193,7 +193,7 @@ public RustServerCodegen() { typeMapping.put("ByteArray", bytesType); typeMapping.put("binary", bytesType); typeMapping.put("boolean", "bool"); - typeMapping.put("date", "chrono::DateTime::"); + typeMapping.put("date", "chrono::naive::NaiveDate"); typeMapping.put("DateTime", "chrono::DateTime::"); typeMapping.put("password", "String"); typeMapping.put("File", bytesType); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttp4sServerCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttp4sServerCodegen.java new file mode 100644 index 000000000000..6eee8734975e --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaHttp4sServerCodegen.java @@ -0,0 +1,852 @@ +/* + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.model.*; +import org.openapitools.codegen.utils.ModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.util.*; +import java.util.stream.Collectors; + +public class ScalaHttp4sServerCodegen extends DefaultCodegen implements CodegenConfig { + private final Logger LOGGER = LoggerFactory.getLogger(ScalaHttp4sServerCodegen.class); + protected String artifactId = "http4s-server"; + protected String artifactVersion = "1.0.0"; + protected String sourceFolder = "scala"; + protected String sourceSubFolder = "main"; + private String packageName = "org.openapitools"; + + public static final String EXCLUDE_SBT = "excludeSbt"; // generate as whole project + public static final String SOURCE_SUBFOLDER = "sourceSubfolder"; // generate as whole project + + public ScalaHttp4sServerCodegen() { + super(); + + modifyFeatureSet(features -> features + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.noneOf(SecurityFeature.class)) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + ); + + embeddedTemplateDir = templateDir = "scala-http4s-server"; + + apiPackage = packageName + ".apis"; + modelPackage = packageName + ".models"; + useOneOfInterfaces = true; + supportsMultipleInheritance = true; + supportsInheritance = true; + supportsMixins = true; + addOneOfInterfaceImports =true; + + + setReservedWordsLowerCase( + Arrays.asList( + // Scala + "abstract", "case", "catch", "class", "def", + "do", "else", "extends", "false", "final", + "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", + "object", "override", "package", "private", "protected", + "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", + "var", "while", "with", "yield", + // Scala-interop languages keywords + "abstract", "continue", "switch", "assert", + "default", "synchronized", "goto", + "break", "double", "implements", "byte", + "public", "throws", "enum", "instanceof", "transient", + "int", "short", "char", "interface", "static", + "void", "finally", "long", "strictfp", "volatile", "const", "float", + "native") + ); + + defaultIncludes = new HashSet<>( + Arrays.asList("double", + "Int", + "Long", + "Float", + "Double", + "char", + "float", + "String", + "boolean", + "Boolean", + "Double", + "Integer", + "Long", + "Float", + "List", + "Set", + "Map") + ); + + typeMapping = new HashMap<>(); + typeMapping.put("string", "String"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("double", "Double"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("decimal", "BigDecimal"); + typeMapping.put("date-time", "ZonedDateTime"); + typeMapping.put("offset-date-time", "OffsetDateTime"); + typeMapping.put("date", "LocalDate"); + typeMapping.put("file", "File"); + typeMapping.put("array", "List"); + typeMapping.put("list", "List"); + typeMapping.put("map", "Map"); + typeMapping.put("object", "Object"); + typeMapping.put("binary", "Array[Byte]"); + typeMapping.put("Date", "LocalDate"); + typeMapping.put("DateTime", "ZonedDateTime"); + typeMapping.put("OffsetDateTime", "OffsetDateTime"); + typeMapping.put("uuid", "UUID"); + + additionalProperties.put("modelPackage", modelPackage()); + additionalProperties.put("apiPackage", apiPackage()); + additionalProperties.put("infoUrl", "http://org.openapitools"); + additionalProperties.put("infoEmail", "team@openapitools.org"); + additionalProperties.put("licenseInfo", "Apache 2.0"); + additionalProperties.put("licenseUrl", "http://apache.org/licenses/LICENSE-2.0.html"); + + + + languageSpecificPrimitives = new HashSet<>( + Arrays.asList( + "String", + "Boolean", + "Double", + "Int", + "Integer", + "Long", + "Float", + "Any", + "AnyVal", + "AnyRef", + "Object", + "BigDecimal" + ) + ); + instantiationTypes.put("array", "ArrayList"); + instantiationTypes.put("map", "HashMap"); + + importMapping = new HashMap<>(); + importMapping.put("UUID", "java.util.UUID"); + importMapping.put("URI", "java.net.URI"); + importMapping.put("File", "java.io.File"); + importMapping.put("Date", "java.util.Date"); + importMapping.put("Timestamp", "java.sql.Timestamp"); + importMapping.put("Map", "scala.collection.immutable.Map"); + importMapping.put("HashMap", "scala.collection.immutable.HashMap"); + importMapping.put("Seq", "scala.collection.immutable.Seq"); + importMapping.put("ArrayBuffer", "scala.collection.mutable.ArrayBuffer"); + importMapping.put("DateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDateTime", "java.time.LocalDateTime"); + importMapping.put("LocalDate", "java.time.LocalDate"); + importMapping.put("LocalTime", "java.time.LocalTime"); + importMapping.put("ZonedDateTime", "java.time.ZonedDateTime"); + importMapping.put("OffsetDateTime", "java.time.OffsetDateTime"); + //refined + importMapping.put("Refined", "eu.timepit.refined.api.Refined"); + importMapping.put("And", "eu.timepit.refined.boolean.And"); + importMapping.put("MinSize", "eu.timepit.refined.collection.MinSize"); + importMapping.put("MaxSize", "eu.timepit.refined.collection.MaxSize"); + importMapping.put("MatchesRegex", "eu.timepit.refined.string.MatchesRegex"); + importMapping.put("Greater", "eu.timepit.refined.numeric.Greater"); + importMapping.put("GreaterEqual", "eu.timepit.refined.numeric.GreaterEqual"); + importMapping.put("Less", "eu.timepit.refined.numeric.Less"); + importMapping.put("LessEqual", "eu.timepit.refined.numeric.LessEqual"); + + + cliOptions.add(new CliOption(EXCLUDE_SBT, "exclude sbt from generation")); + cliOptions.add(new CliOption(SOURCE_SUBFOLDER, "name of subfolder, for example to generate code in src/scala/generated")); + + inlineSchemaOption.put("SKIP_SCHEMA_REUSE", "true"); + inlineSchemaOption.put("REFACTOR_ALLOF_INLINE_SCHEMAS", "true"); + } + + private final static Map locationStatusToResponse = new HashMap<>(); + static { + locationStatusToResponse.put("300", "MultipleChoices"); + locationStatusToResponse.put("301", "MovedPermanently"); + locationStatusToResponse.put("302", "Found"); + locationStatusToResponse.put("303", "SeeOther"); + locationStatusToResponse.put("307", "TemporaryRedirect"); + locationStatusToResponse.put("308", "PermanentRedirect"); + } + + private final static Map wwwAuthStatusToResponse = new HashMap<>(); + static { + wwwAuthStatusToResponse.put("401", "Unauthorized"); + } + + private final static Map allowStatusToResponse = new HashMap<>(); + static { + allowStatusToResponse.put("405", "MethodNotAllowed"); + } + + private final static Map proxyAuthStatusToResponse = new HashMap<>(); + static { + proxyAuthStatusToResponse.put("407", "ProxyAuthenticationRequired"); + } + + private final static Map statusToResponse = new HashMap<>(); + + static { + statusToResponse.put("100", "Continue"); + + statusToResponse.put("101", "SwitchingProtocols"); + + statusToResponse.put("102", "Processing"); + statusToResponse.put("103", "EarlyHints"); + + statusToResponse.put("200", "Ok"); + statusToResponse.put("201", "Created"); + statusToResponse.put("202", "Accepted"); + statusToResponse.put("203", "NonAuthoritativeInformation"); + statusToResponse.put("204", "NoContent"); + statusToResponse.put("205", "ResetContent"); + statusToResponse.put("206", "PartialContent"); + statusToResponse.put("207", "MultiStatus"); + statusToResponse.put("208", "AlreadyReported"); + statusToResponse.put("226", "IMUsed"); + + statusToResponse.put("304", "NotModified"); + statusToResponse.put("305", "UseProxy"); + + statusToResponse.put("400", "BadRequest"); + statusToResponse.put("402", "PaymentRequired"); + statusToResponse.put("403", "Forbidden"); + statusToResponse.put("404", "NotFound"); + statusToResponse.put("406", "NotAcceptable"); + statusToResponse.put("408", "RequestTimeout"); + statusToResponse.put("409", "Conflict"); + statusToResponse.put("410", "Gone"); + statusToResponse.put("411", "LengthRequired"); + statusToResponse.put("412", "PreconditionFailed"); + statusToResponse.put("413", "PayloadTooLarge"); + statusToResponse.put("414", "UriTooLong"); + statusToResponse.put("415", "UnsupportedMediaType"); + statusToResponse.put("416", "RangeNotSatisfiable"); + statusToResponse.put("417", "ExpectationFailed"); + statusToResponse.put("418", "ImATeapot"); + statusToResponse.put("421", "MisdirectedRequest"); + statusToResponse.put("422", "UnprocessableEntity"); + statusToResponse.put("423", "Locked"); + statusToResponse.put("424", "FailedDependency"); + statusToResponse.put("425", "TooEarly"); + statusToResponse.put("426", "UpgradeRequired"); + statusToResponse.put("428", "PreconditionRequired"); + statusToResponse.put("429", "TooManyRequests"); + statusToResponse.put("431", "RequestHeaderFieldsTooLarge"); + statusToResponse.put("451", "UnavailableForLegalReasons"); + + statusToResponse.put("500", "InternalServerError"); + statusToResponse.put("501", "NotImplemented"); + statusToResponse.put("502", "BadGateway"); + statusToResponse.put("503", "ServiceUnavailable"); + statusToResponse.put("504", "GatewayTimeout"); + statusToResponse.put("505", "HttpVersionNotSupported"); + statusToResponse.put("506", "VariantAlsoNegotiates"); + statusToResponse.put("507", "InsufficientStorage"); + statusToResponse.put("508", "LoopDetected"); + statusToResponse.put("510", "NotExtended"); + statusToResponse.put("511", "NetworkAuthenticationRequired"); + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.PACKAGE_NAME)) { + packageName = (String) additionalProperties.get(CodegenConstants.PACKAGE_NAME); + + setApiPackage(packageName + ".apis"); + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage()); + + setModelPackage(packageName + ".models"); + additionalProperties.put(CodegenConstants.PACKAGE_NAME, modelPackage()); + } else { + additionalProperties.put(CodegenConstants.PACKAGE_NAME, packageName); + } + + if (additionalProperties.containsKey(SOURCE_SUBFOLDER)) { + sourceSubFolder = (String) additionalProperties.get(SOURCE_SUBFOLDER); + } + + sourceFolder = "src" + File.separator + sourceSubFolder + File.separator + sourceFolder; + + supportingFiles.add(new SupportingFile("types.mustache", modelFileFolderRelative(), "types.scala")); + supportingFiles.add(new SupportingFile("path.mustache", apiFileFolderRelative(), "path.scala")); + supportingFiles.add(new SupportingFile("query.mustache", apiFileFolderRelative(), "query.scala")); + + supportingFiles.add(new SupportingFile("apis.mustache", packageFileFolderRelative(), "api.scala")); + + apiTemplateFiles.put("api.mustache", ".scala"); + + if (!additionalProperties.containsKey(EXCLUDE_SBT) && !Boolean.parseBoolean((String)additionalProperties.get(EXCLUDE_SBT))) { + supportingFiles.add(new SupportingFile("build.sbt", "", "build.sbt")); + supportingFiles.add(new SupportingFile("build.properties", "project", "build.properties")); + } + } + + @Override + public Map inlineSchemaOption() { + return super.inlineSchemaOption(); + } + + + @Override + public boolean isEnablePostProcessFile() { + return true; + } + + @Override + public void postProcessFile(File file, String fileType) { + System.out.println("postprocess " + file.toString()); + super.postProcessFile(file, fileType); + } + + @Override + public Map postProcessAllModels(Map objs) { + Map modelsMap = super.postProcessAllModels(objs); + + for (ModelsMap mm : modelsMap.values()) { + for (ModelMap model : mm.getModels()) { + // model oneOf as sealed trait + + CodegenModel cModel = model.getModel(); + cModel.getVendorExtensions().put("x-isSealedTrait", !cModel.oneOf.isEmpty()); + + if (cModel.discriminator != null) { + cModel.getVendorExtensions().put("x-use-discr", true); + + if (cModel.discriminator.getMapping() != null) { + cModel.getVendorExtensions().put("x-use-discr-mapping", true); + } + } + // + try { + List exts = (List) cModel.getVendorExtensions().get("x-implements"); + if (exts != null) { + cModel.getVendorExtensions().put("x-extends", exts.subList(0, 1)); + cModel.getVendorExtensions().put("x-extendsWith", exts.subList(1, exts.size())); + } + } catch (IndexOutOfBoundsException ignored) { + } + + // add refined constraints + + for (CodegenProperty prop: cModel.vars) { + Set imports = new TreeSet<>(); + + prop.getVendorExtensions().putAll(refineProp(prop, imports)); + + cModel.imports.addAll(imports); + } + } + } + return modelsMap; + } + + private Map makeRefiined(Set imports, String dataType, ArrayList refined) { + Map vendorExtensions = new HashMap<>(); + if (!refined.isEmpty()) { + imports.add("And"); + imports.add("Refined"); + + String refinedRgt = String.join(" And ", refined); + + vendorExtensions.put("x-type", "Refined[" + dataType + ", " + refinedRgt + "]"); + vendorExtensions.put("x-refined-lft", dataType); + vendorExtensions.put("x-refined-rgt", refinedRgt); + vendorExtensions.put("x-refined", true); + } else { + vendorExtensions.put("x-type", dataType); + } + + return vendorExtensions; + } + + private Map refineProp(IJsonSchemaValidationProperties prop, Set imports) { + Map vendorExtensions = new HashMap<>(); + + vendorExtensions.put("x-type", prop.getDataType()); + + if (prop.getIsString()) { + ArrayList refined = new ArrayList<>(); + + if (prop.getMinLength() != null) { + refined.add("MinSize[" + prop.getMinLength() + "]"); + imports.add("MinSize"); + } + if (prop.getMaxLength() != null) { + refined.add("MaxSize[" + prop.getMaxLength() + "]"); + imports.add("MaxSize"); + } + if (prop.getPattern() != null) { + try { + String fixedPattern = prop.getPattern().substring(1, prop.getPattern().length() - 1); + refined.add("MatchesRegex[\"" + fixedPattern + "\"]"); + imports.add("MatchesRegex"); + } catch (IndexOutOfBoundsException ignored) { + } + } + vendorExtensions.putAll(makeRefiined(imports, prop.getDataType(), refined)); + } + + if ("Int".equals(prop.getDataType()) + || "Long".equals(prop.getDataType()) + || "Float".equals(prop.getDataType()) + || "Double".equals(prop.getDataType()) + || "BigDecimal".equals(prop.getDataType()) + ) { + ArrayList refined = new ArrayList<>(); + + if (prop.getMinimum() != null) { + if (prop.getExclusiveMinimum()) { + refined.add("Greater[" + prop.getMinimum() + "]"); + imports.add("Greater"); + } else { + refined.add("GreaterEqual[" + prop.getMinimum() + "]"); + imports.add("GreaterEqual"); + } + } + if (prop.getMaximum() != null) { + if (prop.getExclusiveMaximum()) { + refined.add("Less[" + prop.getMaximum() + "]"); + imports.add("Less"); + } else { + refined.add("LessEqual[" + prop.getMaximum() + "]"); + imports.add("LessEqual"); + } + } + vendorExtensions.putAll(makeRefiined(imports, prop.getDataType(), refined)); + } + + if (prop.getIsUuid() || "Uuid".equals(prop.getDataType())) { + prop.setDataType("UUID"); + } + + if (prop.getIsArray() && prop.getItems() != null) { + Map subVendorExtensions = refineProp(prop.getItems(), imports); + prop.getItems().getVendorExtensions().putAll(subVendorExtensions); + + ArrayList refined = new ArrayList<>(); + if (prop.getMinItems() != null) { + refined.add("MinSize[" + prop.getMinItems() + "]"); + imports.add("MinSize"); + } + if (prop.getMaxItems() != null) { + refined.add("MaxSize[" + prop.getMaxItems() + "]"); + imports.add("MaxSize"); + } + + vendorExtensions.putAll(makeRefiined(imports, prop.getDataType(), refined)); + } + + return vendorExtensions; + } + + + @Override + public Map postProcessSupportingFileData(Map objs) { + Map bundle = super.postProcessSupportingFileData(objs); + + List models = (List) bundle.get("models"); + TreeSet allImports = new TreeSet<>(); + for (ModelMap mm: models) { + for (String nextImport : mm.getModel().imports) { + String mapping = importMapping().get(nextImport); + if (mapping != null && !defaultIncludes().contains(mapping)) { + allImports.add(mapping); + } + // add instantiation types + mapping = instantiationTypes().get(nextImport); + if (mapping != null && !defaultIncludes().contains(mapping)) { + allImports.add(mapping); + } + } + } + bundle.put("imports", allImports); + bundle.put("packageName", packageName); + + + ApiInfoMap apiInfoMap = (ApiInfoMap) bundle.get("apiInfo"); + Map> authToOperationMap = new TreeMap<>(); + for (OperationsMap op: apiInfoMap.getApis()) { + List> opsByAuth = (List>) op.get("operationsByAuth"); + for (HashMap auth: opsByAuth) { + String autName = (String) auth.get("auth"); + String classname = (String) op.get("classname"); + List classnames = authToOperationMap.computeIfAbsent(autName, k -> new ArrayList<>()); + classnames.add(classname); + } + } + + bundle.put("authToOperationMap", + authToOperationMap.entrySet().stream().map(ent -> { + Map tuple = new HashMap<>(); + String auth = ent.getKey(); + tuple.put("auth", auth); + tuple.put("ops", ent.getValue()); + tuple.put("addMiddleware", !"".equals(auth)); + return tuple; + }).collect(Collectors.toList()) + ); + return bundle; + } + + @Override + public CodegenType getTag() { + return CodegenType.SERVER; + } + + @Override + public String getName() { + return "scala-http4s-server"; + } + + @Override + public String getHelp() { + return "Generates a Scala http4s server bindings."; + } + + @Override + public String escapeReservedWord(String name) { + return "_" + name; + } + + @Override + public String apiFileFolder() { + return outputFolder + File.separator + apiFileFolderRelative() ; + } + + private String apiFileFolderRelative() { + return sourceFolder + File.separator + apiPackage().replace('.', File.separatorChar); + } + + @Override + public String modelFileFolder() { + return outputFolder + File.separator + modelFileFolderRelative(); + } + + public String modelFileFolderRelative() { + return sourceFolder + File.separator + modelPackage().replace('.', File.separatorChar); + } + + public String packageFileFolderRelative() { + return sourceFolder + File.separator + packageName.replace('.', File.separatorChar); + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objsI, List allModels) { + OperationsMap objs = super.postProcessOperationsWithModels(objsI, allModels); + OperationMap operations = objs.getOperations(); + + List operationList = operations.getOperation(); + Set allAuth = new HashSet<>(); + Map> opsByAuth = new HashMap<>(); + + for (CodegenOperation op : operationList) { + + // Converts GET /foo/bar => GET / foo / bar => + generateScalaPath(op); + + // :? fooQueryParam + generateQueryParameters(op); + + // decide wat methods do we need in delegate: + if (op.consumes == null || op.consumes.size() == 0) { + op.vendorExtensions.put("x-generic-body", true); + } else { + if (op.consumes.stream().anyMatch(x -> x.containsKey("isJson"))) { + op.vendorExtensions.put("x-json-body", true); + } + if (op.consumes.stream().anyMatch(x -> !x.containsKey("isJson"))) { + op.vendorExtensions.put("x-generic-body", true); + } + } + + // decide wat methods do we need in responses: + for (CodegenResponse resp: op.responses) { + if (resp.code.equals("0")) + resp.code = "200"; // 200 by default + + String responseName; + + responseName = locationStatusToResponse.get(resp.code); + if (responseName != null) { + resp.vendorExtensions.put("x-response-location", true); + } else { + responseName = wwwAuthStatusToResponse.get(resp.code); + if (responseName != null) { + resp.vendorExtensions.put("x-response-www-auth", true); + } else { + responseName = allowStatusToResponse.get(resp.code); + if (responseName != null) { + resp.vendorExtensions.put("x-response-allow", true); + } else { + responseName = proxyAuthStatusToResponse.get(resp.code); + if (responseName != null) { + resp.vendorExtensions.put("x-response-proxy-auth", true); + } else { + responseName = statusToResponse.get(resp.code); + if (responseName != null) { + resp.vendorExtensions.put("x-response-standard", true); + } else { + throw new IllegalArgumentException("unsupported status " + resp.code); + } + } + } + } + } + + resp.vendorExtensions.put("x-response", responseName); + + if (resp.getContent() == null) { + resp.vendorExtensions.put("x-generic-response", true); // non json resp + } else { + if (resp.getContent().containsKey("application/json")) { + resp.vendorExtensions.put("x-json-response", true); // json resp + } else { + resp.vendorExtensions.put("x-generic-response", true); // non json resp + } + if (resp.getContent().size() > 1) { + resp.vendorExtensions.put("x-generic-response", true); // non json resp + } + } + } + + if (op.authMethods != null) { + for (CodegenSecurity cs: op.authMethods) { + allAuth.add(cs.name); + } + List> authDup = new ArrayList<>(); + for (CodegenSecurity authMeth: op.authMethods) { + Map vals = new HashMap<>(); + vals.put("authName", authMeth.name); + vals.put("operation", op); + authDup.add(vals); + + opsByAuth.computeIfAbsent(authMeth.name, k -> new ArrayList<>()).add(op.operationId); + } + op.vendorExtensions.put("x-authed", authDup); + } else { + opsByAuth.computeIfAbsent("", k -> new ArrayList<>()).add(op.operationId); + } + } + + TreeSet allImports = new TreeSet<>(); + List currentImports = objs.getImports().stream().flatMap(m -> m.values().stream()).collect(Collectors.toList()); + for (CodegenOperation op : operationList) { + for (String nextImport : op.imports) { + String mapping = importMapping().get(nextImport); + if (mapping != null && !defaultIncludes().contains(mapping)) { + if (!currentImports.contains(mapping)) { + allImports.add(mapping); + } + } + // add instantiation types + mapping = instantiationTypes().get(nextImport); + if (mapping != null && !currentImports.contains(mapping)) { + if (!currentImports.contains(mapping)) { + allImports.add(mapping); + } + } + } + } + + + objs.put("operationsByAuth", opsByAuth.entrySet().stream().map(ent -> { + HashMap tuple = new HashMap<>(); + tuple.put("auth", ent.getKey()); + tuple.put("ops", ent.getValue()); + return tuple; + } + ).collect(Collectors.toList())); + objs.put("extraImports", allImports); + objs.put("allAuth", allAuth); + + return objs; + } + + + @SuppressWarnings("Duplicates") + @Override + public String getTypeDeclaration(Schema p) { + if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + Schema inner = ap.getItems(); + return getSchemaType(p) + "[" + getTypeDeclaration(inner) + "]"; + } else if (ModelUtils.isMapSchema(p)) { + Schema inner = ModelUtils.getAdditionalProperties(p); + + return getSchemaType(p) + "[String, " + getTypeDeclaration(inner) + "]"; + } + return super.getTypeDeclaration(p); + } + + @Override + public String getSchemaType(Schema p) { + String schemaType = super.getSchemaType(p); + String type; + if (typeMapping.containsKey(schemaType)) { + type = typeMapping.get(schemaType); + if (languageSpecificPrimitives.contains(type)) { + return toModelName(type); + } + } else { + type = schemaType; + } + return toModelName(type); + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + @Override + public String escapeUnsafeCharacters(String input) { + return input.replace("*/", "*_/").replace("/*", "/_*"); + } + + private void generateScalaPath(CodegenOperation op) { + Set imports = new HashSet<>(); + + String path = op.path; + + // remove first / + if (path.startsWith("/")) { + path = path.substring(1); + } + + // remove last / + if (path.endsWith("/")) { + path = path.substring(0, path.length() - 1); + } + + String[] items = path.split("/", -1); + String scalaPath = ""; + int pathParamIndex = 0; + + for (String item : items) { + + if (item.matches("^\\{(.*)}$")) { // wrap in {} + // find the datatype of the parameter + final CodegenParameter cp = op.pathParams.get(pathParamIndex); + + // TODO: Handle non-primitives… + scalaPath = scalaPath + " / " + cpToPathParameter(cp, imports, cp.vendorExtensions); + + pathParamIndex++; + } else { + scalaPath = scalaPath + " / " + "\"" + item + "\""; + } + } + + op.vendorExtensions.put("x-codegen-path", scalaPath); + op.imports.addAll(imports); + } + + private String cpToPathParameter(CodegenParameter cp, Set imports, Map vendorExtensions) { + // don't support containers and arrays yet, reset to string + if (cp.isContainer || cp.isArray) { + cp.setDataType("String"); + cp.setIsArray(false); + cp.setIsString(true); + cp.isContainer = false; + } + + Map _vendorExtensions = refineProp(cp, imports); + vendorExtensions.putAll(_vendorExtensions); + + if (_vendorExtensions.size() == 1) { // only `x-type` + if ("String".equals(cp.getDataType())) { + return cp.baseName; + } else { + return cp.dataType + "Varr(" + cp.baseName + ")"; + } + } else { + return cp.baseName + "Varr(" + cp.baseName + ")"; + } + } + + private void generateQueryParameters(CodegenOperation op) { + Set imports = new HashSet<>(); + String queryString = ""; + + for (CodegenParameter cp : op.queryParams) { + if (queryString.isEmpty()) { + queryString = queryString + " :? "; + } else { + queryString = queryString + " +& "; + } + + queryString = queryString + cpToQueryParameter(cp, imports, cp.vendorExtensions); + } + + op.vendorExtensions.put("x-codegen-query", queryString); + op.imports.addAll(imports); + } + + private String cpToQueryParameter(CodegenParameter cp, Set imports, Map vendorExtensions) { + // don't support containers and arrays yet, reset to string + if (cp.isContainer && !cp.isArray) { + cp.setDataType("String"); + cp.setIsArray(false); + cp.setIsString(true); + cp.isContainer = false; + } + + vendorExtensions.putAll(refineProp(cp, imports)); + return cp.baseName + "QueryParam(" + cp.baseName + ")"; + } + + @Override + public void postProcess() { + System.out.println("################################################################################"); + System.out.println("# Thanks for using OpenAPI Generator. #"); + System.out.println("# Please consider donation to help us maintain this project \uD83D\uDE4F #"); + System.out.println("# https://opencollective.com/openapi_generator/donate #"); + System.out.println("# #"); + System.out.println("# This generator's contributed by Jim Schubert (https://github.com/jimschubert)#"); + System.out.println("# Please support his work directly via https://patreon.com/jimschubert \uD83D\uDE4F #"); + System.out.println("################################################################################"); + } + + @Override + public GeneratorLanguage generatorLanguage() { return GeneratorLanguage.SCALA; } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPekkoClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPekkoClientCodegen.java new file mode 100644 index 000000000000..f277ab617fbb --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/ScalaPekkoClientCodegen.java @@ -0,0 +1,359 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.languages; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template; +import io.swagger.v3.oas.models.media.ArraySchema; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.security.SecurityScheme; +import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.*; +import org.openapitools.codegen.meta.features.*; +import org.openapitools.codegen.model.ModelMap; +import org.openapitools.codegen.model.OperationMap; +import org.openapitools.codegen.model.OperationsMap; +import org.openapitools.codegen.utils.ModelUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.io.File; +import java.io.IOException; +import java.io.StringWriter; +import java.io.Writer; +import java.util.*; + +import static org.openapitools.codegen.utils.StringUtils.camelize; + +public class ScalaPekkoClientCodegen extends AbstractScalaCodegen implements CodegenConfig { + protected String mainPackage = "org.openapitools.client"; + protected String groupId = "org.openapitools"; + protected String artifactId = "openapi-client"; + protected String artifactVersion = "1.0.0"; + protected String resourcesFolder = "src/main/resources"; + protected String apiDocPath = "docs/"; + protected String modelDocPath = "docs/"; + protected String configKey = "apiRequest"; + protected int defaultTimeoutInMs = 5000; + protected String configKeyPath = mainPackage; + protected boolean registerNonStandardStatusCodes = true; + protected boolean renderJavadoc = true; + protected boolean removeOAuthSecurities = true; + + @SuppressWarnings("hiding") + protected final Logger LOGGER = LoggerFactory.getLogger(ScalaPekkoClientCodegen.class); + + public ScalaPekkoClientCodegen() { + super(); + + modifyFeatureSet(features -> features + .includeDocumentationFeatures(DocumentationFeature.Readme) + .wireFormatFeatures(EnumSet.of(WireFormatFeature.JSON, WireFormatFeature.XML, WireFormatFeature.Custom)) + .securityFeatures(EnumSet.of( + SecurityFeature.BasicAuth, + SecurityFeature.ApiKey, + SecurityFeature.BearerToken + )) + .excludeGlobalFeatures( + GlobalFeature.XMLStructureDefinitions, + GlobalFeature.Callbacks, + GlobalFeature.LinkObjects, + GlobalFeature.ParameterStyling + ) + .excludeSchemaSupportFeatures( + SchemaSupportFeature.Polymorphism + ) + .excludeParameterFeatures( + ParameterFeature.Cookie + ) + .includeClientModificationFeatures( + ClientModificationFeature.BasePath, + ClientModificationFeature.UserAgent + ) + ); + + outputFolder = "generated-code/scala-pekko"; + modelTemplateFiles.put("model.mustache", ".scala"); + apiTemplateFiles.put("api.mustache", ".scala"); + apiDocTemplateFiles.put("api_doc.mustache", ".md"); + modelDocTemplateFiles.put("model_doc.mustache", ".md"); + embeddedTemplateDir = templateDir = "scala-pekko-client"; + apiPackage = mainPackage + ".api"; + modelPackage = mainPackage + ".model"; + invokerPackage = mainPackage + ".core"; + + setReservedWordsLowerCase( + Arrays.asList( + "abstract", "case", "catch", "class", "def", "do", "else", "extends", + "false", "final", "finally", "for", "forSome", "if", "implicit", + "import", "lazy", "match", "new", "null", "object", "override", "package", + "private", "protected", "return", "sealed", "super", "this", "throw", + "trait", "try", "true", "type", "val", "var", "while", "with", "yield") + ); + + additionalProperties.put(CodegenConstants.GROUP_ID, groupId); + additionalProperties.put(CodegenConstants.ARTIFACT_ID, artifactId); + additionalProperties.put(CodegenConstants.ARTIFACT_VERSION, artifactVersion); + additionalProperties.put("configKey", configKey); + additionalProperties.put("configKeyPath", configKeyPath); + additionalProperties.put("defaultTimeout", defaultTimeoutInMs); + if (renderJavadoc) { + additionalProperties.put("javadocRenderer", new JavadocLambda()); + } + additionalProperties.put("fnCapitalize", new CapitalizeLambda()); + additionalProperties.put("fnCamelize", new CamelizeLambda(false)); + additionalProperties.put("fnEnumEntry", new EnumEntryLambda()); + + importMapping.remove("Seq"); + importMapping.remove("List"); + importMapping.remove("Set"); + importMapping.remove("Map"); + importMapping.put("BigDecimal", "java.math.BigDecimal"); + + typeMapping = new HashMap<>(); + typeMapping.put("array", "Seq"); + typeMapping.put("set", "Set"); + typeMapping.put("boolean", "Boolean"); + typeMapping.put("string", "String"); + typeMapping.put("int", "Int"); + typeMapping.put("integer", "Int"); + typeMapping.put("long", "Long"); + typeMapping.put("float", "Float"); + typeMapping.put("byte", "Byte"); + typeMapping.put("short", "Short"); + typeMapping.put("char", "Char"); + typeMapping.put("double", "Double"); + typeMapping.put("object", "Any"); + typeMapping.put("file", "File"); + typeMapping.put("binary", "File"); + typeMapping.put("number", "BigDecimal"); + typeMapping.put("decimal", "BigDecimal"); + + instantiationTypes.put("array", "ListBuffer"); + instantiationTypes.put("map", "Map"); + + cliOptions.add(new CliOption("mainPackage", "Top-level package name, which defines 'apiPackage', 'modelPackage', 'invokerPackage'").defaultValue("org.openapitools.client")); + } + + @Override + public void processOpts() { + super.processOpts(); + if (additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + this.setInvokerPackage((String) additionalProperties.get(CodegenConstants.INVOKER_PACKAGE)); + } + if (additionalProperties.containsKey("mainPackage")) { + setMainPackage((String) additionalProperties.get("mainPackage")); + additionalProperties.replace("configKeyPath", this.configKeyPath); + if (!additionalProperties.containsKey(CodegenConstants.API_PACKAGE)) { + apiPackage = mainPackage + ".api"; + additionalProperties.put(CodegenConstants.API_PACKAGE, apiPackage); + } + if (!additionalProperties.containsKey(CodegenConstants.MODEL_PACKAGE)) { + modelPackage = mainPackage + ".model"; + additionalProperties.put(CodegenConstants.MODEL_PACKAGE, modelPackage); + } + if (!additionalProperties.containsKey(CodegenConstants.INVOKER_PACKAGE)) { + invokerPackage = mainPackage + ".core"; + } + } + additionalProperties.put(CodegenConstants.INVOKER_PACKAGE, invokerPackage); + // make api and model doc path available in mustache template + additionalProperties.put("apiDocPath", apiDocPath); + additionalProperties.put("modelDocPath", modelDocPath); + + supportingFiles.add(new SupportingFile("README.mustache", "", "README.md")); + supportingFiles.add(new SupportingFile("build.sbt.mustache", "", "build.sbt")); + supportingFiles.add(new SupportingFile("pom.mustache", "", "pom.xml")); + supportingFiles.add(new SupportingFile("reference.mustache", resourcesFolder, "reference.conf")); + final String invokerFolder = (sourceFolder + File.separator + invokerPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("apiRequest.mustache", invokerFolder, "ApiRequest.scala")); + supportingFiles.add(new SupportingFile("apiInvoker.mustache", invokerFolder, "ApiInvoker.scala")); + supportingFiles.add(new SupportingFile("requests.mustache", invokerFolder, "requests.scala")); + supportingFiles.add(new SupportingFile("apiSettings.mustache", invokerFolder, "ApiSettings.scala")); + final String apiFolder = (sourceFolder + File.separator + apiPackage).replace(".", File.separator); + supportingFiles.add(new SupportingFile("project/build.properties.mustache", "project", "build.properties")); + supportingFiles.add(new SupportingFile("enumsSerializers.mustache", apiFolder, "EnumsSerializers.scala")); + supportingFiles.add(new SupportingFile("serializers.mustache", invokerFolder, "Serializers.scala")); + } + + @Override + public CodegenType getTag() { + return CodegenType.CLIENT; + } + + @Override + public String getName() { + return "scala-pekko"; + } + + @Override + public String getHelp() { + return "Generates a Scala client library (beta) base on pekko/Spray."; + } + + @Override + public String escapeReservedWord(String name) { + if (this.reservedWordsMappings().containsKey(name)) { + return this.reservedWordsMappings().get(name); + } + return "`" + name + "`"; + } + + @Override + public OperationsMap postProcessOperationsWithModels(OperationsMap objs, List allModels) { + if (registerNonStandardStatusCodes) { + try { + OperationMap opsMap = objs.getOperations(); + HashSet unknownCodes = new HashSet<>(); + for (CodegenOperation operation : opsMap.getOperation()) { + for (CodegenResponse response : operation.responses) { + if ("default".equals(response.code)) { + continue; + } + try { + int code = Integer.parseInt(response.code); + if (code >= 600) { + unknownCodes.add(code); + } + } catch (NumberFormatException e) { + LOGGER.error("Status code is not an integer : response.code", e); + } + } + } + if (!unknownCodes.isEmpty()) { + additionalProperties.put("unknownStatusCodes", unknownCodes); + } + } catch (Exception e) { + LOGGER.error("Unable to find operations List", e); + } + } + return super.postProcessOperationsWithModels(objs, allModels); + } + + @Override + public List fromSecurity(Map schemes) { + final List codegenSecurities = super.fromSecurity(schemes); + if (!removeOAuthSecurities) { + return codegenSecurities; + } + + // Remove OAuth securities + codegenSecurities.removeIf(security -> security.isOAuth); + if (codegenSecurities.isEmpty()) { + return null; + } + return codegenSecurities; + } + + @Override + public String toParamName(String name) { + // obtain the name from parameterNameMapping directly if provided + if (parameterNameMapping.containsKey(name)) { + return parameterNameMapping.get(name); + } + + return formatIdentifier(name, false); + } + + @Override + public String toEnumName(CodegenProperty property) { + return formatIdentifier(property.baseName, true); + } + + @Override + public String toDefaultValue(Schema p) { + if (p.getRequired() != null && p.getRequired().contains(p.getName())) { + return "None"; + } + + if (ModelUtils.isBooleanSchema(p)) { + return null; + } else if (ModelUtils.isDateSchema(p)) { + return null; + } else if (ModelUtils.isDateTimeSchema(p)) { + return null; + } else if (ModelUtils.isNumberSchema(p)) { + return null; + } else if (ModelUtils.isIntegerSchema(p)) { + return null; + } else if (ModelUtils.isMapSchema(p)) { + String inner = getSchemaType(ModelUtils.getAdditionalProperties(p)); + return "Map[String, " + inner + "].empty "; + } else if (ModelUtils.isArraySchema(p)) { + ArraySchema ap = (ArraySchema) p; + String inner = getSchemaType(ap.getItems()); + if (ModelUtils.isSet(ap)) { + return "Set[" + inner + "].empty "; + } + return "Seq[" + inner + "].empty "; + } else if (ModelUtils.isStringSchema(p)) { + return null; + } else { + return null; + } + } + + + private static class JavadocLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + final String[] lines = fragment.split("\\r?\\n"); + final StringBuilder sb = new StringBuilder(); + sb.append(" /**\n"); + for (String line : lines) { + sb.append(" * ").append(line).append("\n"); + } + sb.append(" */\n"); + return sb.toString(); + } + } + + private static class CapitalizeLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return StringUtils.capitalize(fragment); + } + } + + private class EnumEntryLambda extends CustomLambda { + @Override + public String formatFragment(String fragment) { + return formatIdentifier(fragment, true); + } + } + + @Override + public String escapeQuotationMark(String input) { + // remove " to avoid code injection + return input.replace("\"", ""); + } + + public void setMainPackage(String mainPackage) { + this.configKeyPath = this.mainPackage = mainPackage; + } + + @Override + public String apiDocFileFolder() { + return (outputFolder + File.separator + apiDocPath).replace('/', File.separatorChar); + } + + @Override + public String modelDocFileFolder() { + return (outputFolder + File.separator + modelDocPath).replace('/', File.separatorChar); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java index 92a8883d33f6..513cc2b7bfe9 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SpringCodegen.java @@ -21,13 +21,22 @@ import static org.openapitools.codegen.utils.CamelizeOption.LOWERCASE_FIRST_LETTER; import static org.openapitools.codegen.utils.StringUtils.camelize; +import com.samskivert.mustache.Mustache; +import io.swagger.v3.oas.models.Components; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.Operation; +import io.swagger.v3.oas.models.PathItem; +import io.swagger.v3.oas.models.media.MediaType; +import io.swagger.v3.oas.models.media.Schema; +import io.swagger.v3.oas.models.parameters.Parameter; +import io.swagger.v3.oas.models.servers.Server; +import io.swagger.v3.oas.models.tags.Tag; import java.io.File; import java.net.URL; import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; - import org.apache.commons.lang3.StringUtils; import org.apache.commons.lang3.tuple.Pair; import org.openapitools.codegen.CliOption; @@ -63,23 +72,9 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import com.samskivert.mustache.Mustache; - -import io.swagger.v3.oas.models.Components; -import io.swagger.v3.oas.models.OpenAPI; -import io.swagger.v3.oas.models.Operation; -import io.swagger.v3.oas.models.PathItem; -import io.swagger.v3.oas.models.media.MediaType; -import io.swagger.v3.oas.models.media.Schema; -import io.swagger.v3.oas.models.parameters.Parameter; -import io.swagger.v3.oas.models.servers.Server; -import io.swagger.v3.oas.models.tags.Tag; - public class SpringCodegen extends AbstractJavaCodegen implements BeanValidationFeatures, PerformBeanValidationFeatures, OptionalFeatures, SwaggerUIFeatures { private final Logger LOGGER = LoggerFactory.getLogger(SpringCodegen.class); - - public static final String TITLE = "title"; public static final String SERVER_PORT = "serverPort"; public static final String CONFIG_PACKAGE = "configPackage"; @@ -1425,50 +1420,6 @@ public void setRequestMappingMode(RequestMappingMode requestMappingMode) { this.requestMappingMode = requestMappingMode; } - @Override - public CodegenParameter fromParameter( final Parameter parameter, final Set imports ) { - CodegenParameter codegenParameter = super.fromParameter( parameter, imports ); - if(!isListOrSet(codegenParameter)){ - return codegenParameter; - } - codegenParameter.datatypeWithEnum = replaceBeanValidationCollectionType(codegenParameter.items, codegenParameter.datatypeWithEnum ); - codegenParameter.dataType = replaceBeanValidationCollectionType(codegenParameter.items, codegenParameter.dataType ); - return codegenParameter; - } - @Override - public CodegenProperty fromProperty( String name, Schema p, boolean required, boolean schemaIsFromAdditionalProperties ) { - CodegenProperty codegenProperty = super.fromProperty( name, p, required, schemaIsFromAdditionalProperties ); - if(!isListOrSet(codegenProperty)){ - return codegenProperty; - } - codegenProperty.datatypeWithEnum = replaceBeanValidationCollectionType(codegenProperty.items, codegenProperty.datatypeWithEnum ); - codegenProperty.dataType = replaceBeanValidationCollectionType(codegenProperty.items, codegenProperty.dataType ); - return codegenProperty; - } - - // The default validation applied for non-container and non-map types is sufficient for the SpringCodegen. - // Maps are very complex for bean validation, so it's currently not supported. - private static boolean isListOrSet(CodegenProperty codegenProperty) { - return codegenProperty.isContainer && !codegenProperty.isMap; - } - - // The default validation applied for non-container and non-map types is sufficient for the SpringCodegen. - // Maps are very complex for bean validation, so it's currently not supported. - private static boolean isListOrSet(CodegenParameter codegenParameter) { - return codegenParameter.isContainer && !codegenParameter.isMap; - } - - private String replaceBeanValidationCollectionType(CodegenProperty codegenProperty, String dataType) { - if (!useBeanValidation() || !codegenProperty.isModel || isResponseType(codegenProperty)) { - return dataType; - } - - if (StringUtils.isEmpty( dataType ) || dataType.contains( "@Valid" )) { - return dataType; - } - return dataType.replace( "<", "<@Valid " ); - } - public void setResourceFolder( String resourceFolder ) { this.resourceFolder = resourceFolder; } @@ -1476,16 +1427,4 @@ public void setResourceFolder( String resourceFolder ) { public String getResourceFolder() { return resourceFolder; } - - - // This should prevent, that the response data types not contains a @Valid annotation. - // However, the side effect is that attributes with response as name are also affected. - private static boolean isResponseType(CodegenProperty codegenProperty) { - return codegenProperty.baseName.toLowerCase(Locale.ROOT).contains("response"); - } - - // SPRING_HTTP_INTERFACE does not support bean validation. - public boolean useBeanValidation() { - return useBeanValidation && !SPRING_HTTP_INTERFACE.equals(library); - } } diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java index 77c4e5016dbf..afec866d600d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/Swift5ClientCodegen.java @@ -1027,6 +1027,10 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + if (name.length() == 0) { return "empty"; } @@ -1127,6 +1131,10 @@ private String titleCase(final String input) { @Override public String toEnumName(CodegenProperty property) { + if (enumNameMapping.containsKey(property.name)) { + return enumNameMapping.get(property.name); + } + String enumName = toModelName(property.name); // Ensure that the enum type doesn't match a reserved word or diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCombineClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCombineClientCodegen.java index 36daf075bbf4..fd7e9022f30d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCombineClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/SwiftCombineClientCodegen.java @@ -575,6 +575,10 @@ public String toEnumDefaultValue(String value, String datatype) { @Override public String toEnumVarName(String name, String datatype) { + if (enumNameMapping.containsKey(name)) { + return enumNameMapping.get(name); + } + if (name.length() == 0) { return "empty"; } @@ -630,6 +634,10 @@ public String toEnumVarName(String name, String datatype) { @Override public String toEnumName(CodegenProperty property) { + if (enumNameMapping.containsKey(property.name)) { + return enumNameMapping.get(property.name); + } + String enumName = toModelName(property.name); // Ensure that the enum type doesn't match a reserved word or diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java index 3cfe890f600b..a5e6be37b78b 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/languages/TypeScriptFetchClientCodegen.java @@ -530,7 +530,7 @@ public ExtendedCodegenOperation fromOperation(String path, String httpMethod, Op } if (!op.hasReturnPassthroughVoid) { - Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(methodResponse)); + Schema responseSchema = unaliasSchema(ModelUtils.getSchemaFromResponse(openAPI, methodResponse)); ExtendedCodegenProperty cp = null; if (op.returnPassthrough instanceof String && cm != null) { cp = (ExtendedCodegenProperty) this.processCodeGenModel(cm).vars.get(1); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/model/WebhooksMap.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/model/WebhooksMap.java new file mode 100644 index 000000000000..4fd5af073bc3 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/model/WebhooksMap.java @@ -0,0 +1,24 @@ +package org.openapitools.codegen.model; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class WebhooksMap extends HashMap { + public OperationMap getWebhooks() { + return (OperationMap) get("operations"); + } + + public void setWebhooks(OperationMap objs) { + put("operations", objs); + } + + @SuppressWarnings("unchecked") + public List> getImports() { + return (List>) get("imports"); + } + + public void setImports(List> imports) { + put("imports", imports); + } +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/CopyLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/CopyLambda.java new file mode 100644 index 000000000000..f1e4868c59b7 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/CopyLambda.java @@ -0,0 +1,48 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.templating.mustache; + +import java.io.IOException; +import java.io.Writer; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template.Fragment; + +/** + * Saves template text to be used later. + * + * Register: + *
            + * additionalProperties.put("copy", new CopyLambda());
            + * 
            + * + * Use: + *
            + * {{#copy}}{{name}}{{/copy}}
            + * 
            + */ +public class CopyLambda implements Mustache.Lambda { + public String savedContent; + + public CopyLambda() { + } + + @Override + public void execute(Fragment fragment, Writer writer) throws IOException { + savedContent = fragment.execute().stripTrailing(); + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/IndentedLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/IndentedLambda.java index f90b662c6d63..09f669ae3bea 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/IndentedLambda.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/IndentedLambda.java @@ -112,7 +112,7 @@ public void execute(Template.Fragment fragment, Writer writer) throws IOExceptio String prefixedIndention = StringUtils.repeat(new String(Character.toChars(spaceCode)), prefixSpaceCount); StringBuilder sb = new StringBuilder(); // use \n instead of System.lineSeparator (e.g. \r\n in Windows) as templates use \n - String[] lines = text.split("\n"); + String[] lines = text.split("\n", -1); for (int i = 0; i < lines.length; i++) { String line = lines[i]; // Mustache will apply correct indentation to the first line of a template (to match declaration location). diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PasteLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PasteLambda.java new file mode 100644 index 000000000000..ea798d9dc3c3 --- /dev/null +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/PasteLambda.java @@ -0,0 +1,76 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.templating.mustache; + +import java.io.IOException; +import java.io.Writer; + +import com.samskivert.mustache.Mustache; +import com.samskivert.mustache.Template.Fragment; + +/** + * Writes text that was previously saved. + * + * Register: + *
            + * additionalProperties.put("paste", new PasteLambda(copyLambda, true, true, true, false));
            + * 
            + * + * Use: + *
            + * {{#paste}}{{/paste}}
            + * 
            + */ +public class PasteLambda implements Mustache.Lambda { + private final CopyLambda copyLambda; + private final Boolean stripLeading; + private final Boolean stripTrailing; + private final Boolean endWithLineBreak; + private final Boolean clear; + + public PasteLambda(CopyLambda copyLambda, Boolean stripLeading, Boolean stripTrailing, Boolean endWithLineBreak, boolean clear) { + this.copyLambda = copyLambda; + this.stripLeading = stripLeading; + this.stripTrailing = stripTrailing; + this.endWithLineBreak = endWithLineBreak; + this.clear = clear; + } + + @Override + public void execute(Fragment fragment, Writer writer) throws IOException { + String content = this.copyLambda.savedContent; + + if (content == null) { + return; + } + + if (this.stripTrailing){ + content = content.stripTrailing(); + } + if (this.stripLeading) { + content = content.stripLeading(); + } + if (this.endWithLineBreak && !content.endsWith("\n")){ + content = content + "\n"; + } + writer.write(content); + + if (this.clear) { + this.copyLambda.savedContent = null; + } + } +} diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java index 469c7075a221..287e4ea96506 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/templating/mustache/UniqueLambda.java @@ -51,7 +51,7 @@ public UniqueLambda(String delimiter, boolean withNewLine) @Override public void execute(Template.Fragment fragment, Writer writer) throws IOException { - String[] parts = fragment.execute().split(this.delimiter); + String[] parts = fragment.execute().split(this.delimiter, -1); List uniqueLines = Arrays.stream(parts).distinct().collect(Collectors.toList()); diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java index 838df6ce5e09..d19c4f9e7ed0 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ModelUtils.java @@ -35,6 +35,7 @@ import io.swagger.v3.parser.util.SchemaTypeUtil; import org.apache.commons.io.FileUtils; import org.apache.commons.lang3.StringUtils; +import org.openapitools.codegen.CodegenConfig; import org.openapitools.codegen.CodegenModel; import org.openapitools.codegen.IJsonSchemaValidationProperties; import org.openapitools.codegen.config.GlobalSettings; @@ -198,7 +199,7 @@ public static List getSchemasUsedOnlyInFormParam(OpenAPI openAPI) { List schemasUsedInOtherCases = new ArrayList(); visitOpenAPI(openAPI, (s, t) -> { - if (s.get$ref() != null) { + if (s != null && s.get$ref() != null) { String ref = getSimpleRef(s.get$ref()); if ("application/x-www-form-urlencoded".equalsIgnoreCase(t) || "multipart/form-data".equalsIgnoreCase(t)) { @@ -320,6 +321,10 @@ private static void visitContent(OpenAPI openAPI, Content content, OpenAPISchema * @param visitor the visitor function which is invoked for every visited schema. */ private static void visitSchema(OpenAPI openAPI, Schema schema, String mimeType, List visitedSchemas, OpenAPISchemaVisitor visitor) { + if (schema == null) { + return; + } + visitor.visit(schema, mimeType); if (schema.get$ref() != null) { String ref = getSimpleRef(schema.get$ref()); @@ -710,7 +715,7 @@ public static boolean isModel(Schema schema) { return (schema != null) && // has properties ((null != schema.getProperties() && !schema.getProperties().isEmpty()) - // composed schema is a model, consider very simple ObjectSchema a model + // composed schema is a model, consider very simple ObjectSchema a model || isComposedSchema(schema) || schema instanceof ObjectSchema); } @@ -827,6 +832,19 @@ public static boolean isFreeFormObject(Schema schema) { return false; } + public static boolean shouldGenerateFreeFormObjectModel(String name, CodegenConfig config) { + // there are 3 free form use cases + // 1. free form with no validation that is not allOf included in any composed schemas + // 2. free form with validation + // 3. free form that is allOf included in any composed schemas + // this use case arises when using interface schemas + // generators may choose to make models for use case 2 + 3 + Schema refSchema = new Schema(); + refSchema.set$ref("#/components/schemas/" + name); + Schema unaliasedSchema = config.unaliasSchema(refSchema); + return unaliasedSchema.get$ref() != null; + } + /** * If a Schema contains a reference to another Schema with '$ref', returns the referenced Schema if it is found or the actual Schema in the other cases. * @@ -1005,11 +1023,17 @@ public static Schema getSchemaFromRequestBody(RequestBody requestBody) { /** * Return the first defined Schema for a ApiResponse * - * @param response api response of the operation + * @param openAPI OpenAPI spec. + * @param response API response of the operation * @return firstSchema */ - public static Schema getSchemaFromResponse(ApiResponse response) { - return getSchemaFromContent(response.getContent()); + public static Schema getSchemaFromResponse(OpenAPI openAPI, ApiResponse response) { + ApiResponse result = getReferencedApiResponse(openAPI, response); + if (result == null) { + return null; + } else { + return getSchemaFromContent(result.getContent()); + } } /** @@ -1734,7 +1758,7 @@ private static void setNumericValidations(Schema schema, BigDecimal multipleOf, private static void logWarnMessagesForIneffectiveValidations(Set setValidations, Schema schema, Set effectiveValidations) { setValidations.removeAll(effectiveValidations); setValidations.stream().forEach(validation -> { - LOGGER.warn("Validation '" + validation + "' has no effect on schema '"+ schema.getType() +"'. Ignoring!"); + LOGGER.warn("Validation '" + validation + "' has no effect on schema '" + schema.getType() +"'. Ignoring!"); }); } @@ -1838,7 +1862,7 @@ public static boolean isAllOf(Schema schema) { * @return true if allOf is not empty */ public static boolean hasAllOf(Schema schema) { - if (schema.getAllOf() != null && !schema.getAllOf().isEmpty()) { + if (schema != null && schema.getAllOf() != null && !schema.getAllOf().isEmpty()) { return true; } @@ -1954,7 +1978,6 @@ public static boolean hasCommonAttributesDefined(Schema schema) { * Returns true if the schema is a parent (with discriminator). * * @param schema the schema. - * * @return true if the schema is a parent. */ public static boolean isParent(Schema schema) { diff --git a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java index 893cf31332e3..8a6be94b934d 100644 --- a/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java +++ b/modules/openapi-generator/src/main/java/org/openapitools/codegen/utils/ProcessUtils.java @@ -9,6 +9,7 @@ import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Map; public class ProcessUtils { @@ -306,7 +307,7 @@ public static boolean hasHttpBearerMethods(OpenAPI openAPI) { final Map securitySchemes = getSecuritySchemes(openAPI); if (securitySchemes != null) { for (Map.Entry scheme : securitySchemes.entrySet()) { - if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "bearer".equals(scheme.getValue().getScheme())) { + if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "bearer".equals(scheme.getValue().getScheme().strip().toLowerCase(Locale.ROOT))) { return true; } } @@ -325,7 +326,7 @@ public static boolean hasHttpBasicMethods(OpenAPI openAPI) { final Map securitySchemes = getSecuritySchemes(openAPI); if (securitySchemes != null) { for (Map.Entry scheme : securitySchemes.entrySet()) { - if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "basic".equals(scheme.getValue().getScheme())) { + if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "basic".equals(scheme.getValue().getScheme().strip().toLowerCase(Locale.ROOT))) { return true; } } @@ -344,7 +345,7 @@ public static boolean hasHttpSignatureMethods(OpenAPI openAPI) { final Map securitySchemes = getSecuritySchemes(openAPI); if (securitySchemes != null) { for (Map.Entry scheme : securitySchemes.entrySet()) { - if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "signature".equals(scheme.getValue().getScheme())) { + if (SecurityScheme.Type.HTTP.equals(scheme.getValue().getType()) && "signature".equals(scheme.getValue().getScheme().strip().toLowerCase(Locale.ROOT))) { return true; } } diff --git a/modules/openapi-generator/src/main/resources/Ada/config.gpr b/modules/openapi-generator/src/main/resources/Ada/config.gpr index 0567eb7cb9fd..6e7c4514bfa0 100644 --- a/modules/openapi-generator/src/main/resources/Ada/config.gpr +++ b/modules/openapi-generator/src/main/resources/Ada/config.gpr @@ -45,7 +45,7 @@ abstract project Config is when "debug" => for Default_Switches ("Ada") use ("-E"); - when others => + when others => for Default_Switches ("Ada") use ("-E"); end case; @@ -64,12 +64,12 @@ abstract project Config is when "coverage" => for Default_Switches ("ada") use ("-fprofile-arcs"); - - when others => - null; + + when others => + null; end case; - end linker; + end linker; package Ide is for VCS_Kind use "git"; diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache index 74b98f4c0452..b1a5ef55f94a 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-body.mustache @@ -99,7 +99,7 @@ end: // {{/notes}} {{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} -{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}}) +{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}} {{/isNumber}}{{#isLong}}{{{dataType}}} {{/isLong}}{{#isInteger}}{{{dataType}}} *{{/isInteger}}{{#isDouble}}{{{dataType}}} {{/isDouble}}{{#isFloat}}{{{dataType}}} {{/isFloat}}{{#isBoolean}}{{dataType}} *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e {{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}} {{/isDate}}{{#isDateTime}}{{{dataType}}} {{/isDateTime}}{{#isFile}}{{{dataType}}} {{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}} {{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}} {{/isMap}}{{/isContainer}}{{{paramName}}}{{/allParams}}) { list_t *localVarQueryParameters = {{#hasQueryParams}}list_createList();{{/hasQueryParams}}{{^hasQueryParams}}NULL;{{/hasQueryParams}} list_t *localVarHeaderParameters = {{#hasHeaderParams}}list_createList();{{/hasHeaderParams}}{{^hasHeaderParams}}NULL;{{/hasHeaderParams}} @@ -138,7 +138,7 @@ end: snprintf(localVarToReplace_{{paramName}}, sizeOfPathParams_{{paramName}}, "{%s}", "{{baseName}}"); char localVarBuff_{{paramName}}[256]; - intToStr(localVarBuff_{{paramName}}, {{paramName}}); + intToStr(localVarBuff_{{paramName}}, *{{paramName}}); localVarPath = strReplace(localVarPath, localVarToReplace_{{paramName}}, localVarBuff_{{paramName}}); @@ -198,7 +198,19 @@ end: keyValuePair_t *keyPairHeader_{{paramName}} = 0; if ({{paramName}}) { keyHeader_{{{paramName}}} = strdup("{{{baseName}}}"); + {{#isInteger}} + valueHeader_{{{paramName}}} = calloc(1,MAX_NUMBER_LENGTH); + snprintf(valueHeader_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); + {{/isInteger}} + {{#isBoolean}} + valueHeader_{{{paramName}}} = calloc(1,MAX_NUMBER_LENGTH); + snprintf(valueHeader_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); + {{/isBoolean}} + {{^isInteger}} + {{^isBoolean}} valueHeader_{{{paramName}}} = {{#isString}}{{^isEnum}}strdup({{/isEnum}}{{/isString}}({{{paramName}}}){{#isString}}{{^isEnum}}){{/isEnum}}{{/isString}}; + {{/isBoolean}} + {{/isInteger}} keyPairHeader_{{paramName}} = keyValuePair_create(keyHeader_{{{paramName}}}, {{#isEnum}}(void *){{/isEnum}}{{^isString}}&{{/isString}}valueHeader_{{{paramName}}}); list_addElement(localVarHeaderParameters,keyPairHeader_{{paramName}}); } @@ -212,17 +224,7 @@ end: {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}char *{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}char *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}} valueQuery_{{{paramName}}} {{#isString}}{{^isEnum}}= NULL{{/isEnum}}{{/isString}}{{#isInteger}}= NULL{{/isInteger}}{{#isBoolean}}= NULL{{/isBoolean}}; keyValuePair_t *keyPairQuery_{{paramName}} = 0; {{/isArray}} - {{#isInteger}} - if (1) // Always send integer parameters to the API server - {{/isInteger}} - {{#isBoolean}} - if (1) // Always send boolean parameters to the API server - {{/isBoolean}} - {{^isInteger}} - {{^isBoolean}} if ({{paramName}}) - {{/isBoolean}} - {{/isInteger}} { {{#isArray}} list_addElement(localVarQueryParameters,{{paramName}}); @@ -231,11 +233,11 @@ end: keyQuery_{{{paramName}}} = strdup("{{{baseName}}}"); {{#isInteger}} valueQuery_{{{paramName}}} = calloc(1,MAX_NUMBER_LENGTH); - snprintf(valueQuery_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", {{{paramName}}}); + snprintf(valueQuery_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); {{/isInteger}} {{#isBoolean}} valueQuery_{{{paramName}}} = calloc(1,MAX_NUMBER_LENGTH); - snprintf(valueQuery_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", {{{paramName}}}); + snprintf(valueQuery_{{{paramName}}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); {{/isBoolean}} {{^isInteger}} {{^isBoolean}} @@ -243,7 +245,7 @@ end: {{/isBoolean}} {{/isInteger}} keyPairQuery_{{paramName}} = keyValuePair_create(keyQuery_{{{paramName}}}, {{#isEnum}}(void *)strdup({{{operationId}}}_{{enumName}}_ToString( - {{/isEnum}}{{^isString}}{{^isInteger}}{{^isBoolean}}&{{/isBoolean}}{{/isInteger}}{{/isString}}valueQuery_{{{paramName}}}{{#isEnum}})){{/isEnum}}); + {{/isEnum}}{{^isString}}{{^isInteger}}{{^isBoolean}}&{{/isBoolean}}{{/isInteger}}{{/isString}}valueQuery_{{{paramName}}}{{#isEnum}})){{/isEnum}}); list_addElement(localVarQueryParameters,keyPairQuery_{{paramName}}); {{/isArray}} } @@ -271,7 +273,19 @@ end: {{/isFile}} {{^isFile}} keyForm_{{paramName}} = strdup("{{{baseName}}}"); + {{#isInteger}} + valueForm_{{paramName}} = calloc(1,MAX_NUMBER_LENGTH); + snprintf(valueForm_{{paramName}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); + {{/isInteger}} + {{#isBoolean}} + valueForm_{{paramName}} = calloc(1,MAX_NUMBER_LENGTH); + snprintf(valueForm_{{paramName}}, MAX_NUMBER_LENGTH, "%d", *{{{paramName}}}); + {{/isBoolean}} + {{^isInteger}} + {{^isBoolean}} valueForm_{{paramName}} = {{#isString}}{{^isEnum}}strdup({{/isEnum}}{{/isString}}({{{paramName}}}){{#isString}}{{^isEnum}}){{/isEnum}}{{/isString}}; + {{/isBoolean}} + {{/isInteger}} keyPairForm_{{paramName}} = keyValuePair_create(keyForm_{{paramName}},{{#isString}}{{#isEnum}}(void *){{/isEnum}}{{/isString}}{{^isString}}&{{/isString}}valueForm_{{paramName}}); list_addElement(localVarFormParameters,keyPairForm_{{paramName}}); {{/isFile}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache index ecc80212afcf..223043ec1ed6 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api-header.mustache @@ -33,7 +33,7 @@ typedef enum { {{projectName}}_{{operationId}}_{{enumName}}_NULL = 0{{#enumVars // {{/notes}} {{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} -{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}} {{/allParams}}); +{{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}} {{/isNumber}}{{#isLong}}{{{dataType}}} {{/isLong}}{{#isInteger}}{{{dataType}}} *{{/isInteger}}{{#isDouble}}{{{dataType}}} {{/isDouble}}{{#isFloat}}{{{dataType}}} {{/isFloat}}{{#isBoolean}}{{dataType}} *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e {{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}} {{/isDate}}{{#isDateTime}}{{{dataType}}} {{/isDateTime}}{{#isFile}}{{{dataType}}} {{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}} {{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}} {{/isMap}}{{/isContainer}}{{{paramName}}}{{/allParams}}); {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/apiKey.c.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/apiKey.c.mustache index eae9b75f3b47..c65d91c8e9f9 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/apiKey.c.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/apiKey.c.mustache @@ -10,9 +10,9 @@ keyValuePair_t *keyValuePair_create(char *key, void *value) { } keyValuePair_t* keyValuePair_create_allocate(char* key, double value) { - double* boolpointer = malloc(sizeof(value)); - memcpy(boolpointer, &value, sizeof(value)); - return keyValuePair_create(key, boolpointer); + double* boolpointer = malloc(sizeof(value)); + memcpy(boolpointer, &value, sizeof(value)); + return keyValuePair_create(key, boolpointer); } void keyValuePair_free(keyValuePair_t *keyValuePair) { diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api_doc.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api_doc.mustache index 54dfa08df3cf..b8708d96d817 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api_doc.mustache @@ -20,7 +20,7 @@ Method | HTTP request | Description // {{{.}}} // {{/notes}} -{{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}}{{/isNumber}}{{#isLong}}{{{dataType}}}{{/isLong}}{{#isInteger}}{{{dataType}}}{{/isInteger}}{{#isDouble}}{{{dataType}}}{{/isDouble}}{{#isFloat}}{{{dataType}}}{{/isFloat}}{{#isBoolean}}{{dataType}}{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}}{{/isDate}}{{#isDateTime}}{{{dataType}}}{{/isDateTime}}{{#isFile}}{{{dataType}}}{{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e{{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}}{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}}{{/isMap}}{{/isContainer}} {{{paramName}}}{{/allParams}}); +{{#returnType}}{{#returnTypeIsPrimitive}}{{#returnSimpleType}}{{{.}}}*{{/returnSimpleType}}{{^returnSimpleType}}{{#isArray}}{{{.}}}_t*{{/isArray}}{{#isMap}}{{{.}}}{{/isMap}}{{/returnSimpleType}}{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}{{{.}}}_t*{{/returnTypeIsPrimitive}}{{/returnType}}{{^returnType}}void{{/returnType}} {{{classname}}}_{{{operationId}}}(apiClient_t *apiClient{{#allParams}}, {{#isPrimitiveType}}{{#isNumber}}{{{dataType}}} {{/isNumber}}{{#isLong}}{{{dataType}}} {{/isLong}}{{#isInteger}}{{{dataType}}} *{{/isInteger}}{{#isDouble}}{{{dataType}}} {{/isDouble}}{{#isFloat}}{{{dataType}}} {{/isFloat}}{{#isBoolean}}{{dataType}} *{{/isBoolean}}{{#isEnum}}{{#isString}}{{projectName}}_{{operationId}}_{{baseName}}_e {{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}{{{dataType}}} *{{/isString}}{{/isEnum}}{{#isByteArray}}{{{dataType}}} *{{/isByteArray}}{{#isDate}}{{{dataType}}} {{/isDate}}{{#isDateTime}}{{{dataType}}} {{/isDateTime}}{{#isFile}}{{{dataType}}} {{/isFile}}{{#isFreeFormObject}}{{dataType}}_t *{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{^isEnum}}{{{dataType}}}_t *{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}{{datatypeWithEnum}}_e {{/isEnum}}{{/isModel}}{{#isUuid}}{{dataType}} *{{/isUuid}}{{#isEmail}}{{dataType}} {{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}{{dataType}}_t *{{/isArray}}{{#isMap}}{{dataType}} {{/isMap}}{{/isContainer}}{{{paramName}}}{{/allParams}}); ``` ### Parameters @@ -28,7 +28,7 @@ Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **apiClient** | **apiClient_t \*** | context containing the client configuration | {{#allParams}} -**{{paramName}}** | {{#isPrimitiveType}}{{#isNumber}}**{{{dataType}}}**{{/isNumber}}{{#isLong}}**{{{dataType}}}**{{/isLong}}{{#isInteger}}**{{{dataType}}}**{{/isInteger}}{{#isDouble}}**{{{dataType}}}**{{/isDouble}}{{#isFloat}}**{{{dataType}}}**{{/isFloat}}{{#isBoolean}}**{{dataType}}**{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{operationId}}_{{baseName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{{dataType}}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{{dataType}}} \***{{/isByteArray}}{{#isDate}}**{{{dataType}}}**{{/isDate}}{{#isDateTime}}**{{{dataType}}}**{{/isDateTime}}{{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isFreeFormObject}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{^isEnum}}**[{{{dataType}}}_t]({{{baseType}}}.md) \***{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{/isModel}}{{#isUuid}}**{{dataType}} \***{{/isUuid}}{{#isEmail}}**{{dataType}}**{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isArray}}{{#isMap}}**{{dataType}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} +**{{paramName}}** | {{#isPrimitiveType}}{{#isNumber}}**{{{dataType}}}**{{/isNumber}}{{#isLong}}**{{{dataType}}}**{{/isLong}}{{#isInteger}}**{{{dataType}}} \***{{/isInteger}}{{#isDouble}}**{{{dataType}}}**{{/isDouble}}{{#isFloat}}**{{{dataType}}}**{{/isFloat}}{{#isBoolean}}**{{dataType}} \***{{/isBoolean}}{{#isEnum}}{{#isString}}**{{projectName}}_{{operationId}}_{{baseName}}_e**{{/isString}}{{/isEnum}}{{^isEnum}}{{#isString}}**{{{dataType}}} \***{{/isString}}{{/isEnum}}{{#isByteArray}}**{{{dataType}}} \***{{/isByteArray}}{{#isDate}}**{{{dataType}}}**{{/isDate}}{{#isDateTime}}**{{{dataType}}}**{{/isDateTime}}{{#isFile}}**{{{dataType}}}**{{/isFile}}{{#isFreeFormObject}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isFreeFormObject}}{{/isPrimitiveType}}{{^isArray}}{{^isPrimitiveType}}{{#isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{^isEnum}}**[{{{dataType}}}_t]({{{baseType}}}.md) \***{{/isEnum}}{{/isModel}}{{^isModel}}{{#isEnum}}**{{datatypeWithEnum}}_e**{{/isEnum}}{{/isModel}}{{#isUuid}}**{{dataType}} \***{{/isUuid}}{{#isEmail}}**{{dataType}}**{{/isEmail}}{{/isPrimitiveType}}{{/isArray}}{{#isContainer}}{{#isArray}}**[{{dataType}}_t]({{baseType}}.md) \***{{/isArray}}{{#isMap}}**{{dataType}}**{{/isMap}}{{/isContainer}} | {{description}} | {{^required}}[optional] {{/required}}{{#defaultValue}}[default to {{.}}]{{/defaultValue}} {{/allParams}} ### Return type diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/api_test.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/api_test.mustache index 156407a27524..59f165b2525d 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/api_test.mustache @@ -11,5 +11,5 @@ #include "keyValuePair.h" int main() { - printf("Hello world1\n"); + printf("Hello world1\n"); } diff --git a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache index 11dcb74c884c..98bbfd37998f 100644 --- a/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache +++ b/modules/openapi-generator/src/main/resources/C-libcurl/model-body.mustache @@ -77,12 +77,12 @@ end: {{^isContainer}} {{^isModel}} {{#isEnum}} -char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { +char* {{classname}}_{{name}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { char* {{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; - return {{name}}Array[{{name}}]; + return {{name}}Array[{{name}}]; } -{{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}){ +{{projectName}}_{{classVarName}}_{{enumName}}_e {{classname}}_{{name}}_FromString(char* {{name}}){ int stringToReturn = 0; char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); @@ -101,12 +101,12 @@ char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName {{#items}} {{^isModel}} {{#isEnum}} -char* {{name}}{{classname}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { - char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; - return {{name}}Array[{{name}} - 1]; +char* {{classname}}_{{name}}_ToString({{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}) { + char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; + return {{name}}Array[{{name}} - 1]; } -{{projectName}}_{{classVarName}}_{{enumName}}_e {{name}}{{classname}}_FromString(char* {{name}}) { +{{projectName}}_{{classVarName}}_{{enumName}}_e {{classname}}_{{name}}_FromString(char* {{name}}) { int stringToReturn = 0; char *{{name}}Array[] = { "NULL"{{#allowableValues}}{{#values}}, "{{.}}"{{/values}}{{/allowableValues}} }; size_t sizeofArray = sizeof({{name}}Array) / sizeof({{name}}Array[0]); @@ -629,7 +629,7 @@ fail: { goto end; //Enum } - {{name}}Variable = {{name}}{{classname}}_FromString({{{name}}}->valuestring); + {{name}}Variable = {{classname}}_{{name}}_FromString({{{name}}}->valuestring); {{/isString}} {{/isEnum}} {{^isEnum}} @@ -821,7 +821,7 @@ fail: } localMapKeyPair = keyValuePair_create(strdup(localMapObject->string),&localMapObject->valuedouble ); {{/isNumeric}} - {{/items}} + {{/items}} list_addElement({{{name}}}List , localMapKeyPair); } } diff --git a/modules/openapi-generator/src/main/resources/Eiffel/model.mustache b/modules/openapi-generator/src/main/resources/Eiffel/model.mustache index b1f66ca0cf3c..d6018c3f1b0e 100644 --- a/modules/openapi-generator/src/main/resources/Eiffel/model.mustache +++ b/modules/openapi-generator/src/main/resources/Eiffel/model.mustache @@ -24,14 +24,14 @@ feature --Access {{^isInherited}} {{#isPrimitiveType}} {{^isContainer}} - {{name}}: {{{dataType}}} - {{#description}}-- {{{.}}}{{/description}} - {{/isContainer}} + {{name}}: {{{dataType}}} + {{#description}}-- {{{.}}}{{/description}} + {{/isContainer}} {{/isPrimitiveType}} {{#isPrimitiveType}} {{#isContainer}} - {{name}}: detachable {{{datatypeWithEnum}}} - {{#description}}-- {{{.}}}{{/description}} + {{name}}: detachable {{{datatypeWithEnum}}} + {{#description}}-- {{{.}}}{{/description}} {{/isContainer}} {{/isPrimitiveType}} {{^isPrimitiveType}} @@ -45,7 +45,7 @@ feature --Access {{/isContainer}} {{/isPrimitiveType}} {{/isInherited}} - {{/vars}} +{{/vars}} feature -- Change Element diff --git a/modules/openapi-generator/src/main/resources/Java/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/ApiClient.mustache index ed5012fc5cfa..749c4eb2b7bf 100644 --- a/modules/openapi-generator/src/main/resources/Java/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/ApiClient.mustache @@ -533,7 +533,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) { + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } diff --git a/modules/openapi-generator/src/main/resources/Java/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/auth/HttpBearerAuth.mustache index 322281f8716a..6ed21107ddff 100644 --- a/modules/openapi-generator/src/main/resources/Java/auth/HttpBearerAuth.mustache +++ b/modules/openapi-generator/src/main/resources/Java/auth/HttpBearerAuth.mustache @@ -4,13 +4,15 @@ package {{invokerPackage}}.auth; import {{invokerPackage}}.Pair; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; {{>generatedAnnotation}} public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -22,7 +24,7 @@ public class HttpBearerAuth implements Authentication { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -31,12 +33,22 @@ public class HttpBearerAuth implements Authentication { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache index 7a78f616c777..90f6a60ffd8d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/apache-httpclient/ApiClient.mustache @@ -49,6 +49,7 @@ import java.util.List; import java.util.Arrays; import java.util.ArrayList; import java.util.Date; +import java.util.function.Supplier; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -60,6 +61,7 @@ import java.io.InputStream; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; @@ -335,6 +337,20 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { throw new RuntimeException("No Bearer authentication configured!"); } + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier the token supplier function + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } {{/hasHttpBearerMethods}} {{#hasHttpBasicMethods}} @@ -608,7 +624,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) { + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } @@ -770,7 +786,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { String mimeType = contentType.getMimeType(); if (isJsonMime(mimeType)) { try { - return new StringEntity(objectMapper.writeValueAsString(obj), contentType); + return new StringEntity(objectMapper.writeValueAsString(obj), contentType.withCharset(StandardCharsets.UTF_8)); } catch (JsonProcessingException e) { throw new ApiException(e); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/ApiClient.mustache index 4ae744398e3f..a2f52dbc5cca 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/ApiClient.mustache @@ -2,6 +2,7 @@ package {{invokerPackage}}; import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -265,6 +266,15 @@ public class ApiClient { apiAuthorization.setBearerToken(bearerToken); } + /** + * Helper method to configure the supplier of bearer tokens. + * @param tokenSupplier the supplier of bearer tokens. + */ + public void setBearerToken(Supplier tokenSupplier) { + HttpBearerAuth apiAuthorization = getAuthorization(HttpBearerAuth.class); + apiAuthorization.setBearerToken(tokenSupplier); + } + /** * Helper method to configure the first api key found * @param apiKey API key diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/HttpBearerAuth.mustache index 2240a5518b55..ae3427e0e87f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/HttpBearerAuth.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/auth/HttpBearerAuth.mustache @@ -2,13 +2,15 @@ package {{invokerPackage}}.auth; import feign.RequestInterceptor; import feign.RequestTemplate; +import java.util.Optional; +import java.util.function.Supplier; /** * An interceptor that adds the request header needed to use HTTP bearer authentication. */ public class HttpBearerAuth implements RequestInterceptor { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -16,21 +18,35 @@ public class HttpBearerAuth implements RequestInterceptor { /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void apply(RequestTemplate template) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pojo.mustache index 2d6aefc5c390..037cb1b11e62 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pojo.mustache @@ -320,7 +320,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} sb.append("}"); return sb.toString(); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache index 7565e94e41f5..45bdd56aeea9 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/feign/pom.mustache @@ -341,7 +341,7 @@ ch.qos.logback logback-classic - 1.2.12 + 1.3.13 test diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/anyof_model.mustache index 8239a303ffb8..b54b371a1223 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/anyof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/anyof_model.mustache @@ -24,7 +24,7 @@ import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} @JsonDeserialize(using={{classname}}.{{classname}}Deserializer.class) @JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/oneof_model.mustache index 50c1c60efc54..0232e2e60597 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/oneof_model.mustache @@ -26,7 +26,7 @@ import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} @JsonDeserialize(using = {{classname}}.{{classname}}Deserializer.class) @JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache index a1c0af84c602..a82e337d8d03 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey2/pojo.mustache @@ -328,7 +328,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} {{#additionalPropertiesType}} sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/anyof_model.mustache index 8239a303ffb8..b54b371a1223 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/anyof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/anyof_model.mustache @@ -24,7 +24,7 @@ import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} @JsonDeserialize(using={{classname}}.{{classname}}Deserializer.class) @JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/oneof_model.mustache index de29a873b638..043d75e97619 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/oneof_model.mustache @@ -26,7 +26,7 @@ import {{invokerPackage}}.JSON; {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{>xmlAnnotation}} @JsonDeserialize(using = {{classname}}.{{classname}}Deserializer.class) @JsonSerialize(using = {{classname}}.{{classname}}Serializer.class) -public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}}, {{{.}}}{{/vendorExtensions.x-implements}} { +public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-implements}} implements {{{.}}}{{^-last}}, {{/-last}}{{/vendorExtensions.x-implements}} { private static final Logger log = Logger.getLogger({{classname}}.class.getName()); public static class {{classname}}Serializer extends StdSerializer<{{classname}}> { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/pojo.mustache index 16643616ce0a..5446eeba9a0c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/jersey3/pojo.mustache @@ -80,13 +80,22 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/vendorExtensions.x-field-extra-annotation}} {{#vendorExtensions.x-is-jackson-optional-nullable}} {{#isContainer}} + {{#deprecated}} + @Deprecated + {{/deprecated}} private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); {{/isContainer}} {{^isContainer}} + {{#deprecated}} + @Deprecated + {{/deprecated}} private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; {{/isContainer}} {{/vendorExtensions.x-is-jackson-optional-nullable}} {{^vendorExtensions.x-is-jackson-optional-nullable}} + {{#deprecated}} + @Deprecated + {{/deprecated}} private {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; {{/vendorExtensions.x-is-jackson-optional-nullable}} @@ -116,6 +125,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens )); {{/vendorExtensions.x-enum-as-string}} + {{#deprecated}} + @Deprecated + {{/deprecated}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { {{#vendorExtensions.x-enum-as-string}} if (!{{{nameInSnakeCase}}}_VALUES.contains({{name}})) { @@ -256,6 +268,9 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/vendorExtensions.x-is-jackson-optional-nullable}} {{^isReadOnly}} + {{#deprecated}} + @Deprecated + {{/deprecated}} {{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} {{/vendorExtensions.x-setter-extra-annotation}}{{#jackson}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{> jackson_annotations}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{/jackson}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { {{#vendorExtensions.x-enum-as-string}} @@ -328,7 +343,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} {{#additionalPropertiesType}} sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/api.mustache index 22f38b750abf..91eab8c6e0be 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/api.mustache @@ -69,7 +69,50 @@ public interface {{classname}} { {{#hasProduces}} @Produces({ {{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}} }) {{/hasProduces}} +{{^useSingleRequestParameter}} {{^vendorExtensions.x-java-is-response-void}}{{#microprofileMutiny}}Uni<{{{returnType}}}>{{/microprofileMutiny}}{{^microprofileMutiny}}{{{returnType}}}{{/microprofileMutiny}}{{/vendorExtensions.x-java-is-response-void}}{{#vendorExtensions.x-java-is-response-void}}{{#microprofileMutiny}}Uni{{/microprofileMutiny}}{{^microprofileMutiny}}void{{/microprofileMutiny}}{{/vendorExtensions.x-java-is-response-void}} {{nickname}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}}, {{/-last}}{{/allParams}}) throws ApiException, ProcessingException; +{{/useSingleRequestParameter}} +{{#useSingleRequestParameter}} + {{^vendorExtensions.x-java-is-response-void}}{{#microprofileMutiny}}Uni<{{{returnType}}}>{{/microprofileMutiny}}{{^microprofileMutiny}}{{{returnType}}}{{/microprofileMutiny}}{{/vendorExtensions.x-java-is-response-void}}{{#vendorExtensions.x-java-is-response-void}}{{#microprofileMutiny}}Uni{{/microprofileMutiny}}{{^microprofileMutiny}}void{{/microprofileMutiny}}{{/vendorExtensions.x-java-is-response-void}} {{nickname}}({{#hasNonBodyParams}}@BeanParam {{operationIdCamelCase}}Request request{{/hasNonBodyParams}}{{#bodyParams}}{{#hasNonBodyParams}}, {{/hasNonBodyParams}}{{>bodyParams}}{{/bodyParams}}) throws ApiException, ProcessingException; + {{#hasNonBodyParams}} + public class {{operationIdCamelCase}}Request { + + {{#queryParams}} + private {{>queryParams}}; + {{/queryParams}} + {{#headerParams}} + private {{>headerParams}}; + {{/headerParams}} + {{#pathParams}} + private {{>pathParams}}; + {{/pathParams}} + {{#formParams}} + private {{>formParams}}; + {{/formParams}} + + private {{operationIdCamelCase}}Request() { + } + + public static {{operationIdCamelCase}}Request newInstance() { + return new {{operationIdCamelCase}}Request(); + } + + {{#allParams}} + {{^isBodyParam}} + /** + * Set {{paramName}}{{>formParamsNameSuffix}} + * @param {{paramName}}{{>formParamsNameSuffix}} {{description}} ({{^required}}optional{{^isContainer}}{{#defaultValue}}, default to {{.}}{{/defaultValue}}{{/isContainer}}{{/required}}{{#required}}required{{/required}}) + * @return {{operationIdCamelCase}}Request + */ + public {{operationIdCamelCase}}Request {{paramName}}{{>formParamsNameSuffix}}({{>queryParamsImpl}}{{>pathParamsImpl}}{{>headerParamsImpl}}{{>formParamsImpl}}) { + this.{{paramName}}{{>formParamsNameSuffix}} = {{paramName}}{{>formParamsNameSuffix}}; + return this; + } + {{/isBodyParam}} + {{/allParams}} + } + {{/hasNonBodyParams}} +{{/useSingleRequestParameter}} {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumClass.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumClass.mustache index c396cd8af925..cb8539bd10e8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumClass.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumClass.mustache @@ -15,7 +15,7 @@ {{#enumVars}}@XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) {{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/withXml}} {{^withXml}} - {{#enumVars}}{{name}}({{dataType}}.valueOf({{{value}}})){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} + {{#enumVars}}{{name}}({{^isUri}}{{dataType}}.valueOf({{/isUri}}{{{value}}}{{^isUri}}){{/isUri}}){{^-last}}, {{/-last}}{{#-last}};{{/-last}}{{/enumVars}} {{/withXml}} {{/allowableValues}} @@ -65,7 +65,7 @@ public static final class Serializer implements JsonbSerializer<{{datatypeWithEnum}}> { @Override public void serialize({{datatypeWithEnum}} obj, JsonGenerator generator, SerializationContext ctx) { - generator.write(obj.value); + generator.write(obj.value{{#isUri}}.toASCIIString(){{/isUri}}); } } {{/jsonb}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumOuterClass.mustache index 894ce951f389..0d9f7886f8dd 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumOuterClass.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/enumOuterClass.mustache @@ -2,6 +2,9 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; {{/jackson}} +{{#isUri}} +import java.net.URI; +{{/isUri}} /** * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/formParamsNameSuffix.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/formParamsNameSuffix.mustache new file mode 100644 index 000000000000..a44f6d7100bf --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/formParamsNameSuffix.mustache @@ -0,0 +1 @@ +{{#isFormParam}}{{#isFile}}Detail{{/isFile}}{{/isFormParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache index 65da41f74208..aca66a726e83 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pojo.mustache @@ -155,7 +155,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom.mustache index 744d532daf13..21e9df81f6ff 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom.mustache @@ -213,7 +213,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 {{#useBeanValidation}} 2.0.2 {{/useBeanValidation}} @@ -243,4 +243,4 @@ 1.2.0 {{/microprofileMutiny}}
            - \ No newline at end of file + diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom_3.0.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom_3.0.mustache index 02f06b18d621..038b0e28a239 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom_3.0.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/microprofile/pom_3.0.mustache @@ -206,7 +206,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 {{#useBeanValidation}} 3.0.1 {{/useBeanValidation}} @@ -233,4 +233,4 @@ 1.9.1 UTF-8
            - \ No newline at end of file + diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/JSON.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/JSON.mustache index a13bf2fdf3ec..19eea0bcf4c4 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/JSON.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/JSON.mustache @@ -2,6 +2,7 @@ package {{invokerPackage}}; import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} @@ -24,16 +25,17 @@ public class JSON { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .build(); {{#joda}} mapper.registerModule(new JodaModule()); {{/joda}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/anyof_model.mustache index 2097e183dde3..92122997e28d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/anyof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/anyof_model.mustache @@ -231,6 +231,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im StringJoiner joiner = new StringJoiner("&"); {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} if (getActualInstance() instanceof {{{dataType}}}) { {{#isArray}} {{#items.isPrimitiveType}} @@ -352,6 +353,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isArray}} return joiner.toString(); } + {{/vendorExtensions.x-duplicated-data-type}} {{/composedSchemas.oneOf}} return null; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/modelEnum.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/modelEnum.mustache index b4cd2f4109f1..58e25ebe1eee 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/modelEnum.mustache @@ -9,6 +9,9 @@ import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; {{/gson}} +{{#isUri}} +import java.net.URI; +{{/isUri}} /** * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/oneof_model.mustache index 8000994f0e57..9449f9d42c83 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/oneof_model.mustache @@ -264,6 +264,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im StringJoiner joiner = new StringJoiner("&"); {{#composedSchemas.oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} if (getActualInstance() instanceof {{{dataType}}}) { {{#isArray}} {{#items.isPrimitiveType}} @@ -385,6 +386,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isArray}} return joiner.toString(); } + {{/vendorExtensions.x-duplicated-data-type}} {{/composedSchemas.oneOf}} return null; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache index a0c77d53c156..d965736903e4 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/native/pojo.mustache @@ -345,7 +345,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} {{#additionalPropertiesType}} sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/AbstractOpenApiSchema.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/AbstractOpenApiSchema.mustache index e0bcb881ef07..8d11435bef4e 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/AbstractOpenApiSchema.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/AbstractOpenApiSchema.mustache @@ -7,8 +7,6 @@ import java.util.Objects; import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache index d0ee6b629ccb..b031a2404941 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/ApiClient.mustache @@ -53,6 +53,7 @@ import java.time.format.DateTimeFormatter; import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -528,14 +529,23 @@ public class ApiClient { } {{#hasHttpBearerMethods}} - /** - * Helper method to set access token for the first Bearer authentication. - * @param bearerToken Bearer token - */ + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBearerAuth) { - ((HttpBearerAuth) auth).setBearerToken(bearerToken); + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); return; } } @@ -919,7 +929,7 @@ public class ApiClient { List params = new ArrayList(); // preconditions - if (param == null || param.getName() == null || param.getName().isEmpty() || value == null) { + if (param == null || param.getName() == null || param.getName().isEmpty() || value == null || value.isEmpty()) { return params; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache index fbf4807c73e3..1569eed43e43 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/anyof_model.mustache @@ -48,7 +48,9 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#anyOf}} {{^isArray}} + {{^vendorExtensions.x-duplicated-data-type}} final TypeAdapter<{{{dataType}}}> adapter{{{dataType}}} = gson.getDelegateAdapter(this, TypeToken.get({{{dataType}}}.class)); + {{/vendorExtensions.x-duplicated-data-type}} {{/isArray}} {{#isArray}} @@ -68,6 +70,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} // check if the actual instance is of the type `{{{dataType}}}` if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { {{#isPrimitiveType}} @@ -91,6 +94,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isPrimitiveType}} {{/isArray}} } + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} throw new IOException("Failed to serialize as the type doesn't match anyOf schemae: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); @@ -106,6 +110,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} {{^hasVars}} // deserialize {{{dataType}}} try { @@ -184,6 +189,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e); } {{/hasVars}} + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} @@ -210,7 +216,9 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im static { {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} schemas.put("{{{dataType}}}", {{{baseType}}}.class); + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} } @@ -238,6 +246,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isNullable}} {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} if (instance instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { {{#isArray}} List list = (List) instance; @@ -252,6 +261,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isArray}} } + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} throw new RuntimeException("Invalid instance type. Must be {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}"); @@ -270,6 +280,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} /** * Get the actual instance of `{{{dataType}}}`. If the actual instance is not `{{{dataType}}}`, * the ClassCastException will be thrown. @@ -280,6 +291,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im public {{{dataType}}} get{{#isArray}}{{complexType}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException { return ({{{dataType}}})super.getActualInstance(); } + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} @@ -294,6 +306,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im ArrayList errorMessages = new ArrayList<>(); {{#composedSchemas}} {{#anyOf}} + {{^vendorExtensions.x-duplicated-data-type}} // validate the json string with {{{dataType}}} try { {{^hasVars}} @@ -350,6 +363,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); // continue to the next one } + {{/vendorExtensions.x-duplicated-data-type}} {{/anyOf}} {{/composedSchemas}} throw new IOException(String.format("The JSON string is invalid for {{classname}} with anyOf schemas: {{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache index b52a1cbd5cb0..fe08469b577e 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/api.mustache @@ -27,6 +27,7 @@ import java.io.IOException; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{#performBeanValidation}} import {{javaxPackage}}.validation.ConstraintViolation; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBearerAuth.mustache index c8a9fce29650..abe1cb8b878f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBearerAuth.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/auth/HttpBearerAuth.mustache @@ -6,13 +6,15 @@ import {{invokerPackage}}.ApiException; import {{invokerPackage}}.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; {{>generatedAnnotation}} public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -24,7 +26,7 @@ public class HttpBearerAuth implements Authentication { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -33,12 +35,22 @@ public class HttpBearerAuth implements Authentication { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache index 0d0e4cc9481f..85dfdb3c85a2 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.gradle.mustache @@ -115,7 +115,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' {{#openApiNullable}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache index 8d7bd5a68fe8..5dfe99f2b9d8 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/build.sbt.mustache @@ -31,7 +31,7 @@ lazy val root = (project in file(".")). {{#dynamicOperations}} "io.swagger.parser.v3" % "swagger-parser-v3" "2.0.30" % "compile" {{/dynamicOperations}} - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/model.mustache index 74e462b08e21..3a1cca8d7d4f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/model.mustache @@ -13,34 +13,9 @@ import {{import}}; {{#serializableModel}} import java.io.Serializable; {{/serializableModel}} -{{#jackson}} -import com.fasterxml.jackson.annotation.JsonPropertyOrder; -import com.fasterxml.jackson.annotation.JsonTypeName; -{{#withXml}} -import com.fasterxml.jackson.dataformat.xml.annotation.*; -{{/withXml}} -{{#vendorExtensions.x-has-readonly-properties}} -import com.fasterxml.jackson.annotation.JsonCreator; -{{/vendorExtensions.x-has-readonly-properties}} -{{/jackson}} {{#withXml}} import {{javaxPackage}}.xml.bind.annotation.*; {{/withXml}} -{{#jsonb}} -import java.lang.reflect.Type; -import {{javaxPackage}}.json.bind.annotation.JsonbTypeDeserializer; -import {{javaxPackage}}.json.bind.annotation.JsonbTypeSerializer; -import {{javaxPackage}}.json.bind.serializer.DeserializationContext; -import {{javaxPackage}}.json.bind.serializer.JsonbDeserializer; -import {{javaxPackage}}.json.bind.serializer.JsonbSerializer; -import {{javaxPackage}}.json.bind.serializer.SerializationContext; -import {{javaxPackage}}.json.stream.JsonGenerator; -import {{javaxPackage}}.json.stream.JsonParser; -import {{javaxPackage}}.json.bind.annotation.JsonbProperty; -{{#vendorExtensions.x-has-readonly-properties}} -import {{javaxPackage}}.json.bind.annotation.JsonbCreator; -{{/vendorExtensions.x-has-readonly-properties}} -{{/jsonb}} {{#parcelableModel}} import android.os.Parcelable; import android.os.Parcel; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache new file mode 100644 index 000000000000..b955e53f1b7d --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelEnum.mustache @@ -0,0 +1,85 @@ +import java.io.IOException; +{{#isUri}} +import java.net.URI; +{{/isUri}} +import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; + +/** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ +@JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.Adapter.class) +{{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} { + {{#allowableValues}}{{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}}{{/enumVars}}{{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.{{^isString}}equals{{/isString}}{{#isString}}{{#useEnumCaseInsensitive}}equalsIgnoreCase{{/useEnumCaseInsensitive}}{{^useEnumCaseInsensitive}}equals{{/useEnumCaseInsensitive}}{{/isString}}(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } + + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}}{{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isUri}}URI.create({{/isUri}}jsonElement.{{#isNumber}}getAsString(){{/isNumber}}{{#isInteger}}getAsInt(){{/isInteger}}{{#isUri}}getAsString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}getAs{{{dataType}}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } +{{#supportUrlQuery}} + + /** + * Convert the instance into URL query string. + * + * @param prefix prefix of the query string + * @return URL query string + */ + public String toUrlQueryString(String prefix) { + if (prefix == null) { + prefix = ""; + } + + return String.format("%s=%s", prefix, this.toString()); + } +{{/supportUrlQuery}} +} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache new file mode 100644 index 000000000000..06912e9b1ef7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/modelInnerEnum.mustache @@ -0,0 +1,66 @@ + /** + * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} + */ + @JsonAdapter({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.Adapter.class) +{{#withXml}} + @XmlType(name="{{datatypeWithEnum}}") + @XmlEnum({{dataType}}.class) +{{/withXml}} + {{>additionalEnumTypeAnnotations}}public enum {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} { + {{#allowableValues}} + {{#enumVars}} + {{#enumDescription}} + /** + * {{.}} + */ + {{/enumDescription}} + {{#withXml}} + @XmlEnumValue({{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}{{{value}}}{{#isInteger}}"{{/isInteger}}{{#isDouble}}"{{/isDouble}}{{#isLong}}"{{/isLong}}{{#isFloat}}"{{/isFloat}}) + {{/withXml}} + {{{name}}}({{{value}}}){{^-last}}, + {{/-last}}{{#-last}};{{/-last}} + {{/enumVars}} + {{/allowableValues}} + + private {{{dataType}}} value; + + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}({{{dataType}}} value) { + this.value = value; + } + + public {{{dataType}}} getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromValue({{{dataType}}} value) { + for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { + if (b.value.{{^isString}}equals{{/isString}}{{#isString}}{{#useEnumCaseInsensitive}}equalsIgnoreCase{{/useEnumCaseInsensitive}}{{^useEnumCaseInsensitive}}equals{{/useEnumCaseInsensitive}}{{/isString}}(value)) { + return b; + } + } + {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}{{#enumUnknownDefaultCase}}{{#allowableValues}}{{#enumVars}}{{#-last}}return {{{name}}};{{/-last}}{{/enumVars}}{{/allowableValues}}{{/enumUnknownDefaultCase}}{{^enumUnknownDefaultCase}}throw new IllegalArgumentException("Unexpected value '" + value + "'");{{/enumUnknownDefaultCase}}{{/isNullable}} + } + + public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> { + @Override + public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) throws IOException { + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}); + } + + @Override + public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} {{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isUri}}URI.create({{/isUri}}jsonElement.{{#isNumber}}getAsString(){{/isNumber}}{{#isInteger}}getAsInt(){{/isInteger}}{{#isUri}}getAsString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}getAs{{{dataType}}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + } + } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache index c89bbac73a0a..b2ab54955d44 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/oneof_model.mustache @@ -48,7 +48,9 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} {{^isArray}} + {{^vendorExtensions.x-duplicated-data-type}} final TypeAdapter<{{{dataType}}}> adapter{{{dataType}}} = gson.getDelegateAdapter(this, TypeToken.get({{{dataType}}}.class)); + {{/vendorExtensions.x-duplicated-data-type}} {{/isArray}} {{#isArray}} @@ -68,6 +70,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} // check if the actual instance is of the type `{{{dataType}}}` if (value.getActualInstance() instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { {{#isPrimitiveType}} @@ -91,6 +94,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isPrimitiveType}} {{/isArray}} } + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); @@ -131,6 +135,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} {{^hasVars}} // deserialize {{{dataType}}} try { @@ -206,6 +211,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im log.log(Level.FINER, "Input data does not match schema '{{{.}}}'", e); } {{/hasVars}} + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} @@ -238,7 +244,9 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im static { {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} schemas.put("{{{dataType}}}", {{{baseType}}}.class); + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} } @@ -266,6 +274,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isNullable}} {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} if (instance instanceof {{#isArray}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}) { {{#isArray}} List list = (List) instance; @@ -280,6 +289,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{/isArray}} } + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} throw new RuntimeException("Invalid instance type. Must be {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}"); @@ -298,6 +308,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} /** * Get the actual instance of `{{{dataType}}}`. If the actual instance is not `{{{dataType}}}`, * the ClassCastException will be thrown. @@ -308,6 +319,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im public {{{dataType}}} get{{#isArray}}{{complexType}}List{{/isArray}}{{^isArray}}{{{dataType}}}{{/isArray}}() throws ClassCastException { return ({{{dataType}}})super.getActualInstance(); } + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} @@ -323,6 +335,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im ArrayList errorMessages = new ArrayList<>(); {{#composedSchemas}} {{#oneOf}} + {{^vendorExtensions.x-duplicated-data-type}} // validate the json string with {{{dataType}}} try { {{^hasVars}} @@ -379,6 +392,7 @@ public class {{classname}} extends AbstractOpenApiSchema{{#vendorExtensions.x-im errorMessages.add(String.format("Deserialization for {{{dataType}}} failed with `%s`.", e.getMessage())); // continue to the next one } + {{/vendorExtensions.x-duplicated-data-type}} {{/oneOf}} {{/composedSchemas}} if (validCount != 1) { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache index 38fda7ebc64f..fb3d0bce82fa 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pojo.mustache @@ -37,16 +37,6 @@ import {{invokerPackage}}.JSON; @Schema(description = "{{{.}}}") {{/description}} {{/swagger2AnnotationLibrary}} -{{#jackson}} -@JsonPropertyOrder({ -{{#vars}} - {{classname}}.JSON_PROPERTY_{{nameInSnakeCase}}{{^-last}},{{/-last}} -{{/vars}} -}) -{{#isClassnameSanitized}} -@JsonTypeName("{{name}}") -{{/isClassnameSanitized}} -{{/jackson}} {{>additionalModelTypeAnnotations}}{{>generatedAnnotation}}{{#discriminator}}{{>typeInfoAnnotation}}{{/discriminator}}{{>xmlAnnotation}} {{#vendorExtensions.x-class-extra-annotation}} {{{vendorExtensions.x-class-extra-annotation}}} @@ -67,12 +57,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/mostInnerItems}} {{/isContainer}} {{/isEnum}} - {{#gson}} public static final String SERIALIZED_NAME_{{nameInSnakeCase}} = "{{baseName}}"; - {{/gson}} - {{#jackson}} - public static final String JSON_PROPERTY_{{nameInSnakeCase}} = "{{baseName}}"; - {{/jackson}} {{#withXml}} {{#isXmlAttribute}} @XmlAttribute(name = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") @@ -94,26 +79,14 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{/isContainer}} {{/isXmlAttribute}} {{/withXml}} - {{#gson}} {{#deprecated}} @Deprecated {{/deprecated}} @SerializedName(SERIALIZED_NAME_{{nameInSnakeCase}}) - {{/gson}} {{#vendorExtensions.x-field-extra-annotation}} {{{vendorExtensions.x-field-extra-annotation}}} {{/vendorExtensions.x-field-extra-annotation}} - {{#vendorExtensions.x-is-jackson-optional-nullable}} - {{#isContainer}} - private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(); - {{/isContainer}} - {{^isContainer}} - private JsonNullable<{{{datatypeWithEnum}}}> {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; - {{/isContainer}} - {{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}} {{#isDiscriminator}}protected{{/isDiscriminator}}{{^isDiscriminator}}private{{/isDiscriminator}} {{{datatypeWithEnum}}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; - {{/vendorExtensions.x-is-jackson-optional-nullable}} {{/vars}} public {{classname}}() { @@ -122,21 +95,18 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens super(); {{/parcelableModel}} {{/parent}} - {{#gson}} {{#discriminator}} {{^discriminator.isEnum}} this.{{{discriminatorName}}} = this.getClass().getSimpleName(); {{/discriminator.isEnum}} {{/discriminator}} - {{/gson}} } {{#vendorExtensions.x-has-readonly-properties}} {{^withXml}} - {{#jsonb}}@JsonbCreator{{/jsonb}}{{#jackson}}@JsonCreator{{/jackson}} public {{classname}}( {{#readOnlyVars}} - {{#jsonb}}@JsonbProperty("{{baseName}}"){{/jsonb}}{{#jackson}}@JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}){{/jackson}} {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} + {{{datatypeWithEnum}}} {{name}}{{^-last}}, {{/-last}} {{/readOnlyVars}} ) { this(); @@ -153,54 +123,27 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens @Deprecated {{/deprecated}} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { - {{#vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}});{{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}}this.{{name}} = {{name}};{{/vendorExtensions.x-is-jackson-optional-nullable}} + this.{{name}} = {{name}}; return this; } {{#isArray}} public {{classname}} add{{nameInCamelCase}}Item({{{items.datatypeWithEnum}}} {{name}}Item) { - {{#vendorExtensions.x-is-jackson-optional-nullable}} - if (this.{{name}} == null || !this.{{name}}.isPresent()) { - this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}); - } - try { - this.{{name}}.get().add({{name}}Item); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - {{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}} if (this.{{name}} == null) { this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new {{#uniqueItems}}LinkedHashSet{{/uniqueItems}}{{^uniqueItems}}ArrayList{{/uniqueItems}}<>(){{/defaultValue}}; } this.{{name}}.add({{name}}Item); return this; - {{/vendorExtensions.x-is-jackson-optional-nullable}} } {{/isArray}} {{#isMap}} public {{classname}} put{{nameInCamelCase}}Item(String key, {{{items.datatypeWithEnum}}} {{name}}Item) { - {{#vendorExtensions.x-is-jackson-optional-nullable}} - if (this.{{name}} == null || !this.{{name}}.isPresent()) { - this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}); - } - try { - this.{{name}}.get().put(key, {{name}}Item); - } catch (java.util.NoSuchElementException e) { - // this can never happen, as we make sure above that the value is present - } - return this; - {{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}} if (this.{{name}} == null) { this.{{name}} = {{{defaultValue}}}{{^defaultValue}}new HashMap<>(){{/defaultValue}}; } this.{{name}}.put(key, {{name}}Item); return this; - {{/vendorExtensions.x-is-jackson-optional-nullable}} } {{/isMap}} @@ -237,9 +180,6 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{^required}} @{{javaxPackage}}.annotation.Nullable {{/required}} -{{#jsonb}} - @JsonbProperty("{{baseName}}") -{{/jsonb}} {{#useBeanValidation}} {{>beanValidation}} {{/useBeanValidation}} @@ -252,47 +192,15 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens {{#vendorExtensions.x-extra-annotation}} {{{vendorExtensions.x-extra-annotation}}} {{/vendorExtensions.x-extra-annotation}} -{{#vendorExtensions.x-is-jackson-optional-nullable}} - {{!unannotated, Jackson would pick this up automatically and add it *in addition* to the _JsonNullable getter field}} - @JsonIgnore -{{/vendorExtensions.x-is-jackson-optional-nullable}} -{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#jackson}}{{> jackson_annotations}}{{/jackson}}{{/vendorExtensions.x-is-jackson-optional-nullable}} public {{{datatypeWithEnum}}} {{getter}}() { - {{#vendorExtensions.x-is-jackson-optional-nullable}} - {{#isReadOnly}}{{! A readonly attribute doesn't have setter => jackson will set null directly if explicitly returned by API, so make sure we have an empty JsonNullable}} - if ({{name}} == null) { - {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>{{#defaultValue}}of({{{.}}}){{/defaultValue}}{{^defaultValue}}undefined(){{/defaultValue}}; - } - {{/isReadOnly}} - return {{name}}.orElse(null); - {{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}} - return {{name}}; - {{/vendorExtensions.x-is-jackson-optional-nullable}} - } - - {{#vendorExtensions.x-is-jackson-optional-nullable}} -{{> jackson_annotations}} - public JsonNullable<{{{datatypeWithEnum}}}> {{getter}}_JsonNullable() { + public {{{datatypeWithEnum}}} {{getter}}() { return {{name}}; } - {{/vendorExtensions.x-is-jackson-optional-nullable}}{{#vendorExtensions.x-is-jackson-optional-nullable}} - @JsonProperty(JSON_PROPERTY_{{nameInSnakeCase}}) - {{#isReadOnly}}private{{/isReadOnly}}{{^isReadOnly}}public{{/isReadOnly}} void {{setter}}_JsonNullable(JsonNullable<{{{datatypeWithEnum}}}> {{name}}) { - {{! For getters/setters that have name differing from attribute name, we must include setter (albeit private) for jackson to be able to set the attribute}} - this.{{name}} = {{name}}; - } - {{/vendorExtensions.x-is-jackson-optional-nullable}} {{^isReadOnly}} {{#vendorExtensions.x-setter-extra-annotation}} {{{vendorExtensions.x-setter-extra-annotation}}} -{{/vendorExtensions.x-setter-extra-annotation}}{{#jackson}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{> jackson_annotations}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{/jackson}}{{#deprecated}} @Deprecated +{{/vendorExtensions.x-setter-extra-annotation}}{{#deprecated}} @Deprecated {{/deprecated}} public void {{setter}}({{{datatypeWithEnum}}} {{name}}) { - {{#vendorExtensions.x-is-jackson-optional-nullable}} - this.{{name}} = JsonNullable.<{{{datatypeWithEnum}}}>of({{name}}); - {{/vendorExtensions.x-is-jackson-optional-nullable}} - {{^vendorExtensions.x-is-jackson-optional-nullable}} this.{{name}} = {{name}}; - {{/vendorExtensions.x-is-jackson-optional-nullable}} } {{/isReadOnly}} @@ -312,7 +220,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens return false; }{{#hasVars}} {{classname}} {{classVarName}} = ({{classname}}) o; - return {{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}equalsNullable(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}} && + return {{#vars}}{{#isByteArray}}Arrays{{/isByteArray}}{{^isByteArray}}Objects{{/isByteArray}}.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{/vars}}{{#isAdditionalPropertiesTrue}}&& Objects.equals(this.additionalProperties, {{classVarName}}.additionalProperties){{/isAdditionalPropertiesTrue}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} @@ -330,7 +238,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens return HashCodeBuilder.reflectionHashCode(this); {{/useReflectionEqualsHashCode}} {{^useReflectionEqualsHashCode}} - return Objects.hash({{#vars}}{{#vendorExtensions.x-is-jackson-optional-nullable}}hashCodeNullable({{name}}){{/vendorExtensions.x-is-jackson-optional-nullable}}{{^vendorExtensions.x-is-jackson-optional-nullable}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{/vendorExtensions.x-is-jackson-optional-nullable}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#isAdditionalPropertiesTrue}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/isAdditionalPropertiesTrue}}); + return Objects.hash({{#vars}}{{^isByteArray}}{{name}}{{/isByteArray}}{{#isByteArray}}Arrays.hashCode({{name}}){{/isByteArray}}{{^-last}}, {{/-last}}{{/vars}}{{#parent}}{{#hasVars}}, {{/hasVars}}super.hashCode(){{/parent}}{{#isAdditionalPropertiesTrue}}{{#hasVars}}, {{/hasVars}}{{^hasVars}}{{#parent}}, {{/parent}}{{/hasVars}}additionalProperties{{/isAdditionalPropertiesTrue}}); {{/useReflectionEqualsHashCode}} }{{#vendorExtensions.x-jackson-optional-nullable-helpers}} @@ -349,7 +257,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} {{#isAdditionalPropertiesTrue}} sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); @@ -362,7 +270,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ - private{{#jsonb}} static{{/jsonb}} String toIndentedString(Object o) { + private String toIndentedString(Object o) { if (o == null) { return "null"; } @@ -552,6 +460,30 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens } {{/required}} {{/isModel}} + {{#isEnum}} + {{#required}} + // validate the required field `{{{baseName}}}` + {{{datatypeWithEnum}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + {{/required}} + {{^required}} + // validate the optional field `{{{baseName}}}` + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{{datatypeWithEnum}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + } + {{/required}} + {{/isEnum}} + {{#isEnumRef}} + {{#required}} + // validate the required field `{{{baseName}}}` + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + {{/required}} + {{^required}} + // validate the optional field `{{{baseName}}}` + if (jsonObj.get("{{{baseName}}}") != null && !jsonObj.get("{{{baseName}}}").isJsonNull()) { + {{{dataType}}}.validateJsonElement(jsonObj.get("{{{baseName}}}")); + } + {{/required}} + {{/isEnumRef}} {{/isContainer}} {{/vars}} {{/discriminator}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache index 7b4c580c074e..060937260542 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/okhttp-gson/pom.mustache @@ -410,7 +410,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 {{#swagger1AnnotationLibrary}} 1.6.6 {{/swagger1AnnotationLibrary}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/api.mustache index 0642414d608d..7e04598d681d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/api.mustache @@ -32,6 +32,11 @@ import io.swagger.v3.oas.annotations.responses.*; import io.swagger.v3.oas.annotations.security.*; {{/swagger2AnnotationLibrary}} +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache index d84749275bb9..f81e4632b648 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.gradle.mustache @@ -97,8 +97,13 @@ if(hasProperty('target') && target == 'android') { } ext { + {{#swagger1AnnotationLibrary}} swagger_annotations_version = "1.6.6" - rest_assured_version = "4.5.1" + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + swagger_annotations_version = "2.2.15" + {{/swagger2AnnotationLibrary}} + rest_assured_version = "5.3.2" junit_version = "4.13.2" {{#jackson}} jackson_version = "2.13.4" @@ -109,17 +114,22 @@ ext { jakarta_annotation_version = "1.3.5" {{/jackson}} {{#gson}} - gson_version = "2.8.9" - gson_fire_version = "1.8.5" + gson_version = "2.10.1" + gson_fire_version = "1.9.0" {{/gson}} {{#joda}} jodatime_version = "2.10.5" {{/joda}} - okio_version = "1.17.5" + okio_version = "3.6.0" } dependencies { + {{#swagger1AnnotationLibrary}} implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + {{/swagger1AnnotationLibrary}} + {{#swagger2AnnotationLibrary}} + implementation "io.swagger.core.v3:swagger-annotations:$swagger_annotations_version" + {{/swagger2AnnotationLibrary}} implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "io.rest-assured:rest-assured:$rest_assured_version" {{#jackson}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache index 0958cbc1480b..1b9aa139dfc9 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/build.sbt.mustache @@ -30,7 +30,7 @@ lazy val root = (project in file(".")). {{/jackson}} {{#gson}} "com.google.code.gson" % "gson" % "2.8.9", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", {{/gson}} {{#joda}} "joda-time" % "joda-time" % "2.10.5" % "compile", diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache index 54c7b6cbd1b6..4d96d46027cf 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/rest-assured/pom.mustache @@ -345,9 +345,9 @@ {{#swagger2AnnotationLibrary}} 2.2.15 {{/swagger2AnnotationLibrary}} - 4.5.1 + 5.3.2 2.10.1 - 1.8.5 + 1.9.0 {{#joda}} 2.10.5 {{/joda}} @@ -365,7 +365,7 @@ {{#useBeanValidation}} 2.0.2 {{/useBeanValidation}} - 1.17.5 + 3.6.0 4.13.2 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache index 07c079e89229..725e01185296 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resteasy/ApiClient.mustache @@ -498,7 +498,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { if (param.getValue() instanceof File) { File file = (File) param.getValue(); try { - multipart.addFormData(param.getKey(),new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM_TYPE); + multipart.addFormData(param.getKey(),new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM_TYPE, file.getName()); } catch (FileNotFoundException e) { throw new ApiException("Could not serialize multipart/form-data "+e.getMessage()); } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache index 261ace14f6f0..fe355ec358fb 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/ApiClient.mustache @@ -31,6 +31,8 @@ import org.springframework.util.CollectionUtils; import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -105,6 +107,10 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = {{maxAttemptsForRetry}}; + + private long waitTimeMillis = {{waitTimeMillis}}; + private String basePath = "{{basePath}}"; private RestTemplate restTemplate; @@ -167,6 +173,46 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -188,18 +234,18 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { {{#hasHttpBearerMethods}} /** - * Helper method to set token for HTTP bearer authentication. + * Helper method to set access token for the first Bearer authentication. * - * @param bearerToken the token + * @param bearerToken Bearer token */ public void setBearerToken(String bearerToken) { setBearerToken(() -> bearerToken); } /** - * Helper method to set the token supplier for HTTP bearer authentication. + * Helper method to set the supplier of access tokens for Bearer authentication. * - * @param tokenSupplier the token supplier function + * @param tokenSupplier The supplier of bearer tokens */ public void setBearerToken(Supplier tokenSupplier) { for (Authentication auth : authentications.values()) { @@ -721,7 +767,36 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -839,7 +914,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache index cdd2125331f7..16b996ff0bde 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/api.mustache @@ -126,10 +126,12 @@ public class {{classname}} { final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); final MultiValueMap localVarFormParams = new LinkedMultiValueMap();{{#hasQueryParams}} -{{#queryParams}}{{#isExplode}}{{#hasVars}}{{#vars}} localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}}.{{getter}}())); -{{/vars}}{{/hasVars}}{{^hasVars}} localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); -{{/hasVars}}{{/isExplode}}{{^isExplode}} localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); -{{/isExplode}}{{/queryParams}}{{/hasQueryParams}}{{#hasHeaderParams}} + {{#queryParams}}{{#isExplode}}{{#hasVars}} + if ({{paramName}} != null) { + {{#vars}} localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}}.{{getter}}())); + {{/vars}}}{{/hasVars}}{{^hasVars}}localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); + {{/hasVars}}{{/isExplode}}{{^isExplode}}localVarQueryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); + {{/isExplode}}{{/queryParams}}{{/hasQueryParams}}{{#hasHeaderParams}} {{#headerParams}}if ({{paramName}} != null) localVarHeaderParams.add("{{baseName}}", apiClient.parameterToString({{paramName}}));{{^-last}} diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/auth/HttpBearerAuth.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/auth/HttpBearerAuth.mustache index e0924aaf8e1f..e67e76fbf4a7 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/auth/HttpBearerAuth.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/resttemplate/auth/HttpBearerAuth.mustache @@ -14,14 +14,29 @@ public class HttpBearerAuth implements Authentication { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache index 9ba4d1ed6491..a21ced55beca 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.gradle.mustache @@ -119,7 +119,7 @@ ext { {{#joda}} jodatime_version = "2.9.9" {{/joda}} - json_fire_version = "1.8.0" + json_fire_version = "1.9.0" } dependencies { diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache index 724178618be0..7c0ff52b7703 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/build.sbt.mustache @@ -35,7 +35,7 @@ lazy val root = (project in file(".")). {{#joda}} "joda-time" % "joda-time" % "2.9.9" % "compile", {{/joda}} - "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "junit" % "junit" % "4.13.2" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache index a450a583cf51..7f7b9e2b0f2b 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/play26/api.mustache @@ -17,6 +17,11 @@ import okhttp3.MultipartBody; {{#imports}}import {{import}}; {{/imports}} +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache index 36d034f4d282..8b2a61fcfaec 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/retrofit2/pom.mustache @@ -360,7 +360,7 @@ 1.8 ${java.version} ${java.version} - 1.8.3 + 1.9.0 1.6.3 {{#usePlayWS}} 2.15.2 diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache index b574d3bdb48d..d3a75e16528c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/ApiClient.mustache @@ -6,8 +6,6 @@ import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache index 2a266136c30c..a7ea64a15f7f 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/api.mustache @@ -92,11 +92,10 @@ public class {{classname}} { final MultiValueMap formParams = new LinkedMultiValueMap(); {{#hasQueryParams}} - {{#queryParams}} - queryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); - {{/queryParams}} - {{/hasQueryParams}} - {{#hasHeaderParams}} + {{#queryParams}}{{#isExplode}}{{#hasVars}}{{#vars}}queryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}}.{{getter}}())); + {{/vars}}{{/hasVars}}{{^hasVars}}queryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); + {{/hasVars}}{{/isExplode}}{{^isExplode}}queryParams.putAll(apiClient.parameterToMultiValueMap({{#collectionFormat}}ApiClient.CollectionFormat.valueOf("{{{.}}}".toUpperCase(Locale.ROOT)){{/collectionFormat}}{{^collectionFormat}}null{{/collectionFormat}}, "{{baseName}}", {{paramName}})); + {{/isExplode}}{{/queryParams}}{{/hasQueryParams}}{{#hasHeaderParams}} {{#headerParams}} if ({{paramName}} != null) diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache index a8eb081a5abb..53c528209a2d 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/build.gradle.mustache @@ -131,16 +131,16 @@ ext { swagger_annotations_version = "2.2.9" {{/swagger2AnnotationLibrary}} {{#useJakartaEe}} - spring_boot_version = "3.0.1" + spring_boot_version = "3.0.12" jakarta_annotation_version = "2.1.1" - reactor_version = "3.5.1" - reactor_netty_version = "1.1.1" + reactor_version = "3.5.12" + reactor_netty_version = "1.1.13" {{/useJakartaEe}} {{^useJakartaEe}} - spring_boot_version = "2.6.6" + spring_boot_version = "2.7.17" jakarta_annotation_version = "1.3.5" - reactor_version = "3.4.3" - reactor_netty_version = "1.0.4" + reactor_version = "3.4.34" + reactor_netty_version = "1.0.39" {{/useJakartaEe}} jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" diff --git a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache index 9158c35e1a83..84ad1047c61c 100644 --- a/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache +++ b/modules/openapi-generator/src/main/resources/Java/libraries/webclient/pom.mustache @@ -173,16 +173,16 @@ 0.2.6 {{/openApiNullable}} {{#useJakartaEe}} - 3.0.1 + 3.0.12 2.1.1 - 3.5.1 - 1.1.1 + 3.5.12 + 1.1.13 {{/useJakartaEe}} {{^useJakartaEe}} - 2.6.6 + 2.7.17 1.3.5 - 3.4.3 - 1.0.4 + 3.4.34 + 1.0.39 {{/useJakartaEe}} 4.13.2 {{#joda}} diff --git a/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache b/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache index 54d90dae0057..d1ba359d9e38 100644 --- a/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache +++ b/modules/openapi-generator/src/main/resources/Java/modelEnum.mustache @@ -9,6 +9,9 @@ import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; {{/gson}} +{{#isUri}} +import java.net.URI; +{{/isUri}} /** * {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} @@ -67,13 +70,13 @@ import com.google.gson.stream.JsonWriter; public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}> { @Override public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}); } @Override public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { - {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}next{{{dataType}}}(){{/isInteger}}{{/isNumber}}; - return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}}{{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; + return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); } } {{/gson}} diff --git a/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache index 43ad29863f0a..0096d840710f 100644 --- a/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache +++ b/modules/openapi-generator/src/main/resources/Java/modelInnerEnum.mustache @@ -62,12 +62,12 @@ public static class Adapter extends TypeAdapter<{{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}> { @Override public void write(final JsonWriter jsonWriter, final {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} enumeration) throws IOException { - jsonWriter.value(enumeration.getValue()); + jsonWriter.value(enumeration.getValue(){{#isUri}}.toASCIIString(){{/isUri}}); } @Override public {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} read(final JsonReader jsonReader) throws IOException { - {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{^isNumber}}{{^isInteger}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isInteger}}{{/isNumber}}; + {{^isNumber}}{{{dataType}}}{{/isNumber}}{{#isNumber}}String{{/isNumber}} value = {{#isFloat}}(float){{/isFloat}} {{#isUri}}URI.create({{/isUri}}jsonReader.{{#isNumber}}nextString(){{/isNumber}}{{#isInteger}}nextInt(){{/isInteger}}{{#isUri}}nextString()){{/isUri}}{{^isNumber}}{{^isInteger}}{{^isUri}}{{#isFloat}}nextDouble{{/isFloat}}{{^isFloat}}next{{{dataType}}}{{/isFloat}}(){{/isUri}}{{/isInteger}}{{/isNumber}}; return {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.fromValue({{#isNumber}}new BigDecimal({{/isNumber}}value{{#isNumber}}){{/isNumber}}); } } diff --git a/modules/openapi-generator/src/main/resources/Java/pojo.mustache b/modules/openapi-generator/src/main/resources/Java/pojo.mustache index 20f18dab6bff..6c213b93a529 100644 --- a/modules/openapi-generator/src/main/resources/Java/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/Java/pojo.mustache @@ -344,7 +344,7 @@ public class {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{{#vendorExtens sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} sb.append("}"); return sb.toString(); diff --git a/modules/openapi-generator/src/main/resources/JavaInflector/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaInflector/pojo.mustache index e6daab920094..b352785da252 100644 --- a/modules/openapi-generator/src/main/resources/JavaInflector/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaInflector/pojo.mustache @@ -73,7 +73,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/apiService.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/apiService.mustache index 64d61f6d465b..72682d96fba3 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/apiService.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/apiService.mustache @@ -19,6 +19,7 @@ import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/apiServiceImpl.mustache index 1c452eb8d32d..4d20508f3874 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/apiServiceImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/apiServiceImpl.mustache @@ -18,6 +18,7 @@ import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache index f00d72939a7b..afc9931c2414 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/api.mustache @@ -22,6 +22,7 @@ import java.util.Map; import java.util.List; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} @Path("{{commonPath}}") @RequestScoped diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache index 16b7bfacbab2..a057e4c9726f 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiService.mustache @@ -13,6 +13,11 @@ import java.util.List; import java.io.InputStream; +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} + import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache index d096e5e8fc73..45b7aa79db36 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/apiServiceImpl.mustache @@ -12,6 +12,11 @@ import java.util.List; import java.io.InputStream; +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} + import {{javaxPackage}}.enterprise.context.RequestScoped; import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache index 711b94486d7a..f07ef535f3e4 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/model.mustache @@ -7,6 +7,7 @@ import java.io.Serializable; {{/serializableModel}} {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{#models}} {{#model}}{{#description}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache index 6d0d761893e3..13a5cea6f491 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pojo.mustache @@ -81,7 +81,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -95,7 +95,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache index 4b8f2e186582..e997bacf0156 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-cdi/pom.mustache @@ -72,7 +72,7 @@ javax javaee-api - 7.0 + 8.0 provided diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache index 7575f3bf718a..527c389546ba 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pojo.mustache @@ -142,7 +142,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -156,7 +156,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache index 162d5fd4c69a..f08cf3a743a6 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/pom.mustache @@ -105,6 +105,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -212,7 +220,7 @@ 1.5.22 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 {{#useBeanValidation}} 2.0.2 {{/useBeanValidation}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache index 83606b6e4145..5e6c879857c1 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf-ext/server/pom.mustache @@ -126,6 +126,12 @@ javax.ws.rs jsr311-api + + + javax.validation + validation-api + diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache index ee2a028a2ad5..9e707960cc76 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pojo.mustache @@ -190,7 +190,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{/vars}}{{#parent}} && super.equals(o){{/parent}};{{/hasVars}}{{^hasVars}} return true;{{/hasVars}} @@ -206,7 +206,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache index e893f43a51fd..dc79d9d4560a 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/pom.mustache @@ -105,6 +105,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -212,7 +220,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 {{#useBeanValidation}} 2.0.2 {{/useBeanValidation}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/pom.mustache index 62fd7cfcde87..c7c04ac176ab 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/cxf/server/pom.mustache @@ -114,6 +114,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -263,7 +271,7 @@ 1.5.22 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 {{#useBeanValidation}} 2.0.2 {{/useBeanValidation}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache index 65623eff6e02..fb0e53912631 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiService.mustache @@ -20,6 +20,7 @@ import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache index f6243396d88e..145e7fcf93cc 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey1/apiServiceImpl.mustache @@ -20,6 +20,7 @@ import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pojo.mustache index 19b10be5e32e..ff10e14468b9 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pojo.mustache @@ -108,7 +108,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -122,7 +122,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pom.mustache index f20595bb5b5b..8817255f4d9f 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/libraries/jersey3/pom.mustache @@ -222,7 +222,7 @@ 3.1.3 2.15.2 4.13.2 - 1.4.9 + 1.4.14 5.0.0 UTF-8 diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache index 29144ca909ff..6a530aca2879 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/pojo.mustache @@ -108,7 +108,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -122,7 +122,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache index 77b35110bddb..eddab3b1569c 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/pom.mustache @@ -116,6 +116,14 @@ swagger-jersey2-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -214,7 +222,7 @@ 2.35 2.15.2 4.13.2 - 1.2.12 + 1.4.14 4.0.4 UTF-8 diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiService.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiService.mustache index e2b60f723d42..e94f6ddd52ae 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiService.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiService.mustache @@ -13,6 +13,10 @@ import {{package}}.NotFoundException; import java.io.InputStream; +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiServiceImpl.mustache index 484b1cec942c..577f9b165e8b 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiServiceImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/apiServiceImpl.mustache @@ -13,6 +13,10 @@ import {{package}}.NotFoundException; import java.io.InputStream; +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} import {{javaxPackage}}.enterprise.context.RequestScoped; import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/apiServiceImpl.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/apiServiceImpl.mustache index 0035baccec7f..3488840a4627 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/apiServiceImpl.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/apiServiceImpl.mustache @@ -12,6 +12,10 @@ import java.util.List; import java.io.InputStream; +{{#useBeanValidation}} +import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; +{{/useBeanValidation}} import {{javaxPackage}}.ws.rs.core.Response; import {{javaxPackage}}.ws.rs.core.SecurityContext; diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/gradle.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/gradle.mustache index 9b037aa7cc3b..d26efc06cd6a 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/gradle.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/gradle.mustache @@ -10,7 +10,9 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/model.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/model.mustache index 6de67ac4fb17..ac974f01c9b9 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/model.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/model.mustache @@ -9,6 +9,7 @@ import java.io.Serializable; {{/serializableModel}} {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{#models}} {{#model}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pojo.mustache index e41367afced1..7b7aa079788f 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pojo.mustache @@ -52,7 +52,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -66,7 +66,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pom.mustache index c9c74f3224b8..bc5c66425f89 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/eap/pom.mustache @@ -96,6 +96,14 @@ resteasy-validator-provider-11 ${resteasy-version} provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -120,6 +128,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/gradle.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/gradle.mustache index a1943a2f9b82..db988226d430 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/gradle.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/gradle.mustache @@ -10,10 +10,12 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' - providedCompile 'javax:javaee-api:7.0' + providedCompile 'javax:javaee-api:8.0' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' compile 'io.swagger:swagger-annotations:1.5.22' compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final' @@ -23,7 +25,9 @@ dependencies { compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.9.9' compile 'joda-time:joda-time:2.7' //TODO: swaggerFeature - compile 'io.swagger:swagger-jaxrs:1.5.12' + compile('io.swagger:swagger-jaxrs:1.5.12') { + exclude group: "javax.validation", module: "validation-api" + } testCompile 'junit:junit:4.13.2', 'org.hamcrest:hamcrest-core:1.3' diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/model.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/model.mustache index 6de67ac4fb17..ac974f01c9b9 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/model.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/model.mustache @@ -9,6 +9,7 @@ import java.io.Serializable; {{/serializableModel}} {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{#models}} {{#model}} diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pojo.mustache index 88dfa8a5fcf5..2df567dd8108 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pojo.mustache @@ -54,7 +54,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens return false; } {{classname}} {{classVarName}} = ({{classname}}) o;{{#hasVars}} - return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals({{name}}, {{classVarName}}.{{name}}){{^-last}} && + return {{#parent}}super.equals(o) && {{/parent}}{{#vars}}Objects.equals(this.{{name}}, {{classVarName}}.{{name}}){{^-last}} && {{/-last}}{{#-last}};{{/-last}}{{/vars}}{{/hasVars}}{{^hasVars}}{{#parent}}return super.equals(o);{{/parent}}{{^parent}}return true;{{/parent}}{{/hasVars}} } @@ -68,7 +68,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache index c564afa48771..5d41db46781b 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/resteasy/pom.mustache @@ -70,7 +70,7 @@ javax javaee-api - 7.0 + 8.0 provided @@ -114,6 +114,14 @@ resteasy-validator-provider-11 3.6.3.SP1 provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -142,6 +150,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumClass.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumClass.mustache index 0a15f92f3be7..87985b167bdc 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumClass.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumClass.mustache @@ -25,7 +25,7 @@ * Convert a String into {{dataType}}, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static {{datatypeWithEnum}} fromString(String s) { + public static {{datatypeWithEnum}} fromString(String s) { for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -34,8 +34,8 @@ } } {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} - } - + } + @JsonCreator public static {{datatypeWithEnum}} fromValue({{dataType}} value) { for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache index c0aef1d8ddba..17f29417c6db 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/enumOuterClass.mustache @@ -29,7 +29,7 @@ import com.fasterxml.jackson.annotation.JsonValue; * Convert a String into {{dataType}}, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -38,8 +38,8 @@ import com.fasterxml.jackson.annotation.JsonValue; } } {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} - } - + } + @Override @JsonValue public String toString() { diff --git a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache index 40f42a44f83a..8646fe2347f9 100644 --- a/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaJaxRS/spec/pojo.mustache @@ -145,7 +145,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache index bf3cf9d4c014..646364fd2532 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApi.mustache @@ -16,6 +16,7 @@ import java.util.concurrent.CompletableFuture; {{/supportAsync}} {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{>generatedAnnotation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache index f9c14cbde1cf..c7e3dcc271e6 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiController.mustache @@ -32,6 +32,7 @@ import java.util.concurrent.CompletableFuture; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; import com.typesafe.config.Config; {{/useBeanValidation}} diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache index 4328f6292103..a7f44d4d8a67 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/newApiInterface.mustache @@ -26,6 +26,7 @@ import java.util.concurrent.CompletableFuture; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} {{#operations}} diff --git a/modules/openapi-generator/src/main/resources/JavaPlayFramework/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaPlayFramework/pojo.mustache index 8d4e28af4b5a..dfb6062aeb4d 100644 --- a/modules/openapi-generator/src/main/resources/JavaPlayFramework/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaPlayFramework/pojo.mustache @@ -1,6 +1,7 @@ import java.util.Objects; {{#useBeanValidation}} import {{javaxPackage}}.validation.constraints.*; +import {{javaxPackage}}.validation.Valid; {{/useBeanValidation}} /** * {{description}}{{^description}}{{classname}}{{/description}} @@ -126,7 +127,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache index 712b7b6ccc5d..71af750223a1 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/api.mustache @@ -178,7 +178,7 @@ public interface {{classname}} { }{{#hasAuthMethods}}, security = { {{#authMethods}} - @SecurityRequirement(name = "{{name}}"{{#isOAuth}}, scopes={ {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} }{{/isOAuth}}){{^-last}},{{/-last}} + @SecurityRequirement(name = "{{name}}"{{#scopes.0}}, scopes={ {{#scopes}}"{{scope}}"{{^-last}}, {{/-last}}{{/scopes}} }{{/scopes.0}}){{^-last}},{{/-last}} {{/authMethods}} }{{/hasAuthMethods}}{{#externalDocs}}, externalDocs = @ExternalDocumentation(description = "{{externalDocs.description}}", url = "{{externalDocs.url}}"){{/externalDocs}} @@ -196,16 +196,16 @@ public interface {{classname}} { responseContainer = "{{{.}}}"{{/returnContainer}}{{#hasAuthMethods}}, authorizations = { {{#authMethods}} - {{#isOAuth}} + {{#scopes.0}} @Authorization(value = "{{name}}", scopes = { {{#scopes}} @AuthorizationScope(scope = "{{scope}}", description = "{{description}}"){{^-last}},{{/-last}} {{/scopes}} }){{^-last}},{{/-last}} - {{/isOAuth}} - {{^isOAuth}} + {{/scopes.0}} + {{^scopes.0}} @Authorization(value = "{{name}}"){{^-last}},{{/-last}} - {{/isOAuth}} + {{/scopes.0}} {{/authMethods}} }{{/hasAuthMethods}} ) @ApiResponses({ diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidation.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidation.mustache index e427a43a0acd..0aed4a92d734 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidation.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidation.mustache @@ -1 +1 @@ -{{#required}}{{^isReadOnly}}@NotNull {{/isReadOnly}}{{/required}}{{#isContainer}}{{^isPrimitiveType}}{{^isEnum}}@Valid {{/isEnum}}{{/isPrimitiveType}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}@Valid {{/isPrimitiveType}}{{/isContainer}}{{>beanValidationCore}} \ No newline at end of file +{{#required}}{{^isReadOnly}}@NotNull {{/isReadOnly}}{{/required}}{{#isContainer}}{{^isPrimitiveType}}{{^isEnum}}@Valid {{/isEnum}}{{/isPrimitiveType}}{{/isContainer}}{{^isContainer}}{{^isPrimitiveType}}@Valid {{/isPrimitiveType}}{{/isContainer}}{{^openApiNullable}}{{>beanValidationCore}}{{/openApiNullable}}{{#openApiNullable}}{{^useOptional}}{{>beanValidationCore}}{{/useOptional}}{{/openApiNullable}}{{#useOptional}}{{#openApiNullable}}{{#isContainer}}{{^required}}{{>beanValidationCore}}{{/required}}{{/isContainer}}{{/openApiNullable}}{{#openApiNullable}}{{#required}}{{>beanValidationCore}}{{/required}}{{/openApiNullable}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationBodyParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationBodyParams.mustache index 71bc546835e4..6f4e70f06a76 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationBodyParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationBodyParams.mustache @@ -1 +1 @@ -{{! RequestBody required param is responsible for optional and nullability }}{{>beanValidationCore}} \ No newline at end of file +{{^useOptional}}{{>beanValidationCore}}{{/useOptional}}{{#useOptional}}{{#required}}{{>beanValidationCore}}{{/required}}{{/useOptional}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache index 25138626ce7c..1e347f2f9505 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/beanValidationCore.mustache @@ -12,9 +12,9 @@ minLength not set, maxLength set @Size: minItems not set && maxItems set }}{{^minItems}}{{#maxItems}}@Size(max = {{.}}) {{/maxItems}}{{/minItems}}{{! @Email: useBeanValidation -}}{{#isEmail}}{{#useBeanValidation}}@{{javaxPackage}}.validation.constraints.Email{{/useBeanValidation}}{{! +}}{{#isEmail}}{{#useBeanValidation}}@{{javaxPackage}}.validation.constraints.Email {{/useBeanValidation}}{{! @Email: performBeanValidation exclusive -}}{{^useBeanValidation}}{{#performBeanValidation}}@org.hibernate.validator.constraints.Email{{/performBeanValidation}}{{/useBeanValidation}}{{/isEmail}}{{! +}}{{^useBeanValidation}}{{#performBeanValidation}}@org.hibernate.validator.constraints.Email {{/performBeanValidation}}{{/useBeanValidation}}{{/isEmail}}{{! check for integer or long / all others=decimal type with @Decimal* isInteger set }}{{#isInteger}}{{#minimum}}@Min({{.}}) {{/minimum}}{{#maximum}}@Max({{.}}) {{/maximum}}{{/isInteger}}{{! diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache index 9e683484efd5..69d36f1c3b04 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}{{>paramDoc}}{{#useBeanValidation}} @Valid{{>beanValidationBodyParams}}{{/useBeanValidation}} @RequestBody{{^required}}(required = false){{/required}} {{^reactive}}{{{dataType}}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}} {{paramName}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}{{>paramDoc}}{{#useBeanValidation}} @Valid{{>beanValidationBodyParams}}{{/useBeanValidation}} @RequestBody{{^required}}(required = false){{/required}} {{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}Mono<{{{dataType}}}>{{/isArray}}{{#isArray}}Flux<{{{baseType}}}>{{/isArray}}{{/reactive}} {{paramName}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache index b943d221f450..82966fd9d133 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/libraries/spring-cloud/clientConfiguration.mustache @@ -10,6 +10,7 @@ import org.springframework.beans.factory.annotation.Value; {{/authMethods}} {{#hasAuthMethods}} import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; {{#hasApiKeyMethods}} import org.springframework.beans.factory.annotation.Value; {{/hasApiKeyMethods}} @@ -25,7 +26,6 @@ import org.springframework.security.oauth2.core.OAuth2AuthenticationException; import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataType.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataType.mustache index ba9bb946318e..fd94338fcf4d 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataType.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataType.mustache @@ -1 +1 @@ -{{#openApiNullable}}{{#isNullable}}JsonNullable<{{{datatypeWithEnum}}}>{{/isNullable}}{{^isNullable}}{{{datatypeWithEnum}}}{{/isNullable}}{{/openApiNullable}}{{^openApiNullable}}{{{datatypeWithEnum}}}{{/openApiNullable}} \ No newline at end of file +{{#openApiNullable}}{{#isNullable}}JsonNullable<{{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}Optional<{{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{/openApiNullable}}{{{datatypeWithEnum}}}{{#openApiNullable}}{{#isNullable}}>{{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}>{{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{/openApiNullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataTypeBeanValidation.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataTypeBeanValidation.mustache new file mode 100644 index 000000000000..8d6fc6deca2a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/JavaSpring/nullableDataTypeBeanValidation.mustache @@ -0,0 +1 @@ +{{#openApiNullable}}{{#isNullable}}{{^isContainer}}JsonNullable<{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{/isContainer}}{{#isContainer}}JsonNullable<{{/isContainer}}{{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}Optional<{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{/openApiNullable}}{{{datatypeWithEnum}}}{{#openApiNullable}}{{#isNullable}}>{{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}>{{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{/openApiNullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache index c449fae18737..5930383810fc 100644 --- a/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaSpring/pojo.mustache @@ -48,11 +48,6 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{/mostInnerItems}} {{/isContainer}} {{/isEnum}} - {{#jackson}} - {{#withXml}} - @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") - {{/withXml}} - {{/jackson}} {{#gson}} @SerializedName("{{baseName}}") {{/gson}} @@ -65,7 +60,7 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{#isContainer}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} {{#openApiNullable}} - private {{>nullableDataType}} {{name}}{{#isNullable}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(){{/isNullable}}{{^isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isNullable}}; + private {{#isNullable}}{{>nullableDataTypeBeanValidation}} {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined();{{/isNullable}}{{^required}}{{^isNullable}}{{>nullableDataTypeBeanValidation}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/isNullable}}{{/required}}{{#required}}{{^isNullable}}{{>nullableDataTypeBeanValidation}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/isNullable}}{{/required}} {{/openApiNullable}} {{^openApiNullable}} private {{>nullableDataType}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}; @@ -79,7 +74,7 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) {{/isDateTime}} {{#openApiNullable}} - private {{>nullableDataType}} {{name}}{{#isNullable}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined(){{/isNullable}}{{^isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isNullable}}; + private {{#isNullable}}{{>nullableDataTypeBeanValidation}} {{name}} = JsonNullable.<{{{datatypeWithEnum}}}>undefined();{{/isNullable}}{{^required}}{{^isNullable}}{{>nullableDataTypeBeanValidation}} {{name}}{{#useOptional}} = Optional.{{^defaultValue}}empty(){{/defaultValue}}{{#defaultValue}}of({{{.}}}){{/defaultValue}};{{/useOptional}}{{^useOptional}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/useOptional}}{{/isNullable}}{{/required}}{{^isNullable}}{{#required}}{{>nullableDataTypeBeanValidation}} {{name}}{{#defaultValue}} = {{{.}}}{{/defaultValue}};{{/required}}{{/isNullable}} {{/openApiNullable}} {{^openApiNullable}} private {{>nullableDataType}} {{name}}{{#isNullable}} = null{{/isNullable}}{{^isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}}{{/isNullable}}; @@ -103,7 +98,7 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{#vars}} {{#required}} {{#openApiNullable}} - this.{{name}} = {{#isNullable}}JsonNullable.of({{name}}){{/isNullable}}{{^isNullable}}{{name}}{{/isNullable}}; + this.{{name}} = {{#isNullable}}JsonNullable.of({{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}Optional.ofNullable({{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{name}}{{#isNullable}}){{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}){{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}; {{/openApiNullable}} {{^openApiNullable}} this.{{name}} = {{name}}; @@ -118,7 +113,7 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{! begin feature: fluent setter methods }} public {{classname}} {{name}}({{{datatypeWithEnum}}} {{name}}) { {{#openApiNullable}} - this.{{name}} = {{#isNullable}}JsonNullable.of({{name}}){{/isNullable}}{{^isNullable}}{{name}}{{/isNullable}}; + this.{{name}} = {{#isNullable}}JsonNullable.of({{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}Optional.of({{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}{{name}}{{#isNullable}}){{/isNullable}}{{#useOptional}}{{^required}}{{^isNullable}}{{^isContainer}}){{/isContainer}}{{/isNullable}}{{/required}}{{/useOptional}}; {{/openApiNullable}} {{^openApiNullable}} this.{{name}} = {{name}}; @@ -199,11 +194,14 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{/swagger1AnnotationLibrary}} {{#jackson}} @JsonProperty("{{baseName}}") + {{#withXml}} + @JacksonXmlProperty({{#isXmlAttribute}}isAttribute = true, {{/isXmlAttribute}}{{#xmlNamespace}}namespace="{{.}}", {{/xmlNamespace}}localName = "{{xmlName}}{{^xmlName}}{{baseName}}{{/xmlName}}") + {{/withXml}} {{/jackson}} {{#deprecated}} @Deprecated {{/deprecated}} - public {{>nullableDataType}} {{getter}}() { + public {{>nullableDataTypeBeanValidation}} {{getter}}() { return {{name}}; } @@ -286,7 +284,7 @@ public class {{classname}}{{#parent}} extends {{{parent}}}{{/parent}}{{^parent}} {{#parent}} sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}{{#additionalPropertiesType}} sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); {{/additionalPropertiesType}}sb.append("}"); diff --git a/modules/openapi-generator/src/main/resources/JavaVertXServer/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaVertXServer/pojo.mustache index 9b1bb2748faf..f0b46718977e 100644 --- a/modules/openapi-generator/src/main/resources/JavaVertXServer/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaVertXServer/pojo.mustache @@ -53,7 +53,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/pojo.mustache b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/pojo.mustache index 9b1bb2748faf..f0b46718977e 100644 --- a/modules/openapi-generator/src/main/resources/JavaVertXWebServer/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/JavaVertXWebServer/pojo.mustache @@ -53,7 +53,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig index c51d01c26ec2..162983881433 100644 --- a/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig +++ b/modules/openapi-generator/src/main/resources/META-INF/services/org.openapitools.codegen.CodegenConfig @@ -114,9 +114,11 @@ org.openapitools.codegen.languages.RustClientCodegen org.openapitools.codegen.languages.RustServerCodegen org.openapitools.codegen.languages.ScalatraServerCodegen org.openapitools.codegen.languages.ScalaAkkaClientCodegen +org.openapitools.codegen.languages.ScalaPekkoClientCodegen org.openapitools.codegen.languages.ScalaAkkaHttpServerCodegen org.openapitools.codegen.languages.ScalaFinchServerCodegen org.openapitools.codegen.languages.ScalaGatlingCodegen +org.openapitools.codegen.languages.ScalaHttp4sServerCodegen org.openapitools.codegen.languages.ScalaLagomServerCodegen org.openapitools.codegen.languages.ScalaPlayFrameworkServerCodegen org.openapitools.codegen.languages.ScalaSttpClientCodegen @@ -142,3 +144,4 @@ org.openapitools.codegen.languages.TypeScriptRxjsClientCodegen org.openapitools.codegen.languages.WsdlSchemaCodegen org.openapitools.codegen.languages.XojoClientCodegen org.openapitools.codegen.languages.ZapierClientCodegen +org.openapitools.codegen.languages.RustAxumServerCodegen diff --git a/modules/openapi-generator/src/main/resources/apache2/authConf.mustache b/modules/openapi-generator/src/main/resources/apache2/authConf.mustache index b68cf9bc7da8..a455e16dfe99 100644 --- a/modules/openapi-generator/src/main/resources/apache2/authConf.mustache +++ b/modules/openapi-generator/src/main/resources/apache2/authConf.mustache @@ -1,5 +1,5 @@ AuthBasicProvider file - AuthUserFile "{{vendorExtensions.x-codegen-user-info-path}}htpwd" - AuthGroupFile "{{vendorExtensions.x-codegen-user-info-path}}groups" - AuthType basic - AuthName "api" \ No newline at end of file + AuthUserFile "{{vendorExtensions.x-codegen-user-info-path}}htpwd" + AuthGroupFile "{{vendorExtensions.x-codegen-user-info-path}}groups" + AuthType basic + AuthName "api" \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache index 338fbf63591e..62ccdff1bfe6 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/CMakeLists.txt.mustache @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.2) +cmake_minimum_required(VERSION 3.5) project({{{packageName}}}) diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache index f6f4d8907035..a241ce842c3e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.cpp.mustache @@ -409,7 +409,7 @@ void {{prefix}}HttpRequestWorker::on_reply_finished(QNetworkReply *reply) { } process_response(reply); reply->deleteLater(); - emit on_execution_finished(this); + Q_EMIT on_execution_finished(this); } void {{prefix}}HttpRequestWorker::on_reply_timeout(QNetworkReply *reply) { @@ -419,7 +419,7 @@ void {{prefix}}HttpRequestWorker::on_reply_timeout(QNetworkReply *reply) { disconnect(reply, nullptr, nullptr, nullptr); reply->abort(); reply->deleteLater(); - emit on_execution_finished(this); + Q_EMIT on_execution_finished(this); } void {{prefix}}HttpRequestWorker::process_response(QNetworkReply *reply) { diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache index b9dec34915ef..84220c68db19 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/HttpRequest.h.mustache @@ -72,7 +72,7 @@ public: void setRequestCompressionEnabled(bool enable); int getHttpResponseCode() const; -signals: +Q_SIGNALS: void on_execution_finished({{prefix}}HttpRequestWorker *worker); private: diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache index faef6e182a75..39af6328885e 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/README.mustache @@ -42,7 +42,7 @@ class Example : public QObject { {{#allParams}} {{{dataType}}} create(); {{/allParams}} -public slots: +public Q_SLOTS: void exampleFunction1(); }; {{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache index 83db65526da3..0da998eb5060 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-body.mustache @@ -163,7 +163,7 @@ void {{classname}}::enableResponseCompression() { } void {{classname}}::abortRequests() { - emit abortRequestsSignal(); + Q_EMIT abortRequestsSignal(); } QString {{classname}}::getParamStylePrefix(const QString &style) { @@ -676,7 +676,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} connect(this, &{{classname}}::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren<{{prefix}}HttpRequestWorker*>().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } });{{#authMethods}}{{#isOAuth}}{{#isCode}} _OauthMethod = 2; @@ -702,7 +702,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren<{{prefix}}HttpRequestWorker*>().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -732,7 +732,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren<{{prefix}}HttpRequestWorker*>().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -762,7 +762,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren<{{prefix}}HttpRequestWorker*>().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -792,7 +792,7 @@ void {{classname}}::{{nickname}}({{#allParams}}{{#required}}const {{{dataType}}} connect(this, &{{classname}}::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren<{{prefix}}HttpRequestWorker*>().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -857,8 +857,8 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit {{nickname}}Signal({{#returnType}}output{{/returnType}}); - emit {{nickname}}SignalFull(worker{{#returnType}}, output{{/returnType}});{{#authMethods}}{{#isOAuth}}{{#isCode}} + Q_EMIT {{nickname}}Signal({{#returnType}}output{{/returnType}}); + Q_EMIT {{nickname}}SignalFull(worker{{#returnType}}, output{{/returnType}});{{#authMethods}}{{#isOAuth}}{{#isCode}} } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_authFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -870,7 +870,7 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QString tokenUrl("{{tokenUrl}}"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _authFlow.setVariables(authorizationUrl, tokenUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId", "clientSecret"); - emit _authFlow.authenticationNeeded();{{/isCode}} + Q_EMIT _authFlow.authenticationNeeded();{{/isCode}} {{#isImplicit}} } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); @@ -882,7 +882,7 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QString authorizationUrl("{{authorizationUrl}}"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded();{{/isImplicit}} + Q_EMIT _implicitFlow.authenticationNeeded();{{/isImplicit}} {{#isApplication}} } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_credentialFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); @@ -894,7 +894,7 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QString tokenUrl("{{tokenUrl}}"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _credentialFlow.setVariables(tokenUrl , scopeStr, "clientId", "clientSecret"); - emit _credentialFlow.authenticationNeeded();{{/isApplication}} + Q_EMIT _credentialFlow.authenticationNeeded();{{/isApplication}} {{#isPassword}} } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_passwordFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); @@ -906,11 +906,37 @@ void {{classname}}::{{nickname}}Callback({{prefix}}HttpRequestWorker *worker) { QString tokenUrl("{{tokenUrl}}"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _passwordFlow.setVariables(tokenUrl , scopeStr ,"clientId", "clientSecret", "username", "password"); - emit _passwordFlow.authenticationNeeded(); + Q_EMIT _passwordFlow.authenticationNeeded(); {{/isPassword}}{{/isOAuth}}{{/authMethods}} } else { - emit {{nickname}}SignalE({{#returnType}}output, {{/returnType}}error_type, error_str); - emit {{nickname}}SignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT {{nickname}}SignalE({{#returnType}}output, {{/returnType}}error_type, error_str); + Q_EMIT {{nickname}}SignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT {{nickname}}SignalError({{#returnType}}output, {{/returnType}}error_type, error_str); + Q_EMIT {{nickname}}SignalErrorFull(worker, error_type, error_str); } } diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache index 6d1376d52c55..faa0bd472739 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/api-header.mustache @@ -85,22 +85,25 @@ private: {{#operations}}{{#operation}} void {{nickname}}Callback({{prefix}}HttpRequestWorker *worker);{{/operation}}{{/operations}} -signals: +Q_SIGNALS: {{#operations}}{{#operation}} void {{nickname}}Signal({{#returnType}}{{{.}}} summary{{/returnType}});{{/operation}}{{/operations}} {{#operations}}{{#operation}} void {{nickname}}SignalFull({{prefix}}HttpRequestWorker *worker{{#returnType}}, {{{.}}} summary{{/returnType}});{{/operation}}{{/operations}} {{#operations}}{{#operation}} - void {{nickname}}SignalE({{#returnType}}{{{.}}} summary, {{/returnType}}QNetworkReply::NetworkError error_type, QString error_str);{{/operation}}{{/operations}} + Q_DECL_DEPRECATED_X("Use {{nickname}}SignalError() instead") + void {{nickname}}SignalE({{#returnType}}{{{.}}} summary, {{/returnType}}QNetworkReply::NetworkError error_type, QString error_str); + void {{nickname}}SignalError({{#returnType}}{{{.}}} summary, {{/returnType}}QNetworkReply::NetworkError error_type, const QString &error_str);{{/operation}}{{/operations}} {{#operations}}{{#operation}} - void {{nickname}}SignalEFull({{prefix}}HttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str);{{/operation}}{{/operations}} + Q_DECL_DEPRECATED_X("Use {{nickname}}SignalErrorFull() instead") + void {{nickname}}SignalEFull({{prefix}}HttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void {{nickname}}SignalErrorFull({{prefix}}HttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str);{{/operation}}{{/operations}} void abortRequestsSignal(); void allPendingRequestsCompleted(); -public slots: +public Q_SLOTS: void tokenAvailable(); - }; {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache index 65d6609c0d6b..b9927d11d677 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.cpp.mustache @@ -31,7 +31,7 @@ oauthToken OauthBase::getToken(QString scope) void OauthBase::addToken(oauthToken token) { m_oauthTokenMap.insert(token.getScope(),token); - emit tokenReceived(); + Q_EMIT tokenReceived(); } @@ -341,7 +341,7 @@ void ReplyServer::read() } socket->close(); - emit dataReceived(queryParams); + Q_EMIT dataReceived(queryParams); } {{#cppNamespaceDeclarations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.h.mustache index 8b2da7dcf643..dd5ca9474361 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-client/oauth.h.mustache @@ -58,10 +58,10 @@ public: private: QByteArray m_reply; -signals: +Q_SIGNALS: void dataReceived(QMap); -public slots: +public Q_SLOTS: void onConnected(); void read(); void start(); @@ -88,11 +88,11 @@ protected: QString m_scope, m_accessType, m_state, m_redirectUri, m_clientId, m_clientSecret; bool m_linked; -public slots: +public Q_SLOTS: virtual void authenticationNeededCallback()=0; void onFinish(QNetworkReply *rep); -signals: +Q_SIGNALS: void authenticationNeeded(); void tokenReceived(); }; @@ -110,7 +110,7 @@ public: private: ReplyServer m_server; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; void onVerificationReceived(const QMap response); @@ -129,7 +129,7 @@ public: private: ReplyServer m_server; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; void ImplicitTokenReceived(const QMap response); }; @@ -144,7 +144,7 @@ public: void unlink() override; void setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret); -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; }; @@ -162,7 +162,7 @@ public: private: QString m_username, m_password; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; }; diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache index 55a3e3db47fb..47f964a37944 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apihandler.h.mustache @@ -20,7 +20,7 @@ public: virtual ~{{classname}}Handler(); -public slots: +public Q_SLOTS: {{#operations}}{{#operation}}virtual void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); {{/operation}}{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache index 7799749ee8aa..37400ee83168 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.cpp.mustache @@ -108,7 +108,7 @@ void {{classname}}Request::{{nickname}}Request({{#hasPathParams}}{{#pathParams}} {{/isArray}} {{/bodyParam}}{{/bodyParams}} - emit {{nickname}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); + Q_EMIT {{nickname}}({{#allParams}}{{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); } {{/operation}}{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache index b2fad55940be..34dbeea872e0 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirequest.h.mustache @@ -44,7 +44,7 @@ public: void setResponseHeaders(const QMultiMap& headers); -signals: +Q_SIGNALS: {{#operations}}{{#operation}}void {{nickname}}({{#allParams}}{{{dataType}}} {{paramName}}{{^-last}}, {{/-last}}{{/allParams}}); {{/operation}}{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache index f30a069c19b1..d750b2a28766 100644 --- a/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-qt-qhttpengine-server/apirouter.h.mustache @@ -24,7 +24,7 @@ namespace {{this}} { class {{prefix}}ApiRequestHandler : public QHttpEngine::QObjectHandler { Q_OBJECT -signals: +Q_SIGNALS: void requestReceived(QHttpEngine::Socket *socket); protected: @@ -34,10 +34,10 @@ protected: // If the slot requires all data to be received, check to see if this is // already the case, otherwise, wait until the rest of it arrives if (socket->bytesAvailable() >= socket->contentLength()) { - emit requestReceived(socket); + Q_EMIT requestReceived(socket); } else { connect(socket, &QHttpEngine::Socket::readChannelFinished, [this, socket]() { - emit requestReceived(socket); + Q_EMIT requestReceived(socket); }); } } diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache index 80c7b0d4dd70..ea3bd65b95d9 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server-deprecated/api-header.mustache @@ -174,7 +174,7 @@ class {{declspec}} {{classname}} { public: explicit {{classname}}(std::shared_ptr const& restbedService); - virtual ~{{classname}}(); + virtual ~{{classname}}(); {{#operation}} virtual void set{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource(std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource); @@ -185,9 +185,9 @@ public: virtual std::shared_ptr service(); protected: - {{#operation}} - std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; - {{/operation}} + {{#operation}} + std::shared_ptr<{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{classname}}{{vendorExtensions.x-codegen-resource-name}}Resource; + {{/operation}} private: std::shared_ptr m_service; diff --git a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache index b2c7dccf5748..f7cc64d15eed 100644 --- a/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache +++ b/modules/openapi-generator/src/main/resources/cpp-restbed-server/api-header.mustache @@ -137,7 +137,7 @@ class {{declspec}} {{classname}} { public: explicit {{classname}}(std::shared_ptr const& restbedService); - virtual ~{{classname}}(); + virtual ~{{classname}}(); {{#operation}} std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> get{{vendorExtensions.x-codegen-resource-name}}Resource(); @@ -156,9 +156,9 @@ public: virtual std::shared_ptr service(); protected: - {{#operation}} - std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{vendorExtensions.x-codegen-resource-name}}Resource; - {{/operation}} + {{#operation}} + std::shared_ptr<{{classname}}Resources::{{vendorExtensions.x-codegen-resource-name}}Resource> m_sp{{vendorExtensions.x-codegen-resource-name}}Resource; + {{/operation}} private: std::shared_ptr m_service; diff --git a/modules/openapi-generator/src/main/resources/csharp-functions/function.mustache b/modules/openapi-generator/src/main/resources/csharp-functions/function.mustache index 95e3a4274cc3..d288160670cb 100644 --- a/modules/openapi-generator/src/main/resources/csharp-functions/function.mustache +++ b/modules/openapi-generator/src/main/resources/csharp-functions/function.mustache @@ -22,11 +22,9 @@ namespace {{apiPackage}} {{#generateBody}} { var method = this.GetType().GetMethod("{{operationId}}"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<{{{returnType}}}>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<{{{returnType}}}>)method.Invoke(this, new object[] { req, context{{#allParams}}{{#isPathParam}}, {{>paramName}}{{/isPathParam}}{{/allParams}} })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } {{/generateBody}} {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache index 34c2619edced..ee908eb89942 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ApiClient.mustache @@ -564,7 +564,8 @@ namespace {{packageName}}.Client MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; {{#hasOAuthMethods}} diff --git a/modules/openapi-generator/src/main/resources/csharp/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp/ClientUtils.mustache index ab126614f96a..5e43c3d0ec4b 100644 --- a/modules/openapi-generator/src/main/resources/csharp/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/ClientUtils.mustache @@ -31,7 +31,11 @@ namespace {{packageName}}.Client /// static ClientUtils() { - compareLogic = new CompareLogic(); + {{#equatable}} + ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}(); + comparisonConfig.UseHashCodeIdentifier = true; + {{/equatable}} + compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}}); } {{/useCompareNetObjects}} diff --git a/modules/openapi-generator/src/main/resources/csharp/HttpSigningConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp/HttpSigningConfiguration.mustache index 4bc8b396e095..33791a908579 100644 --- a/modules/openapi-generator/src/main/resources/csharp/HttpSigningConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/HttpSigningConfiguration.mustache @@ -102,14 +102,13 @@ namespace {{packageName}}.Client const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -317,6 +316,10 @@ namespace {{packageName}}.Client private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -342,8 +345,10 @@ namespace {{packageName}}.Client private string GetECDSASignature(byte[] dataToSign) { {{#net60OrLater}} - if (!File.Exists(KeyFilePath)) - throw new Exception("key file path does not exist."); + if (!File.Exists(KeyFilePath) && string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } var keyStr = KeyString; const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; @@ -443,6 +448,11 @@ namespace {{packageName}}.Client private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/modules/openapi-generator/src/main/resources/csharp/NullConditionalProperty.mustache b/modules/openapi-generator/src/main/resources/csharp/NullConditionalProperty.mustache index d8ad9266699e..7dcafa8033e4 100644 --- a/modules/openapi-generator/src/main/resources/csharp/NullConditionalProperty.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/NullConditionalProperty.mustache @@ -1 +1 @@ -{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}} \ No newline at end of file +{{#lambda.first}}{{#isNullable}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiKeyToken.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiKeyToken.mustache index 3bee0750d533..273eb2cc75fc 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiKeyToken.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiKeyToken.mustache @@ -15,14 +15,21 @@ namespace {{packageName}}.{{clientPackage}} { private string _raw; + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + /// /// Constructs an ApiKeyToken object. /// /// + /// /// /// - public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { + Header = header; _raw = $"{ prefix }{ value }"; } @@ -30,22 +37,20 @@ namespace {{packageName}}.{{clientPackage}} /// Places the token in the header. /// /// - /// - public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) { - request.Headers.Add(headerName, _raw); + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); } - + /// /// Places the token in the query. /// /// /// /// - /// - public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) { - parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString(){{nrt!}}; + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString(){{nrt!}}; } } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiTestsBase.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiTestsBase.mustache index b78be97e725a..3292a1e8668a 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiTestsBase.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ApiTestsBase.mustache @@ -29,36 +29,36 @@ namespace {{packageName}}.Test.{{apiPackage}} .Configure{{apiName}}((context, services, options) => { {{#lambda.trimTrailingWithNewLine}} - {{#hasApiKeyMethods}} - string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - ApiKeyToken apiKeyToken = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); + {{#apiKeyMethods}} + string apiKeyTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}(apiKeyTokenValue{{-index}}, ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); - {{/hasApiKeyMethods}} - {{#hasHttpBearerMethods}} - string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - BearerToken bearerToken = new{{^net70OrLater}} BearerToken{{/net70OrLater}}(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); + {{/apiKeyMethods}} + {{#httpBearerMethods}} + string bearerTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}(bearerTokenValue{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); - {{/hasHttpBearerMethods}} - {{#hasHttpBasicMethods}} - string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); - string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); - BasicToken basicToken = new{{^net70OrLater}} BasicToken{{/net70OrLater}}(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); + {{/httpBearerMethods}} + {{#httpBasicMethods}} + string basicTokenUsername{{-index}} = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword{{-index}} = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}(basicTokenUsername{{-index}}, basicTokenPassword{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); - {{/hasHttpBasicMethods}} - {{#hasHttpSignatureMethods}} - HttpSigningConfiguration config = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); - {{/hasHttpSignatureMethods}} - {{#hasOAuthMethods}} - string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - OAuthToken oauthToken = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); - {{/hasOAuthMethods}} + {{/httpSignatureMethods}} + {{#oauthMethods}} + string oauthTokenValue{{-index}} = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}(oauthTokenValue{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + {{/oauthMethods}} {{/lambda.trimTrailingWithNewLine}} }); } diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ClientUtils.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ClientUtils.mustache index 2055518bde2b..d862cfb414f3 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ClientUtils.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ClientUtils.mustache @@ -33,7 +33,11 @@ using System.Runtime.CompilerServices; /// static ClientUtils() { - compareLogic = new CompareLogic(); + {{#equatable}} + ComparisonConfig comparisonConfig = new{{^net70OrLater}} ComparisonConfig{{/net70OrLater}}(); + comparisonConfig.UseHashCodeIdentifier = true; + {{/equatable}} + compareLogic = new{{^net70OrLater}} CompareLogic{{/net70OrLater}}({{#equatable}}comparisonConfig{{/equatable}}); } {{/useCompareNetObjects}} @@ -46,6 +50,51 @@ using System.Runtime.CompilerServices; /// public delegate void EventHandler(object sender, T e) where T : EventArgs; + {{#hasApiKeyMethods}} + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + {{#apiKeyMethods}} + /// + /// The {{keyParamName}} header + /// + {{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}{{^-last}},{{/-last}} + {{/apiKeyMethods}} + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + {{>visibility}} static string ApiKeyHeaderToString(ApiKeyHeader value) + { + {{#net80OrLater}} + return value switch + { + {{#apiKeyMethods}} + ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}} => "{{keyParamName}}", + {{/apiKeyMethods}} + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + {{/net80OrLater}} + {{^net80OrLater}} + switch(value) + { + {{#apiKeyMethods}} + case ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}: + return "{{keyParamName}}"; + {{/apiKeyMethods}} + default: + throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)); + } + {{/net80OrLater}} + } + + {{/hasApiKeyMethods}} /// /// Returns true when deserialization succeeds. /// diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateFormats.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateFormats.mustache new file mode 100644 index 000000000000..920ecda88fad --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateFormats.mustache @@ -0,0 +1,2 @@ + "yyyy'-'MM'-'dd", + "yyyyMMdd" diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyJsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyJsonConverter.mustache new file mode 100644 index 000000000000..209979c8db42 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyJsonConverter.mustache @@ -0,0 +1,51 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache new file mode 100644 index 000000000000..17c847365369 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateOnlyNullableJsonConverter.mustache @@ -0,0 +1,56 @@ +{{>partial_header}} +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace {{packageName}}.{{clientPackage}} +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + {{>visibility}} class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { +{{>DateFormats}} + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(){{nrt!}}; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("{{{dateFormat}}}", CultureInfo.InvariantCulture)); + } + } +} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeFormats.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeFormats.mustache index c8887e208599..85ed99a2c9e7 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeFormats.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeFormats.mustache @@ -6,7 +6,9 @@ "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + {{^supportsDateOnly}} "yyyy'-'MM'-'dd", + {{/supportsDateOnly}} "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -15,4 +17,6 @@ "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" \ No newline at end of file + {{^supportsDateOnly}} + "yyyyMMdd" + {{/supportsDateOnly}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeJsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeJsonConverter.mustache index 21d35ec23027..c5187f50815d 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeJsonConverter.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeJsonConverter.mustache @@ -7,7 +7,7 @@ using System.Text.Json.Serialization; namespace {{packageName}}.{{clientPackage}} { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// {{>visibility}} class DateTimeJsonConverter : JsonConverter diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache index 52e2afa0b7ae..646c729478d2 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DateTimeNullableJsonConverter.mustache @@ -7,7 +7,7 @@ using System.Text.Json.Serialization; namespace {{packageName}}.{{clientPackage}} { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for {{#supportsDateOnly}}'date-time'{{/supportsDateOnly}}{{^supportsDateOnly}}'date' and 'date-time'{{/supportsDateOnly}} openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// {{>visibility}} class DateTimeNullableJsonConverter : JsonConverter diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DependencyInjectionTests.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DependencyInjectionTests.mustache index bdee56df2812..9f7b2ea2b3ff 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DependencyInjectionTests.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/DependencyInjectionTests.mustache @@ -16,93 +16,145 @@ namespace {{packageName}}.Test.{{apiPackage}} /// public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).Configure{{apiName}}((context, services, options) => { - {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - {{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - {{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - {{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - {{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken);{{/hasOAuthMethods}} + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).Configure{{apiName}}((context, services, options) => + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).Configure{{apiName}}((context, services, options) => { - {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - {{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - {{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - {{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - {{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken);{{/hasOAuthMethods}} + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} options.Add{{apiName}}HttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).ConfigureServices((host, services) => { services.Add{{apiName}}(options => { - {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - {{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - {{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - {{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - {{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken);{{/hasOAuthMethods}} + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder({{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}Array.Empty(){{/net80OrLater}}).ConfigureServices((host, services) => { services.Add{{apiName}}(options => { - {{#hasApiKeyMethods}}ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - {{/hasApiKeyMethods}}{{#hasHttpBearerMethods}} - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - {{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - {{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - {{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken);{{/hasOAuthMethods}} + {{#lambda.trimTrailingWithNewLine}} + {{#apiKeyMethods}} + ApiKeyToken apiKeyToken{{-index}} = new{{^net70OrLater}} ApiKeyToken{{/net70OrLater}}("", ClientUtils.ApiKeyHeader.{{#lambda.titlecase}}{{keyParamName}}{{/lambda.titlecase}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken{{-index}}); + + {{/apiKeyMethods}} + {{#httpBearerMethods}} + BearerToken bearerToken{{-index}} = new{{^net70OrLater}} BearerToken{{/net70OrLater}}("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken{{-index}}); + + {{/httpBearerMethods}} + {{#httpBasicMethods}} + BasicToken basicToken{{-index}} = new{{^net70OrLater}} BasicToken{{/net70OrLater}}("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken{{-index}}); + + {{/httpBasicMethods}} + {{#httpSignatureMethods}} + HttpSigningConfiguration config{{-index}} = new{{^net70OrLater}} HttpSigningConfiguration{{/net70OrLater}}("", "", null, {{#net80OrLater}}[]{{/net80OrLater}}{{^net80OrLater}}new List(){{/net80OrLater}}, HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken{{-index}} = new{{^net70OrLater}} HttpSignatureToken{{/net70OrLater}}(config{{-index}}, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken{{-index}}); + + {{/httpSignatureMethods}} + {{#oauthMethods}} + OAuthToken oauthToken{{-index}} = new{{^net70OrLater}} OAuthToken{{/net70OrLater}}("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken{{-index}}); + + {{/oauthMethods}} + {{/lambda.trimTrailingWithNewLine}} options.Add{{apiName}}HttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) @@ -116,7 +168,7 @@ namespace {{packageName}}.Test.{{apiPackage}} { {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} - + {{/-last}}{{/apis}}{{/apiInfo}} } @@ -128,7 +180,7 @@ namespace {{packageName}}.Test.{{apiPackage}} { {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingConfigureWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} - + {{/-last}}{{/apis}}{{/apiInfo}} } @@ -152,7 +204,7 @@ namespace {{packageName}}.Test.{{apiPackage}} { {{#apiInfo}}{{#apis}}var {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}} = _hostUsingAddWithoutAClient.Services.GetRequiredService<{{interfacePrefix}}{{classname}}>(); Assert.True({{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}.HttpClient.BaseAddress != null);{{^-last}} - + {{/-last}}{{/apis}}{{/apiInfo}} } } diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache index 1e848862a8bb..d7d1e3bf3a8c 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/HostConfiguration.mustache @@ -35,6 +35,10 @@ namespace {{packageName}}.{{clientPackage}} _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + {{#supportsDateOnly}} + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); + {{/supportsDateOnly}} {{#models}} {{#model}} {{#isEnum}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache index e2aa6a74d6a5..e136dd4d5be1 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/JsonConverter.mustache @@ -38,7 +38,7 @@ JsonTokenType startingTokenType = utf8JsonReader.TokenType; {{#allVars}} - {{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = default; + Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}> {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = default; {{#-last}} {{/-last}} @@ -167,39 +167,39 @@ {{^isMap}} {{^isEnum}} {{^isUuid}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.GetString(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.GetString(){{^isNullable}}{{nrt!}}{{/isNullable}}); {{/isUuid}} {{/isEnum}} {{/isMap}} {{/isString}} {{#isBoolean}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.GetBoolean(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.GetBoolean()); {{/isBoolean}} {{#isNumeric}} {{^isEnum}} {{#isDouble}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.GetDouble(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.GetDouble()); {{/isDouble}} {{#isDecimal}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.GetDecimal(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.GetDecimal()); {{/isDecimal}} {{#isFloat}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = (float)utf8JsonReader.GetDouble(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}(float)utf8JsonReader.GetDouble()); {{/isFloat}} {{#isLong}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int64(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int64()); {{/isLong}} {{^isLong}} {{^isFloat}} {{^isDecimal}} {{^isDouble}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); {{/isDouble}} {{/isDecimal}} {{/isFloat}} @@ -208,36 +208,34 @@ {{/isNumeric}} {{#isDate}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{#supportsDateOnly}}DateOnly{{/supportsDateOnly}}{{^supportsDateOnly}}DateTime{{/supportsDateOnly}}{{#isNullable}}?{{/isNullable}}>(ref utf8JsonReader, jsonSerializerOptions)); {{/isDate}} {{#isDateTime}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); {{/isDateTime}} {{#isEnum}} {{^isMap}} {{#isNumeric}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = ({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}})utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}({{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}})utf8JsonReader.Get{{#vendorExtensions.x-unsigned}}U{{/vendorExtensions.x-unsigned}}Int32()); {{/isNumeric}} {{^isNumeric}} string{{nrt?}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = utf8JsonReader.GetString(); {{^isInnerEnum}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue == null - ? null - : {{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue != null) + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}{{{datatypeWithEnum}}}ValueConverter.FromStringOrDefault({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue)); {{/isInnerEnum}} {{#isInnerEnum}} - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue == null - ? null - : {{classname}}.{{{datatypeWithEnum}}}FromStringOrDefault({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue != null) + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}{{classname}}.{{{datatypeWithEnum}}}FromStringOrDefault({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue)); {{/isInnerEnum}} {{/isNumeric}} {{/isMap}} {{/isEnum}} {{#isUuid}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = utf8JsonReader.GetGuid(); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}utf8JsonReader.GetGuid()); {{/isUuid}} {{^isUuid}} {{^isEnum}} @@ -247,7 +245,7 @@ {{^isDate}} {{^isDateTime}} if (utf8JsonReader.TokenType != JsonTokenType.Null) - {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref utf8JsonReader, jsonSerializerOptions); + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} = {{>OptionProperty}}JsonSerializer.Deserialize<{{{datatypeWithEnum}}}>(ref utf8JsonReader, jsonSerializerOptions){{^isNullable}}{{nrt!}}{{/isNullable}}); {{/isDateTime}} {{/isDate}} {{/isNumeric}} @@ -263,10 +261,17 @@ } } + {{#allVars}} + {{#required}} + if (!{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}.IsSet) + throw new ArgumentException("Property is required for class {{classname}}.", nameof({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}})); + + {{/required}} + {{/allVars}} {{#allVars}} {{^isNullable}} - if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} == null) - throw new ArgumentNullException(nameof({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}), "Property is required for class {{classname}}."); + if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}.IsSet && {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}.Value == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}), "Property is not nullable for class {{classname}}."); {{/isNullable}} {{/allVars}} @@ -275,7 +280,7 @@ {{#model.hasDiscriminatorWithNonEmptyMapping}} {{#mappedModels}} if ({{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}} != null) - return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/allVars}}{{/lambda.joinWithComma}}); + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/allVars}}{{/lambda.joinWithComma}}); {{#-last}} throw new JsonException(); @@ -284,13 +289,23 @@ {{/model.hasDiscriminatorWithNonEmptyMapping}} {{/model.discriminator}} {{^composedSchemas.oneOf}} - return new {{classname}}({{#lambda.joinWithComma}}{{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/allVars}}{{/lambda.joinWithComma}}); + {{^required}} + {{#model.composedSchemas.anyOf}} + Option<{{baseType}}{{>NullConditionalProperty}}> {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}ParsedValue = {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}} == null + ? default + : new Option<{{baseType}}{{>NullConditionalProperty}}>({{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}); + {{/model.composedSchemas.anyOf}} + {{#-last}} + + {{/-last}} + {{/required}} + return new {{classname}}({{#lambda.joinWithComma}}{{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}ParsedValue{{#required}}.Value{{^isNullable}}{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#required}}.Value{{nrt!}}{{^isNullable}}{{#vendorExtensions.x-is-value-type}}.Value{{nrt!}}{{/vendorExtensions.x-is-value-type}}{{/isNullable}}{{/required}} {{/allVars}}{{/lambda.joinWithComma}}); {{/composedSchemas.oneOf}} {{^model.discriminator}} {{#composedSchemas}} {{#oneOf}} if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} != null) - return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/allVars}}{{/lambda.joinWithComma}}); + return new {{classname}}({{#lambda.joinWithComma}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{#model.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#vendorExtensions.x-is-value-type}}{{^isNullable}}.Value{{/isNullable}}{{/vendorExtensions.x-is-value-type}} {{/model.composedSchemas.anyOf}}{{#allVars}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#required}}ParsedValue{{/required}} {{/allVars}}{{/lambda.joinWithComma}}); {{#-last}} throw new JsonException(); @@ -328,10 +343,10 @@ {{^model.discriminator}} {{#composedSchemas}} {{#anyOf}} - if ({{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}} != null) + if ({{#lambda.joinWithAmpersand}}{{^required}}{{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}Option.IsSet {{/required}}{{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}{{^required}}Option.Value{{/required}} != null{{/lambda.joinWithAmpersand}}) { - {{datatypeWithEnum}}JsonConverter {{datatypeWithEnum}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}.GetType())); - {{datatypeWithEnum}}JsonConverter.WriteProperties(ref writer, {{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}, jsonSerializerOptions); + {{datatypeWithEnum}}JsonConverter {{datatypeWithEnum}}JsonConverter = ({{datatypeWithEnum}}JsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert({{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}{{^required}}Option.Value{{/required}}.GetType())); + {{datatypeWithEnum}}JsonConverter.WriteProperties(ref writer, {{#lambda.camelcase_param}}{{model.classname}}{{/lambda.camelcase_param}}.{{datatypeWithEnum}}{{^required}}Option.Value{{/required}}, jsonSerializerOptions); } {{/anyOf}} @@ -354,97 +369,104 @@ {{#lambda.trimTrailingWithNewLine}} {{#lambda.trimLineBreaks}} {{#allVars}} + {{^isNullable}} + {{#vendorExtensions.x-is-reference-type}} + if ({{^required}}{{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.IsSet && {{/required}}{{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} == null) + throw new ArgumentNullException(nameof({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}), "Property is required for class {{classname}}."); + + {{/vendorExtensions.x-is-reference-type}} + {{/isNullable}} + {{/allVars}} + {{#allVars}} {{#isString}} {{^isMap}} {{^isEnum}} {{^isUuid}} + {{#lambda.copy}} writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isUuid}} {{/isEnum}} {{/isMap}} {{/isString}} {{#isBoolean}} - {{#isNullable}} - - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) - writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); - else - writer.WriteNull("{{baseName}}"); - - {{/isNullable}} - {{^isNullable}} - writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); - {{/isNullable}} + {{#lambda.copy}} + writer.WriteBoolean("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isBoolean}} {{^isEnum}} {{#isNumeric}} - {{#isNullable}} - - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) - writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); - else - writer.WriteNull("{{baseName}}"); - - {{/isNullable}} - {{^isNullable}} - writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); - {{/isNullable}} + {{#lambda.copy}} + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isNumeric}} {{/isEnum}} {{#isDate}} - {{#isNullable}} - - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value.ToString({{name}}Format)); - else - writer.WriteNull("{{baseName}}"); - - {{/isNullable}} - {{^isNullable}} - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.ToString({{name}}Format)); - {{/isNullable}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isDate}} {{#isDateTime}} - {{#isNullable}} - - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value.ToString({{name}}Format)); - else - writer.WriteNull("{{baseName}}"); - - {{/isNullable}} - {{^isNullable}} - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.ToString({{name}}Format)); - {{/isNullable}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}.ToString({{name}}Format)); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isDateTime}} {{#isEnum}} {{#isNumeric}} - writer.WriteNumber("{{baseName}}", {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}})); + {{#lambda.copy}} + writer.WriteNumber("{{baseName}}", {{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}})); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isNumeric}} {{^isMap}} {{^isNumeric}} {{#isInnerEnum}} - - var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); + {{#isNullable}} + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); if ({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue != null) writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); else writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{classname}}.{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}{{nrt!}}.Value{{/isNullable}}{{/required}}); + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue); + {{/isNullable}} {{/isInnerEnum}} {{^isInnerEnum}} + {{#lambda.copy}} + {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue + {{/lambda.copy}} + {{#required}} {{#isNullable}} - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} == null) writer.WriteNull("{{baseName}}"); else { - var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{#isNullable}}.Value{{/isNullable}}); + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); {{#allowableValues}} {{#enumVars}} {{#-first}} {{#isString}} - if ({{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue != null){{! we cant use name here because enumVar also has a name property, so use the camel case variant only as a work around }} + if ({{#lambda.pasteLine}}{{/lambda.pasteLine}} != null){{! we cant use name here because enumVar also has a name property, so use the paste lambda instead }} writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue); else writer.WriteNull("{{baseName}}"); @@ -456,44 +478,53 @@ {{/enumVars}} {{/allowableValues}} } - {{/isNullable}} {{^isNullable}} - var {{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{#isNullable}}.Value{{/isNullable}}); + var {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}RawValue = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); {{#allowableValues}} {{#enumVars}} {{#-first}} {{#isString}} - - if ({{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue != null) - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue); - else - writer.WriteNull("{{baseName}}"); - + writer.WriteString("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}); {{/isString}} {{^isString}} - writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_param}}{{nameInCamelCase}}{{/lambda.camelcase_param}}RawValue); + writer.WriteNumber("{{baseName}}", {{#lambda.camelcase_param}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/lambda.camelcase_param}}RawValue); {{/isString}} {{/-first}} {{/enumVars}} {{/allowableValues}} {{/isNullable}} + + {{/required}} + {{^required}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option{{nrt!}}.Value != null) + { + var {{#lambda.pasteLine}}{{/lambda.pasteLine}} = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.Value{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{#isString}}WriteString {{/isString}}{{^isString}}WriteNumber {{/isString}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + var {{#lambda.pasteLine}}{{/lambda.pasteLine}} = {{{datatypeWithEnum}}}ValueConverter.ToJsonValue({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{nrt!}}.Value); + writer.{{#lambda.first}}{{#allowableValues}}{{#enumVars}}{{#isString}}WriteString {{/isString}}{{^isString}}WriteNumber {{/isString}}{{/enumVars}}{{/allowableValues}}{{/lambda.first}}("{{baseName}}", {{#lambda.pasteLine}}{{/lambda.pasteLine}}); + } + {{/isNullable}} + {{/required}} {{/isInnerEnum}} {{/isNumeric}} {{/isMap}} {{/isEnum}} {{#isUuid}} - {{^isNullable}} - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}); - {{/isNullable}} - {{#isNullable}} - - if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} == null) - writer.WriteNull("{{baseName}}"); - else - writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}.Value); - - {{/isNullable}} + {{#lambda.copy}} + writer.WriteString("{{baseName}}", {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{#vendorExtensions.x-is-value-type}}{{nrt!}}.Value{{/vendorExtensions.x-is-value-type}}{{/required}}{{#required}}{{#isNullable}}.Value{{/isNullable}}{{/required}}); + {{/lambda.copy}} + {{#lambda.indent3}} + {{>WriteProperty}} + {{/lambda.indent3}} {{/isUuid}} {{^isUuid}} {{^isEnum}} @@ -502,8 +533,39 @@ {{^isNumeric}} {{^isDate}} {{^isDateTime}} + {{#required}} + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}} != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} writer.WritePropertyName("{{baseName}}"); JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, jsonSerializerOptions); + {{/isNullable}} + {{/required}} + {{^required}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.IsSet) + {{#isNullable}} + if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.Value != null) + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, jsonSerializerOptions); + } + else + writer.WriteNull("{{baseName}}"); + {{/isNullable}} + {{^isNullable}} + { + writer.WritePropertyName("{{baseName}}"); + JsonSerializer.Serialize(writer, {{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}, jsonSerializerOptions); + } + {{/isNullable}} + {{/required}} {{/isDateTime}} {{/isDate}} {{/isNumeric}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelBaseSignature.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelBaseSignature.mustache index 3a1e7c35d69c..b5a2c08ac29c 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelBaseSignature.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelBaseSignature.mustache @@ -1 +1 @@ -{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{#isInherited}}{{^isNew}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/isNew}}{{#isNew}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}){{/isEnum}}{{^isEnum}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}.ToString(){{/isEnum}}{{/isNew}} {{/isInherited}}{{/allVars}} \ No newline at end of file +{{#parentModel.composedSchemas.anyOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{#isArray}}{{{dataFormat}}}{{/isArray}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.anyOf}}{{#allVars}}{{#isInherited}}{{^isNew}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/isNew}}{{#isNew}}{{#isEnum}}{{#isInnerEnum}}{{classname}}.{{/isInnerEnum}}{{{datatypeWithEnum}}}ToJsonValue({{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{^required}}.Value{{/required}}){{/isEnum}}{{^isEnum}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}.ToString(){{/isEnum}}{{/isNew}} {{/isInherited}}{{/allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelSignature.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelSignature.mustache index 0e7bbc90e6bc..faa8273bf2bd 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelSignature.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ModelSignature.mustache @@ -1 +1 @@ -{{#model.allVars}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#defaultValue}} = {{^isDateTime}}{{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}{{{defaultValue}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/defaultValue}}{{^defaultValue}}{{#isNullable}} = default{{/isNullable}}{{/defaultValue}} {{/model.allVars}} \ No newline at end of file +{{#model.allVars}}{{^required}}Option<{{/required}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{#defaultValue}} = {{^required}}default{{/required}}{{#required}}{{^isDateTime}}{{#isString}}{{^isEnum}}@{{/isEnum}}{{/isString}}{{{.}}}{{/isDateTime}}{{#isDateTime}}default{{/isDateTime}}{{/required}}{{/defaultValue}}{{^defaultValue}}{{#lambda.first}}{{#isNullable}} = default {{/isNullable}}{{^required}} = default {{/required}}{{/lambda.first}}{{/defaultValue}} {{/model.allVars}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/Option.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/Option.mustache index 8e0d888a2244..eed49143e41d 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/Option.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/Option.mustache @@ -31,5 +31,17 @@ namespace {{packageName}}.{{clientPackage}} IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/OptionProperty.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/OptionProperty.mustache new file mode 100644 index 000000000000..d7504188775e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/OptionProperty.mustache @@ -0,0 +1 @@ +new Option<{{#isInnerEnum}}{{^isMap}}{{classname}}.{{/isMap}}{{/isInnerEnum}}{{{datatypeWithEnum}}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}}>( \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/README.client.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/README.client.mustache index b071c0cbe699..2f74977652dd 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/README.client.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/README.client.mustache @@ -80,14 +80,18 @@ namespace YourProject public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .Configure{{apiName}}((context, options) => { - {{#authMethods}}// the type of token here depends on the api security specifications - ApiKeyToken token = new(""); + {{#authMethods}} + {{#-first}} + // the type of token here depends on the api security specifications + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); options.AddTokens(token); // optionally choose the method the tokens will be provided with, default is RateLimitProvider options.UseProvider, ApiKeyToken>(); - {{/authMethods}}options.ConfigureJsonOptions((jsonOptions) => + {{/-first}} + {{/authMethods}} + options.ConfigureJsonOptions((jsonOptions) => { // your custom converters if any }); diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/RateLimitProvider`1.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/RateLimitProvider`1.mustache index 5de00d6acf19..a2294050f0da 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/RateLimitProvider`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/RateLimitProvider`1.mustache @@ -4,14 +4,17 @@ #nullable enable {{/nrt}} -using System;{{^netStandard}} -using System.Threading.Channels;{{/netStandard}}{{#netStandard}} -using System.Collections.Concurrent; +using System; +using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks;{{/netStandard}} - -namespace {{packageName}}.{{clientPackage}} {{^netStandard}} +{{^netStandard}} +using System.Threading.Channels; +{{/netStandard}} +{{#netStandard}} +using System.Threading.Channels; +{{/netStandard}} + +namespace {{packageName}}.{{clientPackage}} { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -19,7 +22,7 @@ namespace {{packageName}}.{{clientPackage}} {{^netStandard}} /// {{>visibility}} class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new{{^net70OrLater}} Dictionary>{{/net70OrLater}}(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -30,78 +33,49 @@ namespace {{packageName}}.{{clientPackage}} {{^netStandard}} foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite + {{#lambda.copy}} + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite }; - AvailableTokens = Channel.CreateBounded(options); - - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); - } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); - } -} {{/netStandard}}{{#netStandard}} -{ - /// - /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. - /// - /// - public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase - { - internal ConcurrentDictionary AvailableTokens = new ConcurrentDictionary(); - private SemaphoreSlim _semaphore; - - /// - /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. - /// - /// - public RateLimitProvider(TokenContainer container) : base(container.Tokens) - { - _semaphore = new SemaphoreSlim(1, 1); - - foreach(TTokenBase token in _tokens) - token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - - for (int i = 0; i < _tokens.Length; i++) + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + {{/lambda.copy}} + {{#hasApiKeyMethods}} + if (container is TokenContainer apiKeyTokenContainer) { - _tokens[i].TokenBecameAvailable += ((sender) => - { - TTokenBase token = (TTokenBase)sender; - - AvailableTokens.TryAdd(token, token); - }); - } - } - - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) - { - await _semaphore.WaitAsync().ConfigureAwait(false); + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); - try - { - TTokenBase result = null; - - while (result == null) + foreach (string header in headers) { - TTokenBase tokenToRemove = AvailableTokens.FirstOrDefault().Value; - - if (tokenToRemove != null && AvailableTokens.TryRemove(tokenToRemove, out result)) - return result; + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; - await Task.Delay(40).ConfigureAwait(false); - - tokenToRemove = AvailableTokens.FirstOrDefault().Value; + AvailableTokens.Add(header, Channel.CreateBounded(options)); } - - return result; } - finally + else { - _semaphore.Release(); + {{#lambda.indent1}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/lambda.indent1}} } + {{/hasApiKeyMethods}} + {{^hasApiKeyMethods}} + {{#lambda.pasteLine}}{{/lambda.pasteLine}} + {{/hasApiKeyMethods}} + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}) + { + if (!AvailableTokens.TryGetValue(header, out Channel{{nrt?}} tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } } -}{{/netStandard}} +} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/TokenProvider`1.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/TokenProvider`1.mustache index 5ab2143e9a3a..5297254675f1 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/TokenProvider`1.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/TokenProvider`1.mustache @@ -21,7 +21,7 @@ namespace {{packageName}} /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default{{^netstandard20OrLater}}(System.Threading.CancellationToken){{/netstandard20OrLater}}); /// /// Instantiates a TokenProvider. diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ValidateRegex.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ValidateRegex.mustache new file mode 100644 index 000000000000..78aba8fb3456 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/ValidateRegex.mustache @@ -0,0 +1,7 @@ +// {{{name}}} ({{{dataType}}}) pattern +Regex regex{{{name}}} = new Regex(@"{{{vendorExtensions.x-regex}}}"{{#vendorExtensions.x-modifiers}}{{#-first}}, {{/-first}}RegexOptions.{{{.}}}{{^-last}} | {{/-last}}{{/vendorExtensions.x-modifiers}}); +{{#lambda.copy}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null && {{/lambda.copy}} +if ({{#lambda.first}}{{^required}}{{#lambda.pasteLine}}{{/lambda.pasteLine}} {{/required}}{{#isNullable}}{{#lambda.pasteLine}}{{/lambda.pasteLine}}{{/isNullable}}{{/lambda.first}}!regex{{{name}}}.Match(this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}}{{#isUuid}}.ToString(){{#lambda.first}}{{^required}}{{nrt!}} {{/required}}{{#isNullable}}! {{/isNullable}}{{/lambda.first}}{{/isUuid}}).Success) +{ + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must match a pattern of " + regex{{{name}}}, new [] { "{{{name}}}" }); +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WriteProperty.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WriteProperty.mustache new file mode 100644 index 000000000000..6c9192d85977 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WriteProperty.mustache @@ -0,0 +1,9 @@ +{{#required}} +{{>WritePropertyHelper}} +{{/required}} +{{^required}} +if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}Option.IsSet) + {{#lambda.indent1}} + {{>WritePropertyHelper}} + {{/lambda.indent1}} +{{/required}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WritePropertyHelper.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WritePropertyHelper.mustache new file mode 100644 index 000000000000..8c8e7b4a704a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/WritePropertyHelper.mustache @@ -0,0 +1,9 @@ +{{#isNullable}} +if ({{#lambda.camelcase_param}}{{classname}}{{/lambda.camelcase_param}}.{{name}}{{^required}}Option.Value{{/required}} != null) + {{#lambda.pasteLine}}{{/lambda.pasteLine}} +else + writer.WriteNull("{{baseName}}"); +{{/isNullable}} +{{^isNullable}} +{{#lambda.pasteLine}}{{/lambda.pasteLine}} +{{/isNullable}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache index 596a25eaec93..337f0f32598c 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/api.mustache @@ -7,6 +7,17 @@ {{/nrt}} using System; using System.Collections.Generic; +{{#net80OrLater}} +{{#lambda.uniqueLines}} +{{#operations}} +{{#operation}} +{{#vendorExtensions.x-set-cookie}} +using System.Linq; +{{/vendorExtensions.x-set-cookie}} +{{/operation}} +{{/operations}} +{{/lambda.uniqueLines}} +{{/net80OrLater}} using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -44,10 +55,13 @@ namespace {{packageName}}.{{apiPackage}} /// /// Thrown when fails to make API call {{#allParams}} - /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} /// Cancellation Token to cancel the request. /// <> + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} Task<{{interfacePrefix}}{{operationId}}ApiResponse> {{operationId}}Async({{>OperationSignature}}); /// @@ -57,10 +71,13 @@ namespace {{packageName}}.{{apiPackage}} /// {{notes}} /// {{#allParams}} - /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}} + /// {{description}}{{^required}} (optional{{#defaultValue}}, default to {{.}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} {{/allParams}} /// Cancellation Token to cancel the request. /// <{{nrt?}}> + {{#isDeprecated}} + [Obsolete] + {{/isDeprecated}} Task<{{interfacePrefix}}{{operationId}}ApiResponse{{nrt?}}> {{operationId}}OrDefaultAsync({{>OperationSignature}}); {{^-last}} @@ -183,6 +200,19 @@ namespace {{packageName}}.{{apiPackage}} /// public TokenProvider OauthTokenProvider { get; }{{/hasOAuthMethods}} + {{#net80OrLater}} + {{#lambda.unique}} + {{#operation}} + {{#vendorExtensions.x-set-cookie}} + /// + /// The token cookie container + /// + public {{packageName}}.{{clientPackage}}.CookieContainer CookieContainer { get; } + + {{/vendorExtensions.x-set-cookie}} + {{/operation}} + {{/lambda.unique}} + {{/net80OrLater}} /// /// Initializes a new instance of the class. /// @@ -192,7 +222,8 @@ namespace {{packageName}}.{{apiPackage}} TokenProvider bearerTokenProvider{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}}, TokenProvider basicTokenProvider{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}}, TokenProvider httpSignatureTokenProvider{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}}, - TokenProvider oauthTokenProvider{{/hasOAuthMethods}}) + TokenProvider oauthTokenProvider{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}}, + {{packageName}}.{{clientPackage}}.CookieContainer cookieContainer{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}}) { _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; LoggerFactory = loggerFactory; @@ -203,7 +234,8 @@ namespace {{packageName}}.{{apiPackage}} BearerTokenProvider = bearerTokenProvider;{{/hasHttpBearerMethods}}{{#hasHttpBasicMethods}} BasicTokenProvider = basicTokenProvider;{{/hasHttpBasicMethods}}{{#hasHttpSignatureMethods}} HttpSignatureTokenProvider = httpSignatureTokenProvider;{{/hasHttpSignatureMethods}}{{#hasOAuthMethods}} - OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}} + OauthTokenProvider = oauthTokenProvider;{{/hasOAuthMethods}}{{#net80OrLater}}{{#operation}}{{#lambda.uniqueLines}}{{#vendorExtensions.x-set-cookie}} + CookieContainer = cookieContainer;{{/vendorExtensions.x-set-cookie}}{{/lambda.uniqueLines}}{{/operation}}{{/net80OrLater}} } {{#operation}} @@ -359,17 +391,10 @@ namespace {{packageName}}.{{apiPackage}} {{/-first}} {{/servers}} {{#pathParams}} - {{#required}} uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7B{{baseName}}%7D", Uri.EscapeDataString({{paramName}}.ToString())); - {{/required}} - {{^required}} - - if ({{paramName}}.IsSet) - uriBuilderLocalVar.Path = uriBuilderLocalVar.Path + $"/{ Uri.EscapeDataString({{paramName}}.Value).ToString()) }"; {{#-last}} {{/-last}} - {{/required}} {{/pathParams}} {{#queryParams}} {{#-first}} @@ -468,61 +493,60 @@ namespace {{packageName}}.{{apiPackage}} {{#authMethods}} {{#-first}} List tokenBaseLocalVars = new List(); - {{/-first}} {{#isApiKey}} - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + {{^isKeyInCookie}} + ApiKeyToken apiKeyTokenLocalVar{{-index}} = (ApiKeyToken) await ApiKeyProvider.GetAsync("{{keyParamName}}", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar{{-index}}); + {{#isKeyInHeader}} + apiKeyTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar); - tokenBaseLocalVars.Add(apiKeyTokenLocalVar);{{#isKeyInHeader}} - - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); {{/isKeyInHeader}} + {{/isKeyInCookie}} {{#isKeyInQuery}} - apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "{{keyParamName}}"); + apiKeyTokenLocalVar{{-index}}.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); {{/isKeyInQuery}} {{/isApiKey}} {{/authMethods}} - - {{! below line must be after any UseInQuery calls, but before using the HttpSignatureToken}} httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; {{#authMethods}} {{#isBasicBasic}} - BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BasicToken basicTokenLocalVar{{-index}} = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(basicTokenLocalVar); + tokenBaseLocalVars.Add(basicTokenLocalVar{{-index}}); - basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + basicTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); {{/isBasicBasic}} {{#isBasicBearer}} - BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BearerToken bearerTokenLocalVar{{-index}} = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(bearerTokenLocalVar); + tokenBaseLocalVars.Add(bearerTokenLocalVar{{-index}}); - bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + bearerTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); {{/isBasicBearer}} {{#isOAuth}} - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar{{-index}} = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar{{-index}}); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); + oauthTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, "{{keyParamName}}"); {{/isOAuth}} {{#isHttpSignature}} - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar{{-index}} = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar{{-index}}); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync({{#net60OrLater}}cancellationToken{{/net60OrLater}}).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar{{-index}}.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } {{/isHttpSignature}} {{/authMethods}} @@ -595,6 +619,39 @@ namespace {{packageName}}.{{apiPackage}} {{/-first}} {{/authMethods}} + {{#net80OrLater}} + {{#responses}} + {{#vendorExtensions.x-set-cookie}} + if (httpResponseMessageLocalVar.StatusCode == (HttpStatusCode) {{code}} && httpResponseMessageLocalVar.Headers.TryGetValues("Set-Cookie", out var cookieHeadersLocalVar)) + { + foreach(string cookieHeader in cookieHeadersLocalVar) + { + IList setCookieHeaderValuesLocalVar = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeadersLocalVar.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValueLocalVar in setCookieHeaderValuesLocalVar) + { + Cookie cookieLocalVar = new Cookie(setCookieHeaderValueLocalVar.Name.ToString(), setCookieHeaderValueLocalVar.Value.ToString()) + { + HttpOnly = setCookieHeaderValueLocalVar.HttpOnly + }; + + if (setCookieHeaderValueLocalVar.Expires.HasValue) + cookieLocalVar.Expires = setCookieHeaderValueLocalVar.Expires.Value.UtcDateTime; + + if (setCookieHeaderValueLocalVar.Path.HasValue) + cookieLocalVar.Path = setCookieHeaderValueLocalVar.Path.Value; + + if (setCookieHeaderValueLocalVar.Domain.HasValue) + cookieLocalVar.Domain = setCookieHeaderValueLocalVar.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilderLocalVar.Scheme}://{uriBuilderLocalVar.Host}"), cookieLocalVar); + } + } + } + + {{/vendorExtensions.x-set-cookie}} + {{/responses}} + {{/net80OrLater}} return apiResponseLocalVar; } } diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache index f11dd9ba2b06..f9931574dcf5 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/model.mustache @@ -26,8 +26,8 @@ using OpenAPIClientUtils = {{packageName}}.Client.ClientUtils; {{#useGenericHost}} {{#useSourceGeneration}} using System.Text.Json.Serialization.Metadata; -using {{packageName}}.{{clientPackage}}; {{/useSourceGeneration}} +using {{packageName}}.{{clientPackage}}; {{/useGenericHost}} {{#models}} {{#lambda.trimTrailingWithNewLine}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/modelGeneric.mustache index 5667892c0b11..62ed3f172abe 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/generichost/modelGeneric.mustache @@ -15,19 +15,19 @@ {{#allVars}} /// {{description}}{{^description}}{{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}{{/description}}{{#defaultValue}} (default to {{.}}){{/defaultValue}} {{/allVars}} - {{#model.vendorExtensions.x-model-is-mutatable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutatable}}{{^model.vendorExtensions.x-model-is-mutatable}}internal{{/model.vendorExtensions.x-model-is-mutatable}} {{classname}}({{#lambda.joinWithComma}}{{{dataType}}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} {{#model.composedSchemas.anyOf}}{{{dataType}}}{{>NullConditionalProperty}} {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}} {{/model.composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + {{#model.vendorExtensions.x-model-is-mutatable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutatable}}{{^model.vendorExtensions.x-model-is-mutatable}}internal{{/model.vendorExtensions.x-model-is-mutatable}} {{classname}}({{#lambda.joinWithComma}}{{{dataType}}} {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}} {{#model.composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{dataType}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}} {{/model.composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{#parentModel.composedSchemas.oneOf}}{{#lambda.camelcase_param}}{{parent}}{{/lambda.camelcase_param}}.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{/parentModel.composedSchemas.oneOf}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} { {{#composedSchemas.anyOf}} - {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}; + {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}; {{/composedSchemas.anyOf}} {{name}} = {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}}; {{#allVars}} {{^isInherited}} - {{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{name}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/isInherited}} {{#isInherited}} {{#isNew}} - {{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{name}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/isNew}} {{/isInherited}} {{/allVars}} @@ -49,18 +49,18 @@ {{^composedSchemas.anyOf}} [JsonConstructor] {{/composedSchemas.anyOf}} - {{#model.vendorExtensions.x-model-is-mutatable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutatable}}{{^model.vendorExtensions.x-model-is-mutatable}}internal{{/model.vendorExtensions.x-model-is-mutatable}} {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.anyOf}}{{{name}}}{{>NullConditionalProperty}} {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}} {{/composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} + {{#model.vendorExtensions.x-model-is-mutatable}}{{>visibility}}{{/model.vendorExtensions.x-model-is-mutatable}}{{^model.vendorExtensions.x-model-is-mutatable}}internal{{/model.vendorExtensions.x-model-is-mutatable}} {{classname}}({{#lambda.joinWithComma}}{{#composedSchemas.anyOf}}{{^required}}Option<{{/required}}{{{name}}}{{>NullConditionalProperty}}{{^required}}>{{/required}} {{#lambda.camelcase_param}}{{baseType}}{{/lambda.camelcase_param}} {{/composedSchemas.anyOf}}{{>ModelSignature}}{{/lambda.joinWithComma}}){{#parent}} : base({{#lambda.joinWithComma}}{{>ModelBaseSignature}}{{/lambda.joinWithComma}}){{/parent}} { {{#composedSchemas.anyOf}} - {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{#lambda.titlecase}}{{name}}{{/lambda.titlecase}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/composedSchemas.anyOf}} {{#allVars}} {{^isInherited}} - {{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{name}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/isInherited}} {{#isInherited}} {{#isNew}} - {{name}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; + {{name}}{{^required}}Option{{/required}} = {{#lambda.camelcase_param}}{{name}}{{/lambda.camelcase_param}}; {{/isNew}} {{/isInherited}} {{/allVars}} @@ -84,6 +84,15 @@ {{/complexType}} {{/isEnum}} {{#isEnum}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} /// /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} /// @@ -97,12 +106,21 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{#isNew}}new {{/isNew}}{{{datatypeWithEnum}}}{{>NullConditionalProperty}} {{name}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + public {{#isNew}}new {{/isNew}}{{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{name}}Option; } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} {{/isEnum}} {{/vars}} {{#composedSchemas.anyOf}} {{^vendorExtensions.x-duplicated-data-type}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public {{#isNew}}new {{/isNew}}Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} /// /// {{description}}{{^description}}Gets or Sets {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}{{/description}} /// {{#description}} @@ -113,7 +131,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{{dataType}}}{{>NullConditionalProperty}} {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}Option; } {{^isReadOnly}}set { this.{{#lambda.titlecase}}{{baseType}}{{/lambda.titlecase}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} {{/vendorExtensions.x-duplicated-data-type}} {{/composedSchemas.anyOf}} @@ -137,6 +155,15 @@ {{^isEnum}} {{#isInherited}} {{#isNew}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public new Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} /// /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} /// {{#description}} @@ -148,11 +175,20 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public new {{{datatypeWithEnum}}}{{>NullConditionalProperty}} {{name}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + public new {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this.{{name}}Option } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} {{/isNew}} {{/isInherited}} {{^isInherited}} + {{^required}} + /// + /// Used to track the state of {{{name}}} + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}> {{name}}Option { get; {{^isReadOnly}}private set; {{/isReadOnly}}} + + {{/required}} /// /// {{description}}{{^description}}Gets or Sets {{{name}}}{{/description}} /// {{#description}} @@ -164,7 +200,7 @@ {{#deprecated}} [Obsolete] {{/deprecated}} - public {{{datatypeWithEnum}}}{{>NullConditionalProperty}} {{name}} { get; {{^isReadOnly}}set; {{/isReadOnly}}} + public {{{datatypeWithEnum}}}{{#lambda.first}}{{#isNullable}}{{>NullConditionalProperty}} {{/isNullable}}{{^required}}{{nrt?}}{{^nrt}}{{#vendorExtensions.x-is-value-type}}?{{/vendorExtensions.x-is-value-type}}{{/nrt}} {{/required}}{{/lambda.first}} {{name}} {{#required}}{ get; {{^isReadOnly}}set; {{/isReadOnly}}}{{/required}}{{^required}}{ get { return this. {{name}}Option; } {{^isReadOnly}}set { this.{{name}}Option = new{{^net70OrLater}} Option<{{{datatypeWithEnum}}}{{>NullConditionalProperty}}>{{/net70OrLater}}(value); } {{/isReadOnly}}}{{/required}} {{/isInherited}} {{/isEnum}} @@ -274,16 +310,24 @@ int hashCode = 41; {{/parent}} {{#readOnlyVars}} + {{#required}} {{^isNullable}} hashCode = (hashCode * 59) + {{name}}.GetHashCode(); {{/isNullable}} + {{/required}} {{/readOnlyVars}} {{#readOnlyVars}} - {{#isNullable}} + {{#lambda.copy}} if ({{name}} != null) hashCode = (hashCode * 59) + {{name}}.GetHashCode(); + {{/lambda.copy}} + {{#isNullable}} + {{#lambda.pasteOnce}}{{/lambda.pasteOnce}} {{/isNullable}} + {{^required}} + {{#lambda.pasteOnce}}{{/lambda.pasteOnce}} + {{/required}} {{/readOnlyVars}} {{#isAdditionalPropertiesTrue}} {{^parentModel}} diff --git a/modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache b/modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache index 021fcb79a383..9bed800e40d6 100644 --- a/modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/libraries/httpclient/ApiClient.mustache @@ -91,14 +91,38 @@ namespace {{packageName}}.Client /// Object representation of the JSON string. internal async Task Deserialize(HttpResponseMessage response, Type type) { - IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); + IList headers = new List(); + // process response headers, e.g. Access-Control-Allow-Methods + foreach (var responseHeader in response.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // process response content headers, e.g. Content-Type + foreach (var responseHeader in response.Content.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + // RFC 2183 & RFC 2616 + var fileNameRegex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$", RegexOptions.IgnoreCase); if (type == typeof(byte[])) // return byte array { return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } else if (type == typeof(FileParameter)) { + if (headers != null) { + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + return new FileParameter(fileName, await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + } + } return new FileParameter(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); } @@ -111,10 +135,10 @@ namespace {{packageName}}.Client var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; - var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) { - var match = regex.Match(header.ToString()); + var match = fileNameRegex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); diff --git a/modules/openapi-generator/src/main/resources/csharp/modelInnerEnum.mustache b/modules/openapi-generator/src/main/resources/csharp/modelInnerEnum.mustache index e2b628ebe5ae..462ded84dc17 100644 --- a/modules/openapi-generator/src/main/resources/csharp/modelInnerEnum.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/modelInnerEnum.mustache @@ -74,12 +74,17 @@ {{#isString}} /// {{/isString}} - public static {{>EnumValueDataType}} {{datatypeWithEnum}}ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}} value) + public static {{>EnumValueDataType}}{{#lambda.first}}{{#nrt}}{{#isString}}{{#isNullable}}{{nrt?}} {{^nrt}}{{#vendorExtensions.x-is-value-type}}? {{/vendorExtensions.x-is-value-type}}{{/nrt}}{{/isNullable}}{{/isString}}{{/nrt}}{{/lambda.first}} {{datatypeWithEnum}}ToJsonValue({{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}{{#isString}}{{>NullConditionalProperty}}{{/isString}} value) { {{^isString}} return ({{>EnumValueDataType}}) value; {{/isString}} {{#isString}} + {{#isNullable}} + if (value == null) + return null; + + {{/isNullable}} {{#allowableValues}} {{#enumVars}} if (value == {{datatypeWithEnum}}{{^datatypeWithEnum}}{{classname}}{{/datatypeWithEnum}}.{{name}}) diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache index f75341eaeb82..aa6c35c6d4f7 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_project.mustache @@ -25,7 +25,7 @@ {{#useCompareNetObjects}} - {{! leave at this version until this is fixed https://github.com/GregFinzer/Compare-Net-Objects/issues/282 }} + {{/useCompareNetObjects}} {{^useGenericHost}} @@ -35,15 +35,21 @@ {{/useRestSharp}} {{#useGenericHost}} - - + + {{#supportsRetry}} - + {{/supportsRetry}} + {{#net80OrLater}} + + {{/net80OrLater}} + {{#netStandard}} + + {{/netStandard}} {{/useGenericHost}} {{^useGenericHost}} {{#supportsRetry}} - + {{/supportsRetry}} {{/useGenericHost}} {{#validatable}} diff --git a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache index af6c36c28a36..e6a375fc01f0 100644 --- a/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/netcore_testproject.mustache @@ -9,9 +9,9 @@ - - - + + + diff --git a/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache b/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache index 356b9079d076..18fe4aacc874 100644 --- a/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/nuspec.mustache @@ -42,7 +42,7 @@ {{/validatable}} {{#supportsRetry}} - + {{/supportsRetry}} diff --git a/modules/openapi-generator/src/main/resources/csharp/validatable.mustache b/modules/openapi-generator/src/main/resources/csharp/validatable.mustache index 2352d0d55178..b06b98fc636c 100644 --- a/modules/openapi-generator/src/main/resources/csharp/validatable.mustache +++ b/modules/openapi-generator/src/main/resources/csharp/validatable.mustache @@ -78,7 +78,7 @@ {{/minLength}} {{#maximum}} // {{{name}}} ({{{dataType}}}) maximum - if (this.{{{name}}} > ({{{dataType}}}){{maximum}}) + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} > ({{{dataType}}}){{maximum}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value less than or equal to {{maximum}}.", new [] { "{{{name}}}" }); } @@ -86,7 +86,7 @@ {{/maximum}} {{#minimum}} // {{{name}}} ({{{dataType}}}) minimum - if (this.{{{name}}} < ({{{dataType}}}){{minimum}}) + if ({{#useGenericHost}}{{^required}}this.{{{name}}}Option.IsSet && {{/required}}{{/useGenericHost}}this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} < ({{{dataType}}}){{minimum}}) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for {{{name}}}, must be a value greater than or equal to {{minimum}}.", new [] { "{{{name}}}" }); } @@ -96,7 +96,7 @@ {{^isByteArray}} {{#vendorExtensions.x-is-value-type}} {{#isNullable}} - if (this.{{{name}}} != null){ + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null){ {{#lambda.trimTrailingWithNewLine}} {{#lambda.indent4}} {{>ValidateRegex}} @@ -116,7 +116,7 @@ {{/isNullable}} {{/vendorExtensions.x-is-value-type}} {{^vendorExtensions.x-is-value-type}} - if (this.{{{name}}} != null) { + if (this.{{{name}}}{{#useGenericHost}}{{^required}}Option.Value{{/required}}{{/useGenericHost}} != null) { {{#lambda.trimTrailingWithNewLine}} {{#lambda.indent4}} {{>ValidateRegex}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/analysis_options.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/analysis_options.mustache index 865b3404b402..b625c648d600 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/analysis_options.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/analysis_options.mustache @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart{{#useJsonSerializable}} - lib/{{sourceFolder}}/model/*.g.dart{{/useJsonSerializable}} diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache index e1201880b0c9..03255f3eee86 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/pubspec.mustache @@ -10,7 +10,7 @@ publish_to: {{.}} {{/pubPublishTo}} environment: - sdk: '>=2.15.0 <3.0.0' + sdk: '>={{#useJsonSerializable}}2.17.0{{/useJsonSerializable}}{{^useJsonSerializable}}2.15.0{{/useJsonSerializable}} <3.0.0' dependencies: dio: '^5.2.0' diff --git a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum.mustache b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum.mustache index dbb1ed2cd22a..118fb8fc573b 100644 --- a/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum.mustache +++ b/modules/openapi-generator/src/main/resources/dart/libraries/dio/serialization/json_serializable/enum.mustache @@ -11,7 +11,14 @@ enum {{{classname}}} { /// {{{.}}} {{/description}} @JsonValue({{#isString}}r{{/isString}}{{{value}}}) - {{{name}}}, + {{{name}}}({{^isString}}'{{/isString}}{{#isString}}r{{/isString}}{{{value}}}{{^isString}}'{{/isString}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/enumVars}} {{/allowableValues}} + + const {{{classname}}}(this.value); + + final String value; + + @override + String toString() => value; } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache index 37c3775eb158..99fd8c67458a 100644 --- a/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-echo-server/api.mustache @@ -1,9 +1,9 @@ package handlers {{#operations}} import ( - "{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}/models" - "github.com/labstack/echo/v4" - "net/http" + "{{{gitHost}}}/{{{gitUserId}}}/{{{gitRepoId}}}/models" + "github.com/labstack/echo/v4" + "net/http" ){{#operation}} // {{nickname}} - {{{summary}}} @@ -11,8 +11,8 @@ import ( // Deprecated {{/isDeprecated}} func (c *Container) {{operationId}}(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } -{{/operation}}{{/operations}} \ No newline at end of file +{{/operation}}{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache index 330a32f51534..2e4aa441e22c 100644 --- a/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache +++ b/modules/openapi-generator/src/main/resources/go-echo-server/handler-container.mustache @@ -6,6 +6,6 @@ type Container struct { // NewContainer returns an empty or an initialized container for your handlers. func NewContainer() (Container, error) { - c := Container{} - return c, nil -} \ No newline at end of file + c := Container{} + return c, nil +} diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache index 98b4d20cb613..b939ad04f792 100644 --- a/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache +++ b/modules/openapi-generator/src/main/resources/go-echo-server/hello-world.mustache @@ -2,5 +2,5 @@ package models // HelloWorld is a sample data structure to make sure each endpoint return something. type HelloWorld struct { - Message string `json:"message"` -} \ No newline at end of file + Message string `json:"message"` +} diff --git a/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache index 000243ea05d1..879c6bbb0d60 100644 --- a/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache +++ b/modules/openapi-generator/src/main/resources/go-echo-server/main.mustache @@ -9,7 +9,7 @@ import ( func main() { e := echo.New() - //todo: handle the error! + //todo: handle the error! c, _ := handlers.NewContainer() // Middleware @@ -23,4 +23,4 @@ func main() { // Start server e.Logger.Fatal(e.Start(":{{serverPort}}")) -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache b/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache index 197da1c3312c..e480e2394a88 100644 --- a/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache +++ b/modules/openapi-generator/src/main/resources/go-gin-server/controller-api.mustache @@ -7,12 +7,18 @@ import ( ) type {{classname}} struct { +} + {{#operation}} - // {{httpMethod}} {{{basePathWithoutHost}}}{{{path}}} - // {{{summary}}} +// {{httpMethod}} {{{basePathWithoutHost}}}{{{path}}}{{#summary}} +// {{{.}}} {{/summary}} {{#isDeprecated}} - // Deprecated +// Deprecated {{/isDeprecated}} - {{nickname}} gin.HandlerFunc +func (api *{{classname}}) {{nickname}}(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + {{/operation}} -}{{/operations}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/go-gin-server/routers.mustache b/modules/openapi-generator/src/main/resources/go-gin-server/routers.mustache index d99c4429f622..a2b758c69cc4 100644 --- a/modules/openapi-generator/src/main/resources/go-gin-server/routers.mustache +++ b/modules/openapi-generator/src/main/resources/go-gin-server/routers.mustache @@ -51,17 +51,24 @@ func DefaultHandleFunc(c *gin.Context) { type ApiHandleFunctions struct { {{#apiInfo}}{{#apis}}{{#operations}} // Routes for the {{classname}} part of the API - {{classname}} {{classname}}{{/operations}}{{/apis}}{{/apiInfo}} + {{classname}} {{classname}}{{/operations}}{{/apis}}{{/apiInfo}}{{#webhooks}}{{#operations}} + {{classname}} {{classname}}{{/operations}}{{/webhooks}} } func getRoutes(handleFunctions ApiHandleFunctions) []Route { - return []Route{ - {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} + return []Route{ {{#apiInfo}}{{#apis}}{{#operations}}{{#operation}} { "{{operationId}}", http.Method{{httpMethod}}, "{{{basePathWithoutHost}}}{{{path}}}", handleFunctions.{{classname}}.{{operationId}}, - },{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + },{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}}{{#webhooks}}{{#operations}}{{#operation}} + // webhook handler (adjust path accordingly) + { + "{{operationId}}", + http.Method{{httpMethod}}, + "{{{basePathWithoutHost}}}{{{path}}}", + handleFunctions.{{classname}}.{{operationId}}, + },{{/operation}}{{/operations}}{{/webhooks}} } } diff --git a/modules/openapi-generator/src/main/resources/go-server/api.mustache b/modules/openapi-generator/src/main/resources/go-server/api.mustache index da459dc40e0f..edec16bd4cfa 100644 --- a/modules/openapi-generator/src/main/resources/go-server/api.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/api.mustache @@ -28,5 +28,5 @@ type {{classname}}Servicer interface { {{#operations}}{{#operation}} {{#isDeprecated}} // Deprecated {{/isDeprecated}} - {{operationId}}(context.Context{{#allParams}}, {{dataType}}{{/allParams}}) (ImplResponse, error){{/operation}}{{/operations}} + {{operationId}}(context.Context{{#allParams}}, {{#isNullable}}*{{/isNullable}}{{dataType}}{{/allParams}}) (ImplResponse, error){{/operation}}{{/operations}} }{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache b/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache index 00fec257d6e8..73b495c31103 100644 --- a/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/controller-api.mustache @@ -1,16 +1,19 @@ {{>partial_header}} package {{packageName}} +{{#operations}} import ( "encoding/json" - {{#isBodyParam}} - {{^required}} + {{#isBodyParam}} + {{^required}} "errors" "io" - {{/required}} - {{/isBodyParam}} + {{/required}} + {{/isBodyParam}} "net/http" "strings" +{{#imports}} "{{import}}" + {{/imports}} {{#routers}} {{#mux}} @@ -21,6 +24,7 @@ import ( {{/chi}} {{/routers}} ) +{{/operations}} // {{classname}}Controller binds http requests to an api service and writes the service results to the http response type {{classname}}Controller struct { @@ -168,12 +172,34 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re return } {{/isInteger}} + {{#isDateTime}} + {{paramName}}Param, err := parseTime({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + {{/isDateTime}} {{^isNumber}} {{^isFloat}} {{^isDouble}} {{^isLong}} {{^isInteger}} + {{^isDateTime}} + {{^isEnumRef}} {{paramName}}Param := {{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}} + if {{paramName}}Param == "" { + c.errorHandler(w, r, &RequiredError{"{{baseName}}"}, nil) + return + } + {{/isEnumRef}} + {{#isEnumRef}} + {{paramName}}Param, err := New{{dataType}}FromValue({{#routers}}{{#mux}}params["{{baseName}}"]{{/mux}}{{#chi}}chi.URLParam(r, "{{baseName}}"){{/chi}}{{/routers}}) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + {{/isEnumRef}} + {{/isDateTime}} {{/isInteger}} {{/isLong}} {{/isDouble}} @@ -181,86 +207,189 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{/isNumber}} {{/isPathParam}} {{#isQueryParam}} + {{#isDateTime}} + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}time.Time + if query.Has("{{baseName}}"){ + param, err := parseTime(query.Get("{{baseName}}")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{"{{baseName}}"}, nil) + return + {{/required}} + } + {{/isDateTime}} {{#isNumber}} - {{paramName}}Param, err := parseNumericParameter[float32]( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[float32]({{defaultValue}}, parseFloat32),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[float32](parseFloat32),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[float32](parseFloat32),{{/required}}{{/defaultValue}}{{#minimum}} - WithMinimum[float32]({{minimum}}),{{/minimum}}{{#maximum}} - WithMaximum[float32]({{maximum}}),{{/maximum}} - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}float32 + if query.Has("{{baseName}}") { + param, err := parseNumericParameter[float32]( + query.Get("{{baseName}}"), + WithParse[float32](parseFloat32),{{#minimum}} + WithMinimum[float32]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[float32]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param float32 = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isNumber}} {{#isFloat}} - {{paramName}}Param, err := parseNumericParameter[float32]( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[float32]({{defaultValue}}, parseFloat32),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[float32](parseFloat32),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[float32](parseFloat32),{{/required}}{{/defaultValue}}{{#minimum}} - WithMinimum[float32]({{minimum}}),{{/minimum}}{{#maximum}} - WithMaximum[float32]({{maximum}}),{{/maximum}} - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}float32 + if query.Has("{{baseName}}") { + param, err := parseNumericParameter[float32]( + query.Get("{{baseName}}"), + WithParse[float32](parseFloat32),{{#minimum}} + WithMinimum[float32]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[float32]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param float32 = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isFloat}} {{#isDouble}} - {{paramName}}Param, err := parseNumericParameter[float64]( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[float64]({{defaultValue}}, parseFloat64),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[float64](parseFloat64),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[float64](parseFloat64),{{/required}}{{/defaultValue}}{{#minimum}} - WithMinimum[float64]({{minimum}}),{{/minimum}}{{#maximum}} - WithMaximum[float64]({{maximum}}),{{/maximum}} - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}float64 + if query.Has("{{baseName}}") { + param, err := parseNumericParameter[float64]( + query.Get("{{baseName}}"), + WithParse[float64](parseFloat64),{{#minimum}} + WithMinimum[float64]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[float64]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param float64 = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isDouble}} {{#isLong}} - {{paramName}}Param, err := parseNumericParameter[int64]( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[int64]({{defaultValue}}, parseInt64),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[int64](parseInt64),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[int64](parseInt64),{{/required}}{{/defaultValue}}{{#minimum}} - WithMinimum[int64]({{minimum}}),{{/minimum}}{{#maximum}} - WithMaximum[int64]({{maximum}}),{{/maximum}} - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}int64 + if query.Has("{{baseName}}") { + param, err := parseNumericParameter[int64]( + query.Get("{{baseName}}"), + WithParse[int64](parseInt64),{{#minimum}} + WithMinimum[int64]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[int64]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param int64 = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isLong}} {{#isInteger}} - {{paramName}}Param, err := parseNumericParameter[int32]( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[int32]({{defaultValue}}, parseInt32),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[int32](parseInt32),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[int32](parseInt32),{{/required}}{{/defaultValue}}{{#minimum}} - WithMinimum[int32]({{minimum}}),{{/minimum}}{{#maximum}} - WithMaximum[int32]({{maximum}}),{{/maximum}} - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}int32 + if query.Has("{{baseName}}") { + param, err := parseNumericParameter[int32]( + query.Get("{{baseName}}"), + WithParse[int32](parseInt32),{{#minimum}} + WithMinimum[int32]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[int32]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param int32 = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isInteger}} {{#isBoolean}} - {{paramName}}Param, err := parseBoolParameter( - query.Get("{{baseName}}"),{{#defaultValue}} - WithDefaultOrParse[bool]({{defaultValue}}, parseBool),{{/defaultValue}}{{^defaultValue}}{{#required}} - WithRequire[bool](parseBool),{{/required}}{{/defaultValue}}{{^defaultValue}}{{^required}} - WithParse[bool](parseBool),{{/required}}{{/defaultValue}} - ) - if err != nil { - w.WriteHeader(500) + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}bool + if query.Has("{{baseName}}") { + param, err := parseBoolParameter( + query.Get("{{baseName}}"), + WithParse[bool](parseBool),{{#minimum}} + WithMinimum[bool]({{minimum}}),{{/minimum}}{{#maximum}} + WithMaximum[bool]({{maximum}}),{{/maximum}} + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) return + {{/required}} + {{^required}} + {{#defaultValue}} + var param bool = {{defaultValue}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } {{/isBoolean}} {{#isArray}} @@ -324,12 +453,39 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re return } {{/items.isInteger}} + {{#items.isDateTime}} + {{paramName}}Param, err := parseTimes(query.Get("{{baseName"}})) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + {{/items.isDateTime}} {{^items.isNumber}} {{^items.isFloat}} {{^items.isDouble}} {{^items.isLong}} {{^items.isInteger}} - {{paramName}}Param := strings.Split(query.Get("{{baseName}}"), ",") + {{^items.isEnumRef}} + var {{paramName}}Param []string + if query.Has("{{baseName}}") { + {{paramName}}Param = strings.Split(query.Get("{{baseName}}"), ",") + } + {{/items.isEnumRef}} + {{#items.isEnumRef}} + var {{paramName}}Param []{{items.dataType}} + if query.Has("{{baseName}}") { + paramSplits := strings.Split(query.Get("{{baseName}}"), ",") + {{paramName}}Param = make([]{{items.dataType}}, 0, len(paramSplits)) + for _, param := range paramSplits { + paramEnum, err := New{{items.dataType}}FromValue(param) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + {{paramName}}Param = append({{paramName}}Param, paramEnum) + } + } + {{/items.isEnumRef}} {{/items.isInteger}} {{/items.isLong}} {{/items.isDouble}} @@ -343,15 +499,25 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{^isInteger}} {{^isBoolean}} {{^isArray}} - {{#defaultValue}} - {{paramName}}Param := "{{defaultValue}}" + {{^isDateTime}} + var {{paramName}}Param {{#isNullable}}*{{/isNullable}}{{dataType}} if query.Has("{{baseName}}") { - {{paramName}}Param = query.Get("{{baseName}}") + param := {{^isString}}{{dataType}}({{/isString}}query.Get("{{baseName}}"){{^isString}}){{/isString}} + + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + } else { + {{#required}} + c.errorHandler(w, r, &RequiredError{Field: "{{baseName}}"}, nil) + return + {{/required}} + {{^required}} + {{#defaultValue}} + param := {{^isString}}{{dataType}}({{/isString}}{{defaultValue}}{{^isString}}){{/isString}} + {{paramName}}Param = {{#isNullable}}&{{/isNullable}}param + {{/defaultValue}} + {{/required}} } - {{/defaultValue}} - {{^defaultValue}} - {{paramName}}Param := query.Get("{{baseName}}") - {{/defaultValue}} + {{/isDateTime}} {{/isArray}} {{/isBoolean}} {{/isInteger}} @@ -361,13 +527,21 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{/isNumber}} {{/isQueryParam}} {{#isFormParam}} - {{#isFile}}{{#isArray}} - {{paramName}}Param, err := ReadFormFilesToTempFiles(r, "{{baseName}}"){{/isArray}}{{^isArray}} - {{paramName}}Param, err := ReadFormFileToTempFile(r, "{{baseName}}") - {{/isArray}} - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return + {{#isFile}} + var {{paramName}}Param {{#isArray}}[]*os.File{{/isArray}}{{^isArray}}*os.File{{/isArray}} + { + {{#isArray}} + param, err := ReadFormFilesToTempFiles(r, "{{baseName}}") + {{/isArray}} + {{^isArray}} + param, err := ReadFormFileToTempFile(r, "{{baseName}}") + {{/isArray}} + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + {{paramName}}Param = param } {{/isFile}} {{#isLong}}{{#isArray}} @@ -396,7 +570,12 @@ func (c *{{classname}}Controller) {{nickname}}(w http.ResponseWriter, r *http.Re {{/isArray}}{{/isInteger}} {{^isFile}} {{^isLong}} + {{#isArray}} + {{paramName}}Param := strings.Split(r.FormValue("{{baseName}}"), ",") + {{/isArray}} + {{^isArray}} {{paramName}}Param := r.FormValue("{{baseName}}") + {{/isArray}} {{/isLong}} {{/isFile}} {{/isFormParam}} diff --git a/modules/openapi-generator/src/main/resources/go-server/model.mustache b/modules/openapi-generator/src/main/resources/go-server/model.mustache index f94a100a1913..ce00067fc0b5 100644 --- a/modules/openapi-generator/src/main/resources/go-server/model.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/model.mustache @@ -17,7 +17,44 @@ const ( {{#enumClassPrefix}}{{{classname.toUpperCase}}}_{{/enumClassPrefix}}{{name}} {{{classname}}} = {{{value}}} {{/enumVars}} {{/allowableValues}} -){{/isEnum}}{{^isEnum}}{{#description}} +) + +// Allowed{{{classname}}}EnumValues is all the allowed values of {{{classname}}} enum +var Allowed{{{classname}}}EnumValues = []{{{classname}}}{ + {{#allowableValues}} + {{#enumVars}} + {{{value}}}, + {{/enumVars}} + {{/allowableValues}} +} + +// valid{{{classname}}}EnumValue provides a map of {{classname}}s for fast verification of use input +var valid{{{classname}}}EnumValues = map[{{{classname}}}]struct{}{ + {{#allowableValues}} + {{#enumVars}} + {{{value}}}: {}, + {{/enumVars}} + {{/allowableValues}} +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v {{{classname}}}) IsValid() bool { + _, ok := valid{{{classname}}}EnumValues[v] + return ok +} + +// New{{{classname}}}FromValue returns a pointer to a valid {{{classname}}} +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func New{{{classname}}}FromValue(v {{{format}}}{{^format}}{{dataType}}{{/format}}) ({{{classname}}}, error) { + ev := {{{classname}}}(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for {{{classname}}}: valid values are %v", v, Allowed{{{classname}}}EnumValues) + } +} + +{{/isEnum}}{{^isEnum}}{{#description}} // {{classname}} - {{{description}}}{{/description}} type {{classname}} struct { {{#parent}} diff --git a/modules/openapi-generator/src/main/resources/go-server/routers.mustache b/modules/openapi-generator/src/main/resources/go-server/routers.mustache index 166eb257f8a8..3fe075ec2400 100644 --- a/modules/openapi-generator/src/main/resources/go-server/routers.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/routers.mustache @@ -4,6 +4,7 @@ package {{packageName}} import ( "encoding/json" "errors" + "time" {{#routers}} {{#mux}} "github.com/gorilla/mux" @@ -19,7 +20,7 @@ import ( {{/featureCORS}} {{/chi}} {{/routers}} - "io/ioutil" + "io" "mime/multipart" "net/http" "os" @@ -89,18 +90,33 @@ func NewRouter(routers ...Router) {{#routers}}{{#mux}}*mux.Router{{/mux}}{{#chi} // EncodeJSONResponse uses the json encoder to write an interface to the http response with an optional status code func EncodeJSONResponse(i interface{}, status *int,{{#addResponseHeaders}} headers map[string][]string,{{/addResponseHeaders}} w http.ResponseWriter) error { - {{#addResponseHeaders}} wHeader := w.Header() + {{#addResponseHeaders}} for key, values := range headers { for _, value := range values { wHeader.Add(key, value) } } - wHeader.Set("Content-Type", "application/json; charset=UTF-8") - {{/addResponseHeaders}} - {{^addResponseHeaders}} - w.Header().Set("Content-Type", "application/json; charset=UTF-8") {{/addResponseHeaders}} + + f, ok := i.(*os.File) + if ok { + data, err := io.ReadAll(f) + if err != nil { + return err + } + wHeader.Set("Content-Type", http.DetectContentType(data)) + wHeader.Set("Content-Disposition", "attachment; filename="+f.Name()) + if status != nil { + w.WriteHeader(*status) + } else { + w.WriteHeader(http.StatusOK) + } + _, err = w.Write(data) + return err + } + wHeader.Set("Content-Type", "application/json; charset=UTF-8") + if status != nil { w.WriteHeader(*status) } else { @@ -153,21 +169,42 @@ func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error defer formFile.Close() - fileBytes, err := ioutil.ReadAll(formFile) + // Use .* as suffix, because the asterisk is a placeholder for the random value, + // and the period allows consumers of this file to remove the suffix to obtain the original file name + file, err := os.CreateTemp("", fileHeader.Filename+".*") if err != nil { return nil, err } - file, err := ioutil.TempFile("", fileHeader.Filename) + defer file.Close() + + _, err = io.Copy(file, formFile) if err != nil { return nil, err } + + return file, nil +} - defer file.Close() - - file.Write(fileBytes) +func parseTimes(param string) ([]time.Time, error) { + splits := strings.Split(param, ",") + times := make([]time.Time, 0, len(splits)) + for _, v := range splits { + t, err := parseTime(v) + if err != nil { + return nil, err + } + times = append(times, t) + } + return times, nil +} - return file, nil +// parseTime will parses a string parameter into a time.Time using the RFC3339 format +func parseTime(param string) (time.Time, error) { + if param == "" { + return time.Time{}, nil + } + return time.Parse(time.RFC3339, param) } type Number interface { diff --git a/modules/openapi-generator/src/main/resources/go-server/service.mustache b/modules/openapi-generator/src/main/resources/go-server/service.mustache index 9fb0f66c0b2c..799c68237397 100644 --- a/modules/openapi-generator/src/main/resources/go-server/service.mustache +++ b/modules/openapi-generator/src/main/resources/go-server/service.mustache @@ -23,7 +23,7 @@ func New{{classname}}Service() {{classname}}Servicer { {{#isDeprecated}} // Deprecated {{/isDeprecated}} -func (s *{{classname}}Service) {{nickname}}(ctx context.Context{{#allParams}}, {{paramName}} {{dataType}}{{/allParams}}) (ImplResponse, error) { +func (s *{{classname}}Service) {{nickname}}(ctx context.Context{{#allParams}}, {{paramName}} {{#isNullable}}*{{/isNullable}}{{dataType}}{{/allParams}}) (ImplResponse, error) { // TODO - update {{nickname}} with the required logic for this service method. // Add {{classFilename}}_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. diff --git a/modules/openapi-generator/src/main/resources/go/README.mustache b/modules/openapi-generator/src/main/resources/go/README.mustache index fa3a0adf9e0f..6e98ea75f2bb 100644 --- a/modules/openapi-generator/src/main/resources/go/README.mustache +++ b/modules/openapi-generator/src/main/resources/go/README.mustache @@ -21,7 +21,7 @@ For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) Install the following dependencies: -```shell +```sh go get github.com/stretchr/testify/assert {{#hasOAuthMethods}} go get golang.org/x/oauth2 @@ -31,13 +31,13 @@ go get golang.org/x/net/context Put the package under your project folder and add the following in import: -```golang +```go import {{packageName}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}" ``` To use a proxy, set the environment variable `HTTP_PROXY`: -```golang +```go os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") ``` @@ -47,17 +47,17 @@ Default configuration comes with `Servers` field that contains server objects as ### Select Server Configuration -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. +For using other server than the one defined on index 0 set context value `{{packageName}}.ContextServerIndex` of type `int`. -```golang +```go ctx := context.WithValue(context.Background(), {{packageName}}.ContextServerIndex, 1) ``` ### Templated Server URL -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. +Templated server URL is formatted using default variables from configuration or from context value `{{packageName}}.ContextServerVariables` of type `map[string]string`. -```golang +```go ctx := context.WithValue(context.Background(), {{packageName}}.ContextServerVariables, map[string]string{ "basePath": "v2", }) @@ -69,9 +69,9 @@ Note, enum values are always validated and all unused variables are silently ign Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. +Similar rules for overriding default operation server index and variables applies by using `{{packageName}}.ContextOperationServerIndices` and `{{packageName}}.ContextOperationServerVariables` context maps. -```golang +```go ctx := context.WithValue(context.Background(), {{packageName}}.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -112,11 +112,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + {{packageName}}.ContextAPIKeys, + map[string]{{packageName}}.APIKey{ "{{keyParamName}}": {Key: "API_KEY_STRING"}, }, ) @@ -130,8 +130,8 @@ r, err := client.Service.Operation(auth, args) Example -```golang -auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARER_TOKEN_STRING") +```go +auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "BEARER_TOKEN_STRING") r, err := client.Service.Operation(auth, args) ``` @@ -141,10 +141,10 @@ r, err := client.Service.Operation(auth, args) Example -```golang -auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ - UserName: "username", - Password: "password", +```go +auth := context.WithValue(context.Background(), {{packageName}}.ContextBasicAuth, {{packageName}}.BasicAuth{ + UserName: "username", + Password: "password", }) r, err := client.Service.Operation(auth, args) ``` @@ -155,21 +155,21 @@ r, err := client.Service.Operation(auth, args) Example -```golang - authConfig := client.HttpSignatureAuth{ +```go + authConfig := {{packageName}}.HttpSignatureAuth{ KeyId: "my-key-id", PrivateKeyPath: "rsa.pem", Passphrase: "my-passphrase", - SigningScheme: sw.HttpSigningSchemeHs2019, + SigningScheme: {{packageName}}.HttpSigningSchemeHs2019, SignedHeaders: []string{ - sw.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - sw.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + {{packageName}}.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + {{packageName}}.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. "Date", // The date and time at which the message was originated. "Content-Type", // The Media type of the body of the request. "Digest", // A cryptographic digest of the request body. }, - SigningAlgorithm: sw.HttpSigningAlgorithmRsaPSS, + SigningAlgorithm: {{packageName}}.HttpSigningAlgorithmRsaPSS, SignatureMaxValidity: 5 * time.Minute, } var authCtx context.Context @@ -193,20 +193,20 @@ Example Example -```golang -auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING") +```go +auth := context.WithValue(context.Background(), {{packageName}}.ContextAccessToken, "ACCESSTOKENSTRING") r, err := client.Service.Operation(auth, args) ``` Or via OAuth2 module to automatically refresh tokens and perform user authentication. -```golang +```go import "golang.org/x/oauth2" /* Perform OAuth2 round trip request and obtain a token */ tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) -auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) +auth := context.WithValue(oauth2.NoContext, {{packageName}}.ContextOAuth2, tokenSource) r, err := client.Service.Operation(auth, args) ``` diff --git a/modules/openapi-generator/src/main/resources/go/api.mustache b/modules/openapi-generator/src/main/resources/go/api.mustache index fada916ff9cf..fe01e202b2cf 100644 --- a/modules/openapi-generator/src/main/resources/go/api.mustache +++ b/modules/openapi-generator/src/main/resources/go/api.mustache @@ -124,7 +124,7 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class } localVarPath := localBasePath + "{{{path}}}"{{#pathParams}} - localVarPath = strings.Replace(localVarPath, "{"+"{{baseName}}"+"}", url.PathEscape(parameterValueToString(r.{{paramName}}, "{{paramName}}")), -1){{/pathParams}} + localVarPath = strings.Replace(localVarPath, "{"+"{{{baseName}}}"+"}", url.PathEscape(parameterValueToString(r.{{paramName}}, "{{paramName}}")), -1){{/pathParams}} localVarHeaderParams := make(map[string]string) localVarQueryParams := url.Values{} @@ -189,15 +189,15 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class if reflect.TypeOf(t).Kind() == reflect.Slice { s := reflect.ValueOf(t) for i := 0; i < s.Len(); i++ { - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", s.Index(i).Interface(), "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", s.Index(i).Interface(), "{{collectionFormat}}") } } else { - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", t, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", t, "{{collectionFormat}}") } } {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") {{/isCollectionFormatMulti}} {{/required}} {{^required}} @@ -207,14 +207,14 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class if reflect.TypeOf(t).Kind() == reflect.Slice { s := reflect.ValueOf(t) for i := 0; i < s.Len(); i++ { - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", s.Index(i).Interface(), "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", s.Index(i).Interface(), "{{collectionFormat}}") } } else { - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", t, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", t, "{{collectionFormat}}") } {{/isCollectionFormatMulti}} {{^isCollectionFormatMulti}} - parameterAddToHeaderOrQuery(localVarQueryParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarQueryParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") {{/isCollectionFormatMulti}} {{#defaultValue}}} else { var defaultValue {{{dataType}}} = {{{.}}} @@ -245,23 +245,42 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class } {{#headerParams}} {{#required}} - parameterAddToHeaderOrQuery(localVarHeaderParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarHeaderParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") {{/required}} {{^required}} if r.{{paramName}} != nil { - parameterAddToHeaderOrQuery(localVarHeaderParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarHeaderParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") } {{/required}} {{/headerParams}} {{#formParams}} {{#isFile}} +{{#isArray}} var {{paramName}}LocalVarFormFileName string var {{paramName}}LocalVarFileName string var {{paramName}}LocalVarFileBytes []byte - {{paramName}}LocalVarFormFileName = "{{baseName}}" + {{paramName}}LocalVarFormFileName = "{{{baseName}}}" + {{paramName}}LocalVarFile := r.{{paramName}} + if {{paramName}}LocalVarFile != nil { + // loop through the array to prepare multiple files upload + for _, {{paramName}}LocalVarFileValue := range {{paramName}}LocalVarFile { + fbs, _ := io.ReadAll({{paramName}}LocalVarFileValue) + + {{paramName}}LocalVarFileBytes = fbs + {{paramName}}LocalVarFileName = {{paramName}}LocalVarFileValue.Name() + {{paramName}}LocalVarFileValue.Close() + formFiles = append(formFiles, formFile{fileBytes: {{paramName}}LocalVarFileBytes, fileName: {{paramName}}LocalVarFileName, formFileName: {{paramName}}LocalVarFormFileName}) + } + } +{{/isArray}} +{{^isArray}} + var {{paramName}}LocalVarFormFileName string + var {{paramName}}LocalVarFileName string + var {{paramName}}LocalVarFileBytes []byte + {{paramName}}LocalVarFormFileName = "{{{baseName}}}" {{paramName}}LocalVarFile := r.{{paramName}} if {{paramName}}LocalVarFile != nil { @@ -272,10 +291,11 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class {{paramName}}LocalVarFile.Close() formFiles = append(formFiles, formFile{fileBytes: {{paramName}}LocalVarFileBytes, fileName: {{paramName}}LocalVarFileName, formFileName: {{paramName}}LocalVarFormFileName}) } +{{/isArray}} {{/isFile}} {{^isFile}} {{#required}} - parameterAddToHeaderOrQuery(localVarFormParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarFormParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") {{/required}} {{^required}} {{#isModel}} @@ -284,12 +304,12 @@ func (a *{{{classname}}}Service) {{nickname}}Execute(r {{#structPrefix}}{{&class if err != nil { return {{#returnType}}localVarReturnValue, {{/returnType}}nil, err } - localVarFormParams.Add("{{baseName}}", paramJson) + localVarFormParams.Add("{{{baseName}}}", paramJson) } {{/isModel}} {{^isModel}} if r.{{paramName}} != nil { - parameterAddToHeaderOrQuery(localVarFormParams, "{{baseName}}", r.{{paramName}}, "{{collectionFormat}}") + parameterAddToHeaderOrQuery(localVarFormParams, "{{{baseName}}}", r.{{paramName}}, "{{collectionFormat}}") } {{/isModel}} {{/required}} diff --git a/modules/openapi-generator/src/main/resources/go/api_doc.mustache b/modules/openapi-generator/src/main/resources/go/api_doc.mustache index 623a15be4828..151baa937de5 100644 --- a/modules/openapi-generator/src/main/resources/go/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/go/api_doc.mustache @@ -26,31 +26,31 @@ Method | HTTP request | Description package main import ( - "context" - "fmt" - "os" + "context" + "fmt" + "os" {{#vendorExtensions.x-go-import}} {{{vendorExtensions.x-go-import}}} {{/vendorExtensions.x-go-import}} - {{goImportAlias}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}" + {{goImportAlias}} "{{gitHost}}/{{gitUserId}}/{{gitRepoId}}{{#isGoSubmodule}}/{{packageName}}{{/isGoSubmodule}}" ) func main() { - {{#allParams}} - {{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} - {{/allParams}} - - configuration := {{goImportAlias}}.NewConfiguration() - apiClient := {{goImportAlias}}.NewAPIClient(configuration) - {{#returnType}}resp, {{/returnType}}r, err := apiClient.{{classname}}.{{operationId}}(context.Background(){{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - {{#returnType}} - // response from `{{operationId}}`: {{{.}}} - fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp) - {{/returnType}} + {{#allParams}} + {{paramName}} := {{{vendorExtensions.x-go-example}}} // {{{dataType}}} | {{{description}}}{{^required}} (optional){{/required}}{{#defaultValue}} (default to {{{.}}}){{/defaultValue}} + {{/allParams}} + + configuration := {{goImportAlias}}.NewConfiguration() + apiClient := {{goImportAlias}}.NewAPIClient(configuration) + {{#returnType}}resp, {{/returnType}}r, err := apiClient.{{classname}}.{{operationId}}(context.Background(){{#pathParams}}, {{paramName}}{{/pathParams}}){{#allParams}}{{^isPathParam}}.{{vendorExtensions.x-export-param-name}}({{paramName}}){{/isPathParam}}{{/allParams}}.Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `{{classname}}.{{operationId}}``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + {{#returnType}} + // response from `{{operationId}}`: {{{.}}} + fmt.Fprintf(os.Stdout, "Response from `{{classname}}.{{operationId}}`: %v\n", resp) + {{/returnType}} } ``` diff --git a/modules/openapi-generator/src/main/resources/go/client.mustache b/modules/openapi-generator/src/main/resources/go/client.mustache index 3f6dcb7bf591..f1270b3c692d 100644 --- a/modules/openapi-generator/src/main/resources/go/client.mustache +++ b/modules/openapi-generator/src/main/resources/go/client.mustache @@ -33,8 +33,8 @@ import ( ) var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) ) @@ -528,7 +528,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = f.Seek(0, io.SeekStart) - err = os.Remove(f.Name()) return } if f, ok := v.(**os.File); ok { @@ -541,16 +540,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = (*f).Seek(0, io.SeekStart) - err = os.Remove((*f).Name()) return } - if xmlCheck.MatchString(contentType) { + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } - if jsonCheck.MatchString(contentType) { + if JsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { @@ -615,9 +613,9 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { + } else if XmlCheck.MatchString(contentType) { var bs []byte bs, err = xml.Marshal(body) if err == nil { diff --git a/modules/openapi-generator/src/main/resources/go/model_simple.mustache b/modules/openapi-generator/src/main/resources/go/model_simple.mustache index 84c8b3a9e7ca..64952edcae64 100644 --- a/modules/openapi-generator/src/main/resources/go/model_simple.mustache +++ b/modules/openapi-generator/src/main/resources/go/model_simple.mustache @@ -22,7 +22,7 @@ type {{classname}} struct { {{#deprecated}} // Deprecated {{/deprecated}} - {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{{baseName}}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{{baseName}}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` {{/vars}} {{#isAdditionalPropertiesTrue}} AdditionalProperties map[string]interface{} @@ -32,6 +32,12 @@ type {{classname}} struct { {{#isAdditionalPropertiesTrue}} type _{{{classname}}} {{{classname}}} +{{/isAdditionalPropertiesTrue}} +{{^isAdditionalPropertiesTrue}} +{{#hasRequired}} +type _{{{classname}}} {{{classname}}} + +{{/hasRequired}} {{/isAdditionalPropertiesTrue}} // New{{classname}} instantiates a new {{classname}} object // This constructor will assign default values to properties that have it defined, @@ -260,6 +266,7 @@ func (o *{{classname}}) Unset{{name}}() { {{/required}} {{/vars}} +{{#vendorExtensions.x-go-generate-marshal-json}} func (o {{classname}}) MarshalJSON() ([]byte, error) { toSerialize,err := o.ToMap() if err != nil { @@ -268,6 +275,7 @@ func (o {{classname}}) MarshalJSON() ([]byte, error) { return json.Marshal(toSerialize) } +{{/vendorExtensions.x-go-generate-marshal-json}} func (o {{classname}}) ToMap() (map[string]interface{}, error) { toSerialize := {{#isArray}}make([]interface{}, len(o.Items)){{/isArray}}{{^isArray}}map[string]interface{}{}{{/isArray}} {{#parent}} @@ -295,16 +303,16 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) { {{#vendorExtensions.x-golang-is-container}} {{! support for container fields is not ideal at this point because of lack of Nullable* types}} if o.{{name}} != nil { - toSerialize["{{baseName}}"] = o.{{name}} + toSerialize["{{{baseName}}}"] = o.{{name}} } {{/vendorExtensions.x-golang-is-container}} {{^vendorExtensions.x-golang-is-container}} {{#required}} - toSerialize["{{baseName}}"] = o.{{name}}.Get() + toSerialize["{{{baseName}}}"] = o.{{name}}.Get() {{/required}} {{^required}} if o.{{name}}.IsSet() { - toSerialize["{{baseName}}"] = o.{{name}}.Get() + toSerialize["{{{baseName}}}"] = o.{{name}}.Get() } {{/required}} {{/vendorExtensions.x-golang-is-container}} @@ -312,11 +320,11 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) { {{! if argument is not nullable, don't set it if it is nil}} {{^isNullable}} {{#required}} - toSerialize["{{baseName}}"] = o.{{name}} + toSerialize["{{{baseName}}}"] = o.{{name}} {{/required}} {{^required}} if !IsNil(o.{{name}}) { - toSerialize["{{baseName}}"] = o.{{name}} + toSerialize["{{{baseName}}}"] = o.{{name}} } {{/required}} {{/isNullable}} @@ -332,7 +340,39 @@ func (o {{classname}}) ToMap() (map[string]interface{}, error) { } {{#isAdditionalPropertiesTrue}} -func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { +func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { +{{/isAdditionalPropertiesTrue}} +{{^isAdditionalPropertiesTrue}} +{{#hasRequired}} +func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { +{{/hasRequired}} +{{/isAdditionalPropertiesTrue}} +{{#hasRequired}} + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ +{{#requiredVars}} + "{{baseName}}", +{{/requiredVars}} + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + +{{/hasRequired}} +{{#isAdditionalPropertiesTrue}} {{#parent}} {{^isMap}} type {{classname}}WithoutEmbeddedStruct struct { @@ -345,13 +385,13 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { {{#deprecated}} // Deprecated {{/deprecated}} - {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{baseName}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{baseName}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` + {{name}} {{^required}}{{^isNullable}}{{^isArray}}{{^isFreeFormObject}}*{{/isFreeFormObject}}{{/isArray}}{{/isNullable}}{{/required}}{{{dataType}}} `json:"{{{baseName}}}{{^required}},omitempty{{/required}}"{{#withXml}} xml:"{{{baseName}}}{{#isXmlAttribute}},attr{{/isXmlAttribute}}"{{/withXml}}{{#vendorExtensions.x-go-custom-tag}} {{{.}}}{{/vendorExtensions.x-go-custom-tag}}` {{/vars}} } var{{{classname}}}WithoutEmbeddedStruct := {{{classname}}}WithoutEmbeddedStruct{} - err = json.Unmarshal(bytes, &var{{{classname}}}WithoutEmbeddedStruct) + err = json.Unmarshal(data, &var{{{classname}}}WithoutEmbeddedStruct) if err == nil { var{{{classname}}} := _{{{classname}}}{} {{#vars}} @@ -364,7 +404,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { var{{{classname}}} := _{{{classname}}}{} - err = json.Unmarshal(bytes, &var{{{classname}}}) + err = json.Unmarshal(data, &var{{{classname}}}) if err == nil { o.{{{parent}}} = var{{{classname}}}.{{{parent}}} } else { @@ -373,7 +413,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { {{#vars}} delete(additionalProperties, "{{{baseName}}}") {{/vars}} @@ -404,7 +444,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { {{#isMap}} var{{{classname}}} := _{{{classname}}}{} - err = json.Unmarshal(bytes, &var{{{classname}}}) + err = json.Unmarshal(data, &var{{{classname}}}) if err != nil { return err @@ -414,7 +454,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { {{#vars}} delete(additionalProperties, "{{{baseName}}}") {{/vars}} @@ -427,7 +467,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { {{^parent}} var{{{classname}}} := _{{{classname}}}{} - err = json.Unmarshal(bytes, &var{{{classname}}}) + err = json.Unmarshal(data, &var{{{classname}}}) if err != nil { return err @@ -437,7 +477,7 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { {{#vars}} delete(additionalProperties, "{{{baseName}}}") {{/vars}} @@ -446,12 +486,33 @@ func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { return err {{/parent}} +{{/isAdditionalPropertiesTrue}} +{{#isAdditionalPropertiesTrue}} +} + +{{/isAdditionalPropertiesTrue}} +{{^isAdditionalPropertiesTrue}} +{{#hasRequired}} + var{{{classname}}} := _{{{classname}}}{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&var{{{classname}}}) + + if err != nil { + return err + } + + *o = {{{classname}}}(var{{{classname}}}) + + return err } +{{/hasRequired}} {{/isAdditionalPropertiesTrue}} {{#isArray}} -func (o *{{{classname}}}) UnmarshalJSON(bytes []byte) (err error) { - return json.Unmarshal(bytes, &o.Items) +func (o *{{{classname}}}) UnmarshalJSON(data []byte) (err error) { + return json.Unmarshal(data, &o.Items) } {{/isArray}} diff --git a/modules/openapi-generator/src/main/resources/go/signing.mustache b/modules/openapi-generator/src/main/resources/go/signing.mustache index a271fcfe6acb..57221be25fb5 100644 --- a/modules/openapi-generator/src/main/resources/go/signing.mustache +++ b/modules/openapi-generator/src/main/resources/go/signing.mustache @@ -107,6 +107,7 @@ var supportedSigningSchemes = map[string]bool{ type HttpSignatureAuth struct { KeyId string // A key identifier. PrivateKeyPath string // The path to the private key. + PrivateKeyReader io.Reader // provide the APIKey using the types which implement io.Reader interface. Passphrase string // The passphrase to decrypt the private key, if the key is encrypted. SigningScheme string // The signature scheme, when signing HTTP requests. Supported value is 'hs2019'. // The signature algorithm, when signing HTTP requests. @@ -134,9 +135,12 @@ func (h *HttpSignatureAuth) ContextWithValue(ctx context.Context) (context.Conte if h.KeyId == "" { return nil, fmt.Errorf("key ID must be specified") } - if h.PrivateKeyPath == "" && h.privateKey == nil { + if (len(h.PrivateKeyPath) == 0 && h.PrivateKeyReader == nil) && h.privateKey == nil { return nil, fmt.Errorf("private key path must be specified") } + if len(h.PrivateKeyPath) > 0 && h.PrivateKeyReader != nil{ + return nil, fmt.Errorf("Specify only one of PrivateKeyPath or PrivateKeyReader") + } if _, ok := supportedSigningSchemes[h.SigningScheme]; !ok { return nil, fmt.Errorf("invalid signing scheme: '%v'", h.SigningScheme) } @@ -184,17 +188,21 @@ func (h *HttpSignatureAuth) loadPrivateKey() (err error) { if h.privateKey != nil { return nil } - var file *os.File - file, err = os.Open(h.PrivateKeyPath) - if err != nil { - return fmt.Errorf("cannot load private key '%s'. Error: %v", h.PrivateKeyPath, err) - } - defer func() { - err = file.Close() - }() var priv []byte - priv, err = io.ReadAll(file) - if err != nil { + keyReader := h.PrivateKeyReader + if keyReader == nil { + var file *os.File + file, err = os.Open(h.PrivateKeyPath) + if err != nil { + return fmt.Errorf("cannot load private key '%s'. Error: %v", h.PrivateKeyPath, err) + } + keyReader = file + defer func() { + err = file.Close() + }() + } + priv, err = io.ReadAll(keyReader) + if err != nil{ return err } return h.parsePrivateKey(priv) diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache index 84115fa7d029..ce9f0551c722 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/mp/pojo.mustache @@ -137,7 +137,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache index 84115fa7d029..ce9f0551c722 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/client/libraries/se/pojo.mustache @@ -137,7 +137,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache index 944ae482956d..abc5e56ca789 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/common/pojo.mustache @@ -103,7 +103,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache index 441eab353403..1b67dadb3601 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumClass.mustache @@ -25,7 +25,7 @@ * Convert a String into {{dataType}}, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static {{datatypeWithEnum}} fromString(String s) { + public static {{datatypeWithEnum}} fromString(String s) { for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -34,8 +34,8 @@ } } {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} - } - + } + {{#jackson}}@JsonCreator{{/jackson}} public static {{datatypeWithEnum}} fromValue({{dataType}} value) { for ({{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{{datatypeWithEnum}}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache index 3d9a35ead905..8f4143075c5d 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/enumOuterClass.mustache @@ -32,7 +32,7 @@ import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; * Convert a String into {{dataType}}, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { + public static {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} fromString(String s) { for ({{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}} b : {{#datatypeWithEnum}}{{{.}}}{{/datatypeWithEnum}}{{^datatypeWithEnum}}{{{classname}}}{{/datatypeWithEnum}}.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -41,8 +41,8 @@ import {{rootJavaEEPackage}}.json.bind.annotation.JsonbCreator; } } {{#isNullable}}return null;{{/isNullable}}{{^isNullable}}throw new IllegalArgumentException("Unexpected string value '" + s + "'");{{/isNullable}} - } - + } + @Override {{#jackson}}@JsonValue{{/jackson}} public String toString() { diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache index 8cb61daf3def..373e88642036 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/mp/pojo.mustache @@ -143,7 +143,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}}{{#vendorExtensi StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache index dbe0359ada42..14b9e283fda8 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/model.mustache @@ -2,6 +2,10 @@ package {{package}}; {{#imports}}import {{import}}; {{/imports}} +{{#useBeanValidation}} +import {{rootJavaEEPackage}}.validation.constraints.*; +import {{rootJavaEEPackage}}.validation.Valid; +{{/useBeanValidation}} {{#models}} {{#model}}{{#isEnum}} {{>enumOuterClass}}{{/isEnum}}{{^isEnum}} diff --git a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache index 944ae482956d..abc5e56ca789 100644 --- a/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-helidon/server/libraries/se/pojo.mustache @@ -103,7 +103,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-micronaut/client/api.mustache b/modules/openapi-generator/src/main/resources/java-micronaut/client/api.mustache index 9f0b70835f4e..407f41007216 100644 --- a/modules/openapi-generator/src/main/resources/java-micronaut/client/api.mustache +++ b/modules/openapi-generator/src/main/resources/java-micronaut/client/api.mustache @@ -41,7 +41,7 @@ import io.swagger.v3.oas.annotations.security.SecurityRequirement; {{/generateSwagger2Annotations}} {{#additionalClientTypeAnnotations}} - {{{.}}} + {{{.}}} {{/additionalClientTypeAnnotations}} {{>common/generatedAnnotation}} @Client({{#configureClientId}} diff --git a/modules/openapi-generator/src/main/resources/java-micronaut/common/model/pojo.mustache b/modules/openapi-generator/src/main/resources/java-micronaut/common/model/pojo.mustache index 7bd9ab2c8ebc..335a539963f2 100644 --- a/modules/openapi-generator/src/main/resources/java-micronaut/common/model/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-micronaut/common/model/pojo.mustache @@ -293,7 +293,7 @@ Declare the class with extends and implements sb.append(" ").append(toIndentedString(super.toString())).append("\n"); {{/parent}} {{#vars}} - sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}} sb.append("}"); return sb.toString(); diff --git a/modules/openapi-generator/src/main/resources/java-msf4j-server/pojo.mustache b/modules/openapi-generator/src/main/resources/java-msf4j-server/pojo.mustache index 743698ea9f53..a672b3a763ec 100644 --- a/modules/openapi-generator/src/main/resources/java-msf4j-server/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-msf4j-server/pojo.mustache @@ -118,7 +118,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/gatling/application.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/gatling/application.mustache index 6a42f95f1fab..29787d0b712e 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/gatling/application.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/gatling/application.mustache @@ -9,6 +9,6 @@ akka { } url="http://localhost:8081" -noOfUsers=10 #Number of Users -deleteProductId=4 #Delete the Product by using productID -getProduct=2 #Get the Product \ No newline at end of file +noOfUsers=10 #Number of Users +deleteProductId=4 #Delete the Product by using productID +getProduct=2 #Get the Product \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/logging/httpLoggingFilter.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/logging/httpLoggingFilter.mustache index 7869ab365996..9eff7c7389a8 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/logging/httpLoggingFilter.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/logging/httpLoggingFilter.mustache @@ -80,7 +80,7 @@ public class HttpLoggingFilter implements Filter { .append(bufferedResponse.getStatus()) .append("] [Response Time(ms):").append(elapsedTime) .append("]"); - String [] nonLoggingPaths = {"/v2/api-docs","/swagger-resources","/configuration/security","/swagger-ui.html","/webjars"}; + String [] nonLoggingPaths = {"/v2/api-docs","/swagger-resources","/configuration/security","/swagger-ui.html","/webjars"}; String urlPath = httpServletRequest.getRequestURL().toString(); if (! ( Arrays.stream(nonLoggingPaths).parallel().anyMatch(urlPath::contains) )){ log.info(logMessage.toString()); diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/pojo.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/pojo.mustache index 19ef6761a7a5..c5838cb45f9b 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/pojo.mustache @@ -117,7 +117,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{classname}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{name}}: ").append(toIndentedString({{name}})).append("\n"); + {{#vars}}sb.append(" {{name}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{name}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-pkmst/pom.mustache b/modules/openapi-generator/src/main/resources/java-pkmst/pom.mustache index e2f8e6fefef8..a71a194d56bf 100644 --- a/modules/openapi-generator/src/main/resources/java-pkmst/pom.mustache +++ b/modules/openapi-generator/src/main/resources/java-pkmst/pom.mustache @@ -25,8 +25,8 @@ 2.6.0 1.7.25 4.11 - 1.2.12 - 1.2.12 + 1.4.13 + 1.4.13 2.3.0 2.2.4 3.2.2 diff --git a/modules/openapi-generator/src/main/resources/java-undertow-server/pojo.mustache b/modules/openapi-generator/src/main/resources/java-undertow-server/pojo.mustache index 9f8e20868210..6af043aa9906 100644 --- a/modules/openapi-generator/src/main/resources/java-undertow-server/pojo.mustache +++ b/modules/openapi-generator/src/main/resources/java-undertow-server/pojo.mustache @@ -56,7 +56,7 @@ public class {{classname}} {{#parent}}extends {{{.}}}{{/parent}} {{#vendorExtens StringBuilder sb = new StringBuilder(); sb.append("class {{{classname}}} {\n"); {{#parent}}sb.append(" ").append(toIndentedString(super.toString())).append("\n");{{/parent}} - {{#vars}}sb.append(" {{{name}}}: ").append(toIndentedString({{{name}}})).append("\n"); + {{#vars}}sb.append(" {{{name}}}: ").append({{#isPassword}}"*"{{/isPassword}}{{^isPassword}}toIndentedString({{{name}}}){{/isPassword}}).append("\n"); {{/vars}}sb.append("}"); return sb.toString(); } diff --git a/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache b/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache index e87ccfe2a1c2..c0cfd07749b1 100644 --- a/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache +++ b/modules/openapi-generator/src/main/resources/java-undertow-server/pom.mustache @@ -26,7 +26,7 @@ 1.10 1.2 3.1.2 - 1.2.0 + 1.4.13 4.13.2 2.1.0-beta.124 2.3.5.Final diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache index 63dc33d1dbe4..e3f73ddb85e9 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/build.gradle.mustache @@ -11,7 +11,7 @@ wrapper { buildscript { ext.kotlin_version = '1.8.10' {{#jvm-ktor}} - ext.ktor_version = '2.1.3' + ext.ktor_version = '2.2.3' {{/jvm-ktor}} {{#jvm-retrofit2}} ext.retrofitVersion = '2.9.0' @@ -28,15 +28,17 @@ buildscript { {{#jvm-vertx}} ext.vertx_version = "4.3.3" {{/jvm-vertx}} - {{#jvm-spring-webclient}} + {{#jvm-spring}} {{#useSpringBoot3}} - ext.spring_boot_version = "3.1.0" + ext.spring_boot_version = "3.2.0" {{/useSpringBoot3}} {{^useSpringBoot3}} ext.spring_boot_version = "2.7.12" {{/useSpringBoot3}} + {{#jvm-spring-webclient}} ext.reactor_version = "3.5.6" {{/jvm-spring-webclient}} + {{/jvm-spring}} ext.spotless_version = "6.13.0" repositories { @@ -113,6 +115,13 @@ kotlin { } } {{/useSpringBoot3}}{{/jvm-spring-webclient}} +{{#jvm-spring-restclient}} +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} +{{/jvm-spring-restclient}} dependencies { implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" {{^doNotUseRxAndCoroutines}} @@ -165,9 +174,15 @@ dependencies { implementation "org.springframework.boot:spring-boot-starter-webflux:$spring_boot_version" implementation "io.projectreactor:reactor-core:$reactor_version" {{/jvm-spring-webclient}} + {{#jvm-spring-restclient}} + implementation "org.springframework.boot:spring-boot-starter-web:$spring_boot_version" + {{/jvm-spring-restclient}} {{#threetenbp}} implementation "org.threeten:threetenbp:1.6.8" {{/threetenbp}} + {{#kotlinx-datetime}} + implementation "org.jetbrains.kotlinx:kotlinx-datetime:0.4.0" + {{/kotlinx-datetime}} {{#jvm-retrofit2}} {{#hasOAuthMethods}} implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" @@ -195,6 +210,9 @@ dependencies { {{#kotlinx_serialization}} implementation "com.jakewharton.retrofit:retrofit2-kotlinx-serialization-converter:0.8.0" {{/kotlinx_serialization}} + {{#jackson}} + implementation "com.squareup.retrofit2:converter-jackson:$retrofitVersion" + {{/jackson}} implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" {{/jvm-retrofit2}} testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache index c91f42078fa0..c84e38b3f085 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/data_class.mustache @@ -7,6 +7,9 @@ import com.squareup.moshi.Json import com.squareup.moshi.JsonClass {{/moshi}} {{#jackson}} +{{#enumUnknownDefaultCase}} +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +{{/enumUnknownDefaultCase}} import com.fasterxml.jackson.annotation.JsonProperty {{#discriminator}} import com.fasterxml.jackson.annotation.JsonSubTypes @@ -114,7 +117,7 @@ import {{packageName}}.infrastructure.ITransformForStorage @SerializedName(value = {{#lambda.doublequote}}{{{value}}}{{/lambda.doublequote}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/gson}} {{#jackson}} - @JsonProperty(value = {{#lambda.doublequote}}{{{value}}}{{/lambda.doublequote}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} + @JsonProperty(value = {{#lambda.doublequote}}{{{value}}}{{/lambda.doublequote}}) {{#enumUnknownDefaultCase}}{{#-last}}@JsonEnumDefaultValue {{/-last}}{{/enumUnknownDefaultCase}}{{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} {{/jackson}} {{#kotlinx_serialization}} @SerialName(value = {{#lambda.doublequote}}{{{value}}}{{/lambda.doublequote}}) {{&name}}({{{value}}}){{^-last}},{{/-last}}{{#-last}};{{/-last}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache index 5ed8f4096332..7de4c68ae02e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/infrastructure/RequestConfig.kt.mustache @@ -12,6 +12,7 @@ package {{packageName}}.infrastructure val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/InstantAdapter.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/InstantAdapter.kt.mustache new file mode 100644 index 000000000000..66d389c3f6d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/InstantAdapter.kt.mustache @@ -0,0 +1,56 @@ +package {{packageName}}.infrastructure + +{{#moshi}} +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +{{/moshi}} +{{#gson}} +import com.google.gson.TypeAdapter +import com.google.gson.stream.JsonReader +import com.google.gson.stream.JsonWriter +import com.google.gson.stream.JsonToken.NULL +import java.io.IOException +{{/gson}} +import kotlinx.datetime.Instant + +{{#moshi}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class InstantAdapter { + @ToJson + fun toJson(value: Instant): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): Instant { + return Instant.parse(value) + } + +} +{{/moshi}} +{{#gson}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class InstantAdapter : TypeAdapter() { + @Throws(IOException::class) + override fun write(out: JsonWriter?, value: Instant?) { + if (value == null) { + out?.nullValue() + } else { + out?.value(value.toString()) + } + } + + @Throws(IOException::class) + override fun read(out: JsonReader?): Instant? { + out ?: return null + + when (out.peek()) { + NULL -> { + out.nextNull() + return null + } + else -> { + return Instant.parse(out.nextString()) + } + } + } +} +{{/gson}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache index 312004657281..24b95f65b32a 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/jvm-common/infrastructure/Serializer.kt.mustache @@ -22,9 +22,15 @@ import org.threeten.bp.LocalDate import org.threeten.bp.LocalDateTime import org.threeten.bp.OffsetDateTime {{/threetenbp}} +{{#kotlinx-datetime}} +import kotlinx.datetime.Instant +{{/kotlinx-datetime}} import java.util.UUID {{/gson}} {{#jackson}} +{{#enumUnknownDefaultCase}} +import com.fasterxml.jackson.databind.DeserializationFeature +{{/enumUnknownDefaultCase}} import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -58,6 +64,9 @@ import java.util.concurrent.atomic.AtomicLong @JvmStatic val moshiBuilder: Moshi.Builder = Moshi.Builder() .add(OffsetDateTimeAdapter()) + {{#kotlinx-datetime}} + .add(InstantAdapter()) + {{/kotlinx-datetime}} .add(LocalDateTimeAdapter()) .add(LocalDateAdapter()) .add(UUIDAdapter()) @@ -81,6 +90,9 @@ import java.util.concurrent.atomic.AtomicLong @JvmStatic val gsonBuilder: GsonBuilder = GsonBuilder() .registerTypeAdapter(OffsetDateTime::class.java, OffsetDateTimeAdapter()) + {{#kotlinx-datetime}} + .registerTypeAdapter(Instant::class.java, InstantAdapter()) + {{/kotlinx-datetime}} .registerTypeAdapter(LocalDateTime::class.java, LocalDateTimeAdapter()) .registerTypeAdapter(LocalDate::class.java, LocalDateAdapter()) .registerTypeAdapter(ByteArray::class.java, ByteArrayAdapter()) @@ -95,6 +107,9 @@ import java.util.concurrent.atomic.AtomicLong val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + {{#enumUnknownDefaultCase}} + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) + {{/enumUnknownDefaultCase}} .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) {{/jackson}} {{#kotlinx_serialization}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache index de3db091a8fd..c189f9f9ed93 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-ktor/infrastructure/ApiClient.kt.mustache @@ -13,6 +13,7 @@ import io.ktor.client.request.request import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.http.contentType +import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.Parameters @@ -196,6 +197,9 @@ import {{packageName}}.auth.* this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) setBody(body) } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache index 5ede536438e0..7a436279e40d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/api.mustache @@ -199,17 +199,17 @@ import {{packageName}}.infrastructure.toMultiValue {{#queryParams}} {{^required}} if ({{{paramName}}} != null) { - put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{{paramName}}}.value{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) + put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{#isString}}{{{paramName}}}.value{{/isString}}{{^isString}}{{{paramName}}}.toString(){{/isString}}{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) } {{/required}} {{#required}} {{#isNullable}} if ({{{paramName}}} != null) { - put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{{paramName}}}.value{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) + put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{#isString}}{{{paramName}}}.value{{/isString}}{{^isString}}{{{paramName}}}.toString(){{/isString}}{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) } {{/isNullable}} {{^isNullable}} - put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{{paramName}}}.value{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) + put("{{#lambda.escapeDollar}}{{baseName}}{{/lambda.escapeDollar}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{#isEnum}}{{#isString}}{{{paramName}}}.value{{/isString}}{{^isString}}{{{paramName}}}.toString(){{/isString}}{{/isEnum}}{{^isEnum}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}{{/isEnum}}){{/isContainer}}) {{/isNullable}} {{/required}} {{/queryParams}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache index 36f6ce3288e8..025d8b908bb9 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-okhttp/infrastructure/ApiClient.kt.mustache @@ -35,9 +35,6 @@ import okhttp3.Response {{#jvm-okhttp3}} import okhttp3.internal.Util.EMPTY_REQUEST {{/jvm-okhttp3}} -{{#jvm-okhttp4}} -import okhttp3.internal.EMPTY_REQUEST -{{/jvm-okhttp4}} import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -77,6 +74,10 @@ import com.fasterxml.jackson.core.type.TypeReference import com.squareup.moshi.adapter {{/moshi}} +{{#jvm-okhttp4}} +{{#nonPublicApi}}internal {{/nonPublicApi}} val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() +{{/jvm-okhttp4}} + {{#nonPublicApi}}internal {{/nonPublicApi}}open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { {{#nonPublicApi}}internal {{/nonPublicApi}}companion object { protected const val ContentType = "Content-Type" @@ -299,7 +300,12 @@ import com.squareup.moshi.adapter {{/isKeyInQuery}} } } + {{#isKeyInQuery}} } + {{/isKeyInQuery}} + {{#isKeyInHeader}} + } + {{/isKeyInHeader}} {{/isApiKey}} {{#isBasic}} {{#isBasicBasic}} @@ -406,6 +412,7 @@ import com.squareup.moshi.adapter val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code{{#jvm-okhttp3}}(){{/jvm-okhttp3}}, diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache index d62d00f659c0..52df6a87a623 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-retrofit2/infrastructure/ApiClient.kt.mustache @@ -51,6 +51,7 @@ import retrofit2.converter.moshi.MoshiConverterFactory {{/moshi}} {{#jackson}} import com.fasterxml.jackson.databind.ObjectMapper +import retrofit2.converter.jackson.JacksonConverterFactory {{/jackson}} {{#kotlinx_serialization}} @@ -88,6 +89,9 @@ import okhttp3.MediaType.Companion.toMediaType {{#kotlinx_serialization}} kotlinxSerializationJson.asConverterFactory("application/json".toMediaType()), {{/kotlinx_serialization}} + {{#jackson}} + JacksonConverterFactory.create(), + {{/jackson}} ) ) { private val apiAuthorizations = mutableMapOf() @@ -132,7 +136,7 @@ import okhttp3.MediaType.Companion.toMediaType authNames: Array ) : this(baseUrl, okHttpClientBuilder{{^kotlinx_serialization}}, serializerBuilder{{/kotlinx_serialization}}) { authNames.forEach { authName -> - val auth = when (authName) { {{#authMethods}} + val auth: Interceptor? = when (authName) { {{#authMethods}} {{#isBasicBasic}}"{{name}}" -> HttpBasicAuth() {{/isBasicBasic}}{{#isBasicBearer}}"{{name}}" -> HttpBearerAuth("{{scheme}}") {{/isBasicBearer}}{{#isApiKey}}"{{name}}" -> ApiKeyAuth({{#isKeyInHeader}}"header"{{/isKeyInHeader}}{{#isKeyInQuery}}"query"{{/isKeyInQuery}}{{#isKeyInCookie}}"cookie"{{/isKeyInCookie}}, "{{keyParamName}}") diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/api.mustache new file mode 100644 index 000000000000..5e28a2fc7e24 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/api.mustache @@ -0,0 +1,145 @@ +{{>licenseInfo}} +package {{apiPackage}} + +{{#jackson}} +import com.fasterxml.jackson.annotation.JsonProperty +{{/jackson}} + +import org.springframework.web.client.RestClient +import org.springframework.web.client.RestClientResponseException + +{{#jackson}} +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter +{{/jackson}} +import org.springframework.http.ResponseEntity +import org.springframework.http.MediaType + + +{{#imports}}import {{import}} +{{/imports}} +import {{packageName}}.infrastructure.* + +{{#operations}} +{{#nonPublicApi}}internal {{/nonPublicApi}}class {{classname}}(client: RestClient) : ApiClient(client) { + + {{#jackson}} + constructor(baseUrl: String) : this(RestClient.builder() + .baseUrl(baseUrl) + .messageConverters { it.add(MappingJackson2HttpMessageConverter()) } + .build() + ) + {{/jackson}} + + {{#operation}} + {{#allParams}} + {{#isEnum}} + /** + * enum for parameter {{paramName}} + */ + {{#nonPublicApi}}internal {{/nonPublicApi}}enum class {{enumName}}{{operationIdCamelCase}}(val value: {{^isContainer}}{{dataType}}{{/isContainer}}{{#isContainer}}kotlin.String{{/isContainer}}) { + {{^enumUnknownDefaultCase}} + {{#allowableValues}} + {{#enumVars}} + {{#jackson}} + @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}){{^-last}},{{/-last}} + {{/jackson}} + {{/enumVars}} + {{/allowableValues}} + {{/enumUnknownDefaultCase}} + {{#enumUnknownDefaultCase}} + {{#allowableValues}} + {{#enumVars}} + {{^-last}} + {{#jackson}} + @JsonProperty(value = {{^isString}}"{{/isString}}{{{value}}}{{^isString}}"{{/isString}}) {{&name}}({{{value}}}), + {{/jackson}} + {{/-last}} + {{/enumVars}} + {{/allowableValues}} + {{/enumUnknownDefaultCase}} + } + + {{/isEnum}} + {{/allParams}} + + @Throws(RestClientResponseException::class) + {{#isDeprecated}} + @Deprecated(message = "This operation is deprecated.") + {{/isDeprecated}} + fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): {{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}} { + return {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + .body!! + } + + @Throws(RestClientResponseException::class) + {{#isDeprecated}} + @Deprecated(message = "This operation is deprecated.") + {{/isDeprecated}} + fun {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): ResponseEntity<{{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}> { + val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + return request<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}, {{{returnType}}}{{^returnType}}Unit{{/returnType}}>( + localVariableConfig + ) + } + + {{#isDeprecated}} + @Deprecated(message = "This operation is deprecated.") + {{/isDeprecated}} + fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}> { + val localVariableBody = {{#hasBodyParam}}{{! + }}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{! + }}{{^hasFormParams}}null{{/hasFormParams}}{{! + }}{{#hasFormParams}}mapOf({{#formParams}} + "{{{baseName}}}" to PartConfig(body = {{{paramName}}}{{#isEnum}}.value{{/isEnum}}, headers = mutableMapOf({{#contentType}}"Content-Type" to "{{contentType}}"{{/contentType}})),{{! + }}{{/formParams}}){{/hasFormParams}}{{! + }}{{/hasBodyParam}} + val localVariableQuery = {{^hasQueryParams}}mutableMapOf>() +{{/hasQueryParams}}{{#hasQueryParams}}mutableMapOf>() + .apply { + {{#queryParams}} + {{^required}} + if ({{{paramName}}} != null) { + put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) + } + {{/required}} + {{#required}} + {{#isNullable}} + if ({{{paramName}}} != null) { + put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) + } + {{/isNullable}} + {{^isNullable}} + put("{{baseName}}", {{#isContainer}}toMultiValue({{{paramName}}}.toList(), "{{collectionFormat}}"){{/isContainer}}{{^isContainer}}listOf({{#isDateTime}}parseDateToQueryString({{{paramName}}}){{/isDateTime}}{{#isDate}}parseDateToQueryString({{{paramName}}}){{/isDate}}{{^isDateTime}}{{^isDate}}{{{paramName}}}.toString(){{/isDate}}{{/isDateTime}}){{/isContainer}}) + {{/isNullable}} + {{/required}} + {{/queryParams}} + } + {{/hasQueryParams}} + val localVariableHeaders: MutableMap = mutableMapOf({{#hasFormParams}}"Content-Type" to {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{/hasFormParams}}) + {{#headerParams}} + {{{paramName}}}{{^required}}?{{/required}}.apply { localVariableHeaders["{{baseName}}"] = {{#isContainer}}this.joinToString(separator = collectionDelimiter("{{collectionFormat}}")){{/isContainer}}{{^isContainer}}this.toString(){{/isContainer}} } + {{/headerParams}} + {{^hasFormParams}}{{#hasConsumes}}{{#consumes}}localVariableHeaders["Content-Type"] = "{{{mediaType}}}" + {{/consumes}}{{/hasConsumes}}{{/hasFormParams}}{{#hasProduces}}localVariableHeaders["Accept"] = "{{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}" +{{/hasProduces}} + + val params = mutableMapOf( + {{#pathParams}} + "{{baseName}}" to {{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}{{/isContainer}}, + {{/pathParams}} + ) + + return RequestConfig( + method = RequestMethod.{{httpMethod}}, + path = "{{path}}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = {{#hasAuthMethods}}true{{/hasAuthMethods}}{{^hasAuthMethods}}false{{/hasAuthMethods}}, + body = localVariableBody + ) + } + + {{/operation}} +} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/infrastructure/ApiClient.kt.mustache new file mode 100644 index 000000000000..9d116ed9b175 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-restclient/infrastructure/ApiClient.kt.mustache @@ -0,0 +1,68 @@ +package {{packageName}}.infrastructure; + +import org.springframework.core.ParameterizedTypeReference +import org.springframework.http.HttpHeaders +import org.springframework.http.HttpMethod +import org.springframework.http.MediaType +import org.springframework.web.client.RestClient +import org.springframework.http.ResponseEntity +import org.springframework.util.LinkedMultiValueMap + +open class ApiClient(protected val client: RestClient) { + + protected inline fun request(requestConfig: RequestConfig): ResponseEntity { + return prepare(defaults(requestConfig)) + .retrieve() + .toEntity(object : ParameterizedTypeReference() {}) + } + + protected fun prepare(requestConfig: RequestConfig) = + client.method(requestConfig) + .uri(requestConfig) + .headers(requestConfig) + .nullableBody(requestConfig) + + protected fun defaults(requestConfig: RequestConfig) = + requestConfig.apply { + if (body != null && headers[HttpHeaders.CONTENT_TYPE].isNullOrEmpty()) { + headers[HttpHeaders.CONTENT_TYPE] = MediaType.APPLICATION_JSON_VALUE + } + if (headers[HttpHeaders.ACCEPT].isNullOrEmpty()) { + headers[HttpHeaders.ACCEPT] = MediaType.APPLICATION_JSON_VALUE + } + } + + private fun RestClient.method(requestConfig: RequestConfig)= + method(HttpMethod.valueOf(requestConfig.method.name)) + + private fun RestClient.RequestBodyUriSpec.uri(requestConfig: RequestConfig) = + uri { builder -> + builder + .path(requestConfig.path) + .queryParams(LinkedMultiValueMap(requestConfig.query)) + .build(requestConfig.params) + } + + private fun RestClient.RequestBodySpec.headers(requestConfig: RequestConfig) = + apply { requestConfig.headers.forEach { (name, value) -> header(name, value) } } + + private fun RestClient.RequestBodySpec.nullableBody(requestConfig: RequestConfig) = + apply { if (requestConfig.body != null) body(requestConfig.body) } +} + +inline fun parseDateToQueryString(value : T): String { + {{#toJson}} + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + {{#jackson}} + return Serializer.jacksonObjectMapper.writeValueAsString(value).replace("\"", "") + {{/jackson}} + {{/toJson}} + {{^toJson}} + return value.toString() + {{/toJson}} + } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/api.mustache index 08a573a642b6..199bee644605 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/api.mustache @@ -14,6 +14,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap {{#imports}}import {{import}} {{/imports}} @@ -69,7 +70,7 @@ import {{packageName}}.infrastructure.* {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): Mono<{{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}> { + fun {{operationId}}({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): Mono<{{#returnType}}{{{returnType}}}{{#nullableReturnType}}?{{/nullableReturnType}}{{/returnType}}{{^returnType}}Unit{{/returnType}}> { return {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) .map { it.body } } @@ -78,7 +79,7 @@ import {{packageName}}.infrastructure.* {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - fun {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): Mono> { + fun {{operationId}}WithHttpInfo({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}): Mono> { val localVariableConfig = {{operationId}}RequestConfig({{#allParams}}{{{paramName}}} = {{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) return request<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}, {{{returnType}}}{{^returnType}}Unit{{/returnType}}>( localVariableConfig @@ -88,7 +89,7 @@ import {{packageName}}.infrastructure.* {{#isDeprecated}} @Deprecated(message = "This operation is deprecated.") {{/isDeprecated}} - fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}> { + fun {{operationId}}RequestConfig({{#allParams}}{{{paramName}}}: {{#isEnum}}{{#isContainer}}kotlin.collections.List<{{enumName}}{{operationIdCamelCase}}>{{/isContainer}}{{^isContainer}}{{enumName}}{{operationIdCamelCase}}{{/isContainer}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{^required}}?{{#defaultValue}} = {{^isNumber}}{{#isEnum}}{{enumName}}{{operationIdCamelCase}}.{{enumDefaultValue}}{{/isEnum}}{{^isEnum}}{{{defaultValue}}}{{/isEnum}}{{/isNumber}}{{#isNumber}}{{{defaultValue}}}.toDouble(){{/isNumber}}{{/defaultValue}}{{^defaultValue}} = null{{/defaultValue}}{{/required}}{{^-last}}, {{/-last}}{{/allParams}}) : RequestConfig<{{#hasBodyParam}}{{#bodyParams}}{{{dataType}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{^hasFormParams}}Unit{{/hasFormParams}}{{#hasFormParams}}Map>{{/hasFormParams}}{{/hasBodyParam}}> { val localVariableBody = {{#hasBodyParam}}{{! }}{{#bodyParams}}{{{paramName}}}{{/bodyParams}}{{/hasBodyParam}}{{^hasBodyParam}}{{! }}{{^hasFormParams}}null{{/hasFormParams}}{{! @@ -126,9 +127,16 @@ import {{packageName}}.infrastructure.* {{/consumes}}{{/hasConsumes}}{{/hasFormParams}}{{#hasProduces}}localVariableHeaders["Accept"] = "{{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}" {{/hasProduces}} + val params = mutableMapOf( + {{#pathParams}} + "{{baseName}}" to {{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}{{/isContainer}}, + {{/pathParams}} + ) + return RequestConfig( method = RequestMethod.{{httpMethod}}, - path = "{{path}}"{{#pathParams}}.replace("{"+"{{baseName}}"+"}", encodeURIComponent({{#isContainer}}{{paramName}}.joinToString(","){{/isContainer}}{{^isContainer}}{{{paramName}}}{{#isEnum}}.value{{/isEnum}}.toString(){{/isContainer}})){{/pathParams}}, + path = "{{path}}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = {{#hasAuthMethods}}true{{/hasAuthMethods}}{{^hasAuthMethods}}false{{/hasAuthMethods}}, diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/infrastructure/ApiClient.kt.mustache index d9d956d3fa72..3042e1aecea6 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/jvm-spring-webclient/infrastructure/ApiClient.kt.mustache @@ -4,9 +4,9 @@ import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType -import org.springframework.web.util.UriUtils import org.springframework.web.reactive.function.client.WebClient import org.springframework.http.ResponseEntity +import org.springframework.util.LinkedMultiValueMap import reactor.core.publisher.Mono open class ApiClient(protected val client: WebClient) { @@ -33,19 +33,15 @@ open class ApiClient(protected val client: WebClient) { } } - protected fun encodeURIComponent(uriComponent: kotlin.String) = - UriUtils.encodeFragment(uriComponent, Charsets.UTF_8) - private fun WebClient.method(requestConfig: RequestConfig)= method(HttpMethod.valueOf(requestConfig.method.name)) private fun WebClient.RequestBodyUriSpec.uri(requestConfig: RequestConfig) = uri { builder -> - builder.path(requestConfig.path).apply { - requestConfig.query.forEach { (name, value) -> - queryParam(name, value) - } - }.build() + builder + .path(requestConfig.path) + .queryParams(LinkedMultiValueMap(requestConfig.query)) + .build(requestConfig.params) } private fun WebClient.RequestBodySpec.headers(requestConfig: RequestConfig) = diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache index 21c2f97f0804..e527fb53d363 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/build.gradle.kts.mustache @@ -1,17 +1,17 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform"){{^omitGradlePluginVersions}} version "1.7.21" // kotlin_version{{/omitGradlePluginVersions}} - kotlin("plugin.serialization"){{^omitGradlePluginVersions}} version "1.7.21" // kotlin_version{{/omitGradlePluginVersions}} + kotlin("multiplatform"){{^omitGradlePluginVersions}} version "1.9.20" // kotlin_version{{/omitGradlePluginVersions}} + kotlin("plugin.serialization"){{^omitGradlePluginVersions}} version "1.9.20" // kotlin_version{{/omitGradlePluginVersions}} } group = "{{groupId}}" version = "{{artifactVersion}}" -val kotlin_version = "1.7.21" -val coroutines_version = "1.6.4" -val serialization_version = "1.3.3" -val ktor_version = "2.1.3" +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" repositories { mavenCentral() @@ -19,14 +19,16 @@ repositories { kotlin { jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + iosX64() + iosArm64() + iosSimulatorArm64() js { browser() nodejs() } sourceSets { - val commonMain by getting { + commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") @@ -35,45 +37,45 @@ kotlin { api("io.ktor:ktor-client-serialization:$ktor_version") api("io.ktor:ktor-client-content-negotiation:$ktor_version") api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + {{#kotlinx-datetime}} + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") + {{/kotlinx-datetime}} } } - val commonTest by getting { + commonTest { dependencies { implementation(kotlin("test")) implementation("io.ktor:ktor-client-mock:$ktor_version") } } - val jvmMain by getting { + jvmMain { dependencies { implementation(kotlin("stdlib-jdk7")) implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") } } - val jvmTest by getting { + jvmTest { dependencies { implementation(kotlin("test-junit")) } } - val iosMain by getting { + iosMain { dependencies { api("io.ktor:ktor-client-ios:$ktor_version") } } - val iosTest by getting - - val jsMain by getting { + jsMain { dependencies { api("io.ktor:ktor-client-js:$ktor_version") } } - val jsTest by getting - all { languageSettings.apply { optIn("kotlin.Experimental") diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache index f2077158eb43..a07f17e10b01 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/ApiClient.kt.mustache @@ -10,9 +10,11 @@ import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.serialization.kotlinx.json.json import io.ktor.http.* import io.ktor.http.content.PartData +import io.ktor.http.contentType import kotlin.Unit import kotlinx.serialization.json.Json @@ -165,6 +167,9 @@ import {{packageName}}.auth.* this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) this.setBody(body) } } diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache index 59b8baf4bd4c..b8bb160990ae 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Base64ByteArray.kt.mustache @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(Base64ByteArray.Companion::class) class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache index 8efab6464f46..a11e0525d910 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/Bytes.kt.mustache @@ -82,6 +82,7 @@ private fun ByteReadPacket.encodeBase64(): String = buildString { * * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt */ +@Suppress("DEPRECATION") private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { val data = ByteArray(4) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache index 2f278d20e1e0..80c85b51c723 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/infrastructure/OctetByteArray.kt.mustache @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(OctetByteArray.Companion::class) class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache index f3b0464445ec..358dfa70be50 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_list.mustache @@ -1,6 +1,5 @@ - @Serializable + @Serializable({{operationIdCamelCase}}Request.Companion::class) private class {{operationIdCamelCase}}Request(val value: List<{{#bodyParam}}{{baseType}}{{/bodyParam}}>) { - @Serializer({{operationIdCamelCase}}Request::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Request> { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache index a287882728db..55efd01ad655 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_request_map.mustache @@ -1,6 +1,5 @@ - @Serializable + @Serializable({{operationIdCamelCase}}Request.Companion::class) private class {{operationIdCamelCase}}Request(val value: Map) { - @Serializer({{operationIdCamelCase}}Request::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Request> { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache index 227d6a351f29..3f191db3a67b 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_list.mustache @@ -1,6 +1,5 @@ - @Serializable + @Serializable({{operationIdCamelCase}}Response.Companion::class) private class {{operationIdCamelCase}}Response(val value: List<{{returnBaseType}}>) { - @Serializer({{operationIdCamelCase}}Response::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache index a6bdd6c166a1..bbd342cfa1a8 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-client/libraries/multiplatform/serial_wrapper_response_map.mustache @@ -1,6 +1,5 @@ - @Serializable + @Serializable({{operationIdCamelCase}}Response.Companion::class) private class {{operationIdCamelCase}}Response(val value: Map) { - @Serializer({{operationIdCamelCase}}Response::class) {{#nonPublicApi}}internal {{/nonPublicApi}}companion object : KSerializer<{{operationIdCamelCase}}Response> { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache index 3d547ad13820..8672c263cf5e 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/api.mustache @@ -29,6 +29,9 @@ import org.springframework.validation.annotation.Validated import org.springframework.web.context.request.NativeWebRequest import org.springframework.beans.factory.annotation.Autowired +{{#appendRequestToHandler}} +import org.springframework.http.server.reactive.ServerHttpRequest +{{/appendRequestToHandler}} {{#useBeanValidation}} import {{javaxPackage}}.validation.Valid import {{javaxPackage}}.validation.constraints.DecimalMax @@ -81,13 +84,13 @@ class {{classname}}Controller({{#serviceInterface}}@Autowired(required = true) v value = [{{#responses}}ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{.}}}::class{{/baseType}}{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}},{{/-last}}{{/responses}}]){{/swagger1AnnotationLibrary}} @RequestMapping( method = [RequestMethod.{{httpMethod}}], - value = ["{{#lambda.escapeDoubleQuote}}{{path}}{{/lambda.escapeDoubleQuote}}"]{{#singleContentTypes}}{{#hasProduces}}, + value = ["{{#lambdaEscapeInNormalString}}{{path}}{{/lambdaEscapeInNormalString}}"]{{#singleContentTypes}}{{#hasProduces}}, produces = "{{{vendorExtensions.x-accepts}}}"{{/hasProduces}}{{#hasConsumes}}, consumes = "{{{vendorExtensions.x-content-type}}}"{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}, produces = [{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{#hasConsumes}}, consumes = [{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/singleContentTypes}} ) - {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}): ResponseEntity<{{>returnTypes}}> { + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}{{#appendRequestToHandler}}, serverHttpRequest: ServerHttpRequest{{/appendRequestToHandler}}): ResponseEntity<{{>returnTypes}}> { return {{>returnValue}} } {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/apiController.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/apiController.mustache index 037b9d93d733..fcbc8cc37bca 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/apiController.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/apiController.mustache @@ -13,7 +13,7 @@ import java.util.Optional class {{classname}}Controller( @org.springframework.beans.factory.annotation.Autowired(required = false) delegate: {{classname}}Delegate? ) : {{classname}} { - private val delegate: {{classname}}Delegate + private lateinit var delegate: {{classname}}Delegate init { this.delegate = Optional.ofNullable(delegate).orElse(object : {{classname}}Delegate {}) diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache index be1a5d800e09..97501bac9542 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/apiInterface.mustache @@ -26,6 +26,9 @@ import io.swagger.annotations.AuthorizationScope import org.springframework.http.HttpStatus import org.springframework.http.MediaType import org.springframework.http.ResponseEntity +{{#appendRequestToHandler}} +import org.springframework.http.server.reactive.ServerHttpRequest +{{/appendRequestToHandler}} import org.springframework.web.bind.annotation.* {{#useBeanValidation}} @@ -73,6 +76,7 @@ interface {{classname}} { {{#swagger2AnnotationLibrary}} @Operation( + tags = [{{#tags}}"{{{name}}}",{{/tags}}], summary = "{{{summary}}}", operationId = "{{{operationId}}}", description = """{{{unescapedNotes}}}""", @@ -92,13 +96,13 @@ interface {{classname}} { value = [{{#responses}}ApiResponse(code = {{{code}}}, message = "{{{message}}}"{{#baseType}}, response = {{{.}}}::class{{/baseType}}{{#containerType}}, responseContainer = "{{{.}}}"{{/containerType}}){{^-last}}, {{/-last}}{{/responses}}]){{/swagger1AnnotationLibrary}} @RequestMapping( method = [RequestMethod.{{httpMethod}}], - value = ["{{#lambda.escapeDoubleQuote}}{{path}}{{/lambda.escapeDoubleQuote}}"]{{#singleContentTypes}}{{#hasProduces}}, + value = ["{{#lambdaEscapeInNormalString}}{{path}}{{/lambdaEscapeInNormalString}}"]{{#singleContentTypes}}{{#hasProduces}}, produces = "{{{vendorExtensions.x-accepts}}}"{{/hasProduces}}{{#hasConsumes}}, consumes = "{{{vendorExtensions.x-content-type}}}"{{/hasConsumes}}{{/singleContentTypes}}{{^singleContentTypes}}{{#hasProduces}}, produces = [{{#produces}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/produces}}]{{/hasProduces}}{{#hasConsumes}}, consumes = [{{#consumes}}"{{{mediaType}}}"{{^-last}}, {{/-last}}{{/consumes}}]{{/hasConsumes}}{{/singleContentTypes}} ) - {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}): ResponseEntity<{{>returnTypes}}>{{^skipDefaultInterface}} { + {{#reactive}}{{^isArray}}suspend {{/isArray}}{{/reactive}}fun {{operationId}}({{#allParams}}{{>queryParams}}{{>pathParams}}{{>headerParams}}{{>bodyParams}}{{>formParams}}{{^-last}},{{/-last}}{{/allParams}}{{#appendRequestToHandler}}, serverHttpRequest: ServerHttpRequest{{/appendRequestToHandler}}): ResponseEntity<{{>returnTypes}}>{{^skipDefaultInterface}} { {{^isDelegate}} return {{>returnValue}} {{/isDelegate}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationBodyParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationBodyParams.mustache new file mode 100644 index 000000000000..71bc546835e4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationBodyParams.mustache @@ -0,0 +1 @@ +{{! RequestBody required param is responsible for optional and nullability }}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPath.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationCore.mustache similarity index 100% rename from modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPath.mustache rename to modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationCore.mustache diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache index 3c57e76be1ad..051bd53c0a58 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationPathParams.mustache @@ -1 +1 @@ -{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationPath}} \ No newline at end of file +{{! PathParam is always required, no @NotNull necessary }}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache index cc53bc96232d..9cca8cb88748 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/beanValidationQueryParams.mustache @@ -1 +1 @@ -{{#required}}@NotNull {{/required}}{{>beanValidationPath}} \ No newline at end of file +{{#required}}@NotNull {{/required}}{{>beanValidationCore}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache index 911bea74a1b8..4ca6b20ca93d 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/bodyParams.mustache @@ -1 +1 @@ -{{#isBodyParam}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"], defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"]){{/defaultValue}}{{/allowableValues}}{{/isContainer}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}, allowableValues = "{{{.}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} {{#useBeanValidation}}@Valid{{/useBeanValidation}} @RequestBody{{^required}}(required = false){{/required}} {{{paramName}}}: {{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}} \ No newline at end of file +{{#isBodyParam}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"], defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = ["{{{allowableValues}}}"]){{/defaultValue}}{{/allowableValues}}{{/isContainer}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{^isContainer}}{{#allowableValues}}, allowableValues = "{{{.}}}"{{/allowableValues}}{{/isContainer}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}}{{#useBeanValidation}} @Valid{{>beanValidationBodyParams}}{{/useBeanValidation}} @RequestBody{{^required}}(required = false){{/required}} {{{paramName}}}: {{^reactive}}{{>optionalDataType}}{{/reactive}}{{#reactive}}{{^isArray}}{{>optionalDataType}}{{/isArray}}{{#isArray}}Flow<{{{baseType}}}>{{/isArray}}{{/reactive}}{{/isBodyParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache index 211736d79128..79acd8edb6fc 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassOptVar.mustache @@ -1,5 +1,5 @@ {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} - @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} - @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#deprecated}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}{{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}}{{#deprecated}} @Deprecated(message = ""){{/deprecated}} @get:JsonProperty("{{{baseName}}}"){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}? = {{{defaultValue}}}{{^defaultValue}}null{{/defaultValue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache index d8bb06aa1665..f5814ba3cfbd 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/dataClassReqVar.mustache @@ -1,4 +1,4 @@ {{#useBeanValidation}}{{>beanValidation}}{{>beanValidationModel}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}} - @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} - @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{.}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} + @Schema({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}description = "{{{description}}}"){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}} + @ApiModelProperty({{#example}}example = "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{.}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}", {{/example}}required = true, {{#isReadOnly}}readOnly = {{{isReadOnly}}}, {{/isReadOnly}}value = "{{{description}}}"){{/swagger1AnnotationLibrary}} @get:JsonProperty("{{{baseName}}}", required = true){{#isInherited}} override{{/isInherited}} {{>modelMutable}} {{{name}}}: {{#isEnum}}{{#isArray}}{{baseType}}<{{/isArray}}{{classname}}.{{{nameInCamelCase}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}?{{/isNullable}}{{#defaultValue}} = {{{.}}}{{/defaultValue}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache index 9bc3f6002e99..53c8e620d2a4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/headerParams.mustache @@ -1 +1 @@ -{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationPath}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}", `in` = ParameterIn.HEADER{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isHeaderParam}} \ No newline at end of file +{{#isHeaderParam}}{{#useBeanValidation}}{{>beanValidationCore}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}", `in` = ParameterIn.HEADER{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}){{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#values}}"{{{.}}}"{{^-last}}, {{/-last}}{{/values}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}){{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @RequestHeader(value = "{{baseName}}", required = {{#required}}true{{/required}}{{^required}}false{{/required}}) {{paramName}}: {{>optionalDataType}}{{/isHeaderParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/methodBody.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/methodBody.mustache index 3e3b63e9ab01..30be6d64a4b4 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/methodBody.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/methodBody.mustache @@ -7,7 +7,7 @@ return CompletableFuture.supplyAsync(()-> { {{#async}} {{/async}} for (mediaType in MediaType.parseMediaTypes(request.getHeader("Accept"))) { {{/-first}} {{#async}} {{/async}}{{^async}} {{/async}} if (mediaType.isCompatibleWith(MediaType.valueOf("{{{contentType}}}"))) { -{{#async}} {{/async}}{{^async}} {{/async}} ApiUtil.setExampleResponse(request, "{{{contentType}}}", "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeDoubleQuote}}{{{example}}}{{/lambdaEscapeDoubleQuote}}{{/lambdaRemoveLineBreak}}") +{{#async}} {{/async}}{{^async}} {{/async}} ApiUtil.setExampleResponse(request, "{{{contentType}}}", "{{#lambdaRemoveLineBreak}}{{#lambdaEscapeInNormalString}}{{{example}}}{{/lambdaEscapeInNormalString}}{{/lambdaRemoveLineBreak}}") {{#async}} {{/async}}{{^async}} {{/async}} break {{#async}} {{/async}}{{^async}} {{/async}} } {{#-last}} diff --git a/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache b/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache index 957ca220c3df..18137b282cce 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-spring/pathParams.mustache @@ -1 +1 @@ -{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeDoubleQuote}}{{{value}}}{{/lambdaEscapeDoubleQuote}}"{{^-last}}, {{/-last}}{{/enumVars}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeDoubleQuote}}{{{value}}}{{/lambdaEscapeDoubleQuote}}"{{^-last}}, {{/-last}}{{/enumVars}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @PathVariable("{{baseName}}") {{paramName}}: {{>optionalDataType}}{{/isPathParam}} \ No newline at end of file +{{#isPathParam}}{{#useBeanValidation}}{{>beanValidationPathParams}}{{/useBeanValidation}}{{#swagger2AnnotationLibrary}}@Parameter(description = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}{{#defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]{{^isContainer}}, defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}{{#allowableValues}}{{^defaultValue}}, schema = Schema(allowableValues = [{{#enumVars}}"{{#lambdaEscapeInNormalString}}{{{value}}}{{/lambdaEscapeInNormalString}}"{{^-last}}, {{/-last}}{{/enumVars}}]){{/defaultValue}}{{/allowableValues}}{{^allowableValues}}{{#defaultValue}}{{^isContainer}}, schema = Schema(defaultValue = {{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{{defaultValue}}}{{^isString}}"{{/isString}}{{#isString}}{{#isEnum}}"{{/isEnum}}{{/isString}}{{/isContainer}}{{/defaultValue}}{{/allowableValues}}){{/swagger2AnnotationLibrary}}{{#swagger1AnnotationLibrary}}@ApiParam(value = "{{{description}}}"{{#required}}, required = true{{/required}}{{#allowableValues}}, allowableValues = "{{#enumVars}}{{#lambda.escapeDoubleQuote}}{{{value}}}{{/lambda.escapeDoubleQuote}}{{^-last}}, {{/-last}}{{/enumVars}}"{{/allowableValues}}{{#defaultValue}}, defaultValue = "{{{.}}}"{{/defaultValue}}){{/swagger1AnnotationLibrary}} @PathVariable("{{baseName}}") {{paramName}}: {{>optionalDataType}}{{/isPathParam}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/kotlin-vertx-server/apiProxy.mustache b/modules/openapi-generator/src/main/resources/kotlin-vertx-server/apiProxy.mustache index e689c36f3fd8..31d71455db92 100644 --- a/modules/openapi-generator/src/main/resources/kotlin-vertx-server/apiProxy.mustache +++ b/modules/openapi-generator/src/main/resources/kotlin-vertx-server/apiProxy.mustache @@ -20,7 +20,7 @@ import com.google.gson.Gson {{/imports}} class {{classname}}VertxProxyHandler(private val vertx: Vertx, private val service: {{classname}}, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/modules/openapi-generator/src/main/resources/objc/QueryParamCollection-body.mustache b/modules/openapi-generator/src/main/resources/objc/QueryParamCollection-body.mustache index 09d90abdd636..078ef03f6da3 100644 --- a/modules/openapi-generator/src/main/resources/objc/QueryParamCollection-body.mustache +++ b/modules/openapi-generator/src/main/resources/objc/QueryParamCollection-body.mustache @@ -10,9 +10,9 @@ self = [super init]; if (self) { - _values = values; - _format = format; - } + _values = values; + _format = format; + } return self; } diff --git a/modules/openapi-generator/src/main/resources/objc/xccurrentversion.mustache b/modules/openapi-generator/src/main/resources/objc/xccurrentversion.mustache index 528b389e3efa..0c60ee35d2e9 100644 --- a/modules/openapi-generator/src/main/resources/objc/xccurrentversion.mustache +++ b/modules/openapi-generator/src/main/resources/objc/xccurrentversion.mustache @@ -2,7 +2,7 @@ - _XCCurrentVersionName - {{classPrefix}}Model.xcdatamodel + _XCCurrentVersionName + {{classPrefix}}Model.xcdatamodel diff --git a/modules/openapi-generator/src/main/resources/openapi-static/index.mustache b/modules/openapi-generator/src/main/resources/openapi-static/index.mustache index bce16c47ea3f..3b38c9f86752 100644 --- a/modules/openapi-generator/src/main/resources/openapi-static/index.mustache +++ b/modules/openapi-generator/src/main/resources/openapi-static/index.mustache @@ -30,14 +30,14 @@ {{#apiInfo}} - {{#apis}} + {{#apis}}
              - {{#operations}} - {{#operation}} + {{#operations}} + {{#operation}}
            • {{nickname}}
            • {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/openapi-static/operation.mustache b/modules/openapi-generator/src/main/resources/openapi-static/operation.mustache index 67c6a07f3965..a6977c20f43b 100644 --- a/modules/openapi-generator/src/main/resources/openapi-static/operation.mustache +++ b/modules/openapi-generator/src/main/resources/openapi-static/operation.mustache @@ -16,8 +16,8 @@

              Parameters

                - {{#allParams}} -
              • + {{#allParams}} +
              • {{#isFormParam}}Form: {{/isFormParam}} {{#isQueryParam}}Query: {{/isQueryParam}} {{#isPathParam}}Path: {{/isPathParam}} @@ -27,7 +27,7 @@ {{dataType}}{{#baseType}}({{.}}){{/baseType}} {{#optional}}(optional){{/optional}}

                {{description}}

                -
              • + {{/allParams}}
              {{/operation}} diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/ApiException.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/ApiException.mustache index 2cdb18b83b26..31766db08e7c 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/ApiException.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/ApiException.mustache @@ -3,7 +3,6 @@ * ApiException * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -24,7 +23,6 @@ use stdClass; /** * ApiException Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/Configuration.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/Configuration.mustache index d2b76bf7c00b..b88e8e73a6f2 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/Configuration.mustache @@ -3,7 +3,6 @@ * Configuration * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -23,7 +22,6 @@ use InvalidArgumentException; /** * Configuration Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -421,9 +419,9 @@ class Configuration $report .= ' OS: ' . php_uname() . PHP_EOL; $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; $report .= ' The version of the OpenAPI document: {{version}}' . PHP_EOL; - {{#artifactVersion}} + {{#artifactVersion}} $report .= ' SDK Package Version: {{.}}' . PHP_EOL; - {{/artifactVersion}} + {{/artifactVersion}} $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/HeaderSelector.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/HeaderSelector.mustache index a96501706b0e..e8ae3e2d8102 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/HeaderSelector.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/HeaderSelector.mustache @@ -3,7 +3,6 @@ * HeaderSelector * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -21,7 +20,6 @@ namespace {{invokerPackage}}; /** * HeaderSelector Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/ModelInterface.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/ModelInterface.mustache index fa87d4268805..b8deccf36bb9 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/ModelInterface.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/ModelInterface.mustache @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package {{modelPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/ObjectSerializer.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/ObjectSerializer.mustache index 10c2203227d5..8c8b10a39343 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/ObjectSerializer.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/ObjectSerializer.mustache @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -27,7 +26,6 @@ use {{modelPackage}}\ModelInterface; /** * ObjectSerializer Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -419,10 +417,7 @@ class ObjectSerializer return $deserialized; } - if ($class === 'object') { - settype($data, 'array'); - return $data; - } elseif ($class === 'mixed') { + if ($class === 'mixed') { settype($data, gettype($data)); return $data; } diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/api.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/api.mustache index c4a1faba7c64..25fe70703441 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/api.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/api.mustache @@ -3,7 +3,6 @@ * {{classname}} * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -35,7 +34,6 @@ use {{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -164,7 +162,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/servers}} * @param string $contentType The value for the Content-Type header. Check self::contentTypes['{{{operationId}}}'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#isDeprecated}} @@ -239,7 +237,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/servers}} * @param string $contentType The value for the Content-Type header. Check self::contentTypes['{{{operationId}}}'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) {{#isDeprecated}} @@ -313,7 +311,19 @@ use {{invokerPackage}}\ObjectSerializer; } else { $content = (string) $response->getBody(); if ('{{{dataType}}}' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -334,7 +344,19 @@ use {{invokerPackage}}\ObjectSerializer; } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/api_test.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/api_test.mustache index 7932b5a2ebbd..27fdfebf8f1f 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/api_test.mustache @@ -3,7 +3,6 @@ * {{classname}}Test * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -26,7 +25,6 @@ use PHPUnit\Framework\TestCase; /** * {{classname}}Test Class Doc Comment * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/model.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/model.mustache index ff906509111d..323a21d03d9a 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/model.mustache @@ -6,7 +6,6 @@ * * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -34,7 +33,6 @@ use {{invokerPackage}}\ObjectSerializer; /** * {{classname}} Class Doc Comment * - * @category Class {{#description}} * @description {{.}} {{/description}} diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/model_generic.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/model_generic.mustache index 0a199d959f74..f79f51908882 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/model_generic.mustache @@ -36,7 +36,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par */ protected static array $openAPINullables = [ {{#vars}}'{{name}}' => {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{^-last}}, - {{/-last}}{{/vars}} + {{/-last}}{{/vars}} ]; /** @@ -446,7 +446,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par } {{/minimum}} {{#pattern}} - if ({{#isNullable}}!is_null(${{name}}) && {{/isNullable}}(!preg_match("{{{pattern}}}", ${{name}}))) { + if ({{#isNullable}}!is_null(${{name}}) && {{/isNullable}}(!preg_match("{{{pattern}}}", ObjectSerializer::toString(${{name}})))) { throw new InvalidArgumentException("invalid value for \${{name}} when calling {{classname}}.{{operationId}}, must conform to the pattern {{{pattern}}}."); } {{/pattern}} diff --git a/modules/openapi-generator/src/main/resources/php-nextgen/model_test.mustache b/modules/openapi-generator/src/main/resources/php-nextgen/model_test.mustache index 4941e6b41d22..c6755c3c85bd 100644 --- a/modules/openapi-generator/src/main/resources/php-nextgen/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-nextgen/model_test.mustache @@ -6,7 +6,6 @@ * * PHP version 8.1 * - * @category Class * @package {{invokerPackage}} * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -26,7 +25,6 @@ use PHPUnit\Framework\TestCase; /** * {{classname}}Test Class Doc Comment * - * @category Class * @description {{description}}{{^description}}{{classname}}{{/description}} * @package {{invokerPackage}} * @author OpenAPI Generator team diff --git a/modules/openapi-generator/src/main/resources/php-symfony/api.mustache b/modules/openapi-generator/src/main/resources/php-symfony/api.mustache index 9d9c75dcee6d..50a77182c138 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/api.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/api.mustache @@ -58,7 +58,12 @@ interface {{classname}} * {{/description}} {{#allParams}} + {{#isEnumRef}} + * @param \{{modelPackage}}\{{dataType}}{{^required}}{{^defaultValue}}|null{{/defaultValue}}{{/required}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/isEnumRef}} + {{^isEnumRef}} * @param {{vendorExtensions.x-parameter-type}}{{^required}}{{^defaultValue}}|null{{/defaultValue}}{{/required}} ${{paramName}} {{description}} {{#required}}(required){{/required}}{{^required}}(optional{{#defaultValue}}, default to {{{.}}}{{/defaultValue}}){{/required}}{{#isDeprecated}} (deprecated){{/isDeprecated}} + {{/isEnumRef}} {{/allParams}} * @param int &$responseCode The HTTP Response Code * @param array $responseHeaders Additional HTTP headers to return with the response () @@ -68,8 +73,18 @@ interface {{classname}} * @deprecated {{/isDeprecated}} */ - public function {{operationId}}({{#allParams}}{{^required}}{{^defaultValue}}?{{/defaultValue}}{{/required}}{{#vendorExtensions.x-parameter-type}}{{vendorExtensions.x-parameter-type}} {{/vendorExtensions.x-parameter-type}}${{paramName}}, {{/allParams}}int &$responseCode, array &$responseHeaders): {{{vendorExtensions.x-return-type}}}; - + public function {{operationId}}( + {{#allParams}} + {{#isEnumRef}} + {{^required}}{{^defaultValue}}?{{/defaultValue}}{{/required}}\{{modelPackage}}\{{dataType}} ${{paramName}}, + {{/isEnumRef}} + {{^isEnumRef}} + {{^required}}{{^defaultValue}}?{{/defaultValue}}{{/required}}{{#vendorExtensions.x-parameter-type}}{{vendorExtensions.x-parameter-type}} {{/vendorExtensions.x-parameter-type}}${{paramName}}, + {{/isEnumRef}} + {{/allParams}} + int &$responseCode, + array &$responseHeaders + ): {{{vendorExtensions.x-return-type}}}; {{/operation}} } {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache b/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache index 9f0b2fbea79c..715374267713 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/api_controller.mustache @@ -149,10 +149,10 @@ class {{controllerName}} extends Controller {{^isFile}} {{#isBodyParam}} $inputFormat = $request->getMimeType($request->getContentType()); - ${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}{{#items}}array<{{dataType}}>{{/items}}{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}', $inputFormat); + ${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}{{#items}}array<{{dataType}}>{{/items}}{{/isContainer}}{{^isContainer}}{{#isEnumRef}}\{{modelPackage}}\{{dataType}}{{/isEnumRef}}{{^isEnumRef}}{{dataType}}{{/isEnumRef}}{{/isContainer}}', $inputFormat); {{/isBodyParam}} {{^isBodyParam}} - ${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}array<{{collectionFormat}}{{^collectionFormat}}csv{{/collectionFormat}},{{dataType}}>{{/isContainer}}{{^isContainer}}{{dataType}}{{/isContainer}}', 'string'); + ${{paramName}} = $this->deserialize(${{paramName}}, '{{#isContainer}}array<{{collectionFormat}}{{^collectionFormat}}csv{{/collectionFormat}},{{dataType}}>{{/isContainer}}{{^isContainer}}{{#isEnumRef}}\{{modelPackage}}\{{dataType}}{{/isEnumRef}}{{^isEnumRef}}{{dataType}}{{/isEnumRef}}{{/isContainer}}', 'string'); {{/isBodyParam}} {{/isFile}} {{/allParams}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/api_input_validation.mustache b/modules/openapi-generator/src/main/resources/php-symfony/api_input_validation.mustache index 3cda7622c716..ab8d418f9b76 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/api_input_validation.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/api_input_validation.mustache @@ -38,10 +38,15 @@ $asserts[] = new Assert\File(); {{/isFile}} {{^isFile}} + {{#isEnumRef}} + $asserts[] = new Assert\Type("\{{modelPackage}}\{{dataType}}"); + {{/isEnumRef}} + {{^isEnumRef}} $asserts[] = new Assert\Type("{{dataType}}"); {{^isPrimitiveType}} $asserts[] = new Assert\Valid(); {{/isPrimitiveType}} + {{/isEnumRef}} {{/isFile}} {{/isDateTime}} {{/isDate}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model.mustache index ec0e23540ab6..2c796990ea33 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model.mustache @@ -23,6 +23,7 @@ namespace {{modelPackage}}; use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_enum.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_enum.mustache index 5e6b2aea2157..b12428b10e2d 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_enum.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_enum.mustache @@ -1,19 +1,8 @@ -class {{classname}} +enum {{classname}}: {{dataType}} { - /** - * Possible values of this enum - */ - {{#allowableValues}}{{#enumVars}}const {{{name}}} = {{{value}}}; - {{/enumVars}}{{/allowableValues}} - /** - * Gets allowable values of the enum - * @return string[] - */ - public static function getAllowableEnumValues() - { - return [ - {{#allowableValues}}{{#enumVars}}self::{{{name}}},{{^-last}} - {{/-last}}{{/enumVars}}{{/allowableValues}} - ]; - } +{{#allowableValues}} + {{#enumVars}} + case {{{name}}} = {{{value}}}; + {{/enumVars}} +{{/allowableValues}} } diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache index 2c3636040279..2bb14a388b0b 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_generic.mustache @@ -30,6 +30,37 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}} {{/parentSchema}} return $this->{{name}}; } + {{#isEnumRef}} + /** + * Gets {{name}} for serialization. + * + * @return string|null + */ + public function getSerialized{{nameInCamelCase}}(): string|null + { + return $this->{{name}}?->value ? (string) $this->{{name}}->value : null; + } + {{/isEnumRef}} + + {{#isContainer}} + {{#items}} + {{#isEnumRef}} + /** + * Gets {{name}} for serialization. + * + * @return array + */ + public function getSerialized{{nameInCamelCase}}(): array + { + return array_map( + static fn ($value) => (string) $value->value, + $this->test ?? [] + ); + } + {{/isEnumRef}} + {{/items}} + {{/isContainer}} + /** * Sets {{name}}. * diff --git a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache index 7855e1e1c457..aae9e405aa40 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/model_variables.mustache @@ -36,23 +36,35 @@ {{/isMap}} {{^isMap}} {{#items}} + {{#isEnumRef}} + * @Accessor(getter="getSerialized{{nameInCamelCase}}") + * @Type("array") + {{/isEnumRef}} + {{^isEnumRef}} * @Type("array<{{dataType}}>") + {{/isEnumRef}} {{/items}} {{/isMap}} {{/isContainer}} {{^isContainer}} {{#isDate}} - * @Assert\Date() + * @Assert\Type("\Date") * @Type("DateTime<'Y-m-d'>") {{/isDate}} {{#isDateTime}} - * @Assert\DateTime() + * @Assert\Type("\DateTime")) * @Type("DateTime") {{/isDateTime}} + {{#isEnumRef}} + * @Accessor(getter="getSerialized{{nameInCamelCase}}") + * @Type("string") + {{/isEnumRef}} {{^isDate}} {{^isDateTime}} + {{^isEnumRef}} * @Assert\Type("{{dataType}}") * @Type("{{dataType}}") + {{/isEnumRef}} {{/isDateTime}} {{/isDate}} {{/isContainer}} diff --git a/modules/openapi-generator/src/main/resources/php-symfony/serialization/JmsSerializer.mustache b/modules/openapi-generator/src/main/resources/php-symfony/serialization/JmsSerializer.mustache index 444eef6760ef..62f167951e1e 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/serialization/JmsSerializer.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/serialization/JmsSerializer.mustache @@ -60,7 +60,7 @@ class JmsSerializer implements SerializerInterface private function deserializeString($data, string $type) { // Figure out if we have an array format - if (1 === preg_match('/array<(csv|ssv|tsv|pipes),(int|string)>/i', $type, $matches)) { + if (1 === preg_match('/array<(csv|ssv|tsv|pipes),(.*)>/i', $type, $matches)) { return $this->deserializeArrayString($matches[1], $matches[2], $data); } @@ -75,6 +75,13 @@ class JmsSerializer implements SerializerInterface return $data + 0; } + break; + case 'double': + case 'float': + if (is_float($data) || is_numeric($data)) { + return (float) $data; + } + break; case 'string': break; @@ -97,7 +104,21 @@ class JmsSerializer implements SerializerInterface case '\DateTime': return is_null($data) ? null :new DateTime($data); default: - throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + if (!class_exists($type)) { + throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + } + + $reflectionClass = new \ReflectionClass($type); + if (!$reflectionClass->implementsInterface('\BackedENum')) { + throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + } + + $enum = $type::tryFrom($data); + if (!$enum) { + throw new RuntimeException(sprintf("Unknown %s value in %s enum", $data, $type)); + } + + return $enum; } // If we end up here, just return data diff --git a/modules/openapi-generator/src/main/resources/php-symfony/serialization/SerializerInterface.mustache b/modules/openapi-generator/src/main/resources/php-symfony/serialization/SerializerInterface.mustache index 35ba55e74280..2797f0a4e2b2 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/serialization/SerializerInterface.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/serialization/SerializerInterface.mustache @@ -12,7 +12,7 @@ interface SerializerInterface * * @return string */ - public function serialize($data, string $format): string; + public function serialize($data, string $format): string; /** * Deserializes the given data to the specified type. diff --git a/modules/openapi-generator/src/main/resources/php-symfony/testing/model_test.mustache b/modules/openapi-generator/src/main/resources/php-symfony/testing/model_test.mustache index 1d971d7530aa..86480fbc8284 100644 --- a/modules/openapi-generator/src/main/resources/php-symfony/testing/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/php-symfony/testing/model_test.mustache @@ -19,8 +19,9 @@ * Please update the test case below to test the model. */ -namespace {{modelPackage}}; +namespace {{modelTestsPackage}}; +use {{modelPackage}}\{{classname}}; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -50,7 +51,9 @@ class {{classname}}Test extends TestCase */ public function setUp(): void { - $this->object = $this->getMockBuilder({{classname}}::class)->getMockForAbstractClass(); + {{^isEnum}} + $this->object = $this->getMockBuilder({{classname}}::class)->getMockForAbstractClass(); + {{/isEnum}} } /** @@ -73,8 +76,13 @@ class {{classname}}Test extends TestCase */ public function testTestClassExists(): void { + {{#isEnum}} + $this->assertTrue(enum_exists({{classname}}::class)); + {{/isEnum}} + {{^isEnum}} $this->assertTrue(class_exists({{classname}}::class)); $this->assertInstanceOf({{classname}}::class, $this->object); + {{/isEnum}} } {{#vars}} diff --git a/modules/openapi-generator/src/main/resources/php/Configuration.mustache b/modules/openapi-generator/src/main/resources/php/Configuration.mustache index 60c040a1340c..0f6aaf01f95f 100644 --- a/modules/openapi-generator/src/main/resources/php/Configuration.mustache +++ b/modules/openapi-generator/src/main/resources/php/Configuration.mustache @@ -200,7 +200,7 @@ class Configuration /** * Sets boolean format for query string. * - * @param string $booleanFormatForQueryString Boolean format for query string + * @param string $booleanFormat Boolean format for query string * * @return $this */ @@ -424,9 +424,9 @@ class Configuration $report .= ' OS: ' . php_uname() . PHP_EOL; $report .= ' PHP Version: ' . PHP_VERSION . PHP_EOL; $report .= ' The version of the OpenAPI document: {{version}}' . PHP_EOL; - {{#artifactVersion}} + {{#artifactVersion}} $report .= ' SDK Package Version: {{.}}' . PHP_EOL; - {{/artifactVersion}} + {{/artifactVersion}} $report .= ' Temp Folder Path: ' . self::getDefaultConfiguration()->getTempFolderPath() . PHP_EOL; return $report; @@ -503,18 +503,18 @@ class Configuration * @param array|null $variables hash of variable and the corresponding value (optional) * @return string URL based on host settings */ - public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) + public static function getHostString(array $hostSettings, $hostIndex, array $variables = null) { if (null === $variables) { $variables = []; } // check array index out of bound - if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { - throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostSettings)); } - $host = $hostsSettings[$hostIndex]; + $host = $hostSettings[$hostIndex]; $url = $host["url"]; // go through variable and assign a value diff --git a/modules/openapi-generator/src/main/resources/php/api.mustache b/modules/openapi-generator/src/main/resources/php/api.mustache index 9f36a5175888..30ec1cfc80ab 100644 --- a/modules/openapi-generator/src/main/resources/php/api.mustache +++ b/modules/openapi-generator/src/main/resources/php/api.mustache @@ -69,7 +69,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/consumes}} ],{{/operation}} ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -162,7 +162,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/servers}} * @param string $contentType The value for the Content-Type header. Check self::contentTypes['{{{operationId}}}'] to see the possible values for this operation * - * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @throws \{{invokerPackage}}\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}void{{/returnType}} {{#isDeprecated}} @@ -221,7 +221,7 @@ use {{invokerPackage}}\ObjectSerializer; {{/servers}} * @param string $contentType The value for the Content-Type header. Check self::contentTypes['{{{operationId}}}'] to see the possible values for this operation * - * @throws \{{invokerPackage}}\ApiException on non-2xx response + * @throws \{{invokerPackage}}\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of {{#returnType}}{{#responses}}{{#dataType}}{{^-first}}|{{/-first}}{{/dataType}}{{{dataType}}}{{/responses}}{{/returnType}}{{^returnType}}null{{/returnType}}, HTTP status code, HTTP response headers (array of strings) {{#isDeprecated}} @@ -279,7 +279,19 @@ use {{invokerPackage}}\ObjectSerializer; } else { $content = (string) $response->getBody(); if ('{{{dataType}}}' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -300,7 +312,19 @@ use {{invokerPackage}}\ObjectSerializer; } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/modules/openapi-generator/src/main/resources/php/model_generic.mustache b/modules/openapi-generator/src/main/resources/php/model_generic.mustache index aa508136092a..6b0aa6d39c4b 100644 --- a/modules/openapi-generator/src/main/resources/php/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/php/model_generic.mustache @@ -38,7 +38,7 @@ class {{classname}} {{#parentSchema}}extends {{{parent}}}{{/parentSchema}}{{^par */ protected static array $openAPINullables = [ {{#vars}}'{{name}}' => {{#isNullable}}true{{/isNullable}}{{^isNullable}}false{{/isNullable}}{{^-last}}, - {{/-last}}{{/vars}} + {{/-last}}{{/vars}} ]; /** diff --git a/modules/openapi-generator/src/main/resources/postman-collection/item.mustache b/modules/openapi-generator/src/main/resources/postman-collection/item.mustache index 416e0d8cdada..b5293f8332bf 100644 --- a/modules/openapi-generator/src/main/resources/postman-collection/item.mustache +++ b/modules/openapi-generator/src/main/resources/postman-collection/item.mustache @@ -4,7 +4,7 @@ "item": [ {{#vendorExtensions.postmanRequests}} { - "name": "{{name}}", + "name": "{{{name}}}", "request": { "method": "{{httpMethod}}", "header": [ @@ -12,6 +12,7 @@ { "key": "{{baseName}}", "value": "{{schema.defaultValue}}", + "description": "{{{description}}}", "disabled": {{#schema.defaultValue}}false{{/schema.defaultValue}}{{^schema.defaultValue}}true{{/schema.defaultValue}} }{{^-last}},{{/-last}} {{/headerParams}} @@ -39,8 +40,8 @@ {{#pathParams}} { "key": "{{paramName}}", - "value": "", - "description": "{{description}}" + "value": "{{defaultValue}}", + "description": "{{{description}}}" }{{^-last}},{{/-last}} {{/pathParams}} ], @@ -48,7 +49,9 @@ {{#queryParams}} { "key": "{{paramName}}", - "value": "{{example}}" + "value": "{{example}}", + "description": "{{{description}}}", + "disabled": {{#required}}false{{/required}}{{^required}}true{{/required}} }{{^-last}},{{/-last}} {{/queryParams}} ] diff --git a/modules/openapi-generator/src/main/resources/powershell/Build.ps1.mustache b/modules/openapi-generator/src/main/resources/powershell/Build.ps1.mustache index 6fed374afbda..be74a1180379 100644 --- a/modules/openapi-generator/src/main/resources/powershell/Build.ps1.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/Build.ps1.mustache @@ -39,7 +39,9 @@ function Get-FunctionsToExport { } $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path -$FunctionPath = 'Api', 'Model', 'Client' | ForEach-Object {Join-Path "$ScriptDir\src\{{{packageName}}}\" $_} +$FunctionPath = 'Api', 'Model', 'Client' | Where-Object { + Join-Path "$ScriptDir\src\{{{packageName}}}\" $_ | Test-Path +} | ForEach-Object { Join-Path "$ScriptDir\src\{{{packageName}}}\" $_ } $Manifest = @{ Path = "$ScriptDir\src\{{{packageName}}}\{{{packageName}}}.psd1" diff --git a/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache b/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache index 32795eca3763..feb7ee5ec66b 100644 --- a/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/Org.OpenAPITools.psm1.mustache @@ -17,7 +17,9 @@ $Script:Configuration = [System.Collections.HashTable]@{} $Script:CmdletBindingParameters = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') -'Api', 'Model', 'Client', 'Private' | Get-ChildItem -Path { +'Api', 'Model', 'Client', 'Private' | Where-Object { + Join-Path $PSScriptRoot $_ | Test-Path +} | Get-ChildItem -Path { Join-Path $PSScriptRoot $_ } -Filter '*.ps1' | ForEach-Object { Write-Debug "Importing file: $($_.BaseName)" diff --git a/modules/openapi-generator/src/main/resources/powershell/api.mustache b/modules/openapi-generator/src/main/resources/powershell/api.mustache index e94ffd28275c..79d632682cf3 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api.mustache @@ -178,15 +178,15 @@ function {{{vendorExtensions.x-powershell-method-name}}} { {{#authMethods}} {{#isApiKey}} {{#isKeyInHeader}} - if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["{{{name}}}"]) { - $LocalVarHeaderParameters['{{{name}}}'] = $Configuration["ApiKey"]["{{{name}}}"] - Write-Verbose ("Using API key '{{{name}}}' in the header for authentication in {0}" -f $MyInvocation.MyCommand) + if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["{{{keyParamName}}}"]) { + $LocalVarHeaderParameters['{{{keyParamName}}}'] = $Configuration["ApiKey"]["{{{keyParamName}}}"] + Write-Verbose ("Using API key '{{{keyParamName}}}' in the header for authentication in {0}" -f $MyInvocation.MyCommand) } {{/isKeyInHeader}} {{#isKeyInQuery}} - if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["{{{name}}}"]) { - $LocalVarQueryParameters['{{{name}}}'] = $Configuration["ApiKey"]["{{{name}}}"] - Write-Verbose ("Using API key `{{{name}}}` in the URL query for authentication in {0}" -f $MyInvocation.MyCommand) + if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["{{{keyParamName}}}"]) { + $LocalVarQueryParameters['{{{keyParamName}}}'] = $Configuration["ApiKey"]["{{{keyParamName}}}"] + Write-Verbose ("Using API key `{{{keyParamName}}}` in the URL query for authentication in {0}" -f $MyInvocation.MyCommand) } {{/isKeyInQuery}} {{#isKeyInCookie}} diff --git a/modules/openapi-generator/src/main/resources/powershell/api_client.mustache b/modules/openapi-generator/src/main/resources/powershell/api_client.mustache index f7769247fc49..d58c6750760f 100644 --- a/modules/openapi-generator/src/main/resources/powershell/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/powershell/api_client.mustache @@ -188,7 +188,7 @@ function Invoke-{{{apiNamePrefix}}}ApiClient { } return @{ - Response = DeserializeResponse -Response $Response -ReturnType $ReturnType -ContentTypes $Response.Headers["Content-Type"] + Response = DeserializeResponse -Response $Response.Content -ReturnType $ReturnType -ContentTypes $Response.Headers["Content-Type"] StatusCode = $Response.StatusCode Headers = $Response.Headers } diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/controller_test.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/controller_test.mustache index 7b89e168eb7e..b0360ee0a90a 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/controller_test.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/controller_test.mustache @@ -17,6 +17,8 @@ from aiohttp import FormData {{#operations}} {{#operation}} +pytestmark = pytest.mark.asyncio + {{#vendorExtensions.x-skip-test}} @pytest.mark.skip("{{reason}}") {{/vendorExtensions.x-skip-test}} diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache index e2ef30b1d41e..ae81351135d8 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/requirements.mustache @@ -1,4 +1,4 @@ -connexion[aiohttp,swagger-ui] >= 2.6.0; python_version>="3.6" +connexion[aiohttp,swagger-ui] >= 2.6.0, <3; python_version>="3.6" # 2.3 is the last version that supports python 3.5 connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version=="3.4" # connexion requires werkzeug but connexion < 2.4.0 does not install werkzeug @@ -10,3 +10,4 @@ aiohttp_jinja2 == 1.5.0 {{#featureCORS}} aiohttp_cors >= 0.7.0 {{/featureCORS}} +Flask < 2.3 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-aiohttp/tox.mustache b/modules/openapi-generator/src/main/resources/python-aiohttp/tox.mustache index dfebe7024ae0..7a330dfac98d 100644 --- a/modules/openapi-generator/src/main/resources/python-aiohttp/tox.mustache +++ b/modules/openapi-generator/src/main/resources/python-aiohttp/tox.mustache @@ -5,7 +5,7 @@ skipsdist=True [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - {toxinidir} + {toxinidir} commands= - {{^useNose}}pytest --cov={{#lambda.forwardslash}}{{{pythonSrcRoot}}}{{/lambda.forwardslash}}{{{packageName}}}{{/useNose}}{{#useNose}}nosetests{{/useNose}} + {{^useNose}}pytest --cov={{{packageName}}}{{/useNose}}{{#useNose}}nosetests{{/useNose}} diff --git a/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache index 81d1a746f381..2b4b6d7c4887 100644 --- a/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache +++ b/modules/openapi-generator/src/main/resources/python-fastapi/endpoint_argument_definition.mustache @@ -1 +1 @@ -{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}None{{/defaultValue}}, description="{{description}}"{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}}) \ No newline at end of file +{{#isPathParam}}{{baseName}}{{/isPathParam}}{{^isPathParam}}{{paramName}}{{/isPathParam}}: {{>param_type}} = {{#isPathParam}}Path{{/isPathParam}}{{#isHeaderParam}}Header{{/isHeaderParam}}{{#isFormParam}}Form{{/isFormParam}}{{#isQueryParam}}Query{{/isQueryParam}}{{#isCookieParam}}Cookie{{/isCookieParam}}{{#isBodyParam}}Body{{/isBodyParam}}({{&defaultValue}}{{^defaultValue}}None{{/defaultValue}}, description="{{description}}"{{#isQueryParam}}, alias="{{baseName}}"{{/isQueryParam}}{{#isLong}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isLong}}{{#isInteger}}{{#minimum}}, ge={{.}}{{/minimum}}{{#maximum}}, le={{.}}{{/maximum}}{{/isInteger}}{{#pattern}}, regex=r"{{.}}"{{/pattern}}{{#minLength}}, min_length={{.}}{{/minLength}}{{#maxLength}}, max_length={{.}}{{/maxLength}}) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python-flask/tox.mustache b/modules/openapi-generator/src/main/resources/python-flask/tox.mustache index 76e368c23931..f8a439c09211 100644 --- a/modules/openapi-generator/src/main/resources/python-flask/tox.mustache +++ b/modules/openapi-generator/src/main/resources/python-flask/tox.mustache @@ -5,7 +5,7 @@ skipsdist=True [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - {toxinidir} + {toxinidir} commands= {{^useNose}}pytest --cov={{{pythonSrcRoot}}}{{{packageName}}}{{/useNose}}{{#useNose}}nosetests{{/useNose}} diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/api_client.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/api_client.mustache index 0870094d7835..fe61bd61a5ed 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/api_client.mustache @@ -567,10 +567,10 @@ class ApiClient: if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache new file mode 100644 index 000000000000..c97788d0c5cc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/asyncio/rest.mustache @@ -0,0 +1,241 @@ +# coding: utf-8 + +{{>partial_header}} + +import io +import json +import logging +import re +import ssl + +import aiohttp +from urllib.parse import urlencode, quote_plus + +from {{packageName}}.exceptions import ApiException, ApiValueError + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp, data) -> None: + self.aiohttp_response = resp + self.status = resp.status + self.reason = resp.reason + self.data = data + + def getheaders(self): + """Returns a CIMultiDictProxy of the response headers.""" + return self.aiohttp_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.aiohttp_response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + + # maxsize is number of requests to host that are allowed in parallel + if maxsize is None: + maxsize = configuration.connection_pool_maxsize + + ssl_context = ssl.create_default_context(cafile=configuration.ssl_ca_cert) + if configuration.cert_file: + ssl_context.load_cert_chain( + configuration.cert_file, keyfile=configuration.key_file + ) + + if not configuration.verify_ssl: + ssl_context.check_hostname = False + ssl_context.verify_mode = ssl.CERT_NONE + + connector = aiohttp.TCPConnector( + limit=maxsize, + ssl=ssl_context + ) + + self.proxy = configuration.proxy + self.proxy_headers = configuration.proxy_headers + + # https pool manager + self.pool_manager = aiohttp.ClientSession( + connector=connector, + trust_env=True + ) + + async def close(self): + await self.pool_manager.close() + + async def request(self, method, url, query_params=None, headers=None, + body=None, post_params=None, _preload_content=True, + _request_timeout=None): + """Execute request + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + post_params = post_params or {} + headers = headers or {} + # url already contains the URL query string + # so reset query_params to empty dict + query_params = {} + timeout = _request_timeout or 5 * 60 + + if 'Content-Type' not in headers: + headers['Content-Type'] = 'application/json' + + args = { + "method": method, + "url": url, + "timeout": timeout, + "headers": headers + } + + if self.proxy: + args["proxy"] = self.proxy + if self.proxy_headers: + args["proxy_headers"] = self.proxy_headers + + if query_params: + args["url"] += '?' + urlencode(query_params) + + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if re.search('json', headers['Content-Type'], re.IGNORECASE): + if body is not None: + body = json.dumps(body) + args["data"] = body + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + args["data"] = aiohttp.FormData(post_params) + elif headers['Content-Type'] == 'multipart/form-data': + # must del headers['Content-Type'], or the correct + # Content-Type which generated by aiohttp + del headers['Content-Type'] + data = aiohttp.FormData() + for param in post_params: + k, v = param + if isinstance(v, tuple) and len(v) == 3: + data.add_field(k, + value=v[1], + filename=v[0], + content_type=v[2]) + else: + data.add_field(k, v) + args["data"] = data + + # Pass a `bytes` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, bytes): + args["data"] = body + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + r = await self.pool_manager.request(**args) + if _preload_content: + + data = await r.read() + r = RESTResponse(r, data) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + return r + + async def get_request(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): + return (await self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) + + async def head_request(self, url, headers=None, query_params=None, + _preload_content=True, _request_timeout=None): + return (await self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params)) + + async def options_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def delete_request(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + return (await self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def post_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def put_request(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + return (await self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) + + async def patch_request(self, url, headers=None, query_params=None, + post_params=None, body=None, _preload_content=True, + _request_timeout=None): + return (await self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body)) diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache index f49dee2bed49..1d6d255d2cd5 100644 --- a/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/rest.mustache @@ -16,6 +16,18 @@ from {{packageName}}.exceptions import ApiException, UnauthorizedException, Forb logger = logging.getLogger(__name__) +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + class RESTResponse(io.IOBase): @@ -71,17 +83,29 @@ class RESTClientObject: # https pool manager if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + self.pool_manager = SOCKSProxyManager( + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, diff --git a/modules/openapi-generator/src/main/resources/python-pydantic-v1/tornado/rest.mustache b/modules/openapi-generator/src/main/resources/python-pydantic-v1/tornado/rest.mustache new file mode 100644 index 000000000000..6b91cdef986e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python-pydantic-v1/tornado/rest.mustache @@ -0,0 +1,223 @@ +# coding: utf-8 + +{{>partial_header}} + +import io +import json +import logging +import re + +from urllib.parse import urlencode, quote_plus +import tornado +import tornado.gen +from tornado import httpclient +from urllib3.filepost import encode_multipart_formdata + +from {{packageName}}.exceptions import ApiException, ApiValueError + +logger = logging.getLogger(__name__) + + +class RESTResponse(io.IOBase): + + def __init__(self, resp) -> None: + self.tornado_response = resp + self.status = resp.code + self.reason = resp.reason + + if resp.body: + self.data = resp.body + else: + self.data = None + + def getheaders(self): + """Returns a CIMultiDictProxy of the response headers.""" + return self.tornado_response.headers + + def getheader(self, name, default=None): + """Returns a given response header.""" + return self.tornado_response.headers.get(name, default) + + +class RESTClientObject: + + def __init__(self, configuration, pools_size=4, maxsize=4) -> None: + # maxsize is number of requests to host that are allowed in parallel + + self.ca_certs = configuration.ssl_ca_cert + self.client_key = configuration.key_file + self.client_cert = configuration.cert_file + + self.proxy_port = self.proxy_host = None + + # https pool manager + if configuration.proxy: + self.proxy_port = 80 + self.proxy_host = configuration.proxy + + self.pool_manager = httpclient.AsyncHTTPClient() + + @tornado.gen.coroutine + def request(self, method, url, query_params=None, headers=None, body=None, + post_params=None, _preload_content=True, + _request_timeout=None): + """Execute Request + + :param method: http request method + :param url: http request url + :param query_params: query parameters in the url + :param headers: http request headers + :param body: request json body, for `application/json` + :param post_params: request post parameters, + `application/x-www-form-urlencoded` + and `multipart/form-data` + :param _preload_content: this is a non-applicable field for + the AiohttpClient. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + """ + method = method.upper() + assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', + 'PATCH', 'OPTIONS'] + + if post_params and body: + raise ApiValueError( + "body parameter cannot be used with post_params parameter." + ) + + request = httpclient.HTTPRequest(url) + request.allow_nonstandard_methods = True + request.ca_certs = self.ca_certs + request.client_key = self.client_key + request.client_cert = self.client_cert + request.proxy_host = self.proxy_host + request.proxy_port = self.proxy_port + request.method = method + if headers: + request.headers = headers + if 'Content-Type' not in headers: + request.headers['Content-Type'] = 'application/json' + request.request_timeout = _request_timeout or 5 * 60 + + post_params = post_params or {} + + if query_params: + request.url += '?' + urlencode(query_params) + + # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` + if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: + if re.search('json', headers['Content-Type'], re.IGNORECASE): + if body: + body = json.dumps(body) + request.body = body + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + request.body = urlencode(post_params) + elif headers['Content-Type'] == 'multipart/form-data': + multipart = encode_multipart_formdata(post_params) + request.body, headers['Content-Type'] = multipart + # Pass a `bytes` parameter directly in the body to support + # other content types than Json when `body` argument is provided + # in serialized form + elif isinstance(body, bytes): + request.body = body + else: + # Cannot generate the request from given parameters + msg = """Cannot prepare a request message for provided + arguments. Please check that your arguments match + declared content type.""" + raise ApiException(status=0, reason=msg) + + r = yield self.pool_manager.fetch(request, raise_error=False) + + if _preload_content: + + r = RESTResponse(r) + + # log response body + logger.debug("response body: %s", r.data) + + if not 200 <= r.status <= 299: + raise ApiException(http_resp=r) + + raise tornado.gen.Return(r) + + @tornado.gen.coroutine + def GET(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + result = yield self.request("GET", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def HEAD(self, url, headers=None, query_params=None, _preload_content=True, + _request_timeout=None): + result = yield self.request("HEAD", url, + headers=headers, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + query_params=query_params) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def OPTIONS(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("OPTIONS", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def DELETE(self, url, headers=None, query_params=None, body=None, + _preload_content=True, _request_timeout=None): + result = yield self.request("DELETE", url, + headers=headers, + query_params=query_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def POST(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("POST", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def PUT(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("PUT", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) + + @tornado.gen.coroutine + def PATCH(self, url, headers=None, query_params=None, post_params=None, + body=None, _preload_content=True, _request_timeout=None): + result = yield self.request("PATCH", url, + headers=headers, + query_params=query_params, + post_params=post_params, + _preload_content=_preload_content, + _request_timeout=_request_timeout, + body=body) + raise tornado.gen.Return(result) diff --git a/modules/openapi-generator/src/main/resources/python/api.mustache b/modules/openapi-generator/src/main/resources/python/api.mustache index 5b2369b9033d..92f02ac50d18 100644 --- a/modules/openapi-generator/src/main/resources/python/api.mustache +++ b/modules/openapi-generator/src/main/resources/python/api.mustache @@ -1,24 +1,18 @@ # coding: utf-8 {{>partial_header}} - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated {{#imports}} {{import}} {{/imports}} -from {{packageName}}.api_client import ApiClient +from {{packageName}}.api_client import ApiClient, RequestSerialized from {{packageName}}.api_response import ApiResponse -from {{packageName}}.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from {{packageName}}.rest import RESTResponseType {{#operations}} @@ -35,315 +29,206 @@ class {{classname}}: self.api_client = api_client {{#operation}} + @validate_call -{{#asyncio}} - async def {{operationId}}( - self, - {{#allParams}} - {{paramName}}: {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, - {{/allParams}} - **kwargs, - ) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: -{{/asyncio}} -{{^asyncio}} - def {{operationId}}( - self, - {{#allParams}} - {{paramName}}: {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, - {{/allParams}} - **kwargs, - ) -> {{{returnType}}}{{^returnType}}None{{/returnType}}: -{{/asyncio}} - """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + {{#asyncio}}async {{/asyncio}}def {{operationId}}{{>partial_api_args}} -> {{{returnType}}}{{^returnType}}None{{/returnType}}: +{{>partial_api}} + response_data = {{#asyncio}}await {{/asyncio}}self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + {{#asyncio}}await {{/asyncio}}response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data -{{#notes}} - {{{.}}} # noqa: E501 -{{/notes}} -{{^asyncio}} - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.{{operationId}}({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) - >>> result = thread.get() -{{/asyncio}} + @validate_call + {{#asyncio}}async {{/asyncio}}def {{operationId}}_with_http_info{{>partial_api_args}} -> ApiResponse[{{{returnType}}}{{^returnType}}None{{/returnType}}]: +{{>partial_api}} + response_data = {{#asyncio}}await {{/asyncio}}self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + {{#asyncio}}await {{/asyncio}}response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) -{{#allParams}} - :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} - :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} -{{/allParams}} -{{^asyncio}} - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional -{{/asyncio}} - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: {{returnType}}{{^returnType}}None{{/returnType}} - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the {{operationId}}_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return {{#asyncio}}await {{/asyncio}}self.{{operationId}}_with_http_info.raw_function( - {{#allParams}} - {{paramName}}, - {{/allParams}} - **kwargs, + @validate_call + {{#asyncio}}async {{/asyncio}}def {{operationId}}_without_preload_content{{>partial_api_args}} -> RESTResponseType: +{{>partial_api}} + response_data = {{#asyncio}}await {{/asyncio}}self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - @validate_call -{{#asyncio}} - async def {{operationId}}_with_http_info( - self, - {{#allParams}} - {{paramName}}: {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, - {{/allParams}} - **kwargs, - ) -> ApiResponse: -{{/asyncio}} -{{^asyncio}} - def {{operationId}}_with_http_info( + + def _{{operationId}}_serialize( self, {{#allParams}} - {{paramName}}: {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, + {{paramName}}, {{/allParams}} - **kwargs, - ) -> ApiResponse: -{{/asyncio}} - """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} # noqa: E501 + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: -{{#notes}} - {{{.}}} # noqa: E501 -{{/notes}} -{{^asyncio}} - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.{{operationId}}_with_http_info({{#allParams}}{{paramName}}, {{/allParams}}async_req=True) - >>> result = thread.get() -{{/asyncio}} - -{{#allParams}} - :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} - :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} -{{/allParams}} -{{^asyncio}} - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional -{{/asyncio}} - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: {{#returnType}}tuple({{.}}, status_code(int), headers(HTTPHeaderDict)){{/returnType}}{{^returnType}}None{{/returnType}} - """ - - {{#isDeprecated}} - warnings.warn("{{{httpMethod}}} {{{path}}} is deprecated.", DeprecationWarning) - - {{/isDeprecated}} {{#servers.0}} - _hosts = [ -{{#servers}} - '{{{url}}}'{{^-last}},{{/-last}} -{{/servers}} + _hosts = [{{#servers}} + '{{{url}}}'{{^-last}},{{/-last}}{{/servers}} ] - _host = _hosts[0] - if kwargs.get('_host_index'): - _host_index = int(kwargs.get('_host_index')) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" - % len(_host) - ) - _host = _hosts[_host_index] + _host = _hosts[_host_index] + {{/servers.0}} + {{^servers.0}} + _host = None {{/servers.0}} - _params = locals() - - _all_params = [ -{{#allParams}} - '{{paramName}}'{{^-last}},{{/-last}} -{{/allParams}} - ] - _all_params.extend( - [ -{{^asyncio}} - 'async_req', -{{/asyncio}} - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params{{#servers.0}} and _key != "_host_index"{{/servers.0}}: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method {{operationId}}" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _collection_formats: Dict[str, str] = { + {{#allParams}} + {{#isArray}} + '{{baseName}}': '{{collectionFormat}}', + {{/isArray}} + {{/allParams}} + } - _collection_formats: Dict[str, str] = {} + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None # process the path parameters - _path_params: Dict[str, str] = {} {{#pathParams}} - if _params['{{paramName}}'] is not None: - _path_params['{{baseName}}'] = _params['{{paramName}}']{{#isEnumRef}}.value{{/isEnumRef}} - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - + if {{paramName}} is not None: + _path_params['{{baseName}}'] = {{paramName}}{{#isEnumRef}}.value{{/isEnumRef}} {{/pathParams}} - # process the query parameters - _query_params: List[Tuple[str, str]] = [] {{#queryParams}} - if _params.get('{{paramName}}') is not None: # noqa: E501 + if {{paramName}} is not None: {{#isDateTime}} - if isinstance(_params['{{paramName}}'], datetime): - _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.datetime_format))) + if isinstance({{paramName}}, datetime): + _query_params.append( + ( + '{{baseName}}', + {{paramName}}.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) else: - _query_params.append(('{{baseName}}', _params['{{paramName}}'])) + _query_params.append(('{{baseName}}', {{paramName}})) {{/isDateTime}} - {{^isDateTime}} {{#isDate}} - if isinstance(_params['{{paramName}}'], date): - _query_params.append(('{{baseName}}', _params['{{paramName}}'].strftime(self.api_client.configuration.date_format))) + if isinstance({{paramName}}, date): + _query_params.append( + ( + '{{baseName}}', + {{paramName}}.strftime( + self.api_client.configuration.date_format + ) + ) + ) else: - _query_params.append(('{{baseName}}', _params['{{paramName}}'])) + _query_params.append(('{{baseName}}', {{paramName}})) {{/isDate}} - {{^isDate}} - _query_params.append(('{{baseName}}', _params['{{paramName}}']{{#isEnumRef}}.value{{/isEnumRef}})) - {{/isDate}} - {{/isDateTime}} - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - + {{^isDateTime}}{{^isDate}} + _query_params.append(('{{baseName}}', {{paramName}}{{#isEnumRef}}.value{{/isEnumRef}})) + {{/isDate}}{{/isDateTime}} {{/queryParams}} # process the header parameters - _header_params = dict(_params.get('_headers', {})) {{#headerParams}} - if _params['{{paramName}}'] is not None: - _header_params['{{baseName}}'] = _params['{{paramName}}'] - {{#isArray}} - _collection_formats['{{baseName}}'] = '{{collectionFormat}}' - {{/isArray}} - + if {{paramName}} is not None: + _header_params['{{baseName}}'] = {{paramName}} {{/headerParams}} # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} {{#formParams}} - if _params['{{paramName}}'] is not None: - {{^isFile}} - _form_params.append(('{{{baseName}}}', _params['{{paramName}}'])) - {{/isFile}} + if {{paramName}} is not None: {{#isFile}} - _files['{{{baseName}}}'] = _params['{{paramName}}'] + _files['{{{baseName}}}'] = {{paramName}} + {{/isFile}} + {{^isFile}} + _form_params.append(('{{{baseName}}}', {{paramName}})) {{/isFile}} - {{#isArray}} - _collection_formats['{{{baseName}}}'] = '{{collectionFormat}}' - {{/isArray}} - {{/formParams}} # process the body parameter - _body_params = None {{#bodyParam}} - if _params['{{paramName}}'] is not None: - _body_params = _params['{{paramName}}'] + if {{paramName}} is not None: {{#isBinary}} # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file + if isinstance({{paramName}}, str): + with open({{paramName}}, "rb") as _fp: + _body_params = _fp.read() + else: + _body_params = {{paramName}} + {{/isBinary}} + {{^isBinary}} + _body_params = {{paramName}} {{/isBinary}} - {{/bodyParam}} + + {{#constantParams}} + {{#isQueryParam}} + # Set client side default value of Query Param "{{baseName}}". + _query_params['{{baseName}}'] = {{#_enum}}'{{{.}}}'{{/_enum}} + {{/isQueryParam}} + {{#isHeaderParam}} + # Set client side default value of Header Param "{{baseName}}". + _header_params['{{baseName}}'] = {{#_enum}}'{{{.}}}'{{/_enum}} + {{/isHeaderParam}} + {{/constantParams}} + {{#hasProduces}} # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - [{{#produces}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}}]) # noqa: E501 - + [{{#produces}} + '{{{mediaType}}}'{{^-last}}, {{/-last}}{{/produces}} + ] + ) {{/hasProduces}} + {{#hasConsumes}} # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - [{{#consumes}}'{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}}])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [{{#consumes}} + '{{{mediaType}}}'{{^-last}}, {{/-last}}{{/consumes}} + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type {{/hasConsumes}} - # authentication setting - _auth_settings: List[str] = [{{#authMethods}}'{{name}}'{{^-last}}, {{/-last}}{{/authMethods}}] # noqa: E501 - {{#returnType}} - {{#responses}} - {{#-first}} - _response_types_map: Dict[str, Optional[str]] = { - {{/-first}} - {{^isWildcard}} - '{{code}}': {{#dataType}}"{{.}}"{{/dataType}}{{^dataType}}None{{/dataType}}, - {{/isWildcard}} - {{#-last}} - } - {{/-last}} - {{/responses}} - {{/returnType}} - {{^returnType}} - _response_types_map: Dict[str, Optional[str]] = {} - {{/returnType}} + # authentication setting + _auth_settings: List[str] = [{{#authMethods}} + '{{name}}'{{^-last}}, {{/-last}}{{/authMethods}} + ] - return {{#asyncio}}await {{/asyncio}}self.api_client.call_api( - '{{{path}}}', '{{httpMethod}}', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='{{httpMethod}}', + resource_path='{{{path}}}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, -{{^asyncio}} - async_req=_params.get('async_req'), -{{/asyncio}} - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - {{#servers.0}} - _host=_host, - {{/servers.0}} collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + {{/operation}} {{/operations}} diff --git a/modules/openapi-generator/src/main/resources/python/api_client.mustache b/modules/openapi-generator/src/main/resources/python/api_client.mustache index 0870094d7835..8c9812db7d2b 100644 --- a/modules/openapi-generator/src/main/resources/python/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_client.mustache @@ -2,29 +2,35 @@ {{>partial_header}} -import atexit import datetime from dateutil.parser import parse import json import mimetypes -{{^asyncio}} -from multiprocessing.pool import ThreadPool -{{/asyncio}} import os import re import tempfile from urllib.parse import quote +from typing import Tuple, Optional, List, Dict {{#tornado}} import tornado.gen {{/tornado}} from {{packageName}}.configuration import Configuration -from {{packageName}}.api_response import ApiResponse +from {{packageName}}.api_response import ApiResponse, T as ApiResponseT import {{modelPackage}} from {{packageName}} import rest -from {{packageName}}.exceptions import ApiValueError, ApiException - +from {{packageName}}.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -40,10 +46,6 @@ class ApiClient: the API. :param cookie: a cookie to include in the header when making calls to the API -{{^asyncio}} - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. -{{/asyncio}} """ PRIMITIVE_TYPES = (float, bool, bytes, str, int) @@ -59,15 +61,17 @@ class ApiClient: } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None{{^asyncio}}, pool_threads=1{{/asyncio}}) -> None: + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration -{{^asyncio}} - self.pool_threads = pool_threads -{{/asyncio}} self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} @@ -93,25 +97,7 @@ class ApiClient: return self def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool + pass {{/asyncio}} @property @@ -153,16 +139,42 @@ class ApiClient: """ cls._default = default - {{#tornado}} - @tornado.gen.coroutine - {{/tornado}} - {{#asyncio}}async {{/asyncio}}def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -173,14 +185,17 @@ class ApiClient: header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -192,15 +207,22 @@ class ApiClient: if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: @@ -216,70 +238,102 @@ class ApiClient: # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query + return method, url, header_params, body, post_params + + + {{#tornado}} + @tornado.gen.coroutine + {{/tornado}} + {{#asyncio}}async {{/asyncio}}def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + try: # perform request and return response - response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.request( + response_data = {{#asyncio}}await {{/asyncio}}{{#tornado}}yield {{/tornado}}self.rest_client.request( method, url, - query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') raise e - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - -{{^tornado}} - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) -{{/tornado}} -{{#tornado}} - if _return_http_data_only: - raise tornado.gen.Return(return_data) - else: - raise tornado.gen.Return(ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data)) -{{/tornado}} + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -300,15 +354,17 @@ class ApiClient: elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except @@ -318,10 +374,12 @@ class ApiClient: # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -330,16 +388,12 @@ class ApiClient: :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -356,12 +410,16 @@ class ApiClient: if isinstance(klass, str): if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -382,150 +440,6 @@ class ApiClient: else: return self.__deserialize_model(data, klass) - {{#asyncio}}async {{/asyncio}}def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - {{^asyncio}}async_req=None, {{/asyncio}}_return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - -{{^asyncio}} - To make an async_req request, set the async_req parameter. - -{{/asyncio}} - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. -{{^asyncio}} - :param async_req bool: execute request asynchronously -{{/asyncio}} - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: -{{#asyncio}} - The response. -{{/asyncio}} -{{^asyncio}} - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. -{{/asyncio}} - """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) -{{#asyncio}} - return await self.__call_api(*args) -{{/asyncio}} -{{^asyncio}} - if not async_req: - return self.__call_api(*args) - - return self.pool.apply_async(self.__call_api, args) -{{/asyncio}} - - {{#asyncio}}async {{/asyncio}}def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return {{#asyncio}}await {{/asyncio}}self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return {{#asyncio}}await {{/asyncio}}self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return {{#asyncio}}await {{/asyncio}}self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return {{#asyncio}}await {{/asyncio}}self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return {{#asyncio}}await {{/asyncio}}self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return {{#asyncio}}await {{/asyncio}}self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return {{#asyncio}}await {{/asyncio}}self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -533,10 +447,10 @@ class ApiClient: :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -563,14 +477,14 @@ class ApiClient: :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) + for k, v in params.items() if isinstance(params, dict) else params: if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) @@ -588,7 +502,8 @@ class ApiClient: else: # csv is the default delimiter = ',' new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -611,21 +526,24 @@ class ApiClient: with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None for accept in accepts: if re.search('json', accept, re.IGNORECASE): @@ -648,9 +566,16 @@ class ApiClient: return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -667,21 +592,36 @@ class ApiClient: return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -719,6 +659,9 @@ class ApiClient: Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -728,8 +671,12 @@ class ApiClient: content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/modules/openapi-generator/src/main/resources/python/api_doc.mustache b/modules/openapi-generator/src/main/resources/python/api_doc.mustache index 4a1d3648013c..6a58fc9aa906 100644 --- a/modules/openapi-generator/src/main/resources/python/api_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_doc.mustache @@ -40,6 +40,7 @@ Method | HTTP request | Description {{> api_doc_example }} ### Parameters + {{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} Name | Type | Description | Notes ------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} @@ -61,6 +62,7 @@ Name | Type | Description | Notes {{#responses.0}} ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| {{#responses}} diff --git a/modules/openapi-generator/src/main/resources/python/api_doc_example.mustache b/modules/openapi-generator/src/main/resources/python/api_doc_example.mustache index 15fbe332696a..f5d7eef120ba 100644 --- a/modules/openapi-generator/src/main/resources/python/api_doc_example.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_doc_example.mustache @@ -1,6 +1,5 @@ + ```python -import time -import os import {{{packageName}}} {{#vendorExtensions.x-py-example-import}} {{{.}}} @@ -35,4 +34,4 @@ from pprint import pprint {{{.}}} {{/vendorExtensions.x-py-postponed-example-imports}} {{classname}}.update_forward_refs() -{{/vendorExtensions.x-py-postponed-example-imports.size}} \ No newline at end of file +{{/vendorExtensions.x-py-postponed-example-imports.size}} diff --git a/modules/openapi-generator/src/main/resources/python/api_response.mustache b/modules/openapi-generator/src/main/resources/python/api_response.mustache index a0b62b95246c..9bc7c11f6b9f 100644 --- a/modules/openapi-generator/src/main/resources/python/api_response.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_response.mustache @@ -1,25 +1,21 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel -class ApiResponse: +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): """ API response object """ - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data + model_config = { + "arbitrary_types_allowed": True + } diff --git a/modules/openapi-generator/src/main/resources/python/api_test.mustache b/modules/openapi-generator/src/main/resources/python/api_test.mustache index ad2b8a63fe17..5354d3cba7cc 100644 --- a/modules/openapi-generator/src/main/resources/python/api_test.mustache +++ b/modules/openapi-generator/src/main/resources/python/api_test.mustache @@ -4,14 +4,14 @@ import unittest -from {{apiPackage}}.{{classFilename}} import {{classname}} # noqa: E501 +from {{apiPackage}}.{{classFilename}} import {{classname}} class {{#operations}}Test{{classname}}(unittest.TestCase): """{{classname}} unit test stubs""" def setUp(self) -> None: - self.api = {{classname}}() # noqa: E501 + self.api = {{classname}}() def tearDown(self) -> None: pass @@ -21,7 +21,7 @@ class {{#operations}}Test{{classname}}(unittest.TestCase): """Test case for {{{operationId}}} {{#summary}} - {{{.}}} # noqa: E501 + {{{.}}} {{/summary}} """ pass diff --git a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache index c97788d0c5cc..7cf3499fadf4 100644 --- a/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/asyncio/rest.mustache @@ -4,44 +4,51 @@ import io import json -import logging import re import ssl +from typing import Optional, Union import aiohttp -from urllib.parse import urlencode, quote_plus +import aiohttp_retry from {{packageName}}.exceptions import ApiException, ApiValueError -logger = logging.getLogger(__name__) +RESTResponseType = aiohttp.ClientResponse +ALLOW_RETRY_METHODS = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}) class RESTResponse(io.IOBase): - def __init__(self, resp, data) -> None: - self.aiohttp_response = resp + def __init__(self, resp) -> None: + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = data + self.data = None + + async def read(self): + if self.data is None: + self.data = await self.response.read() + return self.data def getheaders(self): """Returns a CIMultiDictProxy of the response headers.""" - return self.aiohttp_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.aiohttp_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # maxsize is number of requests to host that are allowed in parallel - if maxsize is None: - maxsize = configuration.connection_pool_maxsize + maxsize = configuration.connection_pool_maxsize - ssl_context = ssl.create_default_context(cafile=configuration.ssl_ca_cert) + ssl_context = ssl.create_default_context( + cafile=configuration.ssl_ca_cert + ) if configuration.cert_file: ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file @@ -65,32 +72,59 @@ class RESTClientObject: trust_env=True ) + retries = configuration.retries + self.retry_client: Optional[aiohttp_retry.RetryClient] + if retries is not None: + self.retry_client = aiohttp_retry.RetryClient( + client_session=self.pool_manager, + retry_options=aiohttp_retry.ExponentialRetry( + attempts=retries, + factor=0.0, + start_timeout=0.0, + max_timeout=120.0 + ) + ) + else: + self.retry_client = None + async def close(self): await self.pool_manager.close() - - async def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + if self.retry_client is not None: + await self.retry_client.close() + + async def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Execute request :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for - the AiohttpClient. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -100,8 +134,6 @@ class RESTClientObject: post_params = post_params or {} headers = headers or {} # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = _request_timeout or 5 * 60 if 'Content-Type' not in headers: @@ -119,16 +151,13 @@ class RESTClientObject: if self.proxy_headers: args["proxy_headers"] = self.proxy_headers - if query_params: - args["url"] += '?' + urlencode(query_params) - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if re.search('json', headers['Content-Type'], re.IGNORECASE): if body is not None: body = json.dumps(body) args["data"] = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': args["data"] = aiohttp.FormData(post_params) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct @@ -138,10 +167,12 @@ class RESTClientObject: for param in post_params: k, v = param if isinstance(v, tuple) and len(v) == 3: - data.add_field(k, - value=v[1], - filename=v[0], - content_type=v[2]) + data.add_field( + k, + value=v[1], + filename=v[0], + content_type=v[2] + ) else: data.add_field(k, v) args["data"] = data @@ -158,84 +189,17 @@ class RESTClientObject: declared content type.""" raise ApiException(status=0, reason=msg) - r = await self.pool_manager.request(**args) - if _preload_content: - - data = await r.read() - r = RESTResponse(r, data) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - async def get_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def head_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def options_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return (await self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def post_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return (await self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def patch_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) + pool_manager: Union[aiohttp.ClientSession, aiohttp_retry.RetryClient] + if self.retry_client is not None and method in ALLOW_RETRY_METHODS: + pool_manager = self.retry_client + else: + pool_manager = self.pool_manager + + r = await pool_manager.request(**args) + + return RESTResponse(r) + + + + + diff --git a/modules/openapi-generator/src/main/resources/python/common_README.mustache b/modules/openapi-generator/src/main/resources/python/common_README.mustache index 706d9b344b83..b7ce4615dfdf 100644 --- a/modules/openapi-generator/src/main/resources/python/common_README.mustache +++ b/modules/openapi-generator/src/main/resources/python/common_README.mustache @@ -1,6 +1,5 @@ ```python {{#apiInfo}}{{#apis}}{{#-last}}{{#hasHttpSignatureMethods}}import datetime{{/hasHttpSignatureMethods}}{{/-last}}{{/apis}}{{/apiInfo}} -import time import {{{packageName}}} from {{{packageName}}}.rest import ApiException from pprint import pprint diff --git a/modules/openapi-generator/src/main/resources/python/configuration.mustache b/modules/openapi-generator/src/main/resources/python/configuration.mustache index c3799c0c5e0d..aafd0d6f535b 100644 --- a/modules/openapi-generator/src/main/resources/python/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/python/configuration.mustache @@ -4,10 +4,12 @@ import copy import logging +from logging import FileHandler {{^asyncio}} import multiprocessing {{/asyncio}} import sys +from typing import Optional import urllib3 import http.client as httplib @@ -204,7 +206,7 @@ conf = {{{packageName}}}.Configuration( self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -252,7 +254,7 @@ conf = {{{packageName}}}.Configuration( """ {{/asyncio}} - self.proxy = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None diff --git a/modules/openapi-generator/src/main/resources/python/exceptions.mustache b/modules/openapi-generator/src/main/resources/python/exceptions.mustache index 8a155a9fe08e..a690ceb926cb 100644 --- a/modules/openapi-generator/src/main/resources/python/exceptions.mustache +++ b/modules/openapi-generator/src/main/resources/python/exceptions.mustache @@ -1,6 +1,8 @@ # coding: utf-8 {{>partial_header}} +from typing import Any, Optional +from typing_extensions import Self class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" @@ -91,17 +93,56 @@ class ApiKeyError(OpenApiException, KeyError): class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) def __str__(self): """Custom error messages for exception""" @@ -111,38 +152,30 @@ class ApiException(OpenApiException): error_message += "HTTP response headers: {0}\n".format( self.headers) - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message + class BadRequestException(ApiException): + pass - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + pass class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + pass class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + pass class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + pass def render_path(path_to_item): diff --git a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache index 0c391c0071f7..4c00a2a8324d 100644 --- a/modules/openapi-generator/src/main/resources/python/model_anyof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_anyof.mustache @@ -3,9 +3,6 @@ from inspect import getfullargspec import json import pprint import re # noqa: F401 -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} {{#vendorExtensions.x-py-other-imports}} {{{.}}} {{/vendorExtensions.x-py-other-imports}} @@ -13,12 +10,8 @@ import re # noqa: F401 {{{.}}} {{/vendorExtensions.x-py-model-imports}} from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal -from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Literal, Self +from pydantic import Field {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS = [{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}] @@ -35,10 +28,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} actual_instance: Optional[Union[{{#anyOf}}{{{.}}}{{^-last}}, {{/-last}}{{/anyOf}}]] = None else: actual_instance: Any = None - any_of_schemas: List[str] = Literal[{{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ANY_OF_SCHEMAS] + any_of_schemas: List[str] = Field(default=Literal[{{#anyOf}}"{{.}}"{{^-last}}, {{/-last}}{{/anyOf}}]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } {{#discriminator}} @@ -101,7 +95,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -160,22 +154,20 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], {{#anyOf}}{{.}}{{^-last}}, {{/-last}}{{/anyOf}}]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: - return "null" + return None - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" @@ -183,10 +175,8 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} -from typing import TYPE_CHECKING -if TYPE_CHECKING: - {{{.}}} - # TODO: pydantic v2 +{{{.}}} {{/vendorExtensions.x-py-postponed-model-imports}} - # {{classname}}.model_rebuild() +# TODO: Rewrite to not use raise_errors +{{classname}}.model_rebuild(raise_errors=False) {{/vendorExtensions.x-py-postponed-model-imports.size}} diff --git a/modules/openapi-generator/src/main/resources/python/model_doc.mustache b/modules/openapi-generator/src/main/resources/python/model_doc.mustache index dd54470b3be5..deb49f248848 100644 --- a/modules/openapi-generator/src/main/resources/python/model_doc.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_doc.mustache @@ -4,6 +4,7 @@ {{/description}} ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- {{#vars}}**{{name}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}[**{{dataType}}**]({{complexType}}.md){{/isPrimitiveType}} | {{description}} | {{^required}}[optional] {{/required}}{{#isReadOnly}}[readonly] {{/isReadOnly}}{{#defaultValue}}[default to {{{.}}}]{{/defaultValue}} diff --git a/modules/openapi-generator/src/main/resources/python/model_enum.mustache b/modules/openapi-generator/src/main/resources/python/model_enum.mustache index 0bd7dafbeef8..3f449b121a33 100644 --- a/modules/openapi-generator/src/main/resources/python/model_enum.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_enum.mustache @@ -1,15 +1,10 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} -try: - from typing import Self -except ImportError: - from typing_extensions import Self +{{#vendorExtensions.x-py-other-imports}} +{{{.}}} +{{/vendorExtensions.x-py-other-imports}} +from typing_extensions import Self class {{classname}}({{vendorExtensions.x-py-enum-type}}, Enum): diff --git a/modules/openapi-generator/src/main/resources/python/model_generic.mustache b/modules/openapi-generator/src/main/resources/python/model_generic.mustache index ca6372d2d90c..c9df87810970 100644 --- a/modules/openapi-generator/src/main/resources/python/model_generic.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_generic.mustache @@ -3,25 +3,19 @@ import pprint import re # noqa: F401 import json -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} {{#vendorExtensions.x-py-other-imports}} {{{.}}} {{/vendorExtensions.x-py-other-imports}} {{#vendorExtensions.x-py-model-imports}} {{{.}}} {{/vendorExtensions.x-py-model-imports}} -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}}): """ - {{#description}}{{{description}}} # noqa: E501{{/description}}{{^description}}{{{classname}}}{{/description}} - """ + {{#description}}{{{description}}}{{/description}}{{^description}}{{{classname}}}{{/description}} + """ # noqa: E501 {{#vars}} {{name}}: {{{vendorExtensions.x-py-typing}}} {{/vars}} @@ -83,14 +77,15 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } {{#hasChildren}} {{#discriminator}} # JSON field name that stores the object type - __discriminator_property_name: ClassVar[List[str]] = '{{discriminator.propertyBaseName}}' + __discriminator_property_name: ClassVar[str] = '{{discriminator.propertyBaseName}}' # discriminator mappings __discriminator_value_class_map: ClassVar[Dict[str, str]] = { @@ -98,7 +93,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} } @classmethod - def get_discriminator_value(cls, obj: dict) -> str: + def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: """Returns the discriminator value (object type) of the data""" discriminator_value = obj[cls.__discriminator_property_name] if discriminator_value: @@ -118,7 +113,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}: + def from_json(cls, json_str: str) -> Optional[{{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}]: """Create an instance of {{{classname}}} from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -138,16 +133,18 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} * Fields in `self.additional_properties` are added to the output dict. {{/isAdditionalPropertiesTrue}} """ + excluded_fields: Set[str] = set([ + {{#vendorExtensions.x-py-readonly}} + "{{{.}}}", + {{/vendorExtensions.x-py-readonly}} + {{#isAdditionalPropertiesTrue}} + "additional_properties", + {{/isAdditionalPropertiesTrue}} + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - {{#vendorExtensions.x-py-readonly}} - "{{{.}}}", - {{/vendorExtensions.x-py-readonly}} - {{#isAdditionalPropertiesTrue}} - "additional_properties", - {{/isAdditionalPropertiesTrue}} - }, + exclude=excluded_fields, exclude_none=True, ) {{#allVars}} @@ -237,10 +234,10 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/allVars}} return _dict + {{#hasChildren}} @classmethod - def from_dict(cls, obj: dict) -> {{^hasChildren}}Self{{/hasChildren}}{{#hasChildren}}{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}{{/hasChildren}}: + def from_dict(cls, obj: Dict[str, Any]) -> Optional[{{#discriminator}}Union[{{#children}}Self{{^-last}}, {{/-last}}{{/children}}]{{/discriminator}}{{^discriminator}}Self{{/discriminator}}]: """Create an instance of {{{classname}}} from a dict""" - {{#hasChildren}} {{#discriminator}} # look up the object type based on discriminator mapping object_type = cls.get_discriminator_value(obj) @@ -252,8 +249,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} json.dumps(obj) + ". Discriminator property name: " + cls.__discriminator_property_name + ", mapping: " + json.dumps(cls.__discriminator_value_class_map)) {{/discriminator}} - {{/hasChildren}} - {{^hasChildren}} + {{/hasChildren}} + {{^hasChildren}} + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of {{{classname}}} from a dict""" if obj is None: return None @@ -280,7 +280,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{^items.items.isPrimitiveType}} "{{{baseName}}}": [ [{{{items.items.dataType}}}.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("{{{baseName}}}") + for _item in obj["{{{baseName}}}"] ] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} {{/items.items.isPrimitiveType}} {{/items.isArray}} @@ -290,7 +290,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} {{/items.isEnumOrRef}} {{^items.isEnumOrRef}} - "{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj.get("{{{baseName}}}")] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + "{{{baseName}}}": [{{{items.dataType}}}.from_dict(_item) for _item in obj["{{{baseName}}}"]] if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} {{/items.isEnumOrRef}} {{/items.isPrimitiveType}} {{#items.isPrimitiveType}} @@ -323,14 +323,14 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} if _v is not None else None ) - for _k, _v in obj.get("{{{baseName}}}").items() + for _k, _v in obj.get("{{{baseName}}}", {}).items() ){{^-last}},{{/-last}} {{/items.isArray}} {{/items.isContainer}} {{^items.isContainer}} "{{{baseName}}}": dict( (_k, {{{items.dataType}}}.from_dict(_v)) - for _k, _v in obj.get("{{{baseName}}}").items() + for _k, _v in obj["{{{baseName}}}"].items() ) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} @@ -348,7 +348,7 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{^isContainer}} {{^isPrimitiveType}} {{^isEnumOrRef}} - "{{{baseName}}}": {{{dataType}}}.from_dict(obj.get("{{{baseName}}}")) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} + "{{{baseName}}}": {{{dataType}}}.from_dict(obj["{{{baseName}}}"]) if obj.get("{{{baseName}}}") is not None else None{{^-last}},{{/-last}} {{/isEnumOrRef}} {{#isEnumOrRef}} "{{{baseName}}}": obj.get("{{{baseName}}}"){{^-last}},{{/-last}} @@ -373,15 +373,12 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{/isAdditionalPropertiesTrue}} return _obj - {{/hasChildren}} + {{/hasChildren}} {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} {{{.}}} {{/vendorExtensions.x-py-postponed-model-imports}} -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # {{classname}}.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +{{classname}}.model_rebuild(raise_errors=False) {{/vendorExtensions.x-py-postponed-model-imports.size}} diff --git a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache index 36c46e5c4f2b..9a449100a558 100644 --- a/modules/openapi-generator/src/main/resources/python/model_oneof.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_oneof.mustache @@ -1,24 +1,15 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 -{{#vendorExtensions.x-py-datetime-imports}}{{#-first}}from datetime import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-datetime-imports}} -{{#vendorExtensions.x-py-typing-imports}}{{#-first}}from typing import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-typing-imports}} -{{#vendorExtensions.x-py-pydantic-imports}}{{#-first}}from pydantic import{{/-first}} {{{.}}}{{^-last}},{{/-last}}{{/vendorExtensions.x-py-pydantic-imports}} {{#vendorExtensions.x-py-other-imports}} {{{.}}} {{/vendorExtensions.x-py-other-imports}} {{#vendorExtensions.x-py-model-imports}} {{{.}}} {{/vendorExtensions.x-py-model-imports}} -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self {{#lambda.uppercase}}{{{classname}}}{{/lambda.uppercase}}_ONE_OF_SCHEMAS = [{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] @@ -31,10 +22,11 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{vendorExtensions.x-py-name}}: {{{vendorExtensions.x-py-typing}}} {{/composedSchemas.oneOf}} actual_instance: Optional[Union[{{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]] = None - one_of_schemas: List[str] = Literal[{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}] + one_of_schemas: List[str] = Field(default=Literal[{{#oneOf}}"{{.}}"{{^-last}}, {{/-last}}{{/oneOf}}]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } {{#discriminator}} @@ -101,11 +93,16 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod + {{#isNullable}} + def from_json(cls, json_str: Optional[str]) -> Self: + {{/isNullable}} + {{^isNullable}} def from_json(cls, json_str: str) -> Self: + {{/isNullable}} """Returns the object represented by the json string""" instance = cls.model_construct() {{#isNullable}} @@ -183,19 +180,17 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], {{#oneOf}}{{{.}}}{{^-last}}, {{/-last}}{{/oneOf}}]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type @@ -207,10 +202,8 @@ class {{classname}}({{#parent}}{{{.}}}{{/parent}}{{^parent}}BaseModel{{/parent}} {{#vendorExtensions.x-py-postponed-model-imports.size}} {{#vendorExtensions.x-py-postponed-model-imports}} -from typing import TYPE_CHECKING -if TYPE_CHECKING: - {{{.}}} - # TODO: pydantic v2 +{{{.}}} {{/vendorExtensions.x-py-postponed-model-imports}} - # {{classname}}.model_rebuild() +# TODO: Rewrite to not use raise_errors +{{classname}}.model_rebuild(raise_errors=False) {{/vendorExtensions.x-py-postponed-model-imports.size}} diff --git a/modules/openapi-generator/src/main/resources/python/model_test.mustache b/modules/openapi-generator/src/main/resources/python/model_test.mustache index 2c7fa1f132cc..e0364ce8c163 100644 --- a/modules/openapi-generator/src/main/resources/python/model_test.mustache +++ b/modules/openapi-generator/src/main/resources/python/model_test.mustache @@ -3,11 +3,10 @@ {{>partial_header}} import unittest -import datetime {{#models}} {{#model}} -from {{modelPackage}}.{{classFilename}} import {{classname}} # noqa: E501 +from {{modelPackage}}.{{classFilename}} import {{classname}} class Test{{classname}}(unittest.TestCase): """{{classname}} unit test stubs""" @@ -26,7 +25,7 @@ class Test{{classname}}(unittest.TestCase): optional params are included """ # uncomment below to create an instance of `{{{classname}}}` """ - model = {{classname}}() # noqa: E501 + model = {{classname}}() if include_optional: return {{classname}}( {{#vars}} diff --git a/modules/openapi-generator/src/main/resources/python/partial_api.mustache b/modules/openapi-generator/src/main/resources/python/partial_api.mustache new file mode 100644 index 000000000000..dd3a9a1fa12b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/partial_api.mustache @@ -0,0 +1,52 @@ + """{{#isDeprecated}}(Deprecated) {{/isDeprecated}}{{{summary}}}{{^summary}}{{operationId}}{{/summary}} + + {{#notes}} + {{{.}}} + {{/notes}} + + {{#allParams}} + :param {{paramName}}:{{#description}} {{{.}}}{{/description}}{{#required}} (required){{/required}}{{#optional}}(optional){{/optional}} + :type {{paramName}}: {{dataType}}{{#optional}}, optional{{/optional}} + {{/allParams}} + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + {{#isDeprecated}} + warnings.warn("{{{httpMethod}}} {{{path}}} is deprecated.", DeprecationWarning) + {{/isDeprecated}} + + _param = self._{{operationId}}_serialize( + {{#allParams}} + {{paramName}}={{paramName}}, + {{/allParams}} + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + {{#responses}} + {{^isWildcard}} + '{{code}}': {{#dataType}}"{{.}}"{{/dataType}}{{^dataType}}None{{/dataType}}, + {{/isWildcard}} + {{/responses}} + } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/partial_api_args.mustache b/modules/openapi-generator/src/main/resources/python/partial_api_args.mustache new file mode 100644 index 000000000000..379b67de9875 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/python/partial_api_args.mustache @@ -0,0 +1,18 @@ +( + self, + {{#allParams}} + {{paramName}}: {{{vendorExtensions.x-py-typing}}}{{^required}} = None{{/required}}, + {{/allParams}} + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le={{#servers.size}}{{servers.size}}{{/servers.size}}{{^servers.size}}1{{/servers.size}})] = 0, + ) \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/python/pyproject.mustache b/modules/openapi-generator/src/main/resources/python/pyproject.mustache index 568fa4ebf94e..24030f9e924d 100644 --- a/modules/openapi-generator/src/main/resources/python/pyproject.mustache +++ b/modules/openapi-generator/src/main/resources/python/pyproject.mustache @@ -16,6 +16,7 @@ urllib3 = ">= 1.25.3" python-dateutil = ">=2.8.2" {{#asyncio}} aiohttp = ">= 3.8.4" +aiohttp-retry = ">= 2.8.3" {{/asyncio}} {{#tornado}} tornado = ">=4.2,<5" @@ -31,6 +32,9 @@ typing-extensions = ">=4.7.1" pytest = ">=7.2.1" tox = ">=3.9.0" flake8 = ">=4.0.0" +types-python-dateutil = ">=2.8.19.14" +mypy = "1.4.1" + [build-system] requires = ["setuptools"] @@ -38,3 +42,41 @@ build-backend = "setuptools.build_meta" [tool.pylint.'MESSAGES CONTROL'] extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "{{{packageName}}}", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +strict_concatenate = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true diff --git a/modules/openapi-generator/src/main/resources/python/requirements.mustache b/modules/openapi-generator/src/main/resources/python/requirements.mustache index 0fa8f6fd14da..5412515b5f4a 100644 --- a/modules/openapi-generator/src/main/resources/python/requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python/requirements.mustache @@ -5,6 +5,7 @@ pydantic >= 2 typing-extensions >= 4.7.1 {{#asyncio}} aiohttp >= 3.0.0 +aiohttp-retry >= 2.8.3 {{/asyncio}} {{#hasHttpSignatureMethods}} pycryptodome >= 3.9.0 diff --git a/modules/openapi-generator/src/main/resources/python/rest.mustache b/modules/openapi-generator/src/main/resources/python/rest.mustache index f49dee2bed49..5ad8d52bc4f4 100644 --- a/modules/openapi-generator/src/main/resources/python/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/rest.mustache @@ -4,43 +4,55 @@ import io import json -import logging import re import ssl -from urllib.parse import urlencode, quote_plus import urllib3 -from {{packageName}}.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException +from {{packageName}}.exceptions import ApiException, ApiValueError +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse -logger = logging.getLogger(__name__) + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES class RESTResponse(io.IOBase): def __init__(self, resp) -> None: - self.urllib3_response = resp + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs @@ -49,74 +61,79 @@ class RESTClientObject: else: cert_reqs = ssl.CERT_NONE - addition_pool_args = {} + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries + pool_args['retries'] = configuration.retries if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name + pool_args['server_hostname'] = configuration.tls_server_name if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options + pool_args['socket_options'] = configuration.socket_options - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize # https pool manager + self.pool_manager: urllib3.PoolManager + if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -125,63 +142,84 @@ class RESTClientObject: post_params = post_params or {} headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form + # other content types than JSON when `body` argument is + # provided in serialized form. elif isinstance(body, str) or isinstance(body, bytes): - request_body = body r = self.pool_manager.request( - method, url, + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, body=request_body, - preload_content=_preload_content, + preload_content=False, timeout=timeout, headers=headers) else: @@ -192,102 +230,16 @@ class RESTClientObject: raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) + msg = "\n".join([type(e).__name__, str(e)]) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return RESTResponse(r) diff --git a/modules/openapi-generator/src/main/resources/python/setup.mustache b/modules/openapi-generator/src/main/resources/python/setup.mustache index 1468f827370b..cb372a5e02e5 100644 --- a/modules/openapi-generator/src/main/resources/python/setup.mustache +++ b/modules/openapi-generator/src/main/resources/python/setup.mustache @@ -21,6 +21,7 @@ REQUIRES = [ "python-dateutil", {{#asyncio}} "aiohttp >= 3.0.0", + "aiohttp-retry >= 2.8.3", {{/asyncio}} {{#tornado}} "tornado>=4.2,<5", diff --git a/modules/openapi-generator/src/main/resources/python/signing.mustache b/modules/openapi-generator/src/main/resources/python/signing.mustache index bb2850fdcc09..4d00424ea48f 100644 --- a/modules/openapi-generator/src/main/resources/python/signing.mustache +++ b/modules/openapi-generator/src/main/resources/python/signing.mustache @@ -3,13 +3,16 @@ from base64 import b64encode from Crypto.IO import PEM, PKCS8 from Crypto.Hash import SHA256, SHA512 +from Crypto.Hash.SHA512 import SHA512Hash +from Crypto.Hash.SHA256 import SHA256Hash from Crypto.PublicKey import RSA, ECC from Crypto.Signature import PKCS1_v1_5, pss, DSS +from datetime import timedelta from email.utils import formatdate -import json import os import re from time import time +from typing import List, Optional, Union from urllib.parse import urlencode, urlparse # The constants below define a subset of HTTP headers that can be included in the @@ -58,18 +61,20 @@ HASH_SHA512 = 'sha512' class HttpSigningConfiguration: """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key which is in possession of the API client. - An 'Authorization' header is calculated by creating a hash of select headers, + + An ``Authorization`` header is calculated by creating a hash of select headers, and optionally the body of the HTTP request, then signing the hash value using - a private key. The 'Authorization' header is added to outbound HTTP requests. + a private key. The ``Authorization`` header is added to outbound HTTP requests. :param key_id: A string value specifying the identifier of the cryptographic key, when signing HTTP requests. :param signing_scheme: A string value specifying the signature scheme, when signing HTTP requests. - Supported value are hs2019, rsa-sha256, rsa-sha512. - Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + Supported value are: ``hs2019``, ``rsa-sha256``, ``rsa-sha512``. + Avoid using ``rsa-sha256``, ``rsa-sha512`` as they are deprecated. These values are available for server-side applications that only support the older HTTP signature algorithms. :param private_key_path: A string value specifying the path of the file containing @@ -78,18 +83,19 @@ class HttpSigningConfiguration: the private key. :param signed_headers: A list of strings. Each value is the name of a HTTP header that must be included in the HTTP signature calculation. - The two special signature headers '(request-target)' and '(created)' SHOULD be + The two special signature headers ``(request-target)`` and ``(created)`` SHOULD be included in SignedHeaders. - The '(created)' header expresses when the signature was created. - The '(request-target)' header is a concatenation of the lowercased :method, an + The ``(created)`` header expresses when the signature was created. + The ``(request-target)`` header is a concatenation of the lowercased :method, an ASCII space, and the :path pseudo-headers. When signed_headers is not specified, the client defaults to a single value, - '(created)', in the list of HTTP headers. + ``(created)``, in the list of HTTP headers. When SignedHeaders contains the 'Digest' value, the client performs the following operations: - 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. - 2. Set the 'Digest' header in the request body. - 3. Include the 'Digest' header and value in the HTTP signature. + 1. Calculate a digest of request body, as specified in `RFC3230, + section 4.3.2`_. + 2. Set the ``Digest`` header in the request body. + 3. Include the ``Digest`` header and value in the HTTP signature. :param signing_algorithm: A string value specifying the signature algorithm, when signing HTTP requests. Supported values are: @@ -107,12 +113,16 @@ class HttpSigningConfiguration: :param signature_max_validity: The signature max validity, expressed as a datetime.timedelta value. It must be a positive value. """ - def __init__(self, key_id, signing_scheme, private_key_path, - private_key_passphrase=None, - signed_headers=None, - signing_algorithm=None, - hash_algorithm=None, - signature_max_validity=None) -> None: + def __init__(self, + key_id: str, + signing_scheme: str, + private_key_path: str, + private_key_passphrase: Union[None, str]=None, + signed_headers: Optional[List[str]]=None, + signing_algorithm: Optional[str]=None, + hash_algorithm: Optional[str]=None, + signature_max_validity: Optional[timedelta]=None, + ) -> None: self.key_id = key_id if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) @@ -156,11 +166,11 @@ class HttpSigningConfiguration: if HEADER_AUTHORIZATION in signed_headers: raise Exception("'Authorization' header cannot be included in signed headers") self.signed_headers = signed_headers - self.private_key = None + self.private_key: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None """The private key used to sign HTTP requests. Initialized when the PEM-encoded private key is loaded from a file. """ - self.host = None + self.host: Optional[str] = None """The host name, optionally followed by a colon and TCP port number. """ self._load_private_key() @@ -198,7 +208,7 @@ class HttpSigningConfiguration: def get_public_key(self): """Returns the public key object associated with the private key. """ - pubkey = None + pubkey: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None if isinstance(self.private_key, RSA.RsaKey): pubkey = self.private_key.publickey() elif isinstance(self.private_key, ECC.EccKey): @@ -227,8 +237,11 @@ class HttpSigningConfiguration: elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: # Key is in PKCS8 format, which is capable of holding many different # types of private keys, not just EC keys. - (key_binary, pem_header, is_encrypted) = \ - PEM.decode(pem_data, self.private_key_passphrase) + if self.private_key_passphrase is not None: + passphrase = self.private_key_passphrase.encode("utf-8") + else: + passphrase = None + (key_binary, pem_header, is_encrypted) = PEM.decode(pem_data, passphrase) (oid, privkey, params) = \ PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) if oid == '1.2.840.10045.2.1': @@ -309,8 +322,11 @@ class HttpSigningConfiguration: request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( digest_prefix, b64_body_digest.decode('ascii')) elif hdr_key == HEADER_HOST.lower(): - value = target_host - request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + if isinstance(target_host, bytes): + value = target_host.decode('ascii') + else: + value = target_host + request_headers_dict[HEADER_HOST] = value else: value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) if value is None: @@ -331,6 +347,9 @@ class HttpSigningConfiguration: The prefix is a string that identifies the cryptographic hash. It is used to generate the 'Digest' header as specified in RFC 3230. """ + + digest: Union[SHA256Hash, SHA512Hash] + if self.hash_algorithm == HASH_SHA512: digest = SHA512.new() prefix = 'SHA-512=' diff --git a/modules/openapi-generator/src/main/resources/python/test-requirements.mustache b/modules/openapi-generator/src/main/resources/python/test-requirements.mustache index 3a0d0b939a1e..8e6d8cb13749 100644 --- a/modules/openapi-generator/src/main/resources/python/test-requirements.mustache +++ b/modules/openapi-generator/src/main/resources/python/test-requirements.mustache @@ -1,3 +1,5 @@ pytest~=7.1.3 pytest-cov>=2.8.1 pytest-randomly>=3.12.0 +mypy>=1.4.1 +types-python-dateutil>=2.8.19 diff --git a/modules/openapi-generator/src/main/resources/python/tornado/rest.mustache b/modules/openapi-generator/src/main/resources/python/tornado/rest.mustache index 6b91cdef986e..f4bfbfb23242 100644 --- a/modules/openapi-generator/src/main/resources/python/tornado/rest.mustache +++ b/modules/openapi-generator/src/main/resources/python/tornado/rest.mustache @@ -4,10 +4,9 @@ import io import json -import logging import re -from urllib.parse import urlencode, quote_plus +from urllib.parse import urlencode import tornado import tornado.gen from tornado import httpclient @@ -15,34 +14,33 @@ from urllib3.filepost import encode_multipart_formdata from {{packageName}}.exceptions import ApiException, ApiValueError -logger = logging.getLogger(__name__) - +RESTResponseType = httpclient.HTTPResponse class RESTResponse(io.IOBase): def __init__(self, resp) -> None: - self.tornado_response = resp + self.response = resp self.status = resp.code self.reason = resp.reason + self.data = None - if resp.body: - self.data = resp.body - else: - self.data = None + def read(self): + if self.data is None: + self.data = self.response.body + return self.data def getheaders(self): """Returns a CIMultiDictProxy of the response headers.""" - return self.tornado_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.tornado_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=4) -> None: - # maxsize is number of requests to host that are allowed in parallel + def __init__(self, configuration) -> None: self.ca_certs = configuration.ssl_ca_cert self.client_key = configuration.key_file @@ -58,29 +56,39 @@ class RESTClientObject: self.pool_manager = httpclient.AsyncHTTPClient() @tornado.gen.coroutine - def request(self, method, url, query_params=None, headers=None, body=None, - post_params=None, _preload_content=True, - _request_timeout=None): + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Execute Request :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for - the AiohttpClient. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -103,16 +111,13 @@ class RESTClientObject: post_params = post_params or {} - if query_params: - request.url += '?' + urlencode(query_params) - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if re.search('json', headers['Content-Type'], re.IGNORECASE): if body: body = json.dumps(body) request.body = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': request.body = urlencode(post_params) elif headers['Content-Type'] == 'multipart/form-data': multipart = encode_multipart_formdata(post_params) @@ -131,93 +136,7 @@ class RESTClientObject: r = yield self.pool_manager.fetch(request, raise_error=False) - if _preload_content: - - r = RESTResponse(r) - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) + r = RESTResponse(r) raise tornado.gen.Return(r) - - @tornado.gen.coroutine - def GET(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - result = yield self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def HEAD(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - result = yield self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def OPTIONS(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def DELETE(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - result = yield self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def POST(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def PUT(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) - - @tornado.gen.coroutine - def PATCH(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - result = yield self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - raise tornado.gen.Return(result) diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache index 230d46dc7817..fef2e864c941 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client.mustache @@ -72,68 +72,6 @@ module {{moduleName}} # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - {{#isTyphoeus}} - return @tempfile if return_type == 'File' - {{/isTyphoeus}} - {{#isFaraday}} - if return_type == 'File' - if @config.return_binary_data == true - # return byte stream - encoding = body.encoding - return @stream.join.force_encoding(encoding) - else - # return file instead of binary data - content_disposition = response.headers['Content-Disposition'] - if content_disposition && content_disposition =~ /filename=/i - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - prefix = sanitize_filename(filename) - else - prefix = 'download-' - end - prefix = prefix + '-' unless prefix.end_with?('-') - encoding = body.encoding - @tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile.write(@stream.join.force_encoding(encoding)) - @tempfile.close - @config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - return @tempfile - end - end - {{/isFaraday}} - {{#isHttpx}} - if return_type == 'File' - if @config.return_binary_data == true - # TODO: force response encoding - return body.to_s - else - content_disposition = response.headers['content-disposition'] - if content_disposition && content_disposition =~ /filename=/i - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - prefix = sanitize_filename(filename) - else - prefix = 'download-' - end - prefix = prefix + '-' unless prefix.end_with?('-') - encoding = response.body.encoding - tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - response.copy_to(tempfile) - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - - return tempfile - end - end - {{/isHttpx}} - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache index cc7175e95f12..3392e91033d1 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client_faraday_partial.mustache @@ -3,9 +3,11 @@ # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # the data deserialized from response body (could be nil), response status code and response headers. def call_api(http_method, path, opts = {}) + stream = nil begin response = connection(opts).public_send(http_method.to_sym.downcase) do |req| - build_request(http_method, path, req, opts) + request = build_request(http_method, path, req, opts) + stream = download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' end if config.debugging @@ -30,7 +32,9 @@ fail ApiError.new('Connection failed') end - if opts[:return_type] + if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' + data = deserialize_file(response, stream) + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -72,7 +76,6 @@ request.url url request.params = query_params - download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' request end @@ -109,11 +112,40 @@ end def download_file(request) - @stream = [] + stream = [] # handle streaming Responses request.options.on_data = Proc.new do |chunk, overall_received_bytes| - @stream << chunk + stream << chunk + end + stream + end + + def deserialize_file(response, stream) + body = response.body + if @config.return_binary_data == true + # return byte stream + encoding = body.encoding + stream.join.force_encoding(encoding) + else + # return file instead of binary data + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + tempfile.write(stream.join.force_encoding(encoding)) + tempfile.close + config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + tempfile end end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_httpx_partial.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_httpx_partial.mustache index 537593df1181..7dd5221daccb 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_httpx_partial.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client_httpx_partial.mustache @@ -23,7 +23,9 @@ fail ApiError.new('Connection failed') end - if opts[:return_type] + if opts[:return_type] == 'File' + data = deserialize_file(response) + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -80,6 +82,33 @@ end end + def deserialize_file(response) + body = response.body + if @config.return_binary_data == true + # TODO: force response encoding + body.to_s + else + content_disposition = response.headers['content-disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + response.copy_to(tempfile) + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + + tempfile + end + end + def session return @session if defined?(@session) diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache deleted file mode 100644 index 324034c5f466..000000000000 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_spec.mustache +++ /dev/null @@ -1,257 +0,0 @@ -=begin -{{> api_info}} -=end - -require 'spec_helper' - -describe {{moduleName}}::ApiClient do - context 'initialization' do - context 'URL stuff' do - context 'host' do - it 'removes http from host' do - {{moduleName}}.configure { |c| c.host = 'http://example.com' } - expect({{moduleName}}::Configuration.default.host).to eq('example.com') - end - - it 'removes https from host' do - {{moduleName}}.configure { |c| c.host = 'https://wookiee.com' } - expect({{moduleName}}::ApiClient.default.config.host).to eq('wookiee.com') - end - - it 'removes trailing path from host' do - {{moduleName}}.configure { |c| c.host = 'hobo.com/v4' } - expect({{moduleName}}::Configuration.default.host).to eq('hobo.com') - end - end - - context 'base_path' do - it "prepends a slash to base_path" do - {{moduleName}}.configure { |c| c.base_path = 'v4/dog' } - expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog') - end - - it "doesn't prepend a slash if one is already there" do - {{moduleName}}.configure { |c| c.base_path = '/v4/dog' } - expect({{moduleName}}::Configuration.default.base_path).to eq('/v4/dog') - end - - it "ends up as a blank string if nil" do - {{moduleName}}.configure { |c| c.base_path = nil } - expect({{moduleName}}::Configuration.default.base_path).to eq('') - end - end - end - end - -{{#isTyphoeus}} - describe 'params_encoding in #build_request' do - let(:config) { {{moduleName}}::Configuration.new } - let(:api_client) { {{moduleName}}::ApiClient.new(config) } - - it 'defaults to nil' do - expect({{moduleName}}::Configuration.default.params_encoding).to eq(nil) - expect(config.params_encoding).to eq(nil) - - request = api_client.build_request(:get, '/test') - expect(request.options[:params_encoding]).to eq(nil) - end - - it 'can be customized' do - config.params_encoding = :multi - request = api_client.build_request(:get, '/test') - expect(request.options[:params_encoding]).to eq(:multi) - end - end - - describe 'timeout in #build_request' do - let(:config) { {{moduleName}}::Configuration.new } - let(:api_client) { {{moduleName}}::ApiClient.new(config) } - - it 'defaults to 0' do - expect({{moduleName}}::Configuration.default.timeout).to eq(0) - expect(config.timeout).to eq(0) - - request = api_client.build_request(:get, '/test') - expect(request.options[:timeout]).to eq(0) - end - - it 'can be customized' do - config.timeout = 100 - request = api_client.build_request(:get, '/test') - expect(request.options[:timeout]).to eq(100) - end - end - -{{/isTyphoeus}} - -{{#isFaraday}} - describe 'proxy in #build_connection' do - let(:config) { {{moduleName}}::Configuration.new } - let(:api_client) { {{moduleName}}::ApiClient.new(config) } - let(:proxy_uri) { URI('http://example.org:8080') } - - it 'defaults to nil' do - expect({{moduleName}}::Configuration.default.proxy).to be_nil - expect(config.proxy).to be_nil - - connection = api_client.build_connection - expect(connection.proxy_for_request('/test')).to be_nil - end - - it 'can be customized with a string' do - config.proxy = proxy_uri.to_s - - connection = api_client.build_connection - configured_proxy = connection.proxy_for_request('/test') - - expect(configured_proxy).not_to be_nil - expect(configured_proxy.uri.to_s).to eq proxy_uri.to_s - end - - it 'can be customized with a hash' do - config.proxy = { uri: proxy_uri } - - connection = api_client.build_connection - configured_proxy = connection.proxy_for_request('/test') - - expect(configured_proxy).not_to be_nil - expect(configured_proxy.uri).to eq proxy_uri - end - end -{{/isFaraday}} - - describe '#deserialize' do - it "handles Array" do - api_client = {{moduleName}}::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '[12, 34]') - data = api_client.deserialize(response, 'Array') - expect(data).to be_instance_of(Array) - expect(data).to eq([12, 34]) - end - - it 'handles Array>' do - api_client = {{moduleName}}::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '[[12, 34], [56]]') - data = api_client.deserialize(response, 'Array>') - expect(data).to be_instance_of(Array) - expect(data).to eq([[12, 34], [56]]) - end - - it 'handles Hash' do - api_client = {{moduleName}}::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '{"message": "Hello"}') - data = api_client.deserialize(response, 'Hash') - expect(data).to be_instance_of(Hash) - expect(data).to eq(:message => 'Hello') - end - end - - describe "#object_to_hash" do - it 'ignores nils and includes empty arrays' do - # uncomment below to test object_to_hash for model - # api_client = {{moduleName}}::ApiClient.new - # _model = {{moduleName}}::ModelName.new - # update the model attribute below - # _model.id = 1 - # update the expected value (hash) below - # expected = {id: 1, name: '', tags: []} - # expect(api_client.object_to_hash(_model)).to eq(expected) - end - end - - describe '#build_collection_param' do - let(:param) { ['aa', 'bb', 'cc'] } - let(:api_client) { {{moduleName}}::ApiClient.new } - - it 'works for csv' do - expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') - end - - it 'works for ssv' do - expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') - end - - it 'works for tsv' do - expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") - end - - it 'works for pipes' do - expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') - end - - it 'works for multi' do - expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) - end - - it 'fails for invalid collection format' do - expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') - end - end - - describe '#json_mime?' do - let(:api_client) { {{moduleName}}::ApiClient.new } - - it 'works' do - expect(api_client.json_mime?(nil)).to eq false - expect(api_client.json_mime?('')).to eq false - - expect(api_client.json_mime?('application/json')).to eq true - expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true - expect(api_client.json_mime?('APPLICATION/JSON')).to eq true - - expect(api_client.json_mime?('application/xml')).to eq false - expect(api_client.json_mime?('text/plain')).to eq false - expect(api_client.json_mime?('application/jsonp')).to eq false - end - end - - describe '#select_header_accept' do - let(:api_client) { {{moduleName}}::ApiClient.new } - - it 'works' do - expect(api_client.select_header_accept(nil)).to be_nil - expect(api_client.select_header_accept([])).to be_nil - - expect(api_client.select_header_accept(['application/json'])).to eq('application/json') - expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') - expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') - - expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') - expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') - end - end - - describe '#select_header_content_type' do - let(:api_client) { {{moduleName}}::ApiClient.new } - - it 'works' do - expect(api_client.select_header_content_type(nil)).to be_nil - expect(api_client.select_header_content_type([])).to be_nil - - expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') - expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') - expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') - expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') - expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') - end - end - - describe '#sanitize_filename' do - let(:api_client) { {{moduleName}}::ApiClient.new } - - it 'works' do - expect(api_client.sanitize_filename('sun')).to eq('sun') - expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') - end - end -end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/api_client_typhoeus_partial.mustache b/modules/openapi-generator/src/main/resources/ruby-client/api_client_typhoeus_partial.mustache index 7b961b400d8f..39792eb732b7 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/api_client_typhoeus_partial.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/api_client_typhoeus_partial.mustache @@ -1,9 +1,10 @@ # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -25,7 +26,9 @@ end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -83,9 +86,7 @@ end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -123,6 +124,8 @@ # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -137,19 +140,22 @@ prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/base_object.mustache b/modules/openapi-generator/src/main/resources/ruby-client/base_object.mustache index 4f11ca1bf3c3..ae76c4531d21 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/base_object.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/base_object.mustache @@ -63,7 +63,7 @@ else # model # models (e.g. Pet) or oneOf klass = {{moduleName}}.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/configuration_spec.mustache b/modules/openapi-generator/src/main/resources/ruby-client/configuration_spec.mustache deleted file mode 100644 index 69cd207b1a5b..000000000000 --- a/modules/openapi-generator/src/main/resources/ruby-client/configuration_spec.mustache +++ /dev/null @@ -1,111 +0,0 @@ -=begin -{{> api_info}} -=end - -require 'spec_helper' - -describe {{moduleName}}::Configuration do - let(:config) { {{moduleName}}::Configuration.default } - - before(:each) do - # uncomment below to setup host and base_path - # require 'URI' - # uri = URI.parse("{{{basePath}}}") - # {{moduleName}}.configure do |c| - # c.host = uri.host - # c.base_path = uri.path - # end - end - - describe '#base_url' do - it 'should have the default value' do - # uncomment below to test default value of the base path - # expect(config.base_url).to eq("{{{basePath}}}") - end - - it 'should remove trailing slashes' do - [nil, '', '/', '//'].each do |base_path| - config.base_path = base_path - # uncomment below to test trailing slashes - # expect(config.base_url).to eq("{{{basePath}}}") - end - end - end -{{#isFaraday}} - - describe '#configure_faraday_connection' do - let(:faraday_connection) { Faraday::Connection.new } - - before do - stub_const('CustomAdapter', Class.new(Faraday::Adapter)) - stub_const('AnotherCustomAdapter', Class.new(Faraday::Adapter)) - - config.configure_faraday_connection do |conn| - conn.adapter CustomAdapter - conn.response :logger, nil, headers: true, bodies: true, log_level: :debug do |logger| - logger.filter(/(Authorization: )(.*)/, '\1[REDACTED]') - end - end - end - - it 'adds a block that will be used to configure the connection' do - expect(faraday_connection.adapter).to eq(Faraday::Adapter::NetHttp) - expect(faraday_connection.builder.handlers).to_not include(Faraday::Response::Logger) - - config.configure_connection(faraday_connection) - - expect(faraday_connection.adapter).to eq(CustomAdapter) - expect(faraday_connection.builder.handlers).to include(Faraday::Response::Logger) - end - - it 'supports multiple configuration blocks' do - config.configure_faraday_connection do |conn| - conn.adapter AnotherCustomAdapter - end - - expect(faraday_connection.adapter).to eq(Faraday::Adapter::NetHttp) - expect(faraday_connection.builder.handlers).to_not include(Faraday::Response::Logger) - - config.configure_connection(faraday_connection) - - expect(faraday_connection.adapter).to eq(AnotherCustomAdapter) - expect(faraday_connection.builder.handlers).to include(Faraday::Response::Logger) - end - end -{{/isFaraday}} -{{#isHttpx}} - - describe '#configure' do - let(:session) { HTTPX::Session.new } - - before do - module CustomPlugin - module InstanceMethods; end - end - module AnotherCustomPlugin - module InstanceMethods; end - end - - config.configure_session do |session| - session.plugin(CustomPlugin) - end - end - - it 'adds a block that will be used to configure the connection' do - sess = config.configure(session) - - expect(sess.class.ancestors).to include(CustomPlugin::InstanceMethods) - end - - it 'supports multiple configuration blocks' do - config.configure_session do |session| - session.plugin(AnotherCustomPlugin) - end - sess = config.configure(session) - - expect(sess.class.ancestors).to include(CustomPlugin::InstanceMethods) - expect(sess.class.ancestors).to include(AnotherCustomPlugin::InstanceMethods) - end - end -{{/isHttpx}} -end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/gemspec.mustache b/modules/openapi-generator/src/main/resources/ruby-client/gemspec.mustache index 8fba4b4efd1b..3e4b613face6 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/gemspec.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/gemspec.mustache @@ -18,6 +18,7 @@ Gem::Specification.new do |s| s.description = "{{gemDescription}}{{^gemDescription}}{{{appDescription}}}{{^appDescription}}{{{appName}}} Ruby Gem{{/appDescription}}{{/gemDescription}}" s.license = "{{{gemLicense}}}{{^gemLicense}}Unlicense{{/gemLicense}}" s.required_ruby_version = "{{{gemRequiredRubyVersion}}}{{^gemRequiredRubyVersion}}>= 2.7{{/gemRequiredRubyVersion}}" + s.metadata = {{{gemMetadata}}}{{^gemMetadata}}{}{{/gemMetadata}} {{#isFaraday}} s.add_runtime_dependency 'faraday', '>= 1.0.1', '< 3.0' diff --git a/modules/openapi-generator/src/main/resources/ruby-client/partial_anyof_module.mustache b/modules/openapi-generator/src/main/resources/ruby-client/partial_anyof_module.mustache index b41dd20a7d08..778568c2c31c 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/partial_anyof_module.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/partial_anyof_module.mustache @@ -79,7 +79,7 @@ return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module.mustache b/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module.mustache index 49e7b58d015e..d3a25f69ed5e 100644 --- a/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module.mustache +++ b/modules/openapi-generator/src/main/resources/ruby-client/partial_oneof_module.mustache @@ -121,7 +121,7 @@ return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/modules/openapi-generator/src/main/resources/rust-axum/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust-axum/Cargo.mustache new file mode 100644 index 000000000000..d313de7116bb --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/Cargo.mustache @@ -0,0 +1,68 @@ +[package] +name = "{{{packageName}}}" +version = "{{{packageVersion}}}" +{{#infoEmail}} +authors = ["{{{.}}}"] +{{/infoEmail}} +{{^infoEmail}} +authors = ["OpenAPI Generator team and contributors"] +{{/infoEmail}} +{{#appDescription}} +description = "{{{.}}}" +{{/appDescription}} +{{#licenseInfo}} +license = "{{.}}" +{{/licenseInfo}} +edition = "2021" +{{#publishRustRegistry}} +publish = ["{{.}}"] +{{/publishRustRegistry}} +{{#repositoryUrl}} +repository = "{{.}}" +{{/repositoryUrl}} +{{#documentationUrl}} +documentation = "{{.}}" +{{/documentationUrl}} +{{#homePageUrl}} +homepage = "{{.}} +{{/homePageUrl}} + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/modules/openapi-generator/src/main/resources/rust-axum/README.md b/modules/openapi-generator/src/main/resources/rust-axum/README.md new file mode 100644 index 000000000000..f67e436393b6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/README.md @@ -0,0 +1,19 @@ +# Rust Axum Server Generator Templates + +The Rust Axum Server Generator templates use Mustache Partials. + +The following tree shows which templates include which: + +- `Cargo.mustache` +- `gitignore` +- `header.mustache` +- `lib.mustache` + - `response.mustache` +- `models.mustache` +- `README.mustache` +- `server-mod.mustache` + - `server-imports.mustache` + - `server-route.mustache` + - `server-operation-validate.mustache` + - `server-operation.mustache` +- `types.mustache` diff --git a/modules/openapi-generator/src/main/resources/rust-axum/README.mustache b/modules/openapi-generator/src/main/resources/rust-axum/README.mustache new file mode 100644 index 000000000000..3fe0dcd0dbe5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/README.mustache @@ -0,0 +1,93 @@ +# Rust API for {{{packageName}}} + +{{#appDescriptionWithNewLines}} +{{{.}}} +{{/appDescriptionWithNewLines}} + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: {{{appVersion}}} +{{^hideGenerationTimestamp}}- Build date: {{{generatedDate}}}{{/hideGenerationTimestamp}} + +{{#infoUrl}}For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}){{/infoUrl}} + +This autogenerated project defines an API crate `{{{packageName}}}` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl {{{packageName}}}::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = {{{packageName}}}::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/modules/openapi-generator/src/main/resources/rust-axum/gitignore b/modules/openapi-generator/src/main/resources/rust-axum/gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/modules/openapi-generator/src/main/resources/rust-axum/header.mustache b/modules/openapi-generator/src/main/resources/rust-axum/header.mustache new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/header.mustache @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/lib.mustache b/modules/openapi-generator/src/main/resources/rust-axum/lib.mustache new file mode 100644 index 000000000000..ef07e5afa963 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/lib.mustache @@ -0,0 +1,99 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = "{{{basePathWithoutHost}}}"; +{{#appVersion}} +pub const API_VERSION: &str = "{{{.}}}"; +{{/appVersion}} + +{{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{>response}} + {{/operation}} + {{/operations}} + {{/apis}} +{{/apiInfo}} + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { +{{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + + {{#summary}} + /// {{{.}}}. + /// + {{/summary}} + {{#vendorExtensions}} + /// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}} + async fn {{{x-operation-id}}}( + &self, + method: Method, + host: Host, + cookies: CookieJar, + {{#headerParams.size}} + header_params: models::{{{operationIdCamelCase}}}HeaderParams, + {{/headerParams.size}} + {{#pathParams.size}} + path_params: models::{{{operationIdCamelCase}}}PathParams, + {{/pathParams.size}} + {{#queryParams.size}} + query_params: models::{{{operationIdCamelCase}}}QueryParams, + {{/queryParams.size}} + {{^x-consumes-multipart-related}} + {{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + {{^x-consumes-plain-text}} + body: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}, + {{/x-consumes-plain-text}} + {{#x-consumes-plain-text}} + {{#isString}} + body: String, + {{/isString}} + {{^isString}} + body: Bytes, + {{/isString}} + {{/x-consumes-plain-text}} + {{/vendorExtensions}} + {{/bodyParam}} + {{/x-consumes-multipart}} + {{/x-consumes-multipart-related}} + {{#x-consumes-multipart}} + body: Multipart, + {{/x-consumes-multipart}} + {{#x-consumes-multipart-related}} + body: axum::body::Body, + {{/x-consumes-multipart-related}} + ) -> Result<{{{operationId}}}Response, String>; + {{/vendorExtensions}} + + {{/operation}} + {{/operations}} + {{/apis}} +{{/apiInfo}} +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/modules/openapi-generator/src/main/resources/rust-axum/models.mustache b/modules/openapi-generator/src/main/resources/rust-axum/models.mustache new file mode 100644 index 000000000000..00b23629acb4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/models.mustache @@ -0,0 +1,923 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + +{{! Don't "use" structs here - they can conflict with the names of models, and mean that the code won't compile }} +{{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + +{{#vendorExtensions}} + {{#headerParams.size}} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct {{{operationIdCamelCase}}}HeaderParams { + {{#headerParams}} + {{#hasValidation}} + #[validate( + {{#maxLength}} + {{#minLength}} + length(min = {{minLength}}, max = {{maxLength}}), + {{/minLength}} + {{^minLength}} + length(max = {{maxLength}}), + {{/minLength}} + {{/maxLength}} + {{^maxLength}} + {{#minLength}} + length(min = {{minLength}}), + {{/minLength}} + {{/maxLength}} + {{#pattern}} + {{^isByteArray}} + regex = "RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.uppercase}}", + {{/isByteArray}} + {{#isByteArray}} + custom ="validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.lowercase}}" + {{/isByteArray}} + {{/pattern}} + {{#maximum}} + {{#minimum}} + range(min = {{minimum}}, max = {{maximum}}), + {{/minimum}} + {{^minimum}} + range(max = {{maximum}}), + {{/minimum}} + {{/maximum}} + {{#minimum}} + {{^maximum}} + range(min = {{minimum}}), + {{/maximum}} + {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} + )] + {{/hasValidation}} + pub {{{paramName}}}: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}, + {{/headerParams}} + } + + {{#headerParams}} + {{#hasValidation}} + {{#pattern}} + {{^isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap(); + } + {{/isByteArray}} + {{#isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap(); + } + fn validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.lowercase}}( + b: &ByteArray + ) -> std::result::Result<(), validator::ValidationError> { + if !RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}HeaderParams_{{{paramName}}}{{/lambda.uppercase}}.is_match(&b.0) { + return Err(validator::ValidationError::new("Character not allowed")); + } + std::result::Result::Ok(()) + } + {{/isByteArray}} + {{/pattern}} + {{/hasValidation}} + {{/headerParams}} + + {{/headerParams.size}} + {{#pathParams.size}} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct {{{operationIdCamelCase}}}PathParams { + {{#pathParams}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#isEnum}} + /// Note: inline enums are not fully supported by openapi-generator + {{/isEnum}} + {{#hasValidation}} + #[validate( + {{#maxLength}} + {{#minLength}} + length(min = {{minLength}}, max = {{maxLength}}), + {{/minLength}} + {{^minLength}} + length(max = {{maxLength}}), + {{/minLength}} + {{/maxLength}} + {{^maxLength}} + {{#minLength}} + length(min = {{minLength}}), + {{/minLength}} + {{/maxLength}} + {{#pattern}} + {{^isByteArray}} + regex = "RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.uppercase}}", + {{/isByteArray}} + {{#isByteArray}} + custom ="validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.lowercase}}" + {{/isByteArray}} + {{/pattern}} + {{#maximum}} + {{#minimum}} + range(min = {{minimum}}, max = {{maximum}}), + {{/minimum}} + {{^minimum}} + range(max = {{maximum}}), + {{/minimum}} + {{/maximum}} + {{#minimum}} + {{^maximum}} + range(min = {{minimum}}), + {{/maximum}} + {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} + )] + {{/hasValidation}} + {{#required}} + pub {{{paramName}}}: {{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}, + {{/required}} + {{^required}} + {{#isNullable}} + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + {{/isNullable}} + #[serde(skip_serializing_if="Option::is_none")] + pub {{{paramName}}}: Option<{{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}>, + {{/required}} + {{/pathParams}} + } + + {{#pathParams}} + {{#hasValidation}} + {{#pattern}} + {{^isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap(); + } + {{/isByteArray}} + {{#isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap(); + } + fn validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.lowercase}}( + b: &ByteArray + ) -> std::result::Result<(), validator::ValidationError> { + if !RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}PathParams_{{{paramName}}}{{/lambda.uppercase}}.is_match(&b.0) { + return Err(validator::ValidationError::new("Character not allowed")); + } + std::result::Result::Ok(()) + } + {{/isByteArray}} + {{/pattern}} + {{/hasValidation}} + {{/pathParams}} + + {{/pathParams.size}} + {{#queryParams.size}} + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct {{{operationIdCamelCase}}}QueryParams { + {{#queryParams}} + {{#vendorExtensions}} + {{#description}} + /// {{{.}}} + {{/description}} + {{#isEnum}} + /// Note: inline enums are not fully supported by openapi-generator + {{/isEnum}} + #[serde(rename = "{{{baseName}}}")] + {{#hasValidation}} + #[validate( + {{#maxLength}} + {{#minLength}} + length(min = {{minLength}}, max = {{maxLength}}), + {{/minLength}} + {{^minLength}} + length(max = {{maxLength}}), + {{/minLength}} + {{/maxLength}} + {{^maxLength}} + {{#minLength}} + length(min = {{minLength}}), + {{/minLength}} + {{/maxLength}} + {{#pattern}} + {{^isByteArray}} + regex = "RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.uppercase}}", + {{/isByteArray}} + {{#isByteArray}} + custom ="validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.lowercase}}" + {{/isByteArray}} + {{/pattern}} + {{#maximum}} + {{#minimum}} + range(min = {{minimum}}, max = {{maximum}}), + {{/minimum}} + {{^minimum}} + range(max = {{maximum}}), + {{/minimum}} + {{/maximum}} + {{#minimum}} + {{^maximum}} + range(min = {{minimum}}), + {{/maximum}} + {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} + )] + {{/hasValidation}} + {{#required}} + pub {{{paramName}}}: {{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}, + {{/required}} + {{^required}} + {{#isNullable}} + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + {{/isNullable}} + #[serde(skip_serializing_if="Option::is_none")] + pub {{{paramName}}}: Option<{{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}>, + {{/required}} + {{/vendorExtensions}} + {{/queryParams}} + } + + {{#queryParams}} + {{#hasValidation}} + {{#pattern}} + {{^isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap(); + } + {{/isByteArray}} + {{#isByteArray}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap(); + } + fn validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.lowercase}}( + b: &ByteArray + ) -> std::result::Result<(), validator::ValidationError> { + if !RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}QueryParams_{{{paramName}}}{{/lambda.uppercase}}.is_match(&b.0) { + return Err(validator::ValidationError::new("Character not allowed")); + } + std::result::Result::Ok(()) + } + {{/isByteArray}} + {{/pattern}} + {{/hasValidation}} + {{/queryParams}} + {{/queryParams.size}} +{{/vendorExtensions}} + {{/operation}} + {{/operations}} + {{/apis}} +{{/apiInfo}} + +{{! Don't "use" structs here - they can conflict with the names of models, and mean that the code won't compile }} +{{#models}} +{{#model}} + +{{#description}} +/// {{{.}}} +{{/description}} +{{#isEnum}} +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum {{{classname}}} { +{{#allowableValues}} + {{#enumVars}} + #[serde(rename = {{{value}}})] + {{{name}}}, + {{/enumVars}} +{{/allowableValues}} +} + +impl std::fmt::Display for {{{classname}}} { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { +{{#allowableValues}} + {{#enumVars}} + {{{classname}}}::{{{name}}} => write!(f, {{{value}}}), + {{/enumVars}} +{{/allowableValues}} + } + } +} + +impl std::str::FromStr for {{{classname}}} { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { +{{#allowableValues}} + {{#enumVars}} + {{{value}}} => std::result::Result::Ok({{{classname}}}::{{{name}}}), + {{/enumVars}} +{{/allowableValues}} + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} +{{/isEnum}} +{{^isEnum}} +{{#dataType}} +{{#isMap}} +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +{{/isMap}} +{{^isMap}} +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +{{/isMap}} +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct {{{classname}}}({{{dataType}}}); + +impl validator::Validate for {{{classname}}} { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From<{{{dataType}}}> for {{{classname}}} { + fn from(x: {{{dataType}}}) -> Self { + {{{classname}}}(x) + } +} +{{#vendorExtensions.x-is-string}} + +impl std::string::ToString for {{{classname}}} { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for {{{classname}}} { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok({{{classname}}}(x.to_string())) + } +} +{{/vendorExtensions.x-is-string}} + +impl std::convert::From<{{{classname}}}> for {{{dataType}}} { + fn from(x: {{{classname}}}) -> Self { + x.0 + } +} + +impl std::ops::Deref for {{{classname}}} { + type Target = {{{dataType}}}; + fn deref(&self) -> &{{{dataType}}} { + &self.0 + } +} + +impl std::ops::DerefMut for {{{classname}}} { + fn deref_mut(&mut self) -> &mut {{{dataType}}} { + &mut self.0 + } +} + +{{#additionalPropertiesType}} +/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for {{{classname}}} { + fn to_string(&self) -> String { + // Skipping additionalProperties in query parameter serialization + "".to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for {{{classname}}} { + type Err = &'static str; + + fn from_str(s: &str) -> std::result::Result { + std::result::Result::Err("Parsing additionalProperties for {{{classname}}} is not supported") + } +} +{{/additionalPropertiesType}} +{{/dataType}} +{{^dataType}} +{{#arrayModelType}} +{{! vec}} +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct {{{classname}}}(Vec<{{{arrayModelType}}}>); + +impl validator::Validate for {{{classname}}} { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for {{{classname}}} { + fn from(x: Vec<{{{arrayModelType}}}>) -> Self { + {{{classname}}}(x) + } +} + +impl std::convert::From<{{{classname}}}> for Vec<{{{arrayModelType}}}> { + fn from(x: {{{classname}}}) -> Self { + x.0 + } +} + +impl std::iter::FromIterator<{{{arrayModelType}}}> for {{{classname}}} { + fn from_iter>(u: U) -> Self { + {{{classname}}}(Vec::<{{{arrayModelType}}}>::from_iter(u)) + } +} + +impl std::iter::IntoIterator for {{{classname}}} { + type Item = {{{arrayModelType}}}; + type IntoIter = std::vec::IntoIter<{{{arrayModelType}}}>; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a {{{classname}}} { + type Item = &'a {{{arrayModelType}}}; + type IntoIter = std::slice::Iter<'a, {{{arrayModelType}}}>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut {{{classname}}} { + type Item = &'a mut {{{arrayModelType}}}; + type IntoIter = std::slice::IterMut<'a, {{{arrayModelType}}}>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for {{{classname}}} { + type Target = Vec<{{{arrayModelType}}}>; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for {{{classname}}} { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for {{{classname}}} { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for {{{classname}}} { + type Err = <{{{arrayModelType}}} as std::str::FromStr>::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok({{{classname}}}(items)) + } +} + +{{/arrayModelType}} +{{^arrayModelType}} +{{! general struct}} + +{{#anyOf.size}} +/// Any of: +{{#anyOf}} +/// - {{{.}}} +{{/anyOf}} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct {{{classname}}}(Box); + +impl validator::Validate for {{{classname}}} +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for {{{classname}}} { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for {{{classname}}} { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} +{{/anyOf.size}} + +{{#oneOf.size}} +/// One of: +{{#oneOf}} +/// - {{{.}}} +{{/oneOf}} +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct {{{classname}}}(Box); + +impl validator::Validate for {{{classname}}} +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for {{{classname}}} { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for {{{classname}}} { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} +{{/oneOf.size}} + +{{^anyOf.size}} +{{^oneOf.size}} +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct {{{classname}}} { +{{#vars}} +{{#description}} +/// {{{.}}} +{{/description}} +{{#isEnum}} +/// Note: inline enums are not fully supported by openapi-generator +{{/isEnum}} + #[serde(rename = "{{{baseName}}}")] +{{#hasValidation}} + #[validate( + {{#maxLength}} + {{#minLength}} + length(min = {{minLength}}, max = {{maxLength}}), + {{/minLength}} + {{^minLength}} + length(max = {{maxLength}}), + {{/minLength}} + {{/maxLength}} + {{^maxLength}} + {{#minLength}} + length(min = {{minLength}}), + {{/minLength}} + {{/maxLength}} + {{#pattern}} + {{^isByteArray}} + regex = "RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}", + {{/isByteArray}} + {{#isByteArray}} + custom ="validate_byte_{{#lambda.lowercase}}{{{classname}}}_{{{name}}}{{/lambda.lowercase}}" + {{/isByteArray}} + {{/pattern}} + {{#maximum}} + {{#minimum}} + range(min = {{minimum}}, max = {{maximum}}), + {{/minimum}} + {{^minimum}} + range(max = {{maximum}}), + {{/minimum}} + {{/maximum}} + {{#minimum}} + {{^maximum}} + range(min = {{minimum}}), + {{/maximum}} + {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} + )] +{{/hasValidation}} +{{#required}} + pub {{{name}}}: {{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}, +{{/required}} +{{^required}} +{{#isNullable}} + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] +{{/isNullable}} + #[serde(skip_serializing_if="Option::is_none")] + pub {{{name}}}: Option<{{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}>, +{{/required}} + +{{/vars}} +} + +{{#vars}} +{{#hasValidation}} +{{#pattern}} +{{^isByteArray}} +lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap(); +} +{{/isByteArray}} +{{#isByteArray}} +lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap(); +} +fn validate_byte_{{#lambda.lowercase}}{{{classname}}}_{{{name}}}{{/lambda.lowercase}}( + b: &ByteArray +) -> std::result::Result<(), validator::ValidationError> { + if !RE_{{#lambda.uppercase}}{{{classname}}}_{{{name}}}{{/lambda.uppercase}}.is_match(&b.0) { + return Err(validator::ValidationError::new("Character not allowed")); + } + std::result::Result::Ok(()) +} +{{/isByteArray}} +{{/pattern}} +{{/hasValidation}} +{{/vars}} + +impl {{{classname}}} { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new({{#vars}}{{^defaultValue}}{{{name}}}: {{#isNullable}}Nullable<{{/isNullable}}{{{dataType}}}{{#isNullable}}>{{/isNullable}}, {{/defaultValue}}{{/vars}}) -> {{{classname}}} { + {{{classname}}} { +{{#vars}} {{#defaultValue}}{{{name}}}: {{{defaultValue}}}{{/defaultValue}}{{^defaultValue}}{{{name}}}{{/defaultValue}}, +{{/vars}} + } + } +} + +/// Converts the {{{classname}}} value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for {{{classname}}} { + fn to_string(&self) -> String { + let params: Vec> = vec![ +{{#vars}} +{{#isByteArray}} + // Skipping {{baseName}} in query parameter serialization +{{/isByteArray}} +{{#isBinary}} + // Skipping {{baseName}} in query parameter serialization +{{/isBinary}} +{{#isMap}} + // Skipping {{baseName}} in query parameter serialization +{{/isMap}} +{{^isPrimitiveType}} + // Skipping {{baseName}} in query parameter serialization +{{/isPrimitiveType}} +{{^isByteArray}}{{^isBinary}}{{^isMap}}{{#isPrimitiveType}} +{{#required}} + Some("{{{baseName}}}".to_string()), +{{^isArray}} +{{#isNullable}} + Some(self.{{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string())), +{{/isNullable}} +{{^isNullable}} + Some(self.{{{name}}}.to_string()), +{{/isNullable}} +{{/isArray}} +{{#isArray}} +{{#isNullable}} + Some(self.{{{name}}}.as_ref().map_or(vec!["null".to_string()], |x| x.iter().map(|x| x.to_string()).collect::>().join(","))), +{{/isNullable}} +{{^isNullable}} + Some(self.{{{name}}}.iter().map(|x| x.to_string()).collect::>().join(",")), +{{/isNullable}} +{{/isArray}} +{{/required}} +{{^required}} + self.{{{name}}}.as_ref().map(|{{{name}}}| { + [ + "{{{baseName}}}".to_string(), +{{^isArray}} +{{#isNullable}} + {{{name}}}.as_ref().map_or("null".to_string(), |x| x.to_string()), +{{/isNullable}} +{{^isNullable}} + {{{name}}}.to_string(), +{{/isNullable}} +{{/isArray}} +{{#isArray}} +{{#isNullable}} + {{{name}}}.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")), +{{/isNullable}} +{{^isNullable}} + {{{name}}}.iter().map(|x| x.to_string()).collect::>().join(","), +{{/isNullable}} +{{/isArray}} + ].join(",") + }), +{{/required}} +{{/isPrimitiveType}}{{/isMap}}{{/isBinary}}{{/isByteArray}} +{{/vars}} + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a {{{classname}}} value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for {{{classname}}} { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + {{#vars}} + pub {{{name}}}: Vec<{{{dataType}}}>, + {{/vars}} + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing {{{classname}}}".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + {{#vars}} + {{#isBinary}} + "{{{baseName}}}" => return std::result::Result::Err("Parsing binary data in this style is not supported in {{{classname}}}".to_string()), + {{/isBinary}} + {{^isBinary}} + {{#isByteArray}} + "{{{baseName}}}" => return std::result::Result::Err("Parsing binary data in this style is not supported in {{{classname}}}".to_string()), + {{/isByteArray}} + {{^isByteArray}} + {{#isContainer}} + "{{{baseName}}}" => return std::result::Result::Err("Parsing a container in this style is not supported in {{{classname}}}".to_string()), + {{/isContainer}} + {{^isContainer}} + {{#isNullable}} + "{{{baseName}}}" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in {{{classname}}}".to_string()), + {{/isNullable}} + {{^isNullable}} + #[allow(clippy::redundant_clone)] + "{{{baseName}}}" => intermediate_rep.{{{name}}}.push(<{{{dataType}}} as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + {{/isNullable}} + {{/isContainer}} + {{/isByteArray}} + {{/isBinary}} + {{/vars}} + _ => return std::result::Result::Err("Unexpected key while parsing {{{classname}}}".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok({{{classname}}} { + {{#vars}} + {{#isNullable}} + {{{name}}}: std::result::Result::Err("Nullable types not supported in {{{classname}}}".to_string())?, + {{/isNullable}} + {{^isNullable}} + {{{name}}}: intermediate_rep.{{{name}}}.into_iter().next(){{#required}}.ok_or_else(|| "{{{baseName}}} missing in {{{classname}}}".to_string())?{{/required}}, + {{/isNullable}} + {{/vars}} + }) + } +} +{{/oneOf.size}} +{{/anyOf.size}} +{{/arrayModelType}} + +{{^anyOf.size}} +{{^oneOf.size}} +// Methods for converting between header::IntoHeaderValue<{{{classname}}}> and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue<{{{classname}}}>) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for {{classname}} - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue<{{{classname}}}> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match <{{{classname}}} as std::str::FromStr>::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into {{classname}} - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + +{{/oneOf.size}} +{{/anyOf.size}} + +{{/dataType}} +{{/isEnum}} + +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/response.mustache b/modules/openapi-generator/src/main/resources/rust-axum/response.mustache new file mode 100644 index 000000000000..d99db9516cd3 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/response.mustache @@ -0,0 +1,69 @@ +#[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum {{{operationId}}}Response { +{{#responses}} + {{#message}} + /// {{{.}}}{{/message}} + {{#vendorExtensions}} + {{{x-response-id}}} + {{/vendorExtensions}} + {{^dataType}} + {{#hasHeaders}} + { + {{/hasHeaders}} + {{/dataType}} + {{#dataType}} + {{^hasHeaders}} + {{#vendorExtensions}} + {{#x-produces-plain-text}} + (String) + {{/x-produces-plain-text}} + {{#x-produces-bytes}} + (ByteArray) + {{/x-produces-bytes}} + {{^x-produces-plain-text}} + {{^x-produces-bytes}} + ({{{dataType}}}) + {{/x-produces-bytes}} + {{/x-produces-plain-text}} + {{/vendorExtensions}} + {{/hasHeaders}} + {{#hasHeaders}} + { + {{#vendorExtensions}} + {{#x-produces-plain-text}} + body: String, + {{/x-produces-plain-text}} + {{#x-produces-bytes}} + body: ByteArray, + {{/x-produces-bytes}} + {{^x-produces-plain-text}} + {{^x-produces-bytes}} + body: {{{dataType}}}, + {{/x-produces-bytes}} + {{/x-produces-plain-text}} + {{/vendorExtensions}} + {{/hasHeaders}} + {{/dataType}} + {{#headers}} + {{{name}}}: + {{^required}} + Option< + {{/required}} + {{{dataType}}} + {{^required}} + > + {{/required}} + {{^-last}} + , + {{/-last}} + {{#-last}} + } + {{/-last}} + {{/headers}} + {{^-last}} + , + {{/-last}} +{{/responses}} +} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/server-imports.mustache b/modules/openapi-generator/src/main/resources/rust-axum/server-imports.mustache new file mode 100644 index 000000000000..a460237f55d6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/server-imports.mustache @@ -0,0 +1,13 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; diff --git a/modules/openapi-generator/src/main/resources/rust-axum/server-mod.mustache b/modules/openapi-generator/src/main/resources/rust-axum/server-mod.mustache new file mode 100644 index 000000000000..69a703ca0706 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/server-mod.mustache @@ -0,0 +1,16 @@ +{{>server-imports}} +use crate::{Api{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}, + {{{operationId}}}Response{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} +}; + +{{>server-route}} +{{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} +{{>server-operation-validate}} +{{>server-operation}} + {{/operation}} + {{/operations}} + {{/apis}} +{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/server-operation-validate.mustache b/modules/openapi-generator/src/main/resources/rust-axum/server-operation-validate.mustache new file mode 100644 index 000000000000..6bacec901701 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/server-operation-validate.mustache @@ -0,0 +1,221 @@ +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + #[derive(validator::Validate)] + #[allow(dead_code)] + struct {{{operationIdCamelCase}}}BodyValidator<'a> { + {{#hasValidation}} + #[validate( + {{#maxLength}} + {{#minLength}} + length(min = {{minLength}}, max = {{maxLength}}), + {{/minLength}} + {{^minLength}} + length(max = {{maxLength}}), + {{/minLength}} + {{/maxLength}} + {{^maxLength}} + {{#minLength}} + length(min = {{minLength}}), + {{/minLength}} + {{/maxLength}} + {{#pattern}} + {{#isString}} + regex = "RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.uppercase}}", + {{/isString}} + {{^isString}} + custom ="validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.lowercase}}", + {{/isString}} + {{/pattern}} + {{#maximum}} + {{#minimum}} + range(min = {{minimum}}, max = {{maximum}}), + {{/minimum}} + {{^minimum}} + range(max = {{maximum}}), + {{/minimum}} + {{/maximum}} + {{#minimum}} + {{^maximum}} + range(min = {{minimum}}), + {{/maximum}} + {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} + )] + {{/hasValidation}} + {{^x-consumes-plain-text}} + {{^hasValidation}} + {{^isMap}} + #[validate] + {{/isMap}} + {{/hasValidation}} + body: &'a {{{dataType}}}, + {{/x-consumes-plain-text}} + {{#x-consumes-plain-text}} + {{#isString}} + body: &'a String, + {{/isString}} + {{^isString}} + body: &'a [u8], + {{/isString}} + {{/x-consumes-plain-text}} + } + + {{#hasValidation}} + {{#pattern}} + {{#isString}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.uppercase}}: regex::Regex = regex::Regex::new(r"{{ pattern }}").unwrap(); + } + {{/isString}} + {{^isString}} + lazy_static::lazy_static! { + static ref RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.uppercase}}: regex::bytes::Regex = regex::bytes::Regex::new(r"{{ pattern }}").unwrap(); + } + fn validate_byte_{{#lambda.lowercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.lowercase}}( + b: &[u8] + ) -> std::result::Result<(), validator::ValidationError> { + if !RE_{{#lambda.uppercase}}{{{operationIdCamelCase}}}BodyValidator{{/lambda.uppercase}}.is_match(b) { + return Err(validator::ValidationError::new("Character not allowed")); + } + Ok(()) + } + {{/isString}} + {{/pattern}} + {{/hasValidation}} + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} + +#[tracing::instrument(skip_all)] +fn {{#vendorExtensions}}{{{x-operation-id}}}_validation{{/vendorExtensions}}( +{{#headerParams.size}} + header_params: models::{{{operationIdCamelCase}}}HeaderParams, +{{/headerParams.size}} +{{#pathParams.size}} + path_params: models::{{{operationIdCamelCase}}}PathParams, +{{/pathParams.size}} +{{#queryParams.size}} + query_params: models::{{{operationIdCamelCase}}}QueryParams, +{{/queryParams.size}} +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + {{^x-consumes-plain-text}} + body: {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}, + {{/x-consumes-plain-text}} + {{#x-consumes-plain-text}} + {{#isString}} + body: String, + {{/isString}} + {{^isString}} + body: Bytes, + {{/isString}} + {{/x-consumes-plain-text}} + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} +) -> std::result::Result<( +{{#headerParams.size}} + models::{{{operationIdCamelCase}}}HeaderParams, +{{/headerParams.size}} +{{#pathParams.size}} + models::{{{operationIdCamelCase}}}PathParams, +{{/pathParams.size}} +{{#queryParams.size}} + models::{{{operationIdCamelCase}}}QueryParams, +{{/queryParams.size}} +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + {{^x-consumes-plain-text}} + {{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}, + {{/x-consumes-plain-text}} + {{#x-consumes-plain-text}} + {{#isString}} + String, + {{/isString}} + {{^isString}} + Bytes, + {{/isString}} + {{/x-consumes-plain-text}} + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} +), ValidationErrors> +{ +{{#headerParams.size}} + header_params.validate()?; +{{/headerParams.size}} +{{#pathParams.size}} + path_params.validate()?; +{{/pathParams.size}} +{{#queryParams.size}} + query_params.validate()?; +{{/queryParams.size}} +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + {{^x-consumes-plain-text}} + {{#required}} + let b = {{{operationIdCamelCase}}}BodyValidator { body: &body }; + b.validate()?; + {{/required}} + {{^required}} + if let Some(body) = &body { + let b = {{{operationIdCamelCase}}}BodyValidator { body }; + b.validate()?; + } + {{/required}} + {{/x-consumes-plain-text}} + {{#x-consumes-plain-text}} + {{#hasValidation}} + let b = {{{operationIdCamelCase}}}BodyValidator { body: &body }; + b.validate()?; + {{/hasValidation}} + {{/x-consumes-plain-text}} + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} + +Ok(( +{{#headerParams.size}} + header_params, +{{/headerParams.size}} +{{#pathParams.size}} + path_params, +{{/pathParams.size}} +{{#queryParams.size}} + query_params, +{{/queryParams.size}} +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + body, + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} +)) +} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/server-operation.mustache b/modules/openapi-generator/src/main/resources/rust-axum/server-operation.mustache new file mode 100644 index 000000000000..5ed29495424a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/server-operation.mustache @@ -0,0 +1,309 @@ +/// {{{operationId}}} - {{{httpMethod}}} {{{basePathWithoutHost}}}{{{path}}} +#[tracing::instrument(skip_all)] +async fn {{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}( + method: Method, + host: Host, + cookies: CookieJar, +{{#headerParams.size}} + headers: HeaderMap, +{{/headerParams.size}} +{{#pathParams.size}} + Path(path_params): Path, +{{/pathParams.size}} +{{#queryParams.size}} + Query(query_params): Query, +{{/queryParams.size}} + State(api_impl): State, +{{#vendorExtensions}} +{{^x-consumes-multipart-related}} +{{^x-consumes-multipart}} + {{#bodyParam}} + {{#vendorExtensions}} + {{#x-consumes-json}} + Json(body): Json<{{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}>, + {{/x-consumes-json}} + {{#x-consumes-form-urlencoded}} + Form(body): Form<{{^required}}Option<{{/required}}{{{dataType}}}{{^required}}>{{/required}}>, + {{/x-consumes-form-urlencoded}} + {{#x-consumes-plain-text}} + {{#isString}} + body: String, + {{/isString}} + {{^isString}} + body: Bytes, + {{/isString}} + {{/x-consumes-plain-text}} + {{/vendorExtensions}} + {{/bodyParam}} +{{/x-consumes-multipart}} +{{/x-consumes-multipart-related}} +{{#x-consumes-multipart}} + body: Multipart, +{{/x-consumes-multipart}} +{{#x-consumes-multipart-related}} + body: axum::body::Body, +{{/x-consumes-multipart-related}} +{{/vendorExtensions}} +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ +{{#headerParams}} + {{#-first}} + // Header parameters + let header_params = { + {{/-first}} + let header_{{{paramName}}} = headers.get(HeaderName::from_static("{{{nameInLowerCase}}}")); + + let header_{{{paramName}}} = match header_{{{paramName}}} { + Some(v) => match header::IntoHeaderValue::<{{{dataType}}}>::try_from((*v).clone()) { + Ok(result) => +{{#required}} + result.0, +{{/required}} +{{^required}} + Some(result.0), +{{/required}} + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header {{{baseName}}} - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { +{{#required}} + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required header {{{baseName}}}")).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); +{{/required}} +{{^required}} + None +{{/required}} + } + }; +{{/headerParams}} +{{#headerParams}} + {{#-first}} + + models::{{{operationIdCamelCase}}}HeaderParams { + {{/-first}} + {{{paramName}}}: header_{{{paramName}}}, + {{#-last}} + } + }; + + {{/-last}} +{{/headerParams}} + + {{^disableValidator}} + {{^allowBlockingValidator}} + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + {{/allowBlockingValidator}} + {{#allowBlockingValidator}} + let validation = + {{/allowBlockingValidator}} + {{#vendorExtensions}}{{{x-operation-id}}}_validation{{/vendorExtensions}}( + {{#headerParams.size}} + header_params, + {{/headerParams.size}} + {{#pathParams.size}} + path_params, + {{/pathParams.size}} + {{#queryParams.size}} + query_params, + {{/queryParams.size}} + {{^x-consumes-multipart-related}} + {{^x-consumes-multipart}} + {{#bodyParam}} + body, + {{/bodyParam}} + {{/x-consumes-multipart}} + {{/x-consumes-multipart-related}} + ) + {{^allowBlockingValidator}}).await.unwrap(){{/allowBlockingValidator}}; + + let Ok(( + {{#headerParams.size}} + header_params, + {{/headerParams.size}} + {{#pathParams.size}} + path_params, + {{/pathParams.size}} + {{#queryParams.size}} + query_params, + {{/queryParams.size}} + {{^x-consumes-multipart-related}} + {{^x-consumes-multipart}} + {{#bodyParam}} + body, + {{/bodyParam}} + {{/x-consumes-multipart}} + {{/x-consumes-multipart-related}} + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + {{/disableValidator}} + + let result = api_impl.as_ref().{{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}( + method, + host, + cookies, + {{#headerParams.size}} + header_params, + {{/headerParams.size}} + {{#pathParams.size}} + path_params, + {{/pathParams.size}} + {{#queryParams.size}} + query_params, + {{/queryParams.size}} + {{#vendorExtensions}} + {{^x-consumes-multipart-related}} + {{^x-consumes-multipart}} + {{#bodyParams}} + {{#-first}} + body, + {{/-first}} + {{/bodyParams}} + {{/x-consumes-multipart}} + {{/x-consumes-multipart-related}} + {{#x-consumes-multipart}} + body, + {{/x-consumes-multipart}} + {{#x-consumes-multipart-related}} + body, + {{/x-consumes-multipart-related}} + {{/vendorExtensions}} + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { +{{#responses}} + {{{operationId}}}Response::{{#vendorExtensions}}{{x-response-id}}{{/vendorExtensions}} +{{#dataType}} +{{^headers}} + (body) +{{/headers}} +{{#headers}} +{{#-first}} + { + body, +{{/-first}} + {{{name}}}{{^-last}},{{/-last}} +{{#-last}} + } +{{/-last}} +{{/headers}} +{{/dataType}} +{{^dataType}} +{{#headers}} +{{#-first}} + { +{{/-first}} + {{{name}}}{{^-last}},{{/-last}} +{{#-last}} + } +{{/-last}} +{{/headers}} +{{/dataType}} + => { +{{#headers}} + {{^required}} + if let Some({{{name}}}) = {{{name}}} { + {{/required}} + let {{{name}}} = match header::IntoHeaderValue({{{name}}}).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling {{name}} header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("{{{nameInLowerCase}}}"), + {{name}} + ); + } + {{^required}} + } + {{/required}} +{{/headers}} + + let mut response = response.status({{{code}}}); +{{#produces}} +{{#-first}} +{{#dataType}} +{{#vendorExtensions}} + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("{{{x-mime-type}}}").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + +{{/vendorExtensions}} +{{/dataType}} +{{/-first}} +{{/produces}} +{{#dataType}} +{{#vendorExtensions}} +{{#x-produces-json}} + {{^allowBlockingResponseSerialize}} + let body_content = tokio::task::spawn_blocking(move || + {{/allowBlockingResponseSerialize}} + {{#allowBlockingResponseSerialize}} + let body_content = + {{/allowBlockingResponseSerialize}} + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + }){{^allowBlockingResponseSerialize}}).await.unwrap(){{/allowBlockingResponseSerialize}}?; +{{/x-produces-json}} +{{#x-produces-form-urlencoded}} + {{^allowBlockingResponseSerialize}} + let body_content = tokio::task::spawn_blocking(move || + {{/allowBlockingResponseSerialize}} + {{#allowBlockingResponseSerialize}} + let body_content = + {{/allowBlockingResponseSerialize}} + serde_urlencoded::to_string(body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + }){{^allowBlockingResponseSerialize}}).await.unwrap(){{/allowBlockingResponseSerialize}}?; +{{/x-produces-form-urlencoded}} +{{#x-produces-bytes}} + let body_content = body.0; +{{/x-produces-bytes}} +{{#x-produces-plain-text}} + let body_content = body; +{{/x-produces-plain-text}} +{{/vendorExtensions}} + response.body(Body::from(body_content)) +{{/dataType}} +{{^dataType}} + response.body(Body::empty()) +{{/dataType}} + }, +{{/responses}} + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/server-route.mustache b/modules/openapi-generator/src/main/resources/rust-axum/server-route.mustache new file mode 100644 index 000000000000..2a17022c2c02 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/server-route.mustache @@ -0,0 +1,15 @@ +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + {{#pathMethodOps}} + .route("{{{basePathWithoutHost}}}{{{path}}}", + {{#methodOperations}}{{{method}}}({{{operationID}}}::){{^-last}}.{{/-last}}{{/methodOperations}} + ) + {{/pathMethodOps}} + .with_state(api_impl) +} diff --git a/modules/openapi-generator/src/main/resources/rust-axum/types.mustache b/modules/openapi-generator/src/main/resources/rust-axum/types.mustache new file mode 100644 index 000000000000..1a8e07ef231a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/rust-axum/types.mustache @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use {{{externCrateName}}}::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache index c858295ce903..f74833a77a51 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/client-operation.mustache @@ -310,7 +310,7 @@ match auth_data { {{#authMethods}} {{#isBasicBasic}} - &AuthData::Basic(ref basic_header) => { + AuthData::Basic(basic_header) => { let auth = swagger::auth::Header(basic_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -322,7 +322,7 @@ }, {{/isBasicBasic}} {{#isBasicBearer}} - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -335,7 +335,7 @@ {{/isBasicBearer}} {{#isOAuth}} {{^isBasicBearer}} - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, diff --git a/modules/openapi-generator/src/main/resources/rust-server/example-server-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/example-server-operation.mustache index a96a4fa976cd..43b66ae59e37 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/example-server-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/example-server-operation.mustache @@ -13,7 +13,6 @@ {{/allParams}} context: &C) -> Result<{{{operationId}}}Response, ApiError> { - let context = context.clone(); info!("{{#vendorExtensions}}{{{x-operation-id}}}{{/vendorExtensions}}({{#allParams}}{{#vendorExtensions}}{{{x-format-string}}}{{/vendorExtensions}}{{^-last}}, {{/-last}}{{/allParams}}) - X-Span-ID: {:?}"{{#allParams}}, {{{paramName}}}{{/allParams}}, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/modules/openapi-generator/src/main/resources/rust-server/models.mustache b/modules/openapi-generator/src/main/resources/rust-server/models.mustache index 6472dd601de5..12409addaf37 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/models.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/models.mustache @@ -296,6 +296,19 @@ pub struct {{{classname}}} { range(min = {{minimum}}), {{/maximum}} {{/minimum}} + {{#maxItems}} + {{#minItems}} + length(min = {{minItems}}, max = {{maxItems}}), + {{/minItems}} + {{^minItems}} + length(max = {{maxItems}}), + {{/minItems}} + {{/maxItems}} + {{^maxItems}} + {{#minItems}} + length(min = {{minItems}}), + {{/minItems}} + {{/maxItems}} )] {{/hasValidation}} {{#required}} @@ -389,7 +402,7 @@ impl std::string::ToString for {{{classname}}} { {{/required}} {{^required}} self.{{{name}}}.as_ref().map(|{{{name}}}| { - vec![ + [ "{{{baseName}}}".to_string(), {{^isArray}} {{#isNullable}} diff --git a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache index e7175b1745e9..f0ba616a9abc 100644 --- a/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache +++ b/modules/openapi-generator/src/main/resources/rust-server/server-operation.mustache @@ -574,27 +574,27 @@ {{#vendorExtensions}} {{#x-produces-xml}} {{^x-has-namespace}} - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{#x-has-namespace}} let mut namespaces = std::collections::BTreeMap::new(); // An empty string is used to indicate a global namespace in xmltree. namespaces.insert("".to_string(), {{{dataType}}}::NAMESPACE.to_string()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + let body_content = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); {{/x-has-namespace}} {{/x-produces-xml}} {{#x-produces-json}} - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); {{/x-produces-json}} {{#x-produces-bytes}} - let body = body.0; + let body_content = body.0; {{/x-produces-bytes}} {{#x-produces-plain-text}} - let body = body; + let body_content = body; {{/x-produces-plain-text}} {{/vendorExtensions}} - *response.body_mut() = Body::from(body); + *response.body_mut() = Body::from(body_content); {{/dataType}} }, {{/responses}} diff --git a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache index 2471f2080b91..8c2510345b33 100644 --- a/modules/openapi-generator/src/main/resources/rust/Cargo.mustache +++ b/modules/openapi-generator/src/main/resources/rust/Cargo.mustache @@ -54,7 +54,9 @@ secrecy = "0.8.0" {{/withAWSV4Signature}} {{#reqwest}} {{^supportAsync}} -reqwest = "~0.9" +[dependencies.reqwest] +version = "^0.11" +features = ["json", "blocking", "multipart"] {{/supportAsync}} {{#supportAsync}} {{#supportMiddleware}} diff --git a/modules/openapi-generator/src/main/resources/rust/model.mustache b/modules/openapi-generator/src/main/resources/rust/model.mustache index b36ac2bf2681..e193499d44c9 100644 --- a/modules/openapi-generator/src/main/resources/rust/model.mustache +++ b/modules/openapi-generator/src/main/resources/rust/model.mustache @@ -79,7 +79,7 @@ impl {{{classname}}} { {{#description}} /// {{{.}}} {{/description}} - pub fn new({{#requiredVars}}{{{name}}}: {{#isNullable}}Option<{{/isNullable}}{{#isEnum}}{{#isArray}}Vec<{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}>{{/isNullable}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { + pub fn new({{#requiredVars}}{{{name}}}: {{#isNullable}}Option<{{/isNullable}}{{#isEnum}}{{#isArray}}{{#uniqueItems}}std::collections::HashSet<{{/uniqueItems}}{{^uniqueItems}}Vec<{{/uniqueItems}}{{/isArray}}{{{enumName}}}{{#isArray}}>{{/isArray}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}}>{{/isNullable}}{{^-last}}, {{/-last}}{{/requiredVars}}) -> {{{classname}}} { {{{classname}}} { {{#vars}} {{{name}}}{{^required}}{{#isContainer}}{{#isArray}}: None{{/isArray}}{{#isMap}}: None{{/isMap}}{{^isArray}}{{^isMap}}{{#isNullable}}: None{{/isNullable}}{{/isMap}}{{/isArray}}{{/isContainer}}{{^isContainer}}: None{{/isContainer}}{{/required}}{{#required}}{{#isModel}}: {{^isNullable}}Box::new({{{name}}}){{/isNullable}}{{#isNullable}}if let Some(x) = {{{name}}} {Some(Box::new(x))} else {None}{{/isNullable}}{{/isModel}}{{/required}}, diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache index 5318c5804111..3e130bbbc43f 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api.mustache @@ -244,7 +244,7 @@ pub {{#supportAsync}}async {{/supportAsync}}fn {{{operationId}}}(configuration: {{/hasAuthMethods}} {{#isMultipart}} {{#hasFormParams}} - let mut local_var_form = reqwest::multipart::Form::new(); + let mut local_var_form = reqwest{{^supportAsync}}::blocking{{/supportAsync}}::multipart::Form::new(); {{#formParams}} {{#isFile}} {{^supportAsync}} diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache index f00eb124cd37..347f3337986a 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/api_mod.mustache @@ -35,9 +35,9 @@ impl fmt::Display for Error { Error::Serde(e) => ("serde", e.to_string()), Error::Io(e) => ("IO", e.to_string()), Error::ResponseError(e) => ("response", format!("status code {}", e.status)), - {{#withAWSV4Signature}} + {{#withAWSV4Signature}} Error::AWSV4SignatureError(e) => ("aws v4 signature", e.to_string()), - {{/withAWSV4Signature}} + {{/withAWSV4Signature}} }; write!(f, "error in {}: {}", module, e) } @@ -53,9 +53,9 @@ impl error::Error for Error { Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, - {{#withAWSV4Signature}} - Error::AWSV4SignatureError(_) => return None, - {{/withAWSV4Signature}} + {{#withAWSV4Signature}} + Error::AWSV4SignatureError(_) => return None, + {{/withAWSV4Signature}} }) } } diff --git a/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache b/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache index 32b2fd8a7c57..0de2884a8bb8 100644 --- a/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/rust/reqwest/configuration.mustache @@ -11,7 +11,7 @@ use secrecy::{SecretString, ExposeSecret}; pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client{{/supportMiddleware}}, + pub client: {{#supportMiddleware}}reqwest_middleware::ClientWithMiddleware{{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client{{/supportMiddleware}}, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, @@ -80,7 +80,7 @@ impl Default for Configuration { Configuration { base_path: "{{{basePath}}}".to_owned(), user_agent: {{#httpUserAgent}}Some("{{{.}}}".to_owned()){{/httpUserAgent}}{{^httpUserAgent}}Some("OpenAPI-Generator/{{{version}}}/rust".to_owned()){{/httpUserAgent}}, - client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest::Client::new(){{/supportMiddleware}}, + client: {{#supportMiddleware}}reqwest_middleware::ClientBuilder::new(reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new()).build(){{/supportMiddleware}}{{^supportMiddleware}}reqwest{{^supportAsync}}::blocking{{/supportAsync}}::Client::new(){{/supportMiddleware}}, basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/apiRequest.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/apiRequest.mustache index fd2ba29ea0bd..10be69afa959 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/apiRequest.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/apiRequest.mustache @@ -49,6 +49,8 @@ case class ApiRequest[U]( def withPathParam(name: String, value: Any): ApiRequest[U] = copy[U](pathParams = pathParams + (name -> value)) + def withQueryParam(values: Map[String, Any]): ApiRequest[U] = copy[U](queryParams = queryParams ++ values) + def withQueryParam(name: String, value: Any): ApiRequest[U] = copy[U](queryParams = queryParams + (name -> value)) def withHeaderParam(name: String, value: Any): ApiRequest[U] = copy[U](headerParams = headerParams + (name -> value)) diff --git a/modules/openapi-generator/src/main/resources/scala-akka-client/paramCreation.mustache b/modules/openapi-generator/src/main/resources/scala-akka-client/paramCreation.mustache index 68280bd9a36b..dc7bbc9f434e 100644 --- a/modules/openapi-generator/src/main/resources/scala-akka-client/paramCreation.mustache +++ b/modules/openapi-generator/src/main/resources/scala-akka-client/paramCreation.mustache @@ -1 +1 @@ -"{{baseName}}", {{#isContainer}}ArrayValues({{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{{paramName}}}{{/isContainer}} \ No newline at end of file +{{#isMap}}{{baseName}}{{/isMap}}{{^isMap}}"{{baseName}}", {{#isContainer}}ArrayValues({{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{{paramName}}}{{/isContainer}}{{/isMap}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-gatling/logback.xml b/modules/openapi-generator/src/main/resources/scala-gatling/logback.xml index f60d0182ac31..6e9430f76672 100644 --- a/modules/openapi-generator/src/main/resources/scala-gatling/logback.xml +++ b/modules/openapi-generator/src/main/resources/scala-gatling/logback.xml @@ -9,10 +9,10 @@ - + - + diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/api.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/api.mustache new file mode 100644 index 000000000000..2cb353b03c63 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/api.mustache @@ -0,0 +1,255 @@ +package {{apiPackage}} + +import {{apiPackage}}.path._ +import {{apiPackage}}.query._ + +{{#imports}}import {{import}} +{{/imports}} + +{{#extraImports}}import {{.}} +{{/extraImports}} + +import cats.Monad +import cats.syntax.all._ + +import org.http4s._ +import org.http4s.circe._ +import org.http4s.server._ +import org.http4s.headers._ +import org.http4s.dsl.Http4sDsl +import org.http4s.circe.CirceEntityEncoder._ + +final case class {{classname}}Routes[ + F[_]: JsonDecoder: Monad{{#allAuth}}, {{.}}{{/allAuth}} +](delegate: {{classname}}Delegate[F{{#allAuth}}, {{.}}{{/allAuth}}]) extends Http4sDsl[F] { +{{#operations}} +{{#operation}} + object {{operationId}} { + import {{classname}}Delegate.{{operationId}}Responses + + {{#pathParams}} + {{#vendorExtensions.x-refined}} + object {{baseName}}Varr extends RefinedVarr[{{vendorExtensions.x-refined-lft}}, {{{vendorExtensions.x-refined-rgt}}}] + {{/vendorExtensions.x-refined}} + {{/pathParams}} + {{#queryParams}} + {{#isArray}} + {{#required}} + object {{baseName}}QueryParam extends QuerySeqParamDecoderMatcher[{{{items.vendorExtensions.x-type}}}]("{{baseName}}") + {{/required}} + {{^required}} + object {{baseName}}QueryParam extends OptionalQuerySeqParamDecoderMatcher[{{{items.vendorExtensions.x-type}}}]("{{baseName}}") + {{/required}} + {{/isArray}} + {{^isArray}} + {{#required}} + object {{baseName}}QueryParam extends QueryParamDecoderMatcher[{{{vendorExtensions.x-type}}}]("{{baseName}}") + {{/required}} + {{^required}} + object {{baseName}}QueryParam extends OptionalQueryParamDecoderMatcher[{{{vendorExtensions.x-type}}}]("{{baseName}}") + {{/required}} + {{/isArray}} + {{/queryParams}} + +{{^vendorExtensions.x-authed}} + val route = HttpRoutes.of[F] { + case req @ {{{httpMethod}}} -> Root{{{vendorExtensions.x-codegen-path}}}{{{vendorExtensions.x-codegen-query}}} => + {{#vendorExtensions.x-json-body}} + {{#vendorExtensions.x-generic-body}} + req.contentType match { + case Some(`Content-Type`(MediaType.application.json, _)) => + {{>delegateCallJson}} + case _ => + {{>delegateCallGeneric}} + } + {{/vendorExtensions.x-generic-body}} + {{^vendorExtensions.x-generic-body}} + {{>delegateCallJson}} + {{/vendorExtensions.x-generic-body}} + {{/vendorExtensions.x-json-body}} + {{^vendorExtensions.x-json-body}} + {{>delegateCallGeneric}} + {{/vendorExtensions.x-json-body}} + } + +{{/vendorExtensions.x-authed}} +{{#vendorExtensions.x-authed}} + val route{{authName}} = AuthedRoutes.of[{{authName}}, F] { + case (req @ {{{httpMethod}}} -> Root{{{vendorExtensions.x-codegen-path}}}{{{vendorExtensions.x-codegen-query}}}) as auth => + {{#vendorExtensions.x-json-body}} + {{#vendorExtensions.x-generic-body}} + req.contentType match { + case Some(`Content-Type`(MediaType.application.json, _)) => + {{>delegateCallJson}} + case _ => + {{>delegateCallGeneric}} + } + {{/vendorExtensions.x-generic-body}} + {{^vendorExtensions.x-generic-body}} + {{>delegateCallJson}} + {{/vendorExtensions.x-generic-body}} + {{/vendorExtensions.x-json-body}} + {{^vendorExtensions.x-json-body}} + {{>delegateCallGeneric}} + {{/vendorExtensions.x-json-body}} + } +{{/vendorExtensions.x-authed}} + + val responses: {{operationId}}Responses[F] = new {{operationId}}Responses[F] { + {{#responses}} + {{#vendorExtensions.x-response-location}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(location: Location, value: {{{dataType}}}): F[Response[F]] = {{vendorExtensions.x-response}}(location, value) + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(location: Location): F[Response[F]] = {{vendorExtensions.x-response}}(location) + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-location}} + {{#vendorExtensions.x-response-www-auth}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(authenticate: `WWW-Authenticate`, value: {{{dataType}}}): F[Response[F]] = {{vendorExtensions.x-response}}(authenticate, value) + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(authenticate: `WWW-Authenticate`): F[Response[F]] = {{vendorExtensions.x-response}}(authenticate) + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-www-auth}} + {{#vendorExtensions.x-response-allow}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(allow: Allow, value: {{{dataType}}}): F[Response[F]] = {{vendorExtensions.x-response}}(allow, value) + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(allow: Allow): F[Response[F]] = {{vendorExtensions.x-response}}(allow) + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-allow}} + {{#vendorExtensions.x-response-proxy-auth}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(authenticate: `Proxy-Authenticate`, value: {{{dataType}}}): F[Response[F]] = {{vendorExtensions.x-response}}(value, authenticate) + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(authenticate: `Proxy-Authenticate`): F[Response[F]] = {{vendorExtensions.x-response}}(authenticate) + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-proxy-auth}} + {{#vendorExtensions.x-response-standard}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(value: {{{dataType}}}): F[Response[F]] = {{vendorExtensions.x-response}}(value) + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(): F[Response[F]] = {{vendorExtensions.x-response}}() + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-standard}} + {{/responses}} + } + } +{{/operation}} +{{/operations}} + +{{#operationsByAuth}} + val routes{{auth}} = + {{#ops}} + {{.}}.route{{auth}}{{^-last}} <+>{{/-last}} + {{/ops}} +{{/operationsByAuth}} +} + +object {{classname}}Delegate { +{{#operations}} +{{#operation}} + trait {{operationId}}Responses[F[_]] { + {{#responses}} + {{#vendorExtensions.x-response-location}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(location: Location, value: {{{dataType}}}): F[Response[F]] + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(location: Location): F[Response[F]] + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-location}} + {{#vendorExtensions.x-response-www-auth}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(authenticate: `WWW-Authenticate`, value: {{{dataType}}}): F[Response[F]] + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(authenticate: `WWW-Authenticate`): F[Response[F]] + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-www-auth}} + {{#vendorExtensions.x-response-allow}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(allow: Allow, value: {{{dataType}}}): F[Response[F]] + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(allow: Allow): F[Response[F]] + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-allow}} + {{#vendorExtensions.x-response-proxy-auth}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(authenticate: `Proxy-Authenticate`, value: {{{dataType}}}): F[Response[F]] + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(authenticate: `Proxy-Authenticate`): F[Response[F]] + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-proxy-auth}} + {{#vendorExtensions.x-response-standard}} + {{#vendorExtensions.x-json-response}} + def resp{{code}}(value: {{{dataType}}}): F[Response[F]] + {{/vendorExtensions.x-json-response}} + {{#vendorExtensions.x-generic-response}} + def resp{{code}}(): F[Response[F]] + {{/vendorExtensions.x-generic-response}} + {{/vendorExtensions.x-response-standard}} + {{/responses}} + } + +{{/operation}} +{{/operations}} +} + +trait {{classname}}Delegate[F[_]{{#allAuth}}, {{.}}{{/allAuth}}] { +{{#operations}} +{{#operation}} + + trait {{operationId}} { + import {{classname}}Delegate.{{operationId}}Responses + {{#vendorExtensions.x-json-body}} + +{{^vendorExtensions.x-authed}} + def handle( + req: Request[F], + {{operationId}}: F[{{{bodyParam.dataType}}}], +{{> delegateArgs}} responses: {{operationId}}Responses[F] + ): F[Response[F]] +{{/vendorExtensions.x-authed}} + +{{#vendorExtensions.x-authed}} + def handle_{{authName}}( + auth: {{authName}}, + req: Request[F], + {{operationId}}: F[{{{bodyParam.dataType}}}], +{{> delegateArgs}} responses: {{operationId}}Responses[F] + ): F[Response[F]] + +{{/vendorExtensions.x-authed}} + {{/vendorExtensions.x-json-body}} + + {{#vendorExtensions.x-generic-body}} +{{^vendorExtensions.x-authed}} + def handle( + req: Request[F], +{{> delegateArgs}} responses: {{operationId}}Responses[F] + ): F[Response[F]] +{{/vendorExtensions.x-authed}} + +{{#vendorExtensions.x-authed}} + def handle_{{authName}}( + auth: {{authName}}, + req: Request[F], +{{> delegateArgs}} responses: {{operationId}}Responses[F] + ): F[Response[F]] + +{{/vendorExtensions.x-authed}} + {{/vendorExtensions.x-generic-body}} + } + def {{operationId}}: {{operationId}} + +{{/operation}} +{{/operations}} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/apis.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/apis.mustache new file mode 100644 index 000000000000..98737814e141 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/apis.mustache @@ -0,0 +1,53 @@ +package {{packageName}} + +import org.http4s.circe._ +import cats.Monad +import cats.syntax.all._ +import cats.data.OptionT +import cats.data.Kleisli +import org.http4s._ +import org.http4s.server._ + +import {{apiPackage}}._ + +final case class API [ + F[_]: JsonDecoder: Monad{{#authMethods}}, {{name}}{{/authMethods}} +]( +{{#authMethods}} + {{#lambda.camelcase}}{{name}}{{/lambda.camelcase}}: Kleisli[OptionT[F, *], Request[F], {{name}}], +{{/authMethods}} +)( +{{#apiInfo}} +{{#apis}} +{{#operations}} + delegate{{classname}}: {{classname}}Delegate[F{{#allAuth}}, {{.}}{{/allAuth}}], +{{/operations}} +{{/apis}} +{{/apiInfo}} +){ +{{#authToOperationMap}} +{{#addMiddleware}} + val {{#lambda.camelcase}}{{auth}}{{/lambda.camelcase}}Middleware = AuthMiddleware{{^-last}}.withFallThrough{{/-last}}({{#lambda.camelcase}}{{auth}}{{/lambda.camelcase}}) +{{/addMiddleware}} +{{/authToOperationMap}} + +{{#apiInfo}} +{{#apis}} +{{#operations}} + val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Routes = new {{classname}}Routes(delegate{{classname}}) +{{/operations}} +{{/apis}} +{{/apiInfo}} + +{{#authToOperationMap}} + val routes{{auth}} = {{#addMiddleware}}{{#lambda.camelcase}}{{auth}}{{/lambda.camelcase}}Middleware({{/addMiddleware}} + {{#ops}} + {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}Routes.routes{{auth}}{{^-last}} <+>{{/-last}} + {{/ops}}{{#addMiddleware}}){{/addMiddleware}} +{{/authToOperationMap}} + + val routesAll = +{{#authToOperationMap}} + routes{{auth}}{{^-last}} <+>{{/-last}} +{{/authToOperationMap}} +} diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/build.properties b/modules/openapi-generator/src/main/resources/scala-http4s-server/build.properties new file mode 100644 index 000000000000..875272df2d3c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/build.properties @@ -0,0 +1 @@ +sbt.version=1.8.2 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/build.sbt b/modules/openapi-generator/src/main/resources/scala-http4s-server/build.sbt new file mode 100644 index 000000000000..70c616516402 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/build.sbt @@ -0,0 +1,27 @@ +scalaVersion := "2.13.11" +scalacOptions += "-Ymacro-annotations" + +val circeVersion = "0.14.5" +def circe(artifact: String): ModuleID = "io.circe" %% s"circe-$artifact" % circeVersion + +val http4sVersion = "0.23.23" +def http4s(artifact: String): ModuleID = "org.http4s" %% s"http4s-$artifact" % http4sVersion + +val refinedVersion = "0.9.29" +val refined = Seq( + "eu.timepit" %% "refined" % refinedVersion, + "eu.timepit" %% "refined-cats" % refinedVersion +) + +val catsVersion = "2.10.0" +val cats = Seq("org.typelevel" %% "cats-core" % catsVersion) + +lazy val compilerPlugins = Seq( + compilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), + compilerPlugin("org.typelevel" %% "kind-projector" % "0.13.2" cross CrossVersion.full) +) + +libraryDependencies ++= (Seq( + http4s("core"), http4s("ember-server"), http4s("circe"), http4s("dsl"), + circe("core"), circe("generic"), circe("parser"), circe("refined") +) ++ refined ++ cats ++ compilerPlugins) diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateArgs.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateArgs.mustache new file mode 100644 index 000000000000..327a6a96545f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateArgs.mustache @@ -0,0 +1,21 @@ +{{#pathParams}} + {{baseName}}: {{{vendorExtensions.x-type}}}, +{{/pathParams}} +{{#queryParams}} + {{#isArray}} + {{#required}} + {{baseName}}: List[{{{items.vendorExtensions.x-type}}}], + {{/required}} + {{^required}} + {{baseName}}: Option[List[{{{items.vendorExtensions.x-type}}}]], + {{/required}} + {{/isArray}} + {{^isArray}} + {{#required}} + {{baseName}}: {{{vendorExtensions.x-type}}}, + {{/required}} + {{^required}} + {{baseName}}: Option[{{{vendorExtensions.x-type}}}], + {{/required}} + {{/isArray}} +{{/queryParams}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallGeneric.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallGeneric.mustache new file mode 100644 index 000000000000..d5b1ba61c57c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallGeneric.mustache @@ -0,0 +1,6 @@ +{{^authName}} +delegate.{{operationId}}.handle(req, {{#pathParams}}{{baseName}}, {{/pathParams}}{{#queryParams}}{{baseName}}, {{/queryParams}}responses) +{{/authName}} +{{#authName}} +delegate.{{operationId}}.handle_{{authName}}(auth, req, {{#pathParams}}{{baseName}}, {{/pathParams}}{{#queryParams}}{{baseName}}, {{/queryParams}}responses) +{{/authName}} diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallJson.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallJson.mustache new file mode 100644 index 000000000000..e023b906240b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/delegateCallJson.mustache @@ -0,0 +1,6 @@ +{{^authName}} + delegate.{{operationId}}.handle(req, req.asJsonDecode[{{{bodyParam.dataType}}}] , {{#pathParams}}{{baseName}}, {{/pathParams}}{{#queryParams}}{{baseName}}, {{/queryParams}}responses) +{{/authName}} +{{#authName}} + delegate.{{operationId}}.handle_{{authName}}(auth, req, req.asJsonDecode[{{{bodyParam.dataType}}}] , {{#pathParams}}{{baseName}}, {{/pathParams}}{{#queryParams}}{{baseName}}, {{/queryParams}}responses) +{{/authName}} diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/path.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/path.mustache new file mode 100644 index 000000000000..c35abc8d48cd --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/path.mustache @@ -0,0 +1,62 @@ +package {{apiPackage}} + +import cats.syntax.all._ +import cats.data.ValidatedNel + +import eu.timepit.refined._ +import eu.timepit.refined.api.Refined +import eu.timepit.refined.api.Validate + +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZonedDateTime +import java.util.UUID + +import scala.util.Try + +object path { + trait Varrr[T] { + def unapply(str: String): Option[T] + } + + implicit val LocalDateVarr: Varrr[LocalDate] = new Varrr[LocalDate] { + def unapply(str: String): Option[LocalDate] = Try(LocalDate.parse(str)).toOption + } + + implicit val LocalDateTimeVarr: Varrr[LocalDateTime] = new Varrr[LocalDateTime] { + def unapply(str: String): Option[LocalDateTime] = Try(LocalDateTime.parse(str)).toOption + } + + implicit val ZonedDateTimeVarr: Varrr[ZonedDateTime] = new Varrr[ZonedDateTime] { + def unapply(str: String): Option[ZonedDateTime] = Try(ZonedDateTime.parse(str)).toOption + } + + implicit val UUIDVarr: Varrr[UUID] = new Varrr[UUID] { + def unapply(str: String): Option[UUID] = Try(java.util.UUID.fromString(str)).toOption + } + + implicit val IntVarr: Varrr[Int] = new Varrr[Int] { + def unapply(str: String): Option[Int] = Try(str.toInt).toOption + } + + implicit val LongVarr: Varrr[Long] = new Varrr[Long] { + def unapply(str: String): Option[Long] = Try(str.toLong).toOption + } + + implicit val DoubleVarr: Varrr[Double] = new Varrr[Double] { + def unapply(str: String): Option[Double] = Try(str.toDouble).toOption + } + + implicit val BigDecimalVarr: Varrr[BigDecimal] = new Varrr[BigDecimal] { + def unapply(str: String): Option[BigDecimal] = Try(BigDecimal(str)).toOption + } + + implicit val StringVarr: Varrr[String] = new Varrr[String] { + def unapply(str: String): Option[String] = str.some + } + + abstract class RefinedVarr[T, P](implicit varrr: Varrr[T], validate: Validate[T, P]) extends Varrr[Refined[T, P]] { + def unapply(str: String): Option[Refined[T, P]] = + varrr.unapply(str).flatMap(x => refineV(x).toOption) + } +} diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/query.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/query.mustache new file mode 100644 index 000000000000..52f5fa9ce971 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/query.mustache @@ -0,0 +1,59 @@ +package {{apiPackage}} + +import cats.data.NonEmptyList +import cats.data.ValidatedNel +import cats.syntax.all._ + +import eu.timepit.refined._ +import eu.timepit.refined.api.Refined +import eu.timepit.refined.api.Validate + +import org.http4s.ParseFailure +import org.http4s.QueryParamDecoder +import org.http4s.QueryParameterValue + +import java.time._ +import java.util.UUID + +object query { + implicit def rrrefinedQueryParamDecoder[T, P]( + implicit tDecoder: QueryParamDecoder[T], validate: Validate[T, P] + ): QueryParamDecoder[Refined[T, P]] = new QueryParamDecoder[Refined[T, P]] { + def decode(value: QueryParameterValue): ValidatedNel[ParseFailure,Refined[T, P]] = + tDecoder.decode(value).withEither(t => t.flatMap(x => + refineV(x).leftMap(err => NonEmptyList.one(ParseFailure(err, err))) + )) + } + + abstract class QuerySeqParamDecoderMatcher[T: QueryParamDecoder](name: String) { + def unapply(params: Map[String, Seq[String]]): Option[List[T]] = + params + .get(name) + .flatMap(values => + values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption)) + } + + abstract class OptionalQuerySeqParamDecoderMatcher[T: QueryParamDecoder](name: String) { + def unapply(params: Map[String, List[String]]): Option[Option[List[T]]] = + params + .get(name) + .flatMap(values => + values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption)) + .fold(List.empty[T].some.some)(_.some.some) + } + + implicit lazy val BigDecimalQueryParamDecoder: QueryParamDecoder[BigDecimal] = + QueryParamDecoder.fromUnsafeCast[BigDecimal](x => BigDecimal(x.value))("BigDecimal") + + implicit lazy val LocalDateTimeQueryParamDecoder: QueryParamDecoder[LocalDateTime] = + QueryParamDecoder.fromUnsafeCast[LocalDateTime](x => LocalDateTime.parse(x.value))("LocalDateTime") + + implicit lazy val LocalDateQueryParamDecoder: QueryParamDecoder[LocalDate] = + QueryParamDecoder.fromUnsafeCast[LocalDate](x => LocalDate.parse(x.value))("LocalDateTime") + + implicit lazy val ZonedDateTimeQueryParamDecoder: QueryParamDecoder[ZonedDateTime] = + QueryParamDecoder.fromUnsafeCast[ZonedDateTime](x => ZonedDateTime.parse(x.value))("ZonedDateTime") + + implicit lazy val UUIDQueryParamDecoder: QueryParamDecoder[UUID] = + QueryParamDecoder.fromUnsafeCast[UUID](x => UUID.fromString(x.value))("UUID") +} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-http4s-server/types.mustache b/modules/openapi-generator/src/main/resources/scala-http4s-server/types.mustache new file mode 100644 index 000000000000..53b5851b99ec --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-http4s-server/types.mustache @@ -0,0 +1,98 @@ +package {{modelPackage}} + +import java.time._ + +import io.circe.refined._ +import io.circe.syntax._ +import io.circe.{ Decoder, Encoder } +import io.circe.generic.semiauto.{ deriveDecoder, deriveEncoder } + +{{#imports}} +import {{.}} +{{/imports}} + +{{#models}} +{{#model}} +/** +* {{{description}}} +{{#vars}} +* @param {{name}} {{{description}}} +{{/vars}} +*/ +{{#vendorExtensions.x-isSealedTrait}} +sealed trait {{classname}} +object {{classname}} { + import io.circe.{ Decoder, Encoder } + import io.circe.syntax._ + import cats.syntax.functor._ + +{{^vendorExtensions.x-use-discr}} +// no discriminator + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Encoder: Encoder[{{classname}}] = Encoder.instance { +{{#oneOf}} + case {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}: {{.}} => {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}.asJson +{{/oneOf}} + } + + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Decoder: Decoder[{{classname}}] = + List[Decoder[{{classname}}]]( +{{#oneOf}} + Decoder[{{.}}].widen, +{{/oneOf}} + ).reduceLeft(_ or _) +{{/vendorExtensions.x-use-discr}} +{{#vendorExtensions.x-use-discr}} +{{^vendorExtensions.x-use-discr-mapping}} +// no discriminator mapping + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Encoder: Encoder[{{classname}}] = Encoder.instance { +{{#oneOf}} + case {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}: {{.}} => {{#lambda.camelcase}}{{.}}{{/lambda.camelcase}}.asJson.mapObject(("{{discriminator.propertyName}}" -> "{{.}}".asJson) +: _) +{{/oneOf}} + } + + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Decoder: Decoder[{{classname}}] = Decoder.instance { cursor => + cursor.downField("{{discriminator.propertyName}}").as[String].flatMap { + {{#oneOf}} + case "{{.}}" => + cursor.as[{{.}}] + {{/oneOf}} + } + } +{{/vendorExtensions.x-use-discr-mapping}} +{{#vendorExtensions.x-use-discr-mapping}} +// use discriminator mapping +{{#discriminator}} + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Encoder: Encoder[{{classname}}] = Encoder.instance { +{{#mappedModels}} + case {{#lambda.camelcase}}{{model.classname}}{{/lambda.camelcase}}: {{model.classname}} => {{#lambda.camelcase}}{{model.classname}}{{/lambda.camelcase}}.asJson.mapObject(("{{propertyName}}" -> "{{mappingName}}".asJson) +: _) +{{/mappedModels}} + } + + implicit val {{#lambda.camelcase}}{{classname}}{{/lambda.camelcase}}Decoder: Decoder[{{classname}}] = Decoder.instance { cursor => + cursor.downField("{{propertyName}}").as[String].flatMap { + {{#mappedModels}} + case "{{mappingName}}" => + cursor.as[{{model.classname}}] + {{/mappedModels}} + } + } +{{/discriminator}} +{{/vendorExtensions.x-use-discr-mapping}} +{{/vendorExtensions.x-use-discr}} +} +{{/vendorExtensions.x-isSealedTrait}} + +{{^vendorExtensions.x-isSealedTrait}} +case class {{classname}}( +{{#vars}} + {{name}}: {{^required}}Option[{{{vendorExtensions.x-type}}}]{{/required}}{{#required}}{{{vendorExtensions.x-type}}}{{/required}}{{^-last}},{{/-last}} +{{/vars}} +){{#vendorExtensions.x-extends}} extends {{.}}{{/vendorExtensions.x-extends}}{{#vendorExtensions.x-extendsWith}} with {{.}}{{/vendorExtensions.x-extendsWith}} +object {{classname}} { + implicit val encoder{{classname}}: Encoder[{{classname}}] = deriveEncoder[{{classname}}].mapJson(_.dropNullValues) + implicit val decoder{{classname}}: Decoder[{{classname}}] = deriveDecoder[{{classname}}] +} +{{/vendorExtensions.x-isSealedTrait}} + +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/README.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/README.mustache new file mode 100644 index 000000000000..577f7188ca36 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/README.mustache @@ -0,0 +1,171 @@ +# {{artifactId}} + +{{appName}} +- API version: {{appVersion}} +{{^hideGenerationTimestamp}} + - Build date: {{generatedDate}} +{{/hideGenerationTimestamp}} + +{{{appDescriptionWithNewLines}}} + +{{#infoUrl}} + For more information, please visit [{{{infoUrl}}}]({{{infoUrl}}}) +{{/infoUrl}} + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle/SBT + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + {{{groupId}}} + {{{artifactId}}} + {{{artifactVersion}}} + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "{{{groupId}}}:{{{artifactId}}}:{{{artifactVersion}}}" +``` + +### SBT users + +```scala +libraryDependencies += "{{{groupId}}}" % "{{{artifactId}}}" % "{{{artifactVersion}}}" +``` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```scala +{{#apiInfo}}{{#apis}}{{#-first}}{{#operations}}{{#operation}}{{#-first}} +import {{invokerPackage}}._ +import {{modelPackage}}._ +import {{{package}}}.{{{classname}}} + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object {{{classname}}}Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher{{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + implicit val {{{name}}}: BasicCredentials = BasicCredentials("YOUR USERNAME", "YOUR PASSWORD"){{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + implicit val {{{name}}}: BearerToken = BearerToken("BEARER TOKEN"){{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + implicit val {{{name}}}: ApiKeyValue = ApiKeyValue("YOUR API KEY"){{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + + // Create invoker to execute requests + val apiInvoker = ApiInvoker() + val apiInstance = {{{classname}}}("{{{basePath}}}"){{#allParams}} + val {{{paramName}}}: {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} + {{/allParams}} + + val request = apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(org.openapitools.client.core.ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}"){{#returnType}} + System.out.println(s"Response body: $content"){{/returnType}} + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}") + exception.printStackTrace(); + } + +} +{{/-first}}{{/operation}}{{/operations}}{{/-first}}{{/apis}}{{/apiInfo}} +``` + +## Documentation for API Endpoints + +All URIs are relative to *{{basePath}}* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +{{#apiInfo}}{{#apis}}{{#operations}}{{#operation}}*{{classname}}* | [**{{operationId}}**]({{apiDocPath}}{{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}}{{/apis}}{{/apiInfo}} + +## Documentation for Models + +{{#models}}{{#model}} - [{{classname}}]({{modelDocPath}}{{classname}}.md) +{{/model}}{{/models}} + + +## Documentation for Authorization + +{{^authMethods}}Endpoints do not require authorization.{{/authMethods}} +{{#hasAuthMethods}}Authentication schemes defined for the API:{{/hasAuthMethods}} +{{#authMethods}} + +### {{name}} + +{{#isApiKey}}- **Type**: API key +- **API key parameter name**: {{keyParamName}} +- **Location**: {{#isKeyInQuery}}URL query string{{/isKeyInQuery}}{{#isKeyInHeader}}HTTP header{{/isKeyInHeader}} +{{/isApiKey}} +{{#isBasicBasic}}- **Type**: HTTP basic authentication +{{/isBasicBasic}} +{{#isBasicBearer}}- **Type**: HTTP Bearer Token authentication{{#bearerFormat}} ({{{.}}}){{/bearerFormat}} +{{/isBasicBearer}} +{{#isHttpSignature}}- **Type**: HTTP signature authentication +{{/isHttpSignature}} +{{#isOAuth}}- **Type**: OAuth +- **Flow**: {{flow}} +- **Authorization URL**: {{authorizationUrl}} +- **Scopes**: {{^scopes}}N/A{{/scopes}} +{{#scopes}} - {{scope}}: {{description}} +{{/scopes}} +{{/isOAuth}} + +{{/authMethods}} + +## Author + +{{#apiInfo}}{{#apis}}{{#-last}}{{infoEmail}} +{{/-last}}{{/apis}}{{/apiInfo}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/api.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/api.mustache new file mode 100644 index 000000000000..6da068e37a58 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/api.mustache @@ -0,0 +1,52 @@ +{{>licenseInfo}} +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{invokerPackage}}._ +import {{invokerPackage}}.CollectionFormats._ +import {{invokerPackage}}.ApiKeyLocations._ + +{{#operations}} +object {{classname}} { + + def apply(baseUrl: String = "{{{basePath}}}") = new {{classname}}(baseUrl) +} + +class {{classname}}(baseUrl: String) { + +{{#operation}} +{{#javadocRenderer}} +{{>javadoc}} +{{/javadocRenderer}} + def {{operationId}}({{>methodParameters}}): ApiRequest[{{>operationReturnType}}] = + ApiRequest[{{>operationReturnType}}](ApiMethods.{{httpMethod.toUpperCase}}, baseUrl, "{{{path}}}", {{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}}{{^consumes}}"application/json"{{/consumes}}) + {{#authMethods}}{{#isApiKey}}.withApiKey(apiKey, "{{keyParamName}}", {{#isKeyInQuery}}QUERY{{/isKeyInQuery}}{{#isKeyInHeader}}HEADER{{/isKeyInHeader}}{{#isKeyInCookie}}COOKIE{{/isKeyInCookie}}) + {{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}.withCredentials(basicAuth){{/isBasicBasic}}{{#isBasicBearer}}.withCredentials(bearerToken){{/isBasicBearer}}{{/isBasic}}{{/authMethods}}{{#bodyParam}}.withBody({{paramName}}) + {{/bodyParam}}{{#formParams}}.withFormParam({{>paramCreation}}) + {{/formParams}}{{#queryParams}}.withQueryParam({{>paramCreation}}) + {{/queryParams}}{{#pathParams}}.withPathParam({{>paramCreation}}) + {{/pathParams}}{{#headerParams}}.withHeaderParam({{>paramCreation}}) + {{/headerParams}}{{#responses}}{{^isWildcard}}{{#dataType}}.with{{>responseState}}Response[{{dataType}}]({{code}}) + {{/dataType}}{{^dataType}}.with{{>responseState}}Response[Unit]({{code}}) + {{/dataType}}{{/isWildcard}}{{/responses}}{{#responses}}{{#isWildcard}}{{#dataType}}.withDefault{{>responseState}}Response[{{dataType}}] + {{/dataType}}{{^dataType}}.withDefault{{>responseState}}Response[Unit] + {{/dataType}}{{/isWildcard}}{{/responses}} + {{^responseHeaders.isEmpty}} + object {{#fnCapitalize}}{{operationId}}{{/fnCapitalize}}Headers { + {{#responseHeaders}} + def {{{name}}}(r: ApiReturnWithHeaders) = r.get{{^isContainer}}{{baseType}}{{/isContainer}}{{#isContainer}}String{{/isContainer}}Header("{{baseName}}") + {{/responseHeaders}} + } + {{/responseHeaders.isEmpty}} + +{{/operation}} + + {{#unknownStatusCodes}} + ApiInvoker.addCustomStatusCode({{{value}}}, isSuccess = false) + {{/unknownStatusCodes}} + +} + +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/apiInvoker.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiInvoker.mustache new file mode 100644 index 000000000000..065e2296d0a6 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiInvoker.mustache @@ -0,0 +1,285 @@ +{{>licenseInfo}} +package {{invokerPackage}} + +import java.io.File + +import org.apache.pekko.actor.ActorSystem +import org.apache.pekko.http.scaladsl.Http +import org.apache.pekko.http.scaladsl.coding._ +import org.apache.pekko.http.scaladsl.model.Multipart.FormData.BodyPart +import org.apache.pekko.http.scaladsl.model.Uri.Query +import org.apache.pekko.http.scaladsl.model._ +import org.apache.pekko.http.scaladsl.model.headers._ +import org.apache.pekko.http.scaladsl.unmarshalling.{ Unmarshal, Unmarshaller } +import org.apache.pekko.stream.Materializer +import org.apache.pekko.stream.scaladsl.Source +import org.apache.pekko.util.{ ByteString, Timeout } +import com.github.pjfanning.pekkohttpjson4s.Json4sSupport +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization + +import scala.collection.immutable +import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } +import scala.reflect.ClassTag + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats ++ Serializers.all) + + def apply(serializers: Iterable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats ++ Serializers.all ++ serializers) + + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will fail with a ClassCastException + * + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T: Manifest](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toAkkaHttpMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + +} + +trait UnitJSONSupport { + +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomContentTypes with Json4sSupport { + + import {{{invokerPackage}}}.ApiInvoker._ + import {{{invokerPackage}}}.ParametersMap._ + + implicit val ec: ExecutionContextExecutor = system.dispatcher + implicit val jsonFormats: Formats = formats + + protected val settings: ApiSettings = ApiSettings(system) + + private implicit val materializer: Materializer = Materializer(system) + private implicit val serialization: Serialization = jackson.Serialization + + + private val http = Http() + + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => + Seq( + { _: HttpMessage => settings.compressionEnabled }, + Encoder.DefaultFilter, + (message: HttpMessage) => { + val long = message.entity().getContentLengthOption() + if (long.isPresent) long.getAsLong > settings.compressionSizeThreshold else true + } + ) + .map(f => f(msg)) + .forall(identity) + + + private def addAuthentication(credentialsSeq: Seq[Credentials]) = { + request: HttpRequest => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req.addHeader(Authorization(BasicHttpCredentials(login, password))) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req.addHeader(RawHeader(keyName, keyValue.value)) + case (req, BearerToken(token)) => + req.addHeader(RawHeader("Authorization", s"Bearer $token")) + case (req, _) => req + } + } + + private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = + headers.asFormattedParams + .map { case (name, value) => RawHeader(name, value.toString) } + .to(immutable.Seq) + + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart.fromFile( + name, + ContentType(MediaTypes.`application/octet-stream`), + f, + f.length().toInt + ) + case v: String => + BodyPart.Strict(name, v.toString) + case NumericValue(v) => + BodyPart.Strict(name, v.toString) + case m: ApiModel => + BodyPart.Strict(name, Serialization.write(m)) + } + } + + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.view.mapValues(_.toString).toMap) + case _: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.view.mapValues(_.toString).toMap) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = request + .bodyParam + .map(Extraction.decompose) + .map(compact) + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + val httpRequest = request.method.toAkkaHttpMethod match { + case m@(HttpMethods.GET | HttpMethods.DELETE) => HttpRequest(m, uri) + case m@(HttpMethods.POST | HttpMethods.PUT | HttpMethods.PATCH) => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + HttpRequest(m, uri, entity = c.toEntity) + case Some(c: Multipart.FormData) => + HttpRequest(m, uri, entity = c.toEntity) + case Some(c: String) => + HttpRequest(m, uri, entity = HttpEntity(normalizedContentType(request.contentType), ByteString(c))) + case _ => + HttpRequest(m, uri, entity = HttpEntity(normalizedContentType(request.contentType), ByteString(""))) + } + case m: HttpMethod => HttpRequest(m, uri) + } + + addAuthentication(request.credentials)( + httpRequest.withHeaders(headers(request.headerParams)) + ) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .view + .mapValues(_.toString) + .toMap + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .view + .mapValues(_.toString) + .toMap + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T: Manifest](r: ApiRequest[T]): Future[ApiResponse[T]] = { + implicit val timeout: Timeout = settings.connectionTimeout + + val request = createRequest(makeUri(r), r) + + http + .singleRequest(request) + .map { response => + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding + case HttpEncoding(encoding) => + throw new IllegalArgumentException(s"Unsupported encoding: $encoding") + } + + decoder.decodeMessage(response) + } + .flatMap(unmarshallApiResponse(r)) + } + + def unmarshallApiResponse[T: Manifest](request: ApiRequest[T])(response: HttpResponse): Future[ApiResponse[T]] = { + def responseForState[V](state: ResponseState, value: V): ApiResponse[V] = { + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw ApiError( + response.status.intValue, + "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap + ) + } + } + val mf = implicitly(manifest[T]) + request + .responseForCode(response.status.intValue) match { + case Some((Manifest.Unit, state: ResponseState)) => + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) + case Some((manifest, state: ResponseState)) if manifest == mf => + implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) + Unmarshal(response.entity) + .to[T] + .recoverWith { + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + } + .map(value => responseForState(state, value)) + case None | Some(_) => + Future.failed(ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))) + } + } +} + +sealed trait CustomContentTypes { + + protected def normalizedContentType(original: String): ContentType = + ContentType(parseContentType(original).mediaType, () => HttpCharsets.`UTF-8`) + + protected def parseContentType(contentType: String): ContentType = { + + ContentType.parse(contentType) match { + case Right(ct: ContentType) => + ct + case Left(error: List[ErrorInfo]) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.map(_.summary).mkString(", ")}'" + ) + } + } +} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/apiRequest.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiRequest.mustache new file mode 100644 index 000000000000..10be69afa959 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiRequest.mustache @@ -0,0 +1,57 @@ +{{>licenseInfo}} +package {{invokerPackage}} + +sealed trait ResponseState + +object ResponseState { + + case object Success extends ResponseState + + case object Error extends ResponseState + +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials): ApiRequest[U] = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation): ApiRequest[U] = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody(): ApiRequest[U] = copy[U](bodyParam = None) + + def withBody(body: Any): ApiRequest[U] = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any): ApiRequest[U] = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any): ApiRequest[U] = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(values: Map[String, Any]): ApiRequest[U] = copy[U](queryParams = queryParams ++ values) + + def withQueryParam(name: String, value: Any): ApiRequest[U] = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any): ApiRequest[U] = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/apiSettings.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiSettings.mustache new file mode 100644 index 000000000000..9da1da56cdf0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/apiSettings.mustache @@ -0,0 +1,44 @@ +{{>licenseInfo}} +package {{invokerPackage}} + +import java.util.concurrent.TimeUnit + +import org.apache.pekko.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} +import org.apache.pekko.http.scaladsl.model.{StatusCode, StatusCodes} +import org.apache.pekko.http.scaladsl.model.headers.RawHeader +import com.typesafe.config.Config + +import scala.jdk.CollectionConverters._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("{{configKeyPath}}.{{configKey}}") + + val alwaysTrustCertificates: Boolean = cfg.getBoolean("trust-certificates") + val defaultHeaders: List[RawHeader] = cfg.getConfig("default-headers").entrySet.asScala.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled: Boolean = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold: Int = cfg.getBytes("compression.size-threshold").toInt + val customCodes: List[StatusCode]= cfg.getConfigList("custom-codes").asScala.toList.map { c => + StatusCodes.custom( + c.getInt("code"), + c.getString("reason"), + if (c.hasPath("defaultMessage")) c.getString("defaultMessage") else c.getString("reason"), + c.getBoolean("success"), + if (c.hasPath("allowsEntity")) c.getBoolean("allowsEntity") else true + ) + } +} + +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/api_doc.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/api_doc.mustache new file mode 100644 index 000000000000..236e83ca36aa --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/api_doc.mustache @@ -0,0 +1,114 @@ +# {{classname}}{{#description}} + +{{.}}{{/description}} + +All URIs are relative to *{{basePath}}* + +Method | HTTP request | Description +------------- | ------------- | ------------- +{{#operations}}{{#operation}}[**{{operationId}}**]({{classname}}.md#{{operationId}}) | **{{httpMethod}}** {{path}} | {{summary}} +[**{{operationId}}WithHttpInfo**]({{classname}}.md#{{operationId}}WithHttpInfo) | **{{httpMethod}}** {{path}} | {{summary}} +{{/operation}}{{/operations}} + +{{#operations}} +{{#operation}} + +## {{operationId}} + +> {{operationId}}({{#hasParams}}{{operationId}}Request{{/hasParams}}): ApiRequest[{{#returnType}}{{{returnType}}}{{/returnType}}{{^returnType}}Unit{{/returnType}}] + +{{summary}}{{#notes}} + +{{.}}{{/notes}} + +### Example + +```scala +// Import classes: +{{#imports}} +import {{import}} +{{/imports}} +import {{invokerPackage}}._ +import {{invokerPackage}}.CollectionFormats._ +import {{invokerPackage}}.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + {{#hasAuthMethods}} + {{#authMethods}}{{#isBasic}}{{#isBasicBasic}} + // Configure HTTP basic authorization: {{{name}}} + implicit val {{{name}}}: BasicCredentials = BasicCredentials("YOUR USERNAME", "YOUR PASSWORD"){{/isBasicBasic}}{{#isBasicBearer}} + // Configure HTTP bearer authorization: {{{name}}} + implicit val {{{name}}}: BearerToken = BearerToken("BEARER TOKEN"){{/isBasicBearer}}{{/isBasic}}{{#isApiKey}} + // Configure API key authorization: {{{name}}} + implicit val {{{name}}}: ApiKeyValue = ApiKeyValue("YOUR API KEY"){{/isApiKey}} + {{/authMethods}} + {{/hasAuthMethods}} + + val apiInvoker = ApiInvoker() + val apiInstance = {{{classname}}}("{{{basePath}}}"){{#allParams}} + val {{{paramName}}}: {{{dataType}}} = {{{example}}} // {{{dataType}}} | {{{description}}} + {{/allParams}} + + val request = apiInstance.{{{operationId}}}({{#allParams}}{{{paramName}}}{{^-last}}, {{/-last}}{{/allParams}}) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}"){{#returnType}} + System.out.println(s"Response body: $content"){{/returnType}} + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling {{{classname}}}#{{{operationId}}}") + exception.printStackTrace(); + } +} +``` + +### Parameters + +{{^allParams}}This endpoint does not need any parameter.{{/allParams}}{{#allParams}}{{#-last}} +Name | Type | Description | Notes +------------- | ------------- | ------------- | -------------{{/-last}}{{/allParams}} +{{#allParams}} **{{paramName}}** | {{#isPrimitiveType}}**{{dataType}}**{{/isPrimitiveType}}{{^isPrimitiveType}}{{#isFile}}**{{dataType}}**{{/isFile}}{{^isFile}}[**{{dataType}}**]({{baseType}}.md){{/isFile}}{{/isPrimitiveType}}| {{description}} |{{^required}} [optional]{{/required}}{{^isContainer}}{{#defaultValue}} [default to {{.}}]{{/defaultValue}}{{/isContainer}}{{#allowableValues}} [enum: {{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} +{{/allParams}} + +### Return type + +{{#returnType}}ApiRequest[{{#returnTypeIsPrimitive}}**{{returnType}}**{{/returnTypeIsPrimitive}}{{^returnTypeIsPrimitive}}[**{{returnType}}**]({{returnBaseType}}.md){{/returnTypeIsPrimitive}}]{{/returnType}} +{{^returnType}}ApiRequest[Unit] (empty response body){{/returnType}} + +### Authorization + +{{^authMethods}}No authorization required{{/authMethods}}{{#authMethods}}[{{name}}](../README.md#{{name}}){{^-last}}, {{/-last}}{{/authMethods}} + +### HTTP request headers + +- **Content-Type**: {{#consumes}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/consumes}}{{^consumes}}Not defined{{/consumes}} +- **Accept**: {{#produces}}{{{mediaType}}}{{^-last}}, {{/-last}}{{/produces}}{{^produces}}Not defined{{/produces}} + +{{#responses.0}} +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +{{#responses}} +| **{{code}}** | {{message}} | {{#headers}} * {{baseName}} - {{description}}
              {{/headers}}{{^headers.0}} - {{/headers.0}} | +{{/responses}} +{{/responses.0}} + +{{/operation}} +{{/operations}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/build.sbt.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/build.sbt.mustache new file mode 100644 index 000000000000..478f24c993e7 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/build.sbt.mustache @@ -0,0 +1,29 @@ +version := "{{artifactVersion}}" +name := "{{artifactId}}" +organization := "{{groupId}}" + +scalaVersion := "2.13.12" +val PekkoVersion = "1.0.2" + +libraryDependencies ++= Seq( + "com.typesafe" % "config" % "1.4.3", + "org.apache.pekko" %% "pekko-actor" % PekkoVersion, + "org.apache.pekko" %% "pekko-stream" % PekkoVersion, + "org.apache.pekko" %% "pekko-stream" % PekkoVersion, + "com.github.pjfanning" %% "pekko-http-json4s" % "2.3.2", + "org.json4s" %% "json4s-jackson" % "4.0.7", + "org.json4s" %% "json4s-ext" % "4.0.7", + // test dependencies + "org.scalatest" %% "scalatest" % "3.2.17" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.17.0" % "test" +) + +resolvers ++= Seq(Resolver.mavenLocal) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/class_doc.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/class_doc.mustache new file mode 100644 index 000000000000..0cb62ce8fe5b --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/class_doc.mustache @@ -0,0 +1,32 @@ +# {{#vendorExtensions.x-is-one-of-interface}}Trait {{/vendorExtensions.x-is-one-of-interface}}{{classname}} + +{{#description}}{{&description}} +{{/description}} + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +{{#vars}}**{{name}}** | {{#isEnum}}[**{{datatypeWithEnum}}**](#{{datatypeWithEnum}}){{/isEnum}}{{^isEnum}}{{#isContainer}}{{#isArray}}{{#items}}{{#isModel}}[{{/isModel}}{{/items}}**{{baseType}}{{#items}}<{{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isArray}}{{#isMap}}{{#items}}{{#isModel}}[{{/isModel}}**Map<String, {{dataType}}>**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/items}}{{/isMap}}{{/isContainer}}{{^isContainer}}{{#isModel}}[{{/isModel}}**{{dataType}}**{{#isModel}}]({{^baseType}}{{dataType}}{{/baseType}}{{baseType}}.md){{/isModel}}{{/isContainer}}{{/isEnum}} | {{description}} | {{^required}} [optional]{{/required}}{{#isReadOnly}} [readonly]{{/isReadOnly}} +{{/vars}} +{{#vars}}{{#isEnum}} + +## Enum: {{datatypeWithEnum}} +Allowed values: {{#allowableValues}}[{{#values}}{{{.}}}{{^-last}}, {{/-last}}{{/values}}]{{/allowableValues}} + +{{/isEnum}}{{/vars}} +{{#vendorExtensions.x-implements.0}} + +## Implemented Interfaces + +{{#vendorExtensions.x-implements}} +* {{{.}}} +{{/vendorExtensions.x-implements}} +{{/vendorExtensions.x-implements.0}} +{{#vendorExtensions.x-is-one-of-interface}} +## Implementing Classes + +{{#oneOf}} +* {{{.}}} +{{/oneOf}} +{{/vendorExtensions.x-is-one-of-interface}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/enum_doc.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/enum_doc.mustache new file mode 100644 index 000000000000..20c512aaeae4 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/enum_doc.mustache @@ -0,0 +1,7 @@ +# {{classname}} + +## Enum + +{{#allowableValues}}{{#enumVars}} +* `{{name}}` (value: `{{{value}}}`) +{{/enumVars}}{{/allowableValues}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/enumsSerializers.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/enumsSerializers.mustache new file mode 100644 index 000000000000..8c7e6f2e41e5 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/enumsSerializers.mustache @@ -0,0 +1,42 @@ +{{>licenseInfo}} +package {{apiPackage}} + +{{#models.0}} +import {{modelPackage}}._ +{{/models.0}} +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all: Seq[Serializer[_]] = Seq[Serializer[_]](){{#models}}{{#model}}{{#hasEnums}}{{#vars}}{{#isEnum}} :+ + new EnumNameSerializer({{classname}}Enums.{{datatypeWithEnum}}){{/isEnum}}{{/vars}}{{/hasEnums}}{{/model}}{{/models}} + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass: Class[E#Value] = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/javadoc.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/javadoc.mustache new file mode 100644 index 000000000000..6acaca14ac3a --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/javadoc.mustache @@ -0,0 +1,25 @@ +{{#notes}} +{{{.}}} + +{{/notes}} +Expected answers: +{{#responses}} + code {{code}} : {{{dataType}}} {{#message}}({{{.}}}){{/message}} + {{#headers}} + {{#-first}} + Headers : + {{/-first}} + {{{baseName}}} - {{{description}}} + {{/headers}} +{{/responses}} +{{#authMethods.0}} + +Available security schemes: +{{#authMethods}} + {{name}} ({{type}}) +{{/authMethods}} +{{/authMethods.0}} + +{{#allParams}} +@param {{{paramName}}} {{{description}}} +{{/allParams}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/licenseInfo.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/licenseInfo.mustache new file mode 100644 index 000000000000..16ba21d203d0 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/licenseInfo.mustache @@ -0,0 +1,11 @@ +/** + * {{{appName}}} + * {{{appDescription}}} + * + * {{#version}}The version of the OpenAPI document: {{{.}}}{{/version}} + * {{#infoEmail}}Contact: {{{.}}}{{/infoEmail}} + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/methodParameters.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/methodParameters.mustache new file mode 100644 index 000000000000..9a1b04d7747f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/methodParameters.mustache @@ -0,0 +1 @@ +{{#allParams}}{{paramName}}: {{#required}}{{dataType}}{{/required}}{{^required}}{{#isContainer}}{{dataType}}{{/isContainer}}{{^isContainer}}Option[{{dataType}}]{{/isContainer}}{{/required}}{{^defaultValue}}{{^required}}{{^isContainer}} = None{{/isContainer}}{{/required}}{{/defaultValue}}{{^-last}}, {{/-last}}{{/allParams}}{{#authMethods.0}})(implicit {{#authMethods}}{{#isApiKey}}apiKey: ApiKeyValue{{/isApiKey}}{{#isBasic}}{{#isBasicBasic}}basicAuth: BasicCredentials{{/isBasicBasic}}{{#isBasicBearer}}bearerToken: BearerToken{{/isBasicBearer}}{{/isBasic}}{{^-last}}, {{/-last}}{{/authMethods}}{{/authMethods.0}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/model.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/model.mustache new file mode 100644 index 000000000000..832606e1d866 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/model.mustache @@ -0,0 +1,41 @@ +{{>licenseInfo}} +package {{package}} + +{{#imports}} +import {{import}} +{{/imports}} +import {{invokerPackage}}.ApiModel + +{{#models}} +{{#model}} +case class {{classname}} ( + {{#vars}} + {{#description}} + /* {{{.}}} */ + {{/description}} + {{{name}}}: {{^required}}Option[{{/required}}{{^isEnum}}{{dataType}}{{/isEnum}}{{#isEnum}}{{classname}}Enums.{{datatypeWithEnum}}{{/isEnum}}{{^required}}] = None{{/required}}{{^-last}},{{/-last}} + {{/vars}} +) extends ApiModel + +{{#hasEnums}} +object {{classname}}Enums { + + {{#vars}} + {{#isEnum}} + type {{datatypeWithEnum}} = {{datatypeWithEnum}}.Value + {{/isEnum}} + {{/vars}} + {{#vars}} + {{#isEnum}} + object {{datatypeWithEnum}} extends Enumeration { +{{#_enum}} + val {{#fnEnumEntry}}{{.}}{{/fnEnumEntry}} = Value("{{.}}") +{{/_enum}} + } + + {{/isEnum}} + {{/vars}} +} +{{/hasEnums}} +{{/model}} +{{/models}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/model_doc.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/model_doc.mustache new file mode 100644 index 000000000000..e1025787793c --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/model_doc.mustache @@ -0,0 +1,9 @@ +{{#models}}{{#model}} + +{{#isEnum}} +{{>enum_doc}} +{{/isEnum}} +{{^isEnum}} +{{>class_doc}} +{{/isEnum}} +{{/model}}{{/models}} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/operationReturnType.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/operationReturnType.mustache new file mode 100644 index 000000000000..170935cad639 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/operationReturnType.mustache @@ -0,0 +1 @@ +{{{returnType}}}{{^returnType}}Unit{{/returnType}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/paramCreation.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/paramCreation.mustache new file mode 100644 index 000000000000..dc7bbc9f434e --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/paramCreation.mustache @@ -0,0 +1 @@ +{{#isMap}}{{baseName}}{{/isMap}}{{^isMap}}"{{baseName}}", {{#isContainer}}ArrayValues({{{paramName}}}{{#collectionFormat}}, {{collectionFormat.toUpperCase}}{{/collectionFormat}}){{/isContainer}}{{^isContainer}}{{{paramName}}}{{/isContainer}}{{/isMap}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/pom.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/pom.mustache new file mode 100644 index 000000000000..d8165ad3fa13 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/pom.mustache @@ -0,0 +1,254 @@ + + 4.0.0 + + {{artifactId}} + + {{groupId}} + {{artifactId}} + {{artifactVersion}} + + jar + + + UTF-8 + UTF-8 + + 1.8 + 2.13.12 + 4.0.7 + 4.0.7 + 1.0.2 + 1.0.0 + 1.4.3 + 2.3.2 + 3.2.17 + 3.2.17.0 + + 3.3.1 + + + + + org.scala-lang + scala-library + ${scala.version} + provided + + + com.typesafe + config + ${typesafeconfig.version} + + + org.apache.pekko + pekko-actor_2.13 + ${pekko.version} + + + org.apache.pekko + pekko-stream_2.13 + ${pekko.version} + + + org.apache.pekko + pekko-http_2.13 + ${pekko.http.version} + + + org.json4s + json4s-jackson_2.13 + ${json4s.jackson.version} + + + org.json4s + json4s-ext_2.13 + ${json4s.jackson.version} + + + com.github.pjfanning + pekko-http-json4s_2.13 + ${pekko.http.json4s.version} + + + + + org.scalatest + scalatest_2.13 + ${scala.test.version} + test + + + org.scalatestplus + junit-4-13_2.13 + ${scala.test.plus.version} + test + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.2 + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 4 + pertest + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.0.2 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${java.version} + ${java.version} + + + + net.alchim31.maven + scala-maven-plugin + ${scala.maven.plugin.version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/project/build.properties.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/project/build.properties.mustache new file mode 100644 index 000000000000..8cf07b7c2540 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/project/build.properties.mustache @@ -0,0 +1 @@ +sbt.version=1.9.8 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/reference.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/reference.mustache new file mode 100644 index 000000000000..1a28a8962edc --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/reference.mustache @@ -0,0 +1,24 @@ +{{configKeyPath}} { + + {{configKey}} { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: {{defaultTimeout}}ms + + default-headers { + "userAgent": "{{artifactId}}_{{artifactVersion}}" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/requests.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/requests.mustache new file mode 100644 index 000000000000..56177e11c306 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/requests.mustache @@ -0,0 +1,192 @@ +{{>licenseInfo}} +package {{invokerPackage}} + +import java.io.File +import java.net.URLEncoder +import java.util.UUID +import java.time.OffsetDateTime + +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + + def header(name: String): Option[String] = headers.get(name) + + def getStringHeader(name: String): Option[String] = header(name) + + // workaround: return date time header in string instead of datetime object + def getDateTimeHeader(name: String): Option[String] = header(name) + + def getIntHeader(name: String): Option[Int] = castedHeader(name, java.lang.Integer.parseInt) + + def getLongHeader(name: String): Option[Long] = castedHeader(name, java.lang.Long.parseLong) + + def getFloatHeader(name: String): Option[Float] = castedHeader(name, java.lang.Float.parseFloat) + + def getDoubleHeader(name: String): Option[Double] = castedHeader(name, java.lang.Double.parseDouble) + + def getBooleanHeader(name: String): Option[Boolean] = castedHeader(name, java.lang.Boolean.parseBoolean) + + def getOffsetDateTimeHeader(name: String): Option[OffsetDateTime] = castedHeader(name, java.time.OffsetDateTime.parse) + + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { + Try { + header(name).map(conversion) + }.get + } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tuple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class BearerToken(token: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation + + case object COOKIE extends ApiKeyLocation + +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString: String = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tuples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList: List[(String, Any)] = m.toList.flatMap(formattedParams) + + def asFormattedParams: Map[String, Any] = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => formattedParams(name, opt) + case s: Seq[Any] => formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case v: UUID => formattedParams(name, v.toString) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + } + +} diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/responseState.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/responseState.mustache new file mode 100644 index 000000000000..5b4285523469 --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/responseState.mustache @@ -0,0 +1 @@ +{{#is2xx}}Success{{/is2xx}}{{#is3xx}}Success{{/is3xx}}{{#is4xx}}Error{{/is4xx}}{{#is5xx}}Error{{/is5xx}}{{#isDefault}}Error{{/isDefault}} \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/scala-pekko-client/serializers.mustache b/modules/openapi-generator/src/main/resources/scala-pekko-client/serializers.mustache new file mode 100644 index 000000000000..e66999529d9f --- /dev/null +++ b/modules/openapi-generator/src/main/resources/scala-pekko-client/serializers.mustache @@ -0,0 +1,53 @@ +package {{invokerPackage}} + +{{#java8}} +import java.time.{LocalDate, LocalDateTime, OffsetDateTime, ZoneId} +import java.time.format.DateTimeFormatter +{{/java8}} +{{#joda}} +import org.joda.time.format.ISODateTimeFormat +import org.joda.time.{LocalDate, DateTime} +{{/joda}} +import org.json4s.{Serializer, CustomSerializer, JNull} +import org.json4s.ext.JavaTypesSerializers +import org.json4s.JsonAST.JString + +import scala.util.Try + +object Serializers { + +{{#java8}} + case object DateTimeSerializer extends CustomSerializer[OffsetDateTime]( _ => ( { + case JString(s) => + Try(OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)) orElse + Try(LocalDateTime.parse(s).atZone(ZoneId.systemDefault()).toOffsetDateTime) getOrElse null + }, { + case d: OffsetDateTime => + JString(d.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + })) + + case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( { + case JString(s) => LocalDate.parse(s) + }, { + case d: LocalDate => + JString(d.format(DateTimeFormatter.ISO_LOCAL_DATE)) + })) +{{/java8}} +{{#joda}} + case object DateTimeSerializer extends CustomSerializer[DateTime](_ => ( { + case JString(s) => + ISODateTimeFormat.dateOptionalTimeParser().parseDateTime(s) + }, { + case d: DateTime => JString(ISODateTimeFormat.dateTime().print(d)) + })) + + case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( { + case JString(s) => ISODateTimeFormat.localDateParser().parseLocalDate(s) + }, { + case d: LocalDate => JString(ISODateTimeFormat.date().print(d)) + })) +{{/joda}} + + def all: Seq[Serializer[_]] = JavaTypesSerializers.all :+ DateTimeSerializer :+ LocalDateSerializer + +} diff --git a/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache b/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache index 9ffb2c4f86d8..ff51e00b7f92 100644 --- a/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/OpenAPIDateWithoutTime.mustache @@ -23,11 +23,21 @@ import Foundation case wrappedDate case timezone } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} enum DecodingError: Error { + case notADateString + } /// On decoding ISO8601 timezone is assumed {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - self.wrappedDate = try container.decode(Date.self) + + let dateString = try container.decode(String.self) + guard let date = OpenISO8601DateFormatter.withoutTime.date(from: dateString) else { + throw DecodingError.notADateString + } + self.wrappedDate = date + self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone } @@ -60,10 +70,14 @@ import Foundation return wrappedDate.addingTimeInterval( Double(timezone.secondsFromGMT(for: wrappedDate))) } + + {{#nonPublicApi}}internal{{/nonPublicApi}}{{^nonPublicApi}}public{{/nonPublicApi}} static func == (lhs: Self, rhs: Self) -> Bool { + Calendar.current.compare(lhs.wrappedDate, to: rhs.wrappedDate, toGranularity: .day) == .orderedSame + } } extension OpenAPIDateWithoutTime: JSONEncodable { func encodeToJSON() -> Any { return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate()) } -} \ No newline at end of file +} diff --git a/modules/openapi-generator/src/main/resources/swift5/api.mustache b/modules/openapi-generator/src/main/resources/swift5/api.mustache index 6ef40dfd8985..f39aaddb2b4e 100644 --- a/modules/openapi-generator/src/main/resources/swift5/api.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/api.mustache @@ -406,7 +406,12 @@ extension {{projectName}}API { localVariablePath = localVariablePath.replacingOccurrences(of: "{{=<% %>=}}{<%baseName%>}<%={{ }}=%>", with: {{paramName}}PostEscape, options: .literal, range: nil){{/pathParams}} let localVariableURLString = {{projectName}}API.basePath + localVariablePath {{#bodyParam}} + {{#isBinary}} + let localVariableParameters = ["body": {{paramName}}] + {{/isBinary}} + {{^isBinary}} let localVariableParameters = JSONEncodingHelper.encodingParameters(forEncodableObject: {{paramName}}) + {{/isBinary}} {{/bodyParam}} {{^bodyParam}} {{#hasFormParams}} @@ -431,9 +436,10 @@ extension {{projectName}}API { ]){{/hasQueryParams}}{{^hasQueryParams}} let localVariableUrlComponents = URLComponents(string: localVariableURLString){{/hasQueryParams}} - let localVariableNillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}} - :{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}} - "Content-Type": {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasFormParams}}{{#headerParams}} + let localVariableNillableHeaders: [String: Any?] = [{{^headerParams}}{{^hasFormParams}}{{^hasConsumes}} + :{{/hasConsumes}}{{/hasFormParams}}{{/headerParams}}{{#hasFormParams}} + "Content-Type": {{^consumes}}"multipart/form-data"{{/consumes}}{{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasFormParams}}{{^hasFormParams}}{{#hasConsumes}} + "Content-Type": {{#consumes.0}}"{{{mediaType}}}"{{/consumes.0}},{{/hasConsumes}}{{/hasFormParams}}{{#headerParams}} {{> _param}},{{/headerParams}} ] diff --git a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache index 60cda3243d8b..56637c3ce282 100644 --- a/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache +++ b/modules/openapi-generator/src/main/resources/swift5/libraries/urlsession/URLSessionImplementations.mustache @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/api.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/api.mustache index 0df770bdc0e1..a6a13e318204 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/api.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/api.mustache @@ -4,7 +4,7 @@ {{^withSeparateModelsAndApi}} import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; {{#withNodeImports}} // URLSearchParams not necessarily used @@ -19,7 +19,7 @@ import FormData from 'form-data' import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; {{#models}} {{#model}}{{#isEnum}}{{>modelEnum}}{{/isEnum}}{{#oneOf}}{{#-first}}{{>modelOneOf}}{{/-first}}{{/oneOf}}{{^isEnum}}{{^oneOf}}{{>modelGeneric}}{{/oneOf}}{{/isEnum}}{{/model}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache old mode 100755 new mode 100644 index 091d9f6add58..1b4fe1978ba0 --- a/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/apiInner.mustache @@ -4,7 +4,7 @@ {{>licenseInfo}} import type { Configuration } from '{{apiRelativeToRoot}}configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; {{#withNodeImports}} // URLSearchParams not necessarily used @@ -18,7 +18,7 @@ import FormData from 'form-data' // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '{{apiRelativeToRoot}}common'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '{{apiRelativeToRoot}}base'; +import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError, operationServerMap } from '{{apiRelativeToRoot}}base'; {{#imports}} // @ts-ignore import { {{classname}} } from '{{apiRelativeToRoot}}{{tsModelPackage}}'; @@ -47,7 +47,7 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ - {{nickname}}: async ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options: AxiosRequestConfig = {}): Promise => { + {{nickname}}: async ({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options: RawAxiosRequestConfig = {}): Promise => { {{#allParams}} {{#required}} // verify required parameter '{{paramName}}' is not null or undefined @@ -132,9 +132,19 @@ export const {{classname}}AxiosParamCreator = function (configuration?: Configur localVarQueryParameter['{{baseName}}'] = {{paramName}}; {{/isPrimitiveType}} {{^isPrimitiveType}} - for (let param of Object.keys({{baseName}})) { - localVarQueryParameter[param] = {{baseName}}?.[param]; + {{^isEnumRef}} + {{^isEnum}} + for (const [key, value] of Object.entries({{paramName}})) { + localVarQueryParameter[key] = value; } + {{/isEnum}} + {{/isEnumRef}} + {{#isEnum}} + localVarQueryParameter['{{baseName}}'] = {{paramName}}; + {{/isEnum}} + {{#isEnumRef}} + localVarQueryParameter['{{baseName}}'] = {{paramName}}; + {{/isEnumRef}} {{/isPrimitiveType}} {{/isExplode}} {{^isExplode}} @@ -248,9 +258,11 @@ export const {{classname}}Fp = function(configuration?: Configuration) { * @deprecated{{/isDeprecated}} * @throws {RequiredError} */ - async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>> { + async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>> { const localVarAxiosArgs = await localVarAxiosParamCreator.{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['{{classname}}.{{nickname}}']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, {{/operation}} } @@ -285,7 +297,7 @@ export const {{classname}}Factory = function (configuration?: Configuration, bas * @throws {RequiredError} */ {{#useSingleRequestParameter}} - {{nickname}}({{#allParams.0}}requestParameters: {{classname}}{{operationIdCamelCase}}Request{{^hasRequiredParams}} = {}{{/hasRequiredParams}}, {{/allParams.0}}options?: AxiosRequestConfig): AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}> { + {{nickname}}({{#allParams.0}}requestParameters: {{classname}}{{operationIdCamelCase}}Request{{^hasRequiredParams}} = {}{{/hasRequiredParams}}, {{/allParams.0}}options?: RawAxiosRequestConfig): AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}> { return localVarFp.{{nickname}}({{#allParams.0}}{{#allParams}}requestParameters.{{paramName}}, {{/allParams}}{{/allParams.0}}options).then((request) => request(axios, basePath)); }, {{/useSingleRequestParameter}} @@ -320,7 +332,7 @@ export interface {{classname}}Interface { * @throws {RequiredError} * @memberof {{classname}}Interface */ - {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: AxiosRequestConfig): AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>; + {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: RawAxiosRequestConfig): AxiosPromise<{{{returnType}}}{{^returnType}}void{{/returnType}}>; {{/operation}} } @@ -386,12 +398,12 @@ export class {{classname}} extends BaseAPI { * @memberof {{classname}} */ {{#useSingleRequestParameter}} - public {{nickname}}({{#allParams.0}}requestParameters: {{classname}}{{operationIdCamelCase}}Request{{^hasRequiredParams}} = {}{{/hasRequiredParams}}, {{/allParams.0}}options?: AxiosRequestConfig) { + public {{nickname}}({{#allParams.0}}requestParameters: {{classname}}{{operationIdCamelCase}}Request{{^hasRequiredParams}} = {}{{/hasRequiredParams}}, {{/allParams.0}}options?: RawAxiosRequestConfig) { return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams.0}}{{#allParams}}requestParameters.{{paramName}}, {{/allParams}}{{/allParams.0}}options).then((request) => request(this.axios, this.basePath)); } {{/useSingleRequestParameter}} {{^useSingleRequestParameter}} - public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: AxiosRequestConfig) { + public {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}options?: RawAxiosRequestConfig) { return {{classname}}Fp(this.configuration).{{nickname}}({{#allParams}}{{paramName}}, {{/allParams}}options).then((request) => request(this.axios, this.basePath)); } {{/useSingleRequestParameter}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/baseApi.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/baseApi.mustache old mode 100755 new mode 100644 index 6d6d0febbf1e..d14b428f686f --- a/modules/openapi-generator/src/main/resources/typescript-axios/baseApi.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/baseApi.mustache @@ -5,7 +5,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "{{{basePath}}}".replace(/\/+$/, ""); @@ -28,7 +28,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -42,7 +42,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -59,3 +59,58 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { + {{#apiInfo}} + {{#apis}} + {{#operations}} + {{#operation}} + {{#servers}} + {{#-first}} + "{{{classname}}}.{{{nickname}}}": [ + {{/-first}} + { + url: "{{{url}}}", + description: "{{{description}}}{{^description}}No description provided{{/description}}", + {{#variables}} + {{#-first}} + variables: { + {{/-first}} + {{{name}}}: { + description: "{{{description}}}{{^description}}No description provided{{/description}}", + default_value: "{{{defaultValue}}}", + {{#enumValues}} + {{#-first}} + enum_values: [ + {{/-first}} + "{{{.}}}"{{^-last}},{{/-last}} + {{#-last}} + ] + {{/-last}} + {{/enumValues}} + }{{^-last}},{{/-last}} + {{#-last}} + } + {{/-last}} + {{/variables}} + }{{^-last}},{{/-last}} + {{#-last}} + ], + {{/-last}} + {{/servers}} + {{/operation}} + {{/operations}} + {{/apis}} + {{/apiInfo}} +} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache index eee6b7af3b8d..aa594015c7f9 100755 --- a/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/common.mustache @@ -136,7 +136,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/configuration.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/configuration.mustache index 7c8eca18cb40..836f1275095d 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/configuration.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/configuration.mustache @@ -8,6 +8,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -47,6 +48,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -69,6 +77,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/modelGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/modelGeneric.mustache index 6444507b8ebe..db1cd109c4ab 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/modelGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/modelGeneric.mustache @@ -17,7 +17,7 @@ export interface {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{ * @deprecated {{/deprecated}} */ - '{{baseName}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; + '{{baseName}}'{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{/isEnum}}{{#isNullable}} | null{{/isNullable}}; {{/vars}} }{{#hasEnums}} diff --git a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache index 4ba75b22a0ca..da599f177877 100644 --- a/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-axios/package.mustache @@ -22,11 +22,11 @@ "sideEffects": false, {{/supportsES6}} "scripts": { - "build": "tsc {{#supportsES6}}&& tsc -p tsconfig.esm.json{{/supportsES6}}", + "build": "tsc{{#supportsES6}} && tsc -p tsconfig.esm.json{{/supportsES6}}", "prepare": "npm run build" }, "dependencies": { - "axios": "^0.27.2" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache index 4d736143a80b..23aa2e526804 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/apis.mustache @@ -65,6 +65,9 @@ export interface {{classname}}Interface { {{#summary}} * {{&summary}} {{/summary}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} */ {{^useSingleRequestParameter}} {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<{{{returnType}}}{{^returnType}}void{{/returnType}}>; @@ -97,6 +100,9 @@ export class {{classname}} extends runtime.BaseAPI { {{#summary}} * {{&summary}} {{/summary}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} */ async {{nickname}}Raw({{#allParams.0}}requestParameters: {{#prefixParameterInterfaces}}{{classname}}{{/prefixParameterInterfaces}}{{operationIdCamelCase}}Request, {{/allParams.0}}initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { {{#allParams}} @@ -340,6 +346,9 @@ export class {{classname}} extends runtime.BaseAPI { {{#summary}} * {{&summary}} {{/summary}} + {{#isDeprecated}} + * @deprecated + {{/isDeprecated}} */ {{^useSingleRequestParameter}} async {{nickname}}({{#allParams}}{{paramName}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{dataType}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}, {{/allParams}}initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise<{{{returnType}}}{{^returnType}}void{{/returnType}}> { diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache index d669ea3ee91c..68e5747598a9 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelGenericInterfaces.mustache @@ -16,7 +16,7 @@ export interface {{classname}} {{#parent}}extends {{{.}}} {{/parent}}{ * @deprecated {{/deprecated}} */ - {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; + {{#isReadOnly}}readonly {{/isReadOnly}}{{name}}{{^required}}?{{/required}}: {{#isEnum}}{{{datatypeWithEnum}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}{{^isEnum}}{{{datatype}}}{{#isNullable}} | null{{/isNullable}}{{/isEnum}}; {{/vars}} }{{#hasEnums}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache index fa3e282c1c36..e369f5b9d12c 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/modelOneOf.mustache @@ -1,7 +1,7 @@ {{#hasImports}} {{#oneOf}} +import type { {{{.}}} } from './{{.}}{{importFileExtension}}'; import { - {{{.}}}, instanceOf{{{.}}}, {{{.}}}FromJSON, {{{.}}}FromJSONTyped, diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache index 2ebb53b85fc2..8909906d6745 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/recordGeneric.mustache @@ -164,8 +164,8 @@ class {{classname}}RecordUtils extends ApiRecordUtils<{{classname}}, {{classname {{/items.isEntity}} {{/isArray}} {{/vars}} - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { {{#vars}} diff --git a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache index 0ffada861280..6c625eb1c023 100644 --- a/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-fetch/runtime.mustache @@ -80,7 +80,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache index fe1fbe707ea9..1b4b5804ed48 100644 --- a/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-nestjs/api.module.mustache @@ -1,5 +1,5 @@ {{#useAxiosHttpModule}} -import { DynamicModule, Module, Global } from '@nestjs/common'; +import { DynamicModule, Module, Global, Provider } from '@nestjs/common'; import { HttpModule, HttpService } from '@nestjs/axios'; {{/useAxiosHttpModule}} {{^useAxiosHttpModule}} diff --git a/modules/openapi-generator/src/main/resources/typescript-nestjs/package.mustache b/modules/openapi-generator/src/main/resources/typescript-nestjs/package.mustache index 0ac1e788fb83..1167ea07cd30 100644 --- a/modules/openapi-generator/src/main/resources/typescript-nestjs/package.mustache +++ b/modules/openapi-generator/src/main/resources/typescript-nestjs/package.mustache @@ -32,15 +32,18 @@ "@nestjs/common": "^{{nestVersion}}", "@nestjs/core": "^{{nestVersion}}", "@nestjs/platform-express": "^{{nestVersion}}", + {{#useAxiosHttpModule}} + "@nestjs/axios": "^2.0.0", + {{/useAxiosHttpModule}} "reflect-metadata": "^0.1.13", "rimraf": "^2.6.3", - "rxjs": "^6.5.2" + "rxjs": "^7.1.0" }, "devDependencies": { "@nestjs/testing": "~{{nestVersion}}", "@types/express": "^4.16.0", "@types/jest": "^24.0.15", - "@types/node": "^12.6.1", + "@types/node": "^14.8.2", "@types/supertest": "^2.0.8", "concurrently": "^4.1.1", "nodemon": "^1.19.1", diff --git a/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache b/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache index d4cc5ce27ed1..d84cdec5ff86 100644 --- a/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache +++ b/modules/openapi-generator/src/main/resources/typescript/model/ObjectSerializer.mustache @@ -22,16 +22,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ {{#models}} {{#model}} @@ -59,6 +49,58 @@ let typeMap: {[index: string]: any} = { {{/models}} } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -204,31 +246,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -243,18 +281,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/modules/openapi-generator/src/main/resources/xojo-client/modelInlineEnumDeclaration.mustache b/modules/openapi-generator/src/main/resources/xojo-client/modelInlineEnumDeclaration.mustache index db72b688c349..5e1b63231d93 100644 --- a/modules/openapi-generator/src/main/resources/xojo-client/modelInlineEnumDeclaration.mustache +++ b/modules/openapi-generator/src/main/resources/xojo-client/modelInlineEnumDeclaration.mustache @@ -1,5 +1,5 @@ - #tag Enum, Name = {{enumName}}, Type = Integer, Flags = &h{{^nonPublicApi}}0{{/nonPublicApi}}{{#nonPublicApi}}21{{/nonPublicApi}} - {{#allowableValues}}{{#enumVars}} + #tag Enum, Name = {{enumName}}, Type = Integer, Flags = &h{{^nonPublicApi}}0{{/nonPublicApi}}{{#nonPublicApi}}21{{/nonPublicApi}} + {{#allowableValues}}{{#enumVars}} {{{name}}}{{#isInteger}} = {{{value}}}{{/isInteger}}{{/enumVars}}{{/allowableValues}} - {{#enumUnknownDefaultCase}}Unknown{{#isInteger}} = {{{value}}}{{/isInteger}}{{/enumUnknownDefaultCase}} - #tag EndEnum + {{#enumUnknownDefaultCase}}Unknown{{#isInteger}} = {{{value}}}{{/isInteger}}{{/enumUnknownDefaultCase}} + #tag EndEnum diff --git a/modules/openapi-generator/src/main/resources/zapier/model.mustache b/modules/openapi-generator/src/main/resources/zapier/model.mustache index cf0fb34c6777..0d9e0e787697 100644 --- a/modules/openapi-generator/src/main/resources/zapier/model.mustache +++ b/modules/openapi-generator/src/main/resources/zapier/model.mustache @@ -30,6 +30,9 @@ module.exports = { { key: `${keyPrefix}{{baseName}}`, label: `{{#description}}{{{.}}} - {{/description}}[${labelPrefix}{{baseName}}]`, + {{#required}} + required: true, + {{/required}} {{#isArray}} list: true, type: '{{#items}}{{baseType}}{{/items}}', @@ -56,6 +59,9 @@ module.exports = { { key: `${keyPrefix}{{baseName}}`,{{#items}}{{^isEnumRef}} label: `{{#description}}{{{.}}} - {{/description}}[${labelPrefix}{{baseName}}]`, + {{#required}} + required: true, + {{/required}} children: {{complexType}}.fields(`${keyPrefix}{{baseName}}${!isInput ? '[]' : ''}`, isInput, true), {{/isEnumRef}}{{#isEnumRef}} list: true, type: 'string', diff --git a/modules/openapi-generator/src/main/resources/zapier/package.mustache b/modules/openapi-generator/src/main/resources/zapier/package.mustache index 9759b8520eed..35b04aa13ba3 100644 --- a/modules/openapi-generator/src/main/resources/zapier/package.mustache +++ b/modules/openapi-generator/src/main/resources/zapier/package.mustache @@ -13,8 +13,8 @@ }, "dependencies": { "lodash": "^4.17.21", - "zapier-platform-core": "15.0.1", - "form-data": "2.1.4" + "zapier-platform-core": "15.5.1", + "form-data": "^4.0.0" }, "devDependencies": { "mocha": "^10.2.0", @@ -22,6 +22,6 @@ }, "private": true, "zapier": { - "convertedByCLIVersion": "14.1.1" + "convertedByCLIVersion": "15.5.1" } } \ No newline at end of file diff --git a/modules/openapi-generator/src/main/resources/zapier/utils.mustache b/modules/openapi-generator/src/main/resources/zapier/utils.mustache index a73f00e4778b..201a15fb582b 100644 --- a/modules/openapi-generator/src/main/resources/zapier/utils.mustache +++ b/modules/openapi-generator/src/main/resources/zapier/utils.mustache @@ -1,14 +1,14 @@ const _ = require('lodash') const replacePathParameters = (url) => url.replace(/{([^{}]+)}/g, (keyExpr, key) => `{{bundle.inputData.${key}}}`) -const childMapping = (objectsArray, prefix, model) => objectsArray.map(object => model.mapping({inputData: object}, prefix)) +const childMapping = (objectsArray, prefix, model) => objectsArray ? objectsArray.map(object => model.mapping({inputData: object}, prefix)) : undefined const removeIfEmpty = (obj) => _.isEmpty(JSON.parse(JSON.stringify(obj))) ? undefined : obj const buildKeyAndLabel = (prefix, isInput = true, isArrayChild = false) => { const keyPrefix = !_.isEmpty(prefix) && (!isArrayChild || isInput) ? `${prefix}${isInput ? '.' : '__'}` : prefix const labelPrefix = !_.isEmpty(keyPrefix) ? keyPrefix.replaceAll('__', '.') : '' return { keyPrefix: keyPrefix, - labelPrefix:labelPrefix, + labelPrefix: labelPrefix, } } const isSearchAction = (key) => { diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java index 9debba85c2f3..96662023eb20 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/DefaultCodegenTest.java @@ -51,6 +51,7 @@ import org.testng.annotations.Test; import java.io.File; +import java.io.IOException; import java.nio.file.Files; import java.util.*; import java.util.stream.Collectors; @@ -671,6 +672,15 @@ public void testOneOfEnum() { } Assert.assertTrue(typeSeen); Assert.assertTrue(typeContainsEnums); + + Assert.assertEquals( + ((StringSchema) openAPI.getComponents().getSchemas().get("Dog").getProperties().get("type")).getEnum().size(), + 1 + ); + Assert.assertEquals( + ((StringSchema) openAPI.getComponents().getSchemas().get("Cat").getProperties().get("type")).getEnum().size(), + 1 + ); } @Test @@ -2561,6 +2571,19 @@ public void testMultipleSecuritySchemes() { assertEquals(securities.get(1).name, "api_key"); } + @Test + public void testOpenIdConnectSecuritySchemes() { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_17376.json"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + + final Map securitySchemes = openAPI.getComponents().getSecuritySchemes(); + final List securities = codegen.fromSecurity(securitySchemes); + + assertEquals(securities.size(), 1); + assertEquals(securities.get(0).name, "Our Identity service"); + } + @Test public void testItemsPresent() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7613.yaml"); @@ -4716,6 +4739,7 @@ public void testAllOfDefaultEnumType() { Assert.assertFalse(allOfEnumSchemaProperty.isString); Assert.assertFalse(allOfEnumSchemaProperty.isContainer); Assert.assertFalse(allOfEnumSchemaProperty.isPrimitiveType); + Assert.assertTrue(allOfEnumSchemaProperty.deprecated); Assert.assertEquals(allOfEnumSchemaProperty.defaultValue, "null"); } @@ -4792,9 +4816,24 @@ public void testRequestInlineSingleExample() { assertNotNull(mt.getExample()); } - @Test void testIsXML() { + @Test + void testIsXML() { final DefaultCodegen codegen = new DefaultCodegen(); Assert.assertTrue(codegen.isXmlMimeType("application/xml")); Assert.assertTrue(codegen.isXmlMimeType("application/rss+xml")); } + + @Test + public void testWebhooks() throws IOException { + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_1/webhooks.yaml"); + final DefaultCodegen codegen = new DefaultCodegen(); + codegen.setOpenAPI(openAPI); + + Operation operation = openAPI.getWebhooks().get("newPet").getPost(); + CodegenOperation co = codegen.fromOperation("newPet", "get", operation, null); + + Assert.assertEquals(co.path, "/newPet"); + Assert.assertEquals(co.operationId, "newPetGet"); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ExampleGeneratorTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ExampleGeneratorTest.java index 45b9260830df..844756e9a06d 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ExampleGeneratorTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ExampleGeneratorTest.java @@ -39,6 +39,35 @@ public void generateFromResponseSchemaWithPrimitiveType() { assertEquals("200", examples.get(0).get("statusCode")); } + @Test + public void generateFromResponseSchemaWithDateFormat() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/example_generator_test.yaml"); + + new InlineModelResolver().flatten(openAPI); + + ExampleGenerator exampleGenerator = new ExampleGenerator(openAPI.getComponents().getSchemas(), openAPI); + Set mediaTypeKeys = new TreeSet<>(); + mediaTypeKeys.add("application/json"); + List> examples = exampleGenerator.generateFromResponseSchema( + "200", + openAPI + .getPaths() + .get("/generate_from_response_schema_with_date_format") + .getGet() + .getResponses() + .get("200") + .getContent() + .get("application/json") + .getSchema(), + mediaTypeKeys + ); + + assertEquals(1, examples.size()); + assertEquals("application/json", examples.get(0).get("contentType")); + assertEquals(String.format(Locale.ROOT, "{%n \"date_with_example\" : \"2024-01-01\",%n \"date_without_example\" : \"2000-01-23\"%n}"), examples.get(0).get("example")); + assertEquals("200", examples.get(0).get("statusCode")); + } + @Test public void generateFromResponseSchemaWithNoExample() { OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/example_generator_test.yaml"); @@ -151,4 +180,91 @@ public void generateFromResponseSchemaWithModel() { assertEquals(String.format(Locale.ROOT, "{%n \"example_schema_property\" : \"example schema property value\"%n}"), examples.get(0).get("example")); assertEquals("200", examples.get(0).get("statusCode")); } + + @Test + public void generateFromResponseSchemaWithAllOfComposedModel() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/example_generator_test.yaml"); + + new InlineModelResolver().flatten(openAPI); + + ExampleGenerator exampleGenerator = new ExampleGenerator(openAPI.getComponents().getSchemas(), openAPI); + Set mediaTypeKeys = new TreeSet<>(); + mediaTypeKeys.add("application/json"); + List> examples = exampleGenerator.generateFromResponseSchema( + "200", + openAPI + .getPaths() + .get("/generate_from_response_schema_with_allOf_composed_model") + .getGet() + .getResponses() + .get("200") + .getContent() + .get("application/json") + .getSchema(), + mediaTypeKeys + ); + + assertEquals(1, examples.size()); + assertEquals("application/json", examples.get(0).get("contentType")); + assertEquals(String.format(Locale.ROOT, "{%n \"example_schema_property_composed\" : \"example schema property value composed\",%n \"example_schema_property\" : \"example schema property value\"%n}"), examples.get(0).get("example")); + assertEquals("200", examples.get(0).get("statusCode")); + } + + @Test + public void generateFromResponseSchemaWithOneOfComposedModel() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/example_generator_test.yaml"); + + new InlineModelResolver().flatten(openAPI); + + ExampleGenerator exampleGenerator = new ExampleGenerator(openAPI.getComponents().getSchemas(), openAPI); + Set mediaTypeKeys = new TreeSet<>(); + mediaTypeKeys.add("application/json"); + List> examples = exampleGenerator.generateFromResponseSchema( + "200", + openAPI + .getPaths() + .get("/generate_from_response_schema_with_oneOf_composed_model") + .getGet() + .getResponses() + .get("200") + .getContent() + .get("application/json") + .getSchema(), + mediaTypeKeys + ); + + assertEquals(1, examples.size()); + assertEquals("application/json", examples.get(0).get("contentType")); + assertEquals(String.format(Locale.ROOT, "{%n \"example_schema_property\" : \"example schema property value\"%n}"), examples.get(0).get("example")); + assertEquals("200", examples.get(0).get("statusCode")); + } + + @Test + public void generateFromResponseSchemaWithAnyOfComposedModel() { + OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/example_generator_test.yaml"); + + new InlineModelResolver().flatten(openAPI); + + ExampleGenerator exampleGenerator = new ExampleGenerator(openAPI.getComponents().getSchemas(), openAPI); + Set mediaTypeKeys = new TreeSet<>(); + mediaTypeKeys.add("application/json"); + List> examples = exampleGenerator.generateFromResponseSchema( + "200", + openAPI + .getPaths() + .get("/generate_from_response_schema_with_anyOf_composed_model") + .getGet() + .getResponses() + .get("200") + .getContent() + .get("application/json") + .getSchema(), + mediaTypeKeys + ); + + assertEquals(1, examples.size()); + assertEquals("application/json", examples.get(0).get("contentType")); + assertEquals(String.format(Locale.ROOT, "{%n \"example_schema_property\" : \"example schema property value\"%n}"), examples.get(0).get("example")); + assertEquals("200", examples.get(0).get("statusCode")); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java index 28f6abf540e9..051e961f093a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/OpenAPINormalizerTest.java @@ -26,6 +26,7 @@ import io.swagger.v3.oas.models.PathItem; import io.swagger.v3.oas.models.headers.Header; import io.swagger.v3.oas.models.media.*; +import io.swagger.v3.oas.models.parameters.Parameter; import io.swagger.v3.oas.models.parameters.QueryParameter; import io.swagger.v3.oas.models.parameters.RequestBody; import io.swagger.v3.oas.models.responses.ApiResponse; @@ -242,6 +243,24 @@ public void testOpenAPINormalizerSetTagsInAllOperations() { assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getTags().get(0), "core"); } + @Test + public void testOpenAPINormalizerSetTagsToOperationId() { + OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/enableKeepOnlyFirstTagInOperation_test.yaml"); + + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getTags().size(), 2); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getTags().size(), 1); + + Map options = new HashMap<>(); + options.put("SET_TAGS_TO_OPERATIONID", "true"); + OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, options); + openAPINormalizer.normalize(); + + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getTags().size(), 1); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getTags().size(), 1); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getGet().getTags().get(0), "list"); + assertEquals(openAPI.getPaths().get("/person/display/{personId}").getDelete().getTags().get(0), "delete"); + } + @Test public void testAddUnsignedToIntegerWithInvalidMaxValue() { OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_0/addUnsignedToIntegerWithInvalidMaxValue_test.yaml"); @@ -353,4 +372,46 @@ public void testOpenAPINormalizerRefactorAllOfWithPropertiesOnly() { assertEquals(((Schema) newSchema.getProperties().get("mum_or_dad")).getType(), "string"); assertEquals(newSchema.getRequired().get(0), "isParent"); } + + @Test + public void testNormalize31Schema() { + OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_1/common-parameters.yaml"); + + Map inputRules = Map.of( + "NORMALIZE_31SPEC", "true" + ); + OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, inputRules); + openAPINormalizer.normalize(); + + Schema pet = openAPI.getComponents().getSchemas().get("Pet"); + // verify schema for property id + Schema petSchema = (Schema)pet.getProperties().get("id"); + // both type and types are defined + assertNotNull(petSchema.getType()); + assertNotNull(petSchema.getTypes()); + } + + @Test + public void testNormalize31Parameters() { + OpenAPI openAPI = TestUtils.parseSpec("src/test/resources/3_1/common-parameters.yaml"); + + Map inputRules = Map.of( + "NORMALIZE_31SPEC", "true" + ); + OpenAPINormalizer openAPINormalizer = new OpenAPINormalizer(openAPI, inputRules); + openAPINormalizer.normalize(); + + PathItem pathItem = openAPI.getPaths().get("/pet/{petId}"); + assertNotNull(pathItem); + + // check common parameters + assertEquals(pathItem.getParameters().size(), 1); + assertNotNull(pathItem.getParameters().get(0).getSchema().getType()); + assertNotNull(pathItem.getParameters().get(0).getSchema().getTypes()); + + // check operation (delete) parameters + assertEquals(pathItem.getDelete().getParameters().size(), 1); + assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getType()); + assertNotNull(pathItem.getDelete().getParameters().get(0).getSchema().getTypes()); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java index f5ede0eb5a92..f7fab835e1fa 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/android/AndroidClientCodegenTest.java @@ -70,4 +70,23 @@ public void testAdditionalPropertiesPutForConfigValues() throws Exception { Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.iiii.invoker"); Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), "xyz.yyyyy.iiii.invoker"); } + @Test + public void testHideGenerationTimestampDisabled() throws Exception { + final AndroidClientCodegen codegen = new AndroidClientCodegen(); + codegen.additionalProperties().put("hideGenerationTimestamp", false); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get("hideGenerationTimestamp"), Boolean.FALSE); + Assert.assertFalse(codegen.isHideGenerationTimestamp()); + } + + @Test + public void testHideGenerationTimestampEnabled() throws Exception { + final AndroidClientCodegen codegen = new AndroidClientCodegen(); + codegen.additionalProperties().put("hideGenerationTimestamp", true); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get("hideGenerationTimestamp"), Boolean.TRUE); + Assert.assertTrue(codegen.isHideGenerationTimestamp()); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelEnumTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelEnumTest.java index 718857168182..731c899ac5ee 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelEnumTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelEnumTest.java @@ -28,11 +28,15 @@ import org.openapitools.codegen.languages.CSharpClientCodegen; import org.testng.Assert; import org.testng.annotations.Test; +import org.testng.annotations.DataProvider; import java.util.Arrays; import java.util.HashMap; import java.util.Map; +import org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE; +import static org.openapitools.codegen.CodegenConstants.ENUM_PROPERTY_NAMING_TYPE.*; + public class CSharpModelEnumTest { // TODO there's no parent/child method in ComposeSchema so we will need to revise the code // before we can re-enable the test case below @@ -148,4 +152,54 @@ public void useEmptyEnumSuffixes() { Assert.assertEquals(codegen.toEnumVarName("Aaaa", ""), "Aaaa"); } + @Test(description = "support enum naming style options", dataProvider = "enumVarName") + public void testToEnumVarName(String name, String expected, ENUM_PROPERTY_NAMING_TYPE naming) throws Exception { + final AspNetServerCodegen codegen = new AspNetServerCodegen(); + codegen.setEnumPropertyNaming(naming.name()); + codegen.setEnumValueSuffix(""); + + Assert.assertEquals(codegen.toEnumVarName(name, "string"), expected); + } + + @DataProvider(name = "enumVarName") + public Object[][] provideTestData() + { + return new Object[][] { + { "FooBar", "fooBar", camelCase }, + { "fooBar", "fooBar", camelCase }, + { "foo-bar", "fooBar", camelCase }, + { "foo_bar", "fooBar", camelCase }, + { "foo bar", "fooBar", camelCase }, + { "FOO-BAR", "fOOBAR", camelCase }, // camelize doesn't support uppercase + { "FOO_BAR", "fOOBAR", camelCase }, // ditto + { "FooBar", "FooBar", PascalCase }, + { "fooBar", "FooBar", PascalCase }, + { "foo-bar", "FooBar", PascalCase }, + { "foo_bar", "FooBar", PascalCase }, + { "foo bar", "FooBar", PascalCase }, + { "FOO-BAR", "FOOBAR", PascalCase }, // ditto + { "FOO_BAR", "FOOBAR", PascalCase }, // ditto + { "FooBar", "foo_bar", snake_case }, + { "fooBar", "foo_bar", snake_case }, + { "foo-bar", "foo_bar", snake_case }, + { "foo_bar", "foo_bar", snake_case }, + { "foo bar", "foo_bar", snake_case }, + { "FOO-BAR", "foo_bar", snake_case }, + { "FOO_BAR", "foo_bar", snake_case }, + { "FooBar", "FOO_BAR", UPPERCASE }, + { "fooBar", "FOO_BAR", UPPERCASE }, + { "foo-bar", "FOO_BAR", UPPERCASE }, + { "foo_bar", "FOO_BAR", UPPERCASE }, + { "foo bar", "FOO_BAR", UPPERCASE }, + { "FOO-BAR", "FOO_BAR", UPPERCASE }, + { "FOO_BAR", "FOO_BAR", UPPERCASE }, + { "FooBar", "FooBar", original }, + { "fooBar", "fooBar", original }, + { "foo-bar", "foo_bar", original }, + { "foo_bar", "foo_bar", original }, + { "foo bar", "foo_bar", original }, + { "FOO-BAR", "FOO_BAR", original }, + { "FOO_BAR", "FOO_BAR", original }, + }; + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelTest.java index 5dab275ab541..c16b194e7957 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/csharpnetcore/CSharpModelTest.java @@ -588,7 +588,7 @@ public void arrayModelTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "an array model"); Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "List"); + // TODO: additional properties should be of type Dictionary> Assert.assertEquals(cm.imports.size(), 1); Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); } @@ -608,7 +608,7 @@ public void mapModelTest() { Assert.assertEquals(cm.classname, "Sample"); Assert.assertEquals(cm.description, "a map model"); Assert.assertEquals(cm.vars.size(), 0); - Assert.assertEquals(cm.parent, "Dictionary"); + // TODO: additional properties should be of type Dictionary Assert.assertEquals(cm.imports.size(), 1); Assert.assertEquals(Sets.intersection(cm.imports, Sets.newHashSet("Children")).size(), 1); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java index ce22ca83f46a..cbf73e2877bb 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientCodegenTest.java @@ -291,4 +291,46 @@ public void verifyApiTestWithNullResponse() throws IOException { "httpRes, err := apiClient.PetAPI.PetDelete(context.Background()).Execute()"); } + @Test + public void testAdditionalPropertiesWithGoMod() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_0/petstore_oas3_test.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + System.out.println(files); + files.forEach(File::deleteOnExit); + + Path goModFile = Paths.get(output + "/go.mod"); + TestUtils.assertFileExists(goModFile); + Path goSumFile = Paths.get(output + "/go.sum"); + TestUtils.assertFileExists(goSumFile); + } + + @Test + public void testAdditionalPropertiesWithoutGoMod() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go") + .setInputSpec("src/test/resources/3_0/petstore_oas3_test.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")) + .addAdditionalProperty(GoClientCodegen.WITH_GO_MOD, false); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + System.out.println(files); + files.forEach(File::deleteOnExit); + + Path goModFile = Paths.get(output + "/go.mod"); + TestUtils.assertFileNotExists(goModFile); + Path goSumFile = Paths.get(output + "/go.sum"); + TestUtils.assertFileNotExists(goSumFile); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java index 7ace9c09cab4..8a67ee0e68eb 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoClientOptionsTest.java @@ -51,5 +51,7 @@ protected void verifyOptions() { verify(clientCodegen).setStructPrefix(GoClientOptionsProvider.STRUCT_PREFIX_VALUE); verify(clientCodegen).setWithAWSV4Signature(GoClientOptionsProvider.WITH_AWSV4_SIGNATURE); verify(clientCodegen).setUseOneOfDiscriminatorLookup(GoClientOptionsProvider.USE_ONE_OF_DISCRIMINATOR_LOOKUP_VALUE); + verify(clientCodegen).setWithGoMod(GoClientOptionsProvider.WITH_GO_MOD_VALUE); + verify(clientCodegen).setGenerateMarshalJSON(GoClientOptionsProvider.GENERATE_MARSHAL_JSON_VALUE); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java index ca3a2f66b6fd..f84c74d8ee1a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/go/GoModelTest.java @@ -30,6 +30,8 @@ import org.testng.annotations.DataProvider; import org.testng.annotations.Test; +import java.io.File; + @SuppressWarnings("static-method") public class GoModelTest { @@ -298,4 +300,28 @@ public void modelNameTest(String name, String expectedName) { Assert.assertEquals(cm.name, name); Assert.assertEquals(cm.classname, expectedName); } + + @DataProvider(name = "modelMappedNames") + public static Object[][] mappedNames() { + return new Object[][] { + {"mapped", "Remapped", "model_remapped.go"}, + {"mapped_underscore", "RemappedUnderscore", "model_remapped_underscore.go"}, + }; + } + + @Test(dataProvider = "modelMappedNames", description = "map model names") + public void modelNameMappingsTest(String name, String expectedName, String expectedFilename) { + final Schema model = new Schema(); + final DefaultCodegen codegen = new GoClientCodegen(); + codegen.modelNameMapping().put(name, expectedName); + OpenAPI openAPI = TestUtils.createOpenAPIWithOneSchema(name, model); + codegen.setOpenAPI(openAPI); + final CodegenModel cm = codegen.fromModel(name, model); + + final String fn = codegen.modelFilename("model.mustache", name, ""); + Assert.assertEquals(fn, File.separator + expectedFilename); + + Assert.assertEquals(cm.name, name); + Assert.assertEquals(cm.classname, expectedName); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java index 0602c2af8f24..4d70aa6591dc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/goginserver/GoGinServerCodegenTest.java @@ -59,4 +59,27 @@ public void verifyGoMod() throws IOException { "require github.com/gin-gonic/gin v1.9.1"); } + @Test + public void webhooks() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("go-gin-server") + .setGitUserId("my-user") + .setGitRepoId("my-repo") + .setPackageName("my-package") + .setInputSpec("src/test/resources/3_1/webhooks.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + //files.forEach(File::deleteOnExit); + + TestUtils.assertFileContains(Paths.get(output + "/go/routers.go"), + "NewPetPost"); + TestUtils.assertFileContains(Paths.get(output + "/go/api_default.go"), + " c.JSON(200, gin.H{\"status\": \"OK\"})"); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenExampleValuesTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenExampleValuesTest.java index d9f451a462e0..2cbe4c623646 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenExampleValuesTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenExampleValuesTest.java @@ -153,5 +153,17 @@ public String getHelp() { public String getArtifactVersion() { return this.artifactVersion; } + @Test + void customExampleForEnumValue() { + final AbstractJavaCodegen fakeJavaCodegen = new P_AbstractJavaCodegen(); + final CodegenParameter p = new CodegenParameter(); + p.allowableValues = Collections.singletonMap("values", Arrays.asList("first", "second")); + p.dataType = "WrappedEnum"; + p.example = "CustomEnumValue"; + + fakeJavaCodegen.setParameterExampleValue(p); + // Custom example value should not be modified + Assert.assertEquals(p.example, "CustomEnumValue"); + } } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java index 56be46d46f6f..31c97e6c65fc 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/AbstractJavaCodegenTest.java @@ -332,6 +332,7 @@ public void toEnumValue() { Assert.assertEquals(codegen.toEnumValue("42", "Double"), "42"); Assert.assertEquals(codegen.toEnumValue("1337", "Long"), "1337l"); Assert.assertEquals(codegen.toEnumValue("3.14", "Float"), "3.14f"); + Assert.assertEquals(codegen.toEnumValue("schema.json", "URI"), "URI.create(\"schema.json\")"); } @Test diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java index 5b548acf56cd..b76e29e36b74 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaClientCodegenTest.java @@ -42,6 +42,7 @@ import io.swagger.v3.oas.models.responses.ApiResponse; import io.swagger.v3.parser.core.models.ParseOptions; import io.swagger.v3.parser.util.SchemaTypeUtil; + import java.io.File; import java.io.IOException; import java.nio.charset.StandardCharsets; @@ -63,6 +64,9 @@ import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.stream.Collectors; +import java.util.stream.Stream; + +import junit.framework.AssertionFailedError; import lombok.SneakyThrows; import org.openapitools.codegen.ClientOptInput; import org.openapitools.codegen.CodegenConstants; @@ -98,11 +102,11 @@ public void arraysInRequestBody() { RequestBody body1 = new RequestBody(); body1.setDescription("A list of ids"); - body1.setContent( - new Content() - .addMediaType( - "application/json", - new MediaType().schema(new ArraySchema().items(new StringSchema())))); + body1.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType().schema(new ArraySchema().items(new StringSchema())))); CodegenParameter codegenParameter1 = codegen.fromRequestBody(body1, new HashSet(), null); Assert.assertEquals(codegenParameter1.description, "A list of ids"); Assert.assertEquals(codegenParameter1.dataType, "List"); @@ -110,13 +114,13 @@ public void arraysInRequestBody() { RequestBody body2 = new RequestBody(); body2.setDescription("A list of list of values"); - body2.setContent( - new Content() - .addMediaType( - "application/json", - new MediaType() - .schema( - new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); + body2.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType() + .schema( + new ArraySchema().items(new ArraySchema().items(new IntegerSchema()))))); CodegenParameter codegenParameter2 = codegen.fromRequestBody(body2, new HashSet(), null); Assert.assertEquals(codegenParameter2.description, "A list of list of values"); Assert.assertEquals(codegenParameter2.dataType, "List>"); @@ -124,14 +128,14 @@ public void arraysInRequestBody() { RequestBody body3 = new RequestBody(); body3.setDescription("A list of points"); - body3.setContent( - new Content() - .addMediaType( - "application/json", - new MediaType() - .schema( - new ArraySchema() - .items(new ObjectSchema().$ref("#/components/schemas/Point"))))); + body3.setContent( + new Content() + .addMediaType( + "application/json", + new MediaType() + .schema( + new ArraySchema() + .items(new ObjectSchema().$ref("#/components/schemas/Point"))))); ObjectSchema point = new ObjectSchema(); point.addProperty("message", new StringSchema()); point.addProperty("x", new IntegerSchema().format(SchemaTypeUtil.INTEGER32_FORMAT)); @@ -184,17 +188,17 @@ public void testInitialConfigValues() throws Exception { Assert.assertFalse(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "org.openapitools.client.model"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "org.openapitools.client.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "org.openapitools.client.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.client.api"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "org.openapitools.client.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "org.openapitools.client.api"); Assert.assertEquals(codegen.getInvokerPackage(), "org.openapitools.client"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "org.openapitools.client"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "org.openapitools.client"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_GSON); } @@ -211,16 +215,16 @@ public void testSettersForConfigValues() throws Exception { Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.model"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.api"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), "xyz.yyyyy.zzzzzzz.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.invoker"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.invoker"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.invoker"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_GSON); // the library JavaClientCodegen.OKHTTP_GSON only supports GSON } @@ -228,13 +232,13 @@ public void testSettersForConfigValues() throws Exception { public void testAdditionalPropertiesPutForConfigValues() throws Exception { final JavaClientCodegen codegen = new JavaClientCodegen(); codegen.additionalProperties().put(CodegenConstants.HIDE_GENERATION_TIMESTAMP, "true"); - codegen - .additionalProperties() - .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); - codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); - codegen - .additionalProperties() - .put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.iiii.invoker"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen + .additionalProperties() + .put(CodegenConstants.INVOKER_PACKAGE, "xyz.yyyyy.zzzzzzz.iiii.invoker"); codegen.additionalProperties().put(CodegenConstants.SERIALIZATION_LIBRARY, "JACKSON"); codegen.additionalProperties().put(CodegenConstants.LIBRARY, JavaClientCodegen.JERSEY2); codegen.processOpts(); @@ -242,17 +246,17 @@ public void testAdditionalPropertiesPutForConfigValues() throws Exception { Assert.assertEquals(codegen.additionalProperties().get(CodegenConstants.HIDE_GENERATION_TIMESTAMP), Boolean.TRUE); Assert.assertTrue(codegen.isHideGenerationTimestamp()); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.iiii.invoker"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.iiii.invoker"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.iiii.invoker"); Assert.assertEquals(codegen.getSerializationLibrary(), JavaClientCodegen.SERIALIZATION_LIBRARY_JACKSON); } @@ -263,14 +267,14 @@ public void testGeneratedAuthClassesJersey() throws IOException { File output = Files.createTempDirectory("test").toFile(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.JERSEY3) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.JERSEY3) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); @@ -278,14 +282,14 @@ public void testGeneratedAuthClassesJersey() throws IOException { List files = generator.opts(clientOptInput).generate(); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpSignatureAuth.java"); } @Test @@ -305,9 +309,9 @@ public void testImportMappingResult() throws IOException { List files = generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/QueryApi.java"), - "import java.time.Instant;"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/QueryApi.java"), + "import java.time.Instant;"); } @Test @@ -322,52 +326,52 @@ public void testSupportedSecuritySchemesJersey() throws Exception { @Test public void testPackageNamesSetInvokerDerivedFromApi() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen - .additionalProperties() - .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); - codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.yyyyy.zzzzzzz.aaaaa.api"); codegen.processOpts(); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "xyz.yyyyy.zzzzzzz.aaaaa.api"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "xyz.yyyyy.zzzzzzz.aaaaa.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.aaaaa"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.aaaaa"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.aaaaa"); } @Test public void testPackageNamesSetInvokerDerivedFromModel() { final JavaClientCodegen codegen = new JavaClientCodegen(); - codegen - .additionalProperties() - .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); + codegen + .additionalProperties() + .put(CodegenConstants.MODEL_PACKAGE, "xyz.yyyyy.zzzzzzz.mmmmm.model"); codegen.processOpts(); Assert.assertEquals(codegen.modelPackage(), "xyz.yyyyy.zzzzzzz.mmmmm.model"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm.model"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.MODEL_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm.model"); Assert.assertEquals(codegen.apiPackage(), "org.openapitools.client.api"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), - "org.openapitools.client.api"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.API_PACKAGE), + "org.openapitools.client.api"); Assert.assertEquals(codegen.getInvokerPackage(), "xyz.yyyyy.zzzzzzz.mmmmm"); - Assert.assertEquals( - codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), - "xyz.yyyyy.zzzzzzz.mmmmm"); + Assert.assertEquals( + codegen.additionalProperties().get(CodegenConstants.INVOKER_PACKAGE), + "xyz.yyyyy.zzzzzzz.mmmmm"); } @Test public void testGetSchemaTypeWithComposedSchemaWithAllOf() { - final OpenAPI openAPI = - TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/2_0/composed-allof.yaml"); final JavaClientCodegen codegen = new JavaClientCodegen(); Operation operation = openAPI.getPaths().get("/ping").getPost(); @@ -383,8 +387,8 @@ public void updateCodegenPropertyEnum() { codegen.updateCodegenPropertyEnum(array); - List> enumVars = - (List>) array.getItems().getAllowableValues().get("enumVars"); + List> enumVars = + (List>) array.getItems().getAllowableValues().get("enumVars"); Assert.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assert.assertNotNull(testedEnumVar); @@ -396,15 +400,15 @@ public void updateCodegenPropertyEnum() { public void updateCodegenPropertyEnumWithCustomNames() { final JavaClientCodegen codegen = new JavaClientCodegen(); CodegenProperty array = codegenPropertyWithArrayOfIntegerValues(); - array - .getItems() - .setVendorExtensions( - Collections.singletonMap("x-enum-varnames", Collections.singletonList("ONE"))); + array + .getItems() + .setVendorExtensions( + Collections.singletonMap("x-enum-varnames", Collections.singletonList("ONE"))); codegen.updateCodegenPropertyEnum(array); - List> enumVars = - (List>) array.getItems().getAllowableValues().get("enumVars"); + List> enumVars = + (List>) array.getItems().getAllowableValues().get("enumVars"); Assert.assertNotNull(enumVars); Map testedEnumVar = enumVars.get(0); Assert.assertNotNull(testedEnumVar); @@ -455,32 +459,32 @@ public void testGeneratePing() throws Exception { TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiClient.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiException.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ApiResponse.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ServerConfiguration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ServerConfiguration.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/ServerVariable.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/Authentication.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/auth/HttpBearerAuth.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Configuration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/GzipRequestInterceptor.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/GzipRequestInterceptor.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/JSON.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/Pair.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ProgressRequestBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/xyz/abcdef/ProgressResponseBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ProgressRequestBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/xyz/abcdef/ProgressResponseBody.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/xyz/abcdef/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java"); + TestUtils.ensureContainsFile(files, output, "src/test/java/xyz/abcdef/api/DefaultApiTest.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "public class DefaultApi"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "public class DefaultApi"); output.deleteOnExit(); } @@ -528,49 +532,49 @@ public void testGeneratePingSomeObj() throws Exception { TestUtils.ensureContainsFile(files, output, "api/openapi.yaml"); TestUtils.ensureContainsFile(files, output, "src/main/AndroidManifest.xml"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/api/xxxx/PingApi.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiCallback.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiClient.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiException.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ApiResponse.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerConfiguration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ServerVariable.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/ApiKeyAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/Authentication.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBasicAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/auth/HttpBearerAuth.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/Configuration.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/GzipRequestInterceptor.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/JSON.java"); TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/invoker/xxxx/Pair.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"); - TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/model/xxxx/SomeObj.java"); - TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"); - TestUtils.ensureContainsFile( - files, output, "src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressRequestBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/ProgressResponseBody.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/zz/yyyy/invoker/xxxx/StringUtil.java"); + TestUtils.ensureContainsFile(files, output, "src/main/java/zz/yyyy/model/xxxx/SomeObj.java"); + TestUtils.ensureContainsFile(files, output, "src/test/java/zz/yyyy/api/xxxx/PingApiTest.java"); + TestUtils.ensureContainsFile( + files, output, "src/test/java/zz/yyyy/model/xxxx/SomeObjTest.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), - "public class SomeObj", - "Boolean isActive()"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/zz/yyyy/model/xxxx/SomeObj.java"), + "public class SomeObj", + "Boolean isActive()"); output.deleteOnExit(); } @@ -597,12 +601,12 @@ public void testJdkHttpClient() throws Exception { Assert.assertEquals(files.size(), 32); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "public class DefaultApi", - "import java.net.http.HttpClient;", - "import java.net.http.HttpRequest;", - "import java.net.http.HttpResponse;"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "public class DefaultApi", + "import java.net.http.HttpClient;", + "import java.net.http.HttpRequest;", + "import java.net.http.HttpResponse;"); TestUtils.assertFileContains(Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), "public class ApiClient", @@ -620,14 +624,14 @@ public void testJdkHttpClientWithAndWithoutDiscriminator() throws Exception { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.NATIVE) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.NATIVE) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/2_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); @@ -706,26 +710,26 @@ public void testAuthorizationScopeValues_Issue392() { clientOptInput.config(new JavaClientCodegen()); defaultGenerator.opts(clientOptInput); - final List codegenOperations = - defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); - - // Verify GET only has 'read' scope - final CodegenOperation getCodegenOperation = - codegenOperations.stream() - .filter(it -> it.httpMethod.equals("GET")) - .collect(Collectors.toList()) - .get(0); + final List codegenOperations = + defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); + + // Verify GET only has 'read' scope + final CodegenOperation getCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 1); final List> getScopes = getCodegenOperation.authMethods.get(0).scopes; assertEquals(getScopes.size(), 1, "GET scopes don't match. actual::" + getScopes); - // POST operation should have both 'read' and 'write' scope on it - final CodegenOperation postCodegenOperation = - codegenOperations.stream() - .filter(it -> it.httpMethod.equals("POST")) - .collect(Collectors.toList()) - .get(0); + // POST operation should have both 'read' and 'write' scope on it + final CodegenOperation postCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("POST")) + .collect(Collectors.toList()) + .get(0); assertTrue(postCodegenOperation.hasAuthMethods); assertEquals(postCodegenOperation.authMethods.size(), 1); final List> postScopes = postCodegenOperation.authMethods.get(0).scopes; @@ -762,6 +766,50 @@ public void testAuthorizationScopeValues_Issue6733() throws IOException { files.forEach(File::deleteOnExit); } + @Test + public void testMultiPartSpecifiesFileName_Issue17367() throws IOException { + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTEASY) + .setValidateSpec(false) + .setInputSpec("src/test/resources/3_0/issue-17367.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + + DefaultGenerator generator = new DefaultGenerator(); + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "true"); + generator.setGenerateMetadata(false); + List files = generator.opts(clientOptInput).generate(); + try { + validateJavaSourceFiles(files); + File apiClient = files.stream() + .filter(f -> f.getName().equals("ApiClient.java")) + .findFirst() + .orElseThrow(() -> new AssertionFailedError( + "ApiClient.java not found")); + + Stream contents = Arrays.stream(Files.readString(apiClient.toPath(), + StandardCharsets.UTF_8).split("\n")); + + // https://docs.jboss.org/resteasy/docs/6.2.5.Final/javadocs/org/jboss/resteasy/plugins/providers/multipart/MultipartFormDataOutput.html#addFormData(java.lang.String,java.lang.Object,jakarta.ws.rs.core.MediaType,java.lang.String) + assertTrue(contents.anyMatch(l -> l.matches( + ".*multipart\\.addFormData\\(param.getKey\\(\\),\\s*" + + "new\\s+FileInputStream\\(file\\),\\s*" + + "MediaType\\.APPLICATION_OCTET_STREAM_TYPE,\\s*" + + "file.getName\\(\\)\\);.*"))); + } finally { + files.forEach(File::deleteOnExit); + } + } + @Test public void testAuthorizationsMethodsSizeWhenFiltered() { final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue4584.yaml"); @@ -773,14 +821,14 @@ public void testAuthorizationsMethodsSizeWhenFiltered() { clientOptInput.config(new JavaClientCodegen()); defaultGenerator.opts(clientOptInput); - final List codegenOperations = - defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); - - final CodegenOperation getCodegenOperation = - codegenOperations.stream() - .filter(it -> it.httpMethod.equals("GET")) - .collect(Collectors.toList()) - .get(0); + final List codegenOperations = + defaultGenerator.processPaths(openAPI.getPaths()).get("Pet"); + + final CodegenOperation getCodegenOperation = + codegenOperations.stream() + .filter(it -> it.httpMethod.equals("GET")) + .collect(Collectors.toList()) + .get(0); assertTrue(getCodegenOperation.hasAuthMethods); assertEquals(getCodegenOperation.authMethods.size(), 2); } @@ -843,8 +891,8 @@ public void testSchemaMapping() throws IOException { .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); - Assert.assertEquals( - clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); + Assert.assertEquals( + clientOptInput.getConfig().schemaMapping().get("TypeAlias"), "foo.bar.TypeAlias"); DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); @@ -859,19 +907,19 @@ public void testSchemaMapping() throws IOException { validateJavaSourceFiles(files); Assert.assertEquals(files.size(), 1); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/ParentType.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/ParentType.java"); String parentTypeContents = ""; try { - File file = - files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); + File file = + files.stream().filter(f -> f.getName().endsWith("ParentType.java")).findFirst().get(); parentTypeContents = new String(Files.readAllBytes(file.toPath()), StandardCharsets.UTF_8); } catch (IOException ignored) { } - final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL); + final Pattern FIELD_PATTERN = Pattern.compile(".* private (.*?) typeAlias;.*", Pattern.DOTALL); Matcher fieldMatcher = FIELD_PATTERN.matcher(parentTypeContents); Assert.assertTrue(fieldMatcher.matches()); @@ -882,8 +930,8 @@ public void testSchemaMapping() throws IOException { @Test public void testBearerAuth() { - final OpenAPI openAPI = - TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/3_0/pingBearerAuth.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); List security = codegen.fromSecurity(openAPI.getComponents().getSecuritySchemes()); @@ -1107,20 +1155,20 @@ public void testRestTemplateFormMultipart() throws IOException { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArrayWithHttpInfo(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArrayWithHttpInfo(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - // mixed - "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", + // mixed + "multipartMixedWithHttpInfo(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", - // single file - "multipartSingleWithHttpInfo(File file)", - "formParams.add(\"file\", new FileSystemResource(file));"); + // single file + "multipartSingleWithHttpInfo(File file)", + "formParams.add(\"file\", new FileSystemResource(file));"); } /** @@ -1156,20 +1204,20 @@ public void testWebClientFormMultipart() throws IOException { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(List files)", - "formParams.addAll(\"files\"," - + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(List files)", + "formParams.addAll(\"files\"," + + " files.stream().map(FileSystemResource::new).collect(Collectors.toList()));", - // mixed - "multipartMixed(File file, MultipartMixedMarker marker)", - "formParams.add(\"file\", new FileSystemResource(file));", + // mixed + "multipartMixed(File file, MultipartMixedMarker marker)", + "formParams.add(\"file\", new FileSystemResource(file));", - // single file - "multipartSingle(File file)", - "formParams.add(\"file\", new FileSystemResource(file));"); + // single file + "multipartSingle(File file)", + "formParams.add(\"file\", new FileSystemResource(file));"); } @Test @@ -1181,32 +1229,32 @@ public void shouldGenerateBlockingAndNoBlockingOperationsForWebClient() throws I File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec( - "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setAdditionalProperties(properties) + .setInputSpec( + "src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(configurator.toClientOptInput()).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("StoreApi.java")) - .assertMethod("getInventory") - .hasReturnType( - "Mono>") // explicit 'x-webclient-blocking: false' which overrides - // global config - .toFileAssert() - .assertMethod("placeOrder") - .hasReturnType("Order"); // use global config + JavaFileAssert.assertThat(files.get("StoreApi.java")) + .assertMethod("getInventory") + .hasReturnType( + "Mono>") // explicit 'x-webclient-blocking: false' which overrides + // global config + .toFileAssert() + .assertMethod("placeOrder") + .hasReturnType("Order"); // use global config - JavaFileAssert.assertThat(files.get("PetApi.java")) - .assertMethod("findPetsByStatus") - .hasReturnType( - "List"); // explicit 'x-webclient-blocking: true' which overrides global config + JavaFileAssert.assertThat(files.get("PetApi.java")) + .assertMethod("findPetsByStatus") + .hasReturnType( + "List"); // explicit 'x-webclient-blocking: true' which overrides global config } @Test @@ -1224,20 +1272,20 @@ public void testAllowModelWithNoProperties() throws Exception { List files = generator.opts(clientOptInput).generate(); Assert.assertEquals(files.size(), 49); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/RealCommand.java"); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/model/Command.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/RealCommand.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/model/Command.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/RealCommand.java"), - "class RealCommand {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/RealCommand.java"), + "class RealCommand {"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/Command.java"), - "class Command {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/Command.java"), + "class Command {"); output.deleteOnExit(); } @@ -1276,29 +1324,29 @@ public void testRestTemplateWithUseAbstractionForFiles() throws IOException { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(java.util.Collection files)", - "multipartArrayWithHttpInfo(java.util.Collection" - + " files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(java.util.Collection files)", + "multipartArrayWithHttpInfo(java.util.Collection" + + " files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - // mixed - "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", - "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" - + " marker)", - "formParams.add(\"file\", file);", + // mixed + "multipartMixed(org.springframework.core.io.Resource file, MultipartMixedMarker marker)", + "multipartMixedWithHttpInfo(org.springframework.core.io.Resource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", - // single file - "multipartSingle(org.springframework.core.io.Resource file)", - "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", - "formParams.add(\"file\", file);"); + // single file + "multipartSingle(org.springframework.core.io.Resource file)", + "multipartSingleWithHttpInfo(org.springframework.core.io.Resource file)", + "formParams.add(\"file\", file);"); } @Test void testNotDuplicateOauth2FlowsScopes() { - final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/issue_7614.yaml"); final ClientOptInput clientOptInput = new ClientOptInput() .openAPI(openAPI) @@ -1310,8 +1358,8 @@ void testNotDuplicateOauth2FlowsScopes() { final Map> paths = defaultGenerator.processPaths(openAPI.getPaths()); final List codegenOperations = paths.values().stream().flatMap(Collection::stream).collect(Collectors.toList()); - final CodegenOperation getWithBasicAuthAndOauth = - getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); + final CodegenOperation getWithBasicAuthAndOauth = + getByOperationId(codegenOperations, "getWithBasicAuthAndOauth"); assertEquals(getWithBasicAuthAndOauth.authMethods.size(), 3); assertEquals(getWithBasicAuthAndOauth.authMethods.get(0).name, "basic_auth"); final Map passwordFlowScope = getWithBasicAuthAndOauth.authMethods.get(1).scopes.get(0); @@ -1319,10 +1367,10 @@ void testNotDuplicateOauth2FlowsScopes() { assertEquals(passwordFlowScope.get("description"), "create from password flow"); final Map clientCredentialsFlow = getWithBasicAuthAndOauth.authMethods.get(2).scopes.get(0); assertEquals(clientCredentialsFlow.get("scope"), "something:create"); - assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); + assertEquals(clientCredentialsFlow.get("description"), "create from client credentials flow"); - final CodegenOperation getWithOauthAuth = - getByOperationId(codegenOperations, "getWithOauthAuth"); + final CodegenOperation getWithOauthAuth = + getByOperationId(codegenOperations, "getWithOauthAuth"); assertEquals(getWithOauthAuth.authMethods.size(), 2); final Map passwordFlow = getWithOauthAuth.authMethods.get(0).scopes.get(0); assertEquals(passwordFlow.get("scope"), "something:create"); @@ -1330,22 +1378,22 @@ void testNotDuplicateOauth2FlowsScopes() { final Map clientCredentialsCreateFlow = getWithOauthAuth.authMethods.get(1).scopes.get(0); assertEquals(clientCredentialsCreateFlow.get("scope"), "something:create"); - assertEquals( - clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); + assertEquals( + clientCredentialsCreateFlow.get("description"), "create from client credentials flow"); final Map clientCredentialsProcessFlow = getWithOauthAuth.authMethods.get(1).scopes.get(1); assertEquals(clientCredentialsProcessFlow.get("scope"), "something:process"); - assertEquals( - clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); + assertEquals( + clientCredentialsProcessFlow.get("description"), "process from client credentials flow"); } private CodegenOperation getByOperationId(List codegenOperations, String operationId) { - return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) - .orElseThrow( - () -> - new IllegalStateException( - String.format( - Locale.ROOT, "Operation with id [%s] does not exist", operationId))); + return getByCriteria(codegenOperations, (co) -> co.operationId.equals(operationId)) + .orElseThrow( + () -> + new IllegalStateException( + String.format( + Locale.ROOT, "Operation with id [%s] does not exist", operationId))); } private Optional getByCriteria(List codegenOperations, Predicate filter) { @@ -1369,22 +1417,22 @@ public void testCustomMethodParamsAreCamelizedWhenUsingFeign() throws IOExceptio DefaultGenerator generator = new DefaultGenerator(); List files = generator.opts(clientOptInput).generate(); - TestUtils.ensureContainsFile( - files, output, "src/main/java/org/openapitools/client/api/DefaultApi.java"); + TestUtils.ensureContainsFile( + files, output, "src/main/java/org/openapitools/client/api/DefaultApi.java"); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@RequestLine(\"POST /events/{eventId}:undelete\")"); - TestUtils.assertFileNotContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "event_id"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "@RequestLine(\"POST /events/{eventId}:undelete\")"); + TestUtils.assertFileNotContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "event_id"); - // baseName is kept for form parameters - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "@Param(\"some_file\") File someFile"); + // baseName is kept for form parameters + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "@Param(\"some_file\") File someFile"); output.deleteOnExit(); } @@ -1422,20 +1470,20 @@ public void testWebClientWithUseAbstractionForFiles() throws IOException { validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/MultipartApi.java"); - TestUtils.assertFileContains( - defaultApi, - // multiple files - "multipartArray(java.util.Collection files)", - "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", + TestUtils.assertFileContains( + defaultApi, + // multiple files + "multipartArray(java.util.Collection files)", + "formParams.addAll(\"files\", files.stream().collect(Collectors.toList()));", - // mixed - "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker" - + " marker)", - "formParams.add(\"file\", file);", + // mixed + "multipartMixed(org.springframework.core.io.AbstractResource file, MultipartMixedMarker" + + " marker)", + "formParams.add(\"file\", file);", - // single file - "multipartSingle(org.springframework.core.io.AbstractResource file)", - "formParams.add(\"file\", file);"); + // single file + "multipartSingle(org.springframework.core.io.AbstractResource file)", + "formParams.add(\"file\", file);"); } /** @@ -1521,10 +1569,10 @@ public void testNativeClientWhiteSpacePathParamEncoding() throws IOException { Assert.assertEquals(files.size(), 35); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), - "public static String urlEncode(String s) { return URLEncoder.encode(s," - + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/ApiClient.java"), + "public static String urlEncode(String s) { return URLEncoder.encode(s," + + " UTF_8).replaceAll(\"\\\\+\", \"%20\"); }"); } /** @@ -1552,16 +1600,16 @@ public void testNativeClientExplodedQueryParamObject() throws IOException { Assert.assertEquals(files.size(), 38); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\"," - + " queryObject.getSince()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\"," - + " queryObject.getSinceBuild()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\"," - + " queryObject.getMaxBuilds()));", - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\"," - + " queryObject.getMaxWaitSecs()));"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"since\"," + + " queryObject.getSince()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"sinceBuild\"," + + " queryObject.getSinceBuild()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxBuilds\"," + + " queryObject.getMaxBuilds()));", + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"maxWaitSecs\"," + + " queryObject.getMaxWaitSecs()));"); } @Test @@ -1658,9 +1706,9 @@ public void testDefaultMicroprofileRestClientVersion() throws Exception { "1.2.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.8"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import javax."); output.deleteOnExit(); } @@ -1687,26 +1735,26 @@ public void testMicroprofileRestClientVersion_1_4_1() throws Exception { validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/pom.xml"), - "1.4.1"); + TestUtils.assertFileContains( + Paths.get(output + "/pom.xml"), + "1.4.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.2.1"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "1.8"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import javax."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import javax."); output.deleteOnExit(); } - @Test( - expectedExceptions = IllegalArgumentException.class, - expectedExceptionsMessageRegExp = - "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." - + " Supported versions are 1.4.1, 2.0, 3.0") - public void testMicroprofileRestClientIncorrectVersion() throws Exception { + @Test( + expectedExceptions = IllegalArgumentException.class, + expectedExceptionsMessageRegExp = + "Version incorrectVersion of MicroProfile Rest Client is not supported or incorrect." + + " Supported versions are 1.4.1, 2.0, 3.0") + public void testMicroprofileRestClientIncorrectVersion() throws Exception { Map properties = new HashMap<>(); properties.put(JavaClientCodegen.MICROPROFILE_REST_CLIENT_VERSION, "incorrectVersion"); @@ -1754,9 +1802,9 @@ public void testMicroprofileRestClientVersion_3_0() throws Exception { "3.0.4"); TestUtils.assertFileContains(Paths.get(output + "/pom.xml"), "11"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), - "import jakarta."); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/PetApi.java"), + "import jakarta."); output.deleteOnExit(); } @@ -1781,17 +1829,17 @@ public void testMicroprofileGenerateCorrectJsonbCreator_issue12622() throws Exce Map files = generator.opts(clientOptInput).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("Foo.java")) - .assertConstructor("String", "Integer") - .hasParameter("b") - .assertParameterAnnotations() - .containsWithNameAndAttributes( - "JsonbProperty", ImmutableMap.of("value", "\"b\"", "nillable", "true")) - .toParameter() - .toConstructor() - .hasParameter("c") - .assertParameterAnnotations() - .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"c\"")); + JavaFileAssert.assertThat(files.get("Foo.java")) + .assertConstructor("String", "Integer") + .hasParameter("b") + .assertParameterAnnotations() + .containsWithNameAndAttributes( + "JsonbProperty", ImmutableMap.of("value", "\"b\"", "nillable", "true")) + .toParameter() + .toConstructor() + .hasParameter("c") + .assertParameterAnnotations() + .containsWithNameAndAttributes("JsonbProperty", ImmutableMap.of("value", "\"c\"")); } @Test @@ -1802,14 +1850,14 @@ public void testJavaClientDefaultValues_issueNoNumber() throws Exception { File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setAdditionalProperties(properties) - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setInputSpec( - "src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setAdditionalProperties(properties) + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setInputSpec( + "src/test/resources/bugs/java-codegen-empty-array-as-default-value/issue_wrong-default.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); @@ -1847,13 +1895,13 @@ public void testWebClientJsonCreatorWithNullable_issue12790() throws Exception { Map files = generator.opts(clientOptInput).generate().stream() .collect(Collectors.toMap(File::getName, Function.identity())); - JavaFileAssert.assertThat(files.get("TestObject.java")) - .printFileContent() - .assertConstructor("String", "String") - .bodyContainsLines( - "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" - + " JsonNullable.of(nullableProperty);", - "this.notNullableProperty = notNullableProperty;"); + JavaFileAssert.assertThat(files.get("TestObject.java")) + .printFileContent() + .assertConstructor("String", "String") + .bodyContainsLines( + "this.nullableProperty = nullableProperty == null ? JsonNullable.undefined() :" + + " JsonNullable.of(nullableProperty);", + "this.notNullableProperty = notNullableProperty;"); } @Test @@ -1881,12 +1929,12 @@ public void testRestTemplateResponseTypeWithUseAbstractionForFiles() throws IOEx validateJavaSourceFiles(files); Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); - TestUtils.assertFileContains( - defaultApi, - "org.springframework.core.io.Resource resourceInResponse()", - "ResponseEntity resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localReturnType = new" - + " ParameterizedTypeReference()"); + TestUtils.assertFileContains( + defaultApi, + "org.springframework.core.io.Resource resourceInResponse()", + "ResponseEntity resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localReturnType = new" + + " ParameterizedTypeReference()"); } public void testExtraAnnotations(String library) throws IOException { @@ -1914,8 +1962,8 @@ public void testExtraAnnotations(String library) throws IOException { generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); generator.opts(clientOptInput).generate(); - TestUtils.assertExtraAnnotationFiles( - outputPath + "/src/main/java/org/openapitools/client/model"); + TestUtils.assertExtraAnnotationFiles( + outputPath + "/src/main/java/org/openapitools/client/model"); } /** @@ -1958,17 +2006,17 @@ public void testReturnTypeMapping() throws IOException { final CodegenConfigurator configurator = new CodegenConfigurator() .setGeneratorName("java") .setInputSpec("src/test/resources/3_0/issue14525.yaml") - .addTypeMapping("array","Stack") - .addImportMapping("Stack","java.util.Stack") + .addTypeMapping("array", "Stack") + .addImportMapping("Stack", "java.util.Stack") .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), - "import java.util.Stack;"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/api/DefaultApi.java"), + "import java.util.Stack;"); } @Test @@ -1990,10 +2038,10 @@ public void testNativeClientExplodedQueryParamWithArrayProperty() throws IOExcep DefaultGenerator generator = new DefaultGenerator(); generator.opts(clientOptInput).generate(); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), - "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"multi\", \"values\"," - + " queryObject.getValues()));"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/api/DefaultApi.java"), + "localVarQueryParams.addAll(ApiClient.parameterToPairs(\"multi\", \"values\"," + + " queryObject.getValues()));"); } @Test @@ -2020,18 +2068,18 @@ public void testJdkHttpClientWithAndWithoutParentExtension() throws Exception { generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); List files = generator.opts(clientOptInput).generate(); - Assert.assertEquals(files.size(), 24); + Assert.assertEquals(files.size(), 27); validateJavaSourceFiles(files); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/Child.java"), - "public class Child extends Person {"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/Adult.java"), - "public class Adult extends Person {"); - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/xyz/abcdef/model/AnotherChild.java"), - "public class AnotherChild {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/Child.java"), + "public class Child extends Person {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/Adult.java"), + "public class Adult extends Person {"); + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/xyz/abcdef/model/AnotherChild.java"), + "public class AnotherChild {"); } @Test @@ -2039,10 +2087,10 @@ public void testDiscriminatorWithMappingIssue14731() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2055,7 +2103,7 @@ public void testDiscriminatorWithMappingIssue14731() throws IOException { DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); @@ -2069,14 +2117,14 @@ public void testDiscriminatorWithMappingIssue14731() throws IOException { generator.opts(input).generate(); - assertFileNotContains( - Paths.get( - outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java"), - "@JsonTypeName"); - assertFileNotContains( - Paths.get( - outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java"), - "@JsonTypeName"); + assertFileNotContains( + Paths.get( + outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingADTO.java"), + "@JsonTypeName"); + assertFileNotContains( + Paths.get( + outputPath + "/src/main/java/org/openapitools/client/model/ChildWithMappingBDTO.java"), + "@JsonTypeName"); } @Test @@ -2084,10 +2132,10 @@ public void testDiscriminatorWithoutMappingIssue14731() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14731.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2100,7 +2148,7 @@ public void testDiscriminatorWithoutMappingIssue14731() throws IOException { DefaultGenerator generator = new DefaultGenerator(); generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); - generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "false"); codegen.setUseOneOfInterfaces(true); codegen.setLegacyDiscriminatorBehavior(false); @@ -2116,16 +2164,16 @@ public void testDiscriminatorWithoutMappingIssue14731() throws IOException { generator.opts(input).generate(); - assertFileContains( - Paths.get( - outputPath - + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java"), - "@JsonTypeName"); - assertFileContains( - Paths.get( - outputPath - + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java"), - "@JsonTypeName"); + assertFileContains( + Paths.get( + outputPath + + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingADTO.java"), + "@JsonTypeName"); + assertFileContains( + Paths.get( + outputPath + + "/src/main/java/org/openapitools/client/model/ChildWithoutMappingBDTO.java"), + "@JsonTypeName"); } @Test @@ -2133,10 +2181,10 @@ public void testForJavaNativeJsonSubtype() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2150,53 +2198,53 @@ public void testForJavaNativeJsonSubtype() throws IOException { generator.opts(input).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"Cat\", Cat.class)"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"cat\", Cat.class);"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"dog\", Dog.class);"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put(\"lizard\", Lizard.class);"); - - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"cat\", Cat.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"dog\", Dog.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"lizard\", Lizard.class)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "mappings.put(\"Pet\", Pet.class)"); - - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"Cat\", Cat.class)"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"cat\", Cat.class);"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"dog\", Dog.class);"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put(\"lizard\", Lizard.class);"); + + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"cat\", Cat.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"dog\", Dog.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"lizard\", Lizard.class)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "mappings.put(\"Pet\", Pet.class)"); + + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); } @Test @@ -2207,21 +2255,45 @@ public void shouldProperlyExplodeRestTemplateQueryParameters_issue907() { JavaClientCodegen.RESTTEMPLATE ); - JavaFileAssert.assertThat(files.get("DefaultApi.java")) - .printFileContent() - .assertMethod("searchWithHttpInfo") - .bodyContainsLines( - "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"regular-param\"," - + " regularParam));") - .bodyContainsLines( - "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someString\"," - + " objectParam.getSomeString()));") - .bodyContainsLines( - "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someBoolean\"," - + " objectParam.getSomeBoolean()));") - .bodyContainsLines( - "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someInteger\"," - + " objectParam.getSomeInteger()));"); + JavaFileAssert.assertThat(files.get("DefaultApi.java")) + .printFileContent() + .assertMethod("searchWithHttpInfo") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"regular-param\"," + + " regularParam));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someString\"," + + " objectParam.getSomeString()));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someBoolean\"," + + " objectParam.getSomeBoolean()));") + .bodyContainsLines( + "localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someInteger\"," + + " objectParam.getSomeInteger()));"); + } + + @Test + public void shouldProperlyExplodeWebClientQueryParameters() { + final Map files = generateFromContract( + "src/test/resources/3_0/java/explode-query-parameter.yaml", + JavaClientCodegen.WEBCLIENT + ); + + JavaFileAssert.assertThat(files.get("DefaultApi.java")) + .printFileContent() + .assertMethod("searchRequestCreation") + .bodyContainsLines( + "queryParams.putAll(apiClient.parameterToMultiValueMap(null, \"regular-param\"," + + " regularParam));") + .bodyContainsLines( + "queryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someString\"," + + " objectParam.getSomeString()));") + .bodyContainsLines( + "queryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someBoolean\"," + + " objectParam.getSomeBoolean()));") + .bodyContainsLines( + "queryParams.putAll(apiClient.parameterToMultiValueMap(null, \"someInteger\"," + + " objectParam.getSomeInteger()));"); } private static Map generateFromContract(final String pathToSpecification, final String library) { @@ -2255,10 +2327,10 @@ public void testForJavaApacheHttpClientJsonSubtype() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_14917.yaml", null, new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2272,51 +2344,51 @@ public void testForJavaApacheHttpClientJsonSubtype() throws IOException { generator.opts(input).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "mappings.put"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" - + " \"petType\", visible = true)"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); - assertFileNotContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "mappings.put"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.PROPERTY, property =" + + " \"petType\", visible = true)"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"cat\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"dog\")"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"lizard\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Cat.class, name = \"Cat\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Dog.class, name = \"Dog\")"); + assertFileNotContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + "@JsonSubTypes.Type(value = Lizard.class, name = \"Lizard\")"); } @Test public void testIsOverriddenProperty() { - final OpenAPI openAPI = - TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); + final OpenAPI openAPI = + TestUtils.parseFlattenSpec("src/test/resources/3_0/allOf_composition_discriminator.yaml"); JavaClientCodegen codegen = new JavaClientCodegen(); Schema test1 = openAPI.getComponents().getSchemas().get("Cat"); @@ -2337,13 +2409,13 @@ public void testForJavaApacheHttpClientOverrideSetter() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation( - "src/test/resources/3_0/allOf_composition_discriminator.yaml", - null, - new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation( + "src/test/resources/3_0/allOf_composition_discriminator.yaml", + null, + new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2357,12 +2429,12 @@ public void testForJavaApacheHttpClientOverrideSetter() throws IOException { generator.opts(input).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - " @Override\n" + " public Cat petType(String petType) {"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - " }\n" + "\n" + " public Pet petType(String petType) {\n"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + " @Override\n" + " public Cat petType(String petType) {"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + " }\n" + "\n" + " public Pet petType(String petType) {\n"); } @Test @@ -2370,13 +2442,13 @@ public void testForJavaNativeClientOverrideSetter() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); String outputPath = output.getAbsolutePath().replace('\\', '/'); - OpenAPI openAPI = - new OpenAPIParser() - .readLocation( - "src/test/resources/3_0/allOf_composition_discriminator.yaml", - null, - new ParseOptions()) - .getOpenAPI(); + OpenAPI openAPI = + new OpenAPIParser() + .readLocation( + "src/test/resources/3_0/allOf_composition_discriminator.yaml", + null, + new ParseOptions()) + .getOpenAPI(); JavaClientCodegen codegen = new JavaClientCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -2390,12 +2462,12 @@ public void testForJavaNativeClientOverrideSetter() throws IOException { generator.opts(input).generate(); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), - " @Override\n" + " public Cat petType(String petType) {"); - assertFileContains( - Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), - " }\n" + "\n" + " public Pet petType(String petType) {\n"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Cat.java"), + " @Override\n" + " public Cat petType(String petType) {"); + assertFileContains( + Paths.get(outputPath + "/src/main/java/org/openapitools/client/model/Pet.java"), + " }\n" + "\n" + " public Pet petType(String petType) {\n"); } @Test @@ -2414,29 +2486,70 @@ public void testDeprecatedProperty() throws Exception { validateJavaSourceFiles(files); - // deprecated builder method - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); - - // deprecated getter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" - + " @javax.annotation.Nullable\n" - + "\n" - + " public Boolean getDeclawed() {"); - // deprecated setter - TestUtils.assertFileContains( - Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), - "@Deprecated\n" + " public void setDeclawed(Boolean declawed) {"); + // deprecated builder method + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); + + // deprecated getter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + + " @javax.annotation.Nullable\n" + + "\n" + + " public Boolean getDeclawed() {"); + // deprecated setter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + " public void setDeclawed(Boolean declawed) {"); + + output.deleteOnExit(); + } + + @Test + public void testDeprecatedPropertyJersey3() throws Exception { + File output = Files.createTempDirectory("test").toFile(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.JERSEY3) + .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(clientOptInput).generate(); + + validateJavaSourceFiles(files); + + // deprecated builder method + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + " public BigDog declawed(Boolean declawed) {"); + + // deprecated getter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + + " @jakarta.annotation.Nullable\n" + + " @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" + + "\n" + + " public Boolean getDeclawed() {"); + // deprecated setter + TestUtils.assertFileContains( + Paths.get(output + "/src/main/java/org/openapitools/client/model/BigDog.java"), + "@Deprecated\n" + + " @JsonProperty(JSON_PROPERTY_DECLAWED)\n" + + " @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS)\n" + + " public void setDeclawed(Boolean declawed) {"); output.deleteOnExit(); } @DataProvider(name = "shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684") public static Object[][] shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684_dataProvider() { - return new Object[][] {{"okhttp-gson"}, {"jersey2"}, {"jersey3"}, {"native"}}; + return new Object[][]{{"okhttp-gson"}, {"jersey2"}, {"jersey3"}, {"native"}}; } @Test(dataProvider = "shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue15684") @@ -2444,14 +2557,14 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 File output = Files.createTempDirectory("test").toFile(); output.deleteOnExit(); - final CodegenConfigurator configurator = - new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(library) - .addAdditionalProperty( - AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") - .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + final CodegenConfigurator configurator = + new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(library) + .addAdditionalProperty( + AbstractJavaCodegen.ADDITIONAL_MODEL_TYPE_ANNOTATIONS, "@annotation1;@annotation2") + .setInputSpec("src/test/resources/3_0/deprecated-properties.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); final ClientOptInput clientOptInput = configurator.toClientOptInput(); DefaultGenerator generator = new DefaultGenerator(); @@ -2459,13 +2572,13 @@ public void shouldNotAddAdditionalModelAnnotationsToAbstractOpenApiSchema_issue1 .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert.assertThat(files.get("AbstractOpenApiSchema.java")) - .assertTypeAnnotations() - .doesNotContainsWithName("annotation1") - .doesNotContainsWithName("annotation2"); + .assertTypeAnnotations() + .doesNotContainsWithName("annotation1") + .doesNotContainsWithName("annotation2"); JavaFileAssert.assertThat(files.get("Animal.java")) - .assertTypeAnnotations() - .containsWithName("annotation1") - .containsWithName("annotation2"); + .assertTypeAnnotations() + .containsWithName("annotation1") + .containsWithName("annotation2"); } @Test @@ -2577,16 +2690,16 @@ public void testWebClientSupportListOfStringReturnType_issue7118() throws IOExce validateJavaSourceFiles(files); Path userApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/UsersApi.java"); - TestUtils.assertFileContains( - userApi, - // set of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", - "getUserIdSetRequestCreation().toEntity(localVarReturnType)", - // list of string - "ParameterizedTypeReference> localVarReturnType = new" - + " ParameterizedTypeReference>() {};", - "getUserIdListRequestCreation().toEntity(localVarReturnType)"); + TestUtils.assertFileContains( + userApi, + // set of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdSetRequestCreation().toEntity(localVarReturnType)", + // list of string + "ParameterizedTypeReference> localVarReturnType = new" + + " ParameterizedTypeReference>() {};", + "getUserIdListRequestCreation().toEntity(localVarReturnType)"); } @Test @@ -2607,12 +2720,12 @@ public void testEnumCaseInsensitive_issue8084() throws IOException { DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(files.get("EnumTest.java")); javaFileAssert - .assertMethod("fromValue") - .bodyContainsLines("if (b.value.equalsIgnoreCase(value)) {"); + .assertMethod("fromValue") + .bodyContainsLines("if (b.value.equalsIgnoreCase(value)) {"); } @Test @@ -2633,12 +2746,12 @@ public void testEnumCaseSensitive_issue8084() throws IOException { DefaultGenerator generator = new DefaultGenerator(); Map files = generator.opts(input).generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(files.get("EnumTest.java")); javaFileAssert - .assertMethod("fromValue") - .bodyContainsLines("if (b.value.equals(value)) {"); + .assertMethod("fromValue") + .bodyContainsLines("if (b.value.equals(value)) {"); } @Test @@ -2651,11 +2764,11 @@ public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() thr output.deleteOnExit(); final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("java") - .setLibrary(JavaClientCodegen.WEBCLIENT) - .setAdditionalProperties(properties) - .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.WEBCLIENT) + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/issue13146_file_abstraction_response.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); DefaultGenerator generator = new DefaultGenerator(); @@ -2667,12 +2780,13 @@ public void testWebClientResponseTypeWithUseAbstractionForFiles_issue16589() thr Path defaultApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/ResourceApi.java"); TestUtils.assertFileContains(defaultApi, - "Mono resourceInResponse()", - "Mono> resourceInResponseWithHttpInfo()", - "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference()" + "Mono resourceInResponse()", + "Mono> resourceInResponseWithHttpInfo()", + "ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference()" ); } + @Test public void testHandleConstantParams() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); output.deleteOnExit(); @@ -2682,20 +2796,174 @@ public void testHandleConstantParams() throws IOException { clientOptInput.openAPI(openAPI); JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); javaClientCodegen.setOutputDir(output.getAbsolutePath()); - javaClientCodegen.additionalProperties().put(JavaClientCodegen.AUTOSET_CONSTANTS, "true"); + javaClientCodegen.additionalProperties().put(CodegenConstants.AUTOSET_CONSTANTS, "true"); javaClientCodegen.setAutosetConstants(true); clientOptInput.config(javaClientCodegen); defaultGenerator.opts(clientOptInput); Map files = defaultGenerator.generate().stream() - .collect(Collectors.toMap(File::getName, Function.identity())); + .collect(Collectors.toMap(File::getName, Function.identity())); File apiFile = files.get("HelloExampleApi.java"); assertNotNull(apiFile); JavaFileAssert.assertThat(apiFile) - .assertMethod("helloCall", "String", "ApiCallback") - .bodyContainsLines( - "localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); + .assertMethod("helloCall", "String", "ApiCallback") + .bodyContainsLines( + "localVarHeaderParams.put(\"X-CUSTOM_CONSTANT_HEADER\", \"CONSTANT_VALUE\")"); + } + + @Test + public void testAllOfWithSinglePrimitiveTypeRef() throws IOException { + File output = Files.createTempDirectory("test_allOf_primitive_type").toFile().getCanonicalFile(); + output.deleteOnExit(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allof_primitive.yaml"); + final DefaultGenerator defaultGenerator = new DefaultGenerator(); + final ClientOptInput clientOptInput = new ClientOptInput(); + clientOptInput.openAPI(openAPI); + JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); + javaClientCodegen.setOutputDir(output.getAbsolutePath()); + javaClientCodegen.setAutosetConstants(true); + clientOptInput.config(javaClientCodegen); + defaultGenerator.opts(clientOptInput); + + Map files = defaultGenerator.generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + File apiFile = files.get("AllOfDatetime.java"); + assertEquals(apiFile, null); + } + + @Test + public void testOpenAPIGeneratorIgnoreListOption() throws IOException { + File output = Files.createTempDirectory("openapi_generator_ignore_list_test_folder").toFile().getCanonicalFile(); + output.deleteOnExit(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/allof_primitive.yaml"); + final DefaultGenerator defaultGenerator = new DefaultGenerator(); + final ClientOptInput clientOptInput = new ClientOptInput(); + clientOptInput.openAPI(openAPI); + JavaClientCodegen javaClientCodegen = new JavaClientCodegen(); + javaClientCodegen.setOutputDir(output.getAbsolutePath()); + javaClientCodegen.setAutosetConstants(true); + javaClientCodegen.openapiGeneratorIgnoreList().add("README.md"); + javaClientCodegen.openapiGeneratorIgnoreList().add("pom.xml"); + clientOptInput.config(javaClientCodegen); + defaultGenerator.opts(clientOptInput); + + Map files = defaultGenerator.generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + // make sure README.md and pom.xml are not generated + assertEquals(files.get("README.md"), null); + assertEquals(files.get("pom.xml"), null); + } + + @Test + public void testRestTemplateHandleURIEnum() throws IOException { + String[] expectedInnerEnumLines = new String[] { + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))" + }; + + String[] expectedEnumLines = new String[] { + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" + }; + + testHandleURIEnum(JavaClientCodegen.RESTTEMPLATE, expectedInnerEnumLines, expectedEnumLines); + } + + @Test + public void testOkHttpGsonHandleURIEnum() throws IOException { + String[] expectedInnerEnumLines = new String[] { + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", + "jsonWriter.value(enumeration.getValue().toASCIIString())", + "URI value = URI.create(jsonReader.nextString())", + "URI value = URI.create(jsonElement.getAsString())" + }; + + String[] expectedEnumLines = new String[] { + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))", + "jsonWriter.value(enumeration.getValue().toASCIIString())", + "URI value = URI.create(jsonReader.nextString())", + "URI value = URI.create(jsonElement.getAsString())" + }; + + testHandleURIEnum(JavaClientCodegen.OKHTTP_GSON, expectedInnerEnumLines, expectedEnumLines); + } + + @Test + public void testMicroprofileHandleURIEnum() throws IOException { + String[] expectedInnerEnumLines = new String[] { + "V1_SCHEMA_JSON(URI.create(\"https://example.com/v1/schema.json\"))", + "V2_SCHEMA_JSON(URI.create(\"https://example.com/v2/schema.json\"))", + "generator.write(obj.value.toASCIIString())" + }; + + String[] expectedEnumLines = new String[] { + "V1_METADATA_JSON(URI.create(\"https://example.com/v1/metadata.json\"))", + "V2_METADATA_JSON(URI.create(\"https://example.com/v2/metadata.json\"))" + }; + + testHandleURIEnum(JavaClientCodegen.MICROPROFILE, expectedInnerEnumLines, expectedEnumLines); + } + + private void testHandleURIEnum(String library, String[] expectedInnerEnumLines, String[] expectedEnumLines) throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(library) + .setInputSpec("src/test/resources/3_0/enum-and-inner-enum-uri.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + final ClientOptInput clientOptInput = configurator.toClientOptInput(); + final DefaultGenerator defaultGenerator = new DefaultGenerator(); + + defaultGenerator.opts(clientOptInput); + + Map files = defaultGenerator.generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + // enum + File modelFile = files.get("Metadata.java"); + assertNotNull(modelFile); + JavaFileAssert.assertThat(modelFile).fileContains(expectedEnumLines); + + // Inner enum + File apiFile = files.get("V1SchemasGetDefaultResponse.java"); + assertNotNull(apiFile); + JavaFileAssert.assertThat(apiFile).fileContains(expectedInnerEnumLines); + } + + @Test + public void testQueryParamsExploded_whenQueryParamIsNull() throws IOException { + + Map properties = new HashMap<>(); + properties.put(CodegenConstants.API_PACKAGE, "xyz.abcdef.api"); + + File output = Files.createTempDirectory("test").toFile(); + output.deleteOnExit(); + + final CodegenConfigurator configurator = new CodegenConfigurator() + .setGeneratorName("java") + .setLibrary(JavaClientCodegen.RESTTEMPLATE) + .setAdditionalProperties(properties) + .setInputSpec("src/test/resources/3_0/issue_17555.yaml") + .setOutputDir(output.getAbsolutePath().replace("\\", "/")); + + + DefaultGenerator generator = new DefaultGenerator(); + List files = generator.opts(configurator.toClientOptInput()).generate(); + files.forEach(File::deleteOnExit); + + validateJavaSourceFiles(files); + + + Path petApi = Paths.get(output + "/src/main/java/xyz/abcdef/api/DepartmentApi.java"); + TestUtils.assertFileContains(petApi, "if (filter != null) {"); } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaValidationArrayPrimitivesTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaValidationArrayPrimitivesTest.java new file mode 100644 index 000000000000..7d20e42b195b --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/JavaValidationArrayPrimitivesTest.java @@ -0,0 +1,410 @@ +/* + * Copyright 2022 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.java; + +import io.swagger.parser.OpenAPIParser; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.parser.core.models.ParseOptions; +import org.openapitools.codegen.ClientOptInput; +import org.openapitools.codegen.CodegenConstants; +import org.openapitools.codegen.DefaultGenerator; +import org.openapitools.codegen.java.assertions.JavaFileAssert; +import org.openapitools.codegen.languages.*; +import org.testng.annotations.DataProvider; +import org.testng.annotations.Test; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.util.Map; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.stream.Collectors; + +public class JavaValidationArrayPrimitivesTest { + private static Consumer> assertWithValidationWithoutJsonNullable() { + return files -> JavaFileAssert.assertThat(files.get("Foo.java")) + .isNormalClass() + .hasProperty("stringPattern") + .withType("Set<@Pattern(regexp = \"[a-z]\") String>") + .toType() + .hasProperty("stringMaxMinLength") + .withType("Set<@Size(min = 1, max = 10) String>") + .toType() + .hasProperty("stringMinLength") + .withType("List<@Size(min = 1) String>") + .toType() + .hasProperty("stringMaxLength") + .withType("Set<@Size(max = 1) String>") + .toType() + .hasProperty("stringEmail") + .withType("List<@Email String>") + .toType() + .hasProperty("intMinMax") + .withType("List<@Min(1) @Max(10) Integer>") + .toType() + .hasProperty("intMin") + .withType("List<@Min(1) Integer>") + .toType() + .hasProperty("intMax") + .withType("List<@Max(10) Integer>") + .toType() + .hasProperty("numberMinMax") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMin") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMax") + .withType("List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("stringPatternWithMin") + .withType("Set<@Pattern(regexp = \"^\\\\d{3}-\\\\d{2}-\\\\d{4}$\") @Size(min = 10) String>") + .toType() + .hasProperty("stringPatternNullable") + .withType("Set<@Pattern(regexp = \"^\\\\d{3}-\\\\d{2}-\\\\d{4}$\") String>") + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType("Set<@Size(min = 1, max = 10) String>") + .toType() + .hasProperty("stringMinLengthNullable") + .withType("List<@Size(min = 1) String>") + .toType() + .hasProperty("stringMaxLengthNullable") + .withType("Set<@Size(max = 1) String>") + .toType() + .hasProperty("stringNumbers") + .withType("Set<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("intMinMaxNullable") + .withType("List<@Min(1) @Max(10) Integer>") + .toType() + .hasProperty("intMinNullable") + .withType("List<@Min(1) Integer>") + .toType() + .hasProperty("intMaxNullable") + .withType("List<@Max(10) Integer>") + .toType() + .hasProperty("numberMinMaxNullable") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMinNullable") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMaxNullable") + .withType("List<@DecimalMax(value = \"10\", inclusive = true) BigDecimal>") + .toType(); + } + + private static Consumer> assertWithValidationWithJsonNullable() { + return files -> JavaFileAssert.assertThat(files.get("Foo.java")) + .isNormalClass() + .hasProperty("stringPattern") + .withType("Set<@Pattern(regexp = \"[a-z]\") String>") + .toType() + .hasProperty("stringMaxMinLength") + .withType("Set<@Size(min = 1, max = 10) String>") + .toType() + .hasProperty("stringMinLength") + .withType("List<@Size(min = 1) String>") + .toType() + .hasProperty("stringMaxLength") + .withType("Set<@Size(max = 1) String>") + .toType() + .hasProperty("stringEmail") + .withType("List<@Email String>") + .toType() + .hasProperty("intMinMax") + .withType("List<@Min(1) @Max(10) Integer>") + .toType() + .hasProperty("intMin") + .withType("List<@Min(1) Integer>") + .toType() + .hasProperty("intMax") + .withType("List<@Max(10) Integer>") + .toType() + .hasProperty("numberMinMax") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMin") + .withType("List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("numberMax") + .withType("List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("stringPatternWithMin") + .withType("JsonNullable>") + .toType() + .hasProperty("stringPatternNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMinLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMaxLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringNumbers") + .withType("Set<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>") + .toType() + .hasProperty("intMinMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("intMinNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("intMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMinMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMinNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMaxNullable") + .withType("JsonNullable>") + .toType(); + } + + @DataProvider(name = "javaCodegensUsedBeanValidation") + public static Object[][] javaCodegensUsedBeanValidation() { + return new Object[][]{ + {new JavaCXFClientCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaClientCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaPlayFrameworkCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaMicronautClientCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaMicronautServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaJAXRSCXFCDIServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaCXFExtServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaResteasyServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaJAXRSSpecServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaJerseyServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new JavaResteasyEapServerCodegen(), assertWithValidationWithoutJsonNullable()}, + {new SpringCodegen(), assertWithValidationWithJsonNullable()} + }; + } + + @Test(dataProvider = "javaCodegensUsedBeanValidation") + public void shouldAddValidAnnotationIntoCollectionWhenBeanValidationIsEnabled_issue4947(final AbstractJavaCodegen codegen, final Consumer> asserts) throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_4947.yaml", null, new ParseOptions()).getOpenAPI(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + + final ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + final DefaultGenerator generator = new DefaultGenerator(); + final Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + asserts.accept(files); + } + + private static Consumer> assertWithoutValidationWithoutJsonNullable() { + return files -> JavaFileAssert.assertThat(files.get("Foo.java")) + .isNormalClass() + .hasProperty("stringPattern") + .withType("Set") + .toType() + .hasProperty("stringMaxMinLength") + .withType("Set") + .toType() + .hasProperty("stringMinLength") + .withType("List") + .toType() + .hasProperty("stringMaxLength") + .withType("Set") + .toType() + .hasProperty("stringEmail") + .withType("List") + .toType() + .hasProperty("intMinMax") + .withType("List") + .toType() + .hasProperty("intMin") + .withType("List") + .toType() + .hasProperty("intMax") + .withType("List") + .toType() + .hasProperty("numberMinMax") + .withType("List") + .toType() + .hasProperty("numberMin") + .withType("List") + .toType() + .hasProperty("numberMax") + .withType("List") + .toType() + .hasProperty("stringPatternWithMin") + .withType("Set") + .toType() + .hasProperty("stringPatternNullable") + .withType("Set") + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType("Set") + .toType() + .hasProperty("stringMinLengthNullable") + .withType("List") + .toType() + .hasProperty("stringMaxLengthNullable") + .withType("Set") + .toType() + .hasProperty("intMinMaxNullable") + .withType("List") + .toType() + .hasProperty("intMinNullable") + .withType("List") + .toType() + .hasProperty("intMaxNullable") + .withType("List") + .toType() + .hasProperty("numberMinMaxNullable") + .withType("List") + .toType() + .hasProperty("numberMinNullable") + .withType("List") + .toType() + .hasProperty("numberMaxNullable") + .withType("List") + .toType(); + } + + private static Consumer> assertWithoutValidationWithJsonNullable() { + return files -> JavaFileAssert.assertThat(files.get("Foo.java")) + .isNormalClass() + .hasProperty("stringPattern") + .withType("Set") + .toType() + .hasProperty("stringMaxMinLength") + .withType("Set") + .toType() + .hasProperty("stringMinLength") + .withType("List") + .toType() + .hasProperty("stringMaxLength") + .withType("Set") + .toType() + .hasProperty("stringEmail") + .withType("List") + .toType() + .hasProperty("intMinMax") + .withType("List") + .toType() + .hasProperty("intMin") + .withType("List") + .toType() + .hasProperty("intMax") + .withType("List") + .toType() + .hasProperty("numberMinMax") + .withType("List") + .toType() + .hasProperty("numberMin") + .withType("List") + .toType() + .hasProperty("numberMax") + .withType("List") + .toType() + .hasProperty("stringPatternWithMin") + .withType("JsonNullable>") + .toType() + .hasProperty("stringPatternNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMinLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("stringMaxLengthNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("intMinMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("intMinNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("intMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMinMaxNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMinNullable") + .withType("JsonNullable>") + .toType() + .hasProperty("numberMaxNullable") + .withType("JsonNullable>") + .toType(); + } + + @DataProvider(name = "javaCodegensNotUsedBeanValidation") + public static Object[][] javaCodegensNotUsedBeanValidation() { + return new Object[][]{ + {new JavaCXFClientCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaClientCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaPlayFrameworkCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaMicronautClientCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaMicronautServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaJAXRSCXFCDIServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaCXFExtServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaResteasyServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaJAXRSSpecServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaJerseyServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new JavaResteasyEapServerCodegen(), assertWithoutValidationWithoutJsonNullable()}, + {new SpringCodegen(), assertWithoutValidationWithJsonNullable()} + }; + } + + @Test(dataProvider = "javaCodegensNotUsedBeanValidation") + public void shouldNotAddValidAnnotationIntoCollectionWhenBeanValidationIsNotEnabled_issue4947(final AbstractJavaCodegen codegen, final Consumer> asserts) throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + final OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_4947.yaml", null, new ParseOptions()).getOpenAPI(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "false"); + + final ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + final DefaultGenerator generator = new DefaultGenerator(); + final Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + asserts.accept(files); + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/MethodAssert.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/MethodAssert.java index 0eed63a86a5e..cdfb564ff75a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/MethodAssert.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/assertions/MethodAssert.java @@ -54,6 +54,13 @@ public MethodAssert doesNotHaveParameter(final String paramName) { return this; } + public MethodAssert doesNotHaveParameters() { + Assertions.assertThat(actual.getParameters()) + .withFailMessage("Method %s shouldn't have parameter, but it does", methodSignature) + .isEmpty(); + return this; + } + public MethodAssert bodyContainsLines(final String... lines) { Assertions.assertThat(isWithImplementation()) .withFailMessage("Method %s is abstract", methodSignature) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java index 9d5288406071..1ca5bc0af9db 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/java/spring/SpringCodegenTest.java @@ -47,6 +47,7 @@ import java.io.File; import java.io.IOException; +import java.math.BigDecimal; import java.nio.file.Files; import java.nio.file.Paths; import java.util.HashMap; @@ -56,6 +57,7 @@ import java.util.function.Function; import java.util.stream.Collectors; +import org.apache.commons.lang3.StringUtils; import org.assertj.core.api.MapAssert; import org.openapitools.codegen.CliOption; import org.openapitools.codegen.ClientOptInput; @@ -178,6 +180,84 @@ public void doAnnotateDatesOnModelParameters() throws IOException { .doesNotHaveComment(); } + @Test + public void doAnnotateDatesOnModelParametersWithOptionalAndJsonNullable() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_5436.yml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOpenApiNullable(true); + codegen.setUseOptional(true); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(CXFServerFeatures.LOAD_TEST_DATA_FROM_FILE, "true"); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/api/ZebrasApi.java")) + .assertTypeAnnotations() + .hasSize(3) + .containsWithName("Validated") + .containsWithName("Generated") + .containsWithNameAndAttributes("Generated", ImmutableMap.of( + "value", "\"org.openapitools.codegen.languages.SpringCodegen\"" + )) + .containsWithNameAndAttributes("Tag", ImmutableMap.of( + "name", "\"zebras\"" + )) + .toType() + .assertMethod("getZebras") + .hasReturnType("ResponseEntity") + .assertMethodAnnotations() + .hasSize(2) + .containsWithNameAndAttributes("Operation", ImmutableMap.of("operationId", "\"getZebras\"")) + .containsWithNameAndAttributes("RequestMapping", ImmutableMap.of( + "method", "RequestMethod.GET", + "value", "\"/zebras\"" + )) + .toMethod() + .hasParameter("limit").withType("Optional") + .assertParameterAnnotations() + .containsWithName("Valid") + .containsWithNameAndAttributes("Parameter", ImmutableMap.of("name", "\"limit\"")) + .containsWithNameAndAttributes("RequestParam", ImmutableMap.of("required", "false", "value", "\"limit\"")) + .toParameter() + .toMethod() + .hasParameter("animalParams").withType("Optional") + .toMethod() + .commentContainsLines("GET /zebras", "@param limit (optional)") + .bodyContainsLines("return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED)"); + + JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/AnimalParams.java")) + .hasImports("org.springframework.format.annotation.DateTimeFormat") + .hasProperty("born").withType("Optional") + .assertPropertyAnnotations() + .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE")) + .toProperty() + .toType() + .hasProperty("lastSeen").withType("Optional") + .assertPropertyAnnotations() + .containsWithNameAndAttributes("DateTimeFormat", ImmutableMap.of("iso", "DateTimeFormat.ISO.DATE_TIME")) + .toProperty().toType() + .assertMethod("born", "LocalDate") + .bodyContainsLines("this.born = Optional.of(born)") + .doesNotHaveComment(); + } + @Test public void doGenerateCookieParams() throws IOException { File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); @@ -866,7 +946,7 @@ public void shouldAddValidAnnotationIntoCollectionWhenBeanValidationIsEnabled_is .withType( "Map" ) .toType() .hasProperty("response") - .withType( "JsonNullable>" ) + .withType( "JsonNullable>" ) .toType() .hasProperty("nullableDtos") .withType( "JsonNullable>" ) @@ -893,6 +973,100 @@ public void shouldAddValidAnnotationIntoCollectionWhenBeanValidationIsEnabled_is .withType( "Set" ); } + + + @Test + public void shouldAddValidAnnotationIntoCollectionWhenBeanValidationIsEnabled_issue17150() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/spring/issue_17150.yaml", null, new ParseOptions()).getOpenAPI(); + SpringCodegen codegen = new SpringCodegen(); + codegen.setLibrary(SPRING_CLOUD_LIBRARY); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(SpringCodegen.USE_BEANVALIDATION, "true"); + // codegen.additionalProperties().put(SpringCodegen.PERFORM_BEANVALIDATION, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + codegen.setUseSpringBoot3(true); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + JavaFileAssert.assertThat(files.get("Foo.java")) + .isNormalClass() + .hasImports("jakarta.validation.Valid") + .hasImports("jakarta.validation.constraints") + .hasProperty("stringPattern") + .withType( "Set<@Pattern(regexp = \"[a-z]\") String>" ) + .toType() + .hasProperty("stringMaxMinLength") + .withType( "Set<@Size(min = 1, max = 10) String>" ) + .toType() + .hasProperty("stringMinLength") + .withType( "List<@Size(min = 1) String>" ) + .toType() + .hasProperty("stringMaxLength") + .withType( "Set<@Size(max = 1) String>" ) + .toType() + .hasProperty("intMinMax") + .withType( "List<@Min(1) @Max(10) Integer>" ) + .toType() + .hasProperty("intMin") + .withType( "List<@Min(1) Integer>" ) + .toType() + .hasProperty("intMax") + .withType( "List<@Max(10) Integer>" ) + .toType() + .hasProperty("numberMinMax") + .withType( "List<@DecimalMin(value = \"1\", inclusive = false) @DecimalMax(value = \"10\", inclusive = false) BigDecimal>" ) + .toType() + .hasProperty("numberMin") + .withType( "List<@DecimalMin(value = \"1\", inclusive = false) BigDecimal>" ) + .toType() + .hasProperty("numberMax") + .withType( "List<@DecimalMax(value = \"10\", inclusive = false) BigDecimal>" ) + .toType() + + .hasProperty("stringPatternNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("stringMinLengthNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("stringMaxLengthNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("intMinMaxNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("intMinNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("intMaxNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("numberMinMaxNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("numberMinNullable") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("numberMaxNullable") + .withType( "JsonNullable>" ) + .toType() + ; + } + // Helper function, intended to reduce boilerplate private Map generateFiles(SpringCodegen codegen, String filePath) throws IOException { final File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); @@ -2550,6 +2724,7 @@ public void shouldGenerateJsonPropertyAnnotationLocatedInGetters_issue5705() thr .readLocation("src/test/resources/3_0/spring/petstore-with-fake-endpoints-models-for-testing.yaml", null, new ParseOptions()).getOpenAPI(); SpringCodegen codegen = new SpringCodegen(); codegen.setLibrary(SPRING_BOOT); + codegen.setWithXml(true); codegen.setOutputDir(output.getAbsolutePath()); ClientOptInput input = new ClientOptInput() @@ -2564,34 +2739,42 @@ public void shouldGenerateJsonPropertyAnnotationLocatedInGetters_issue5705() thr .hasProperty("normalPropertyName") .assertPropertyAnnotations() .doesNotContainsWithName("JsonProperty") + .doesNotContainsWithName("JacksonXmlProperty") .toProperty().toType() .hasProperty("UPPER_CASE_PROPERTY_SNAKE") .assertPropertyAnnotations() .doesNotContainsWithName("JsonProperty") + .doesNotContainsWithName("JacksonXmlProperty") .toProperty().toType() .hasProperty("lowerCasePropertyDashes") .assertPropertyAnnotations() .doesNotContainsWithName("JsonProperty") + .doesNotContainsWithName("JacksonXmlProperty") .toProperty().toType() .hasProperty("propertyNameWithSpaces") .assertPropertyAnnotations() .doesNotContainsWithName("JsonProperty") + .doesNotContainsWithName("JacksonXmlProperty") .toProperty().toType() .assertMethod("getNormalPropertyName") .assertMethodAnnotations() .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "\"normalPropertyName\"")) + .containsWithNameAndAttributes("JacksonXmlProperty", ImmutableMap.of("localName", "\"normalPropertyName\"")) .toMethod().toFileAssert() .assertMethod("getUPPERCASEPROPERTYSNAKE") .assertMethodAnnotations() .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "\"UPPER_CASE_PROPERTY_SNAKE\"")) + .containsWithNameAndAttributes("JacksonXmlProperty", ImmutableMap.of("localName", "\"UPPER_CASE_PROPERTY_SNAKE\"")) .toMethod().toFileAssert() .assertMethod("getLowerCasePropertyDashes") .assertMethodAnnotations() .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "\"lower-case-property-dashes\"")) + .containsWithNameAndAttributes("JacksonXmlProperty", ImmutableMap.of("localName", "\"lower-case-property-dashes\"")) .toMethod().toFileAssert() .assertMethod("getPropertyNameWithSpaces") .assertMethodAnnotations() - .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "\"property name with spaces\"")); + .containsWithNameAndAttributes("JsonProperty", ImmutableMap.of("value", "\"property name with spaces\"")) + .containsWithNameAndAttributes("JacksonXmlProperty", ImmutableMap.of("localName", "\"property name with spaces\"")); } @Test @@ -3090,6 +3273,985 @@ public void doCallFluentParentSettersFromChildModel() throws IOException { .assertNoMethod("setAlias"); } + + + @Test + public void testModelsWithNoneOptionalAndJsonNullable() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_14765.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOpenApiNullable(true); + codegen.setUseOptional(false); + codegen.setUseSpringBoot3(true); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + + JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/Animal.java")) + .hasImports("jakarta.validation.Valid") + .hasImports("jakarta.validation.constraints") + + .hasProperty("name") + .withType( "String" ) + .toType() + .hasProperty("age") + .withType( "JsonNullable" ) + .toType() + .hasProperty("alias") + .withType( "JsonNullable" ) + .toType() + .hasProperty("color") + .withType( "String" ) + .toType() + .hasProperty("names") + .withType( "List" ) + .toType() + .hasProperty("colors") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("stringPattern") + .withType( "String" ) + .toType() + .hasProperty("stringMaxMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMaxLength") + .withType( "String" ) + .toType() + .hasProperty("stringEmail") + .withType( "String" ) + .toType() + .hasProperty("intMinMax") + .withType( "Integer" ) + .toType() + .hasProperty("intMin") + .withType( "Integer" ) + .toType() + .hasProperty("intMax") + .withType( "Integer" ) + .toType() + .hasProperty("numberMinMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMin") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("stringDefault") + .withType( "String" ) + .toType() + .fileContains("stringDefault = \"ABC\"") + .hasProperty("zebra") + .withType( "Zebra" ) + .toType() + + .hasProperty("stringPatternNullable") + .withType( "JsonNullable<@Pattern(regexp = \"[a-z]\") String>" ) + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType( "JsonNullable<@Size(min = 1, max = 10) String>" ) + .toType() + .hasProperty("stringMinLengthNullable") + .withType( "JsonNullable<@Size(min = 1) String>" ) + .toType() + .hasProperty("stringMaxLengthNullable") + .withType( "JsonNullable<@Size(max = 1) String>" ) + .toType() + .hasProperty("intMinMaxNullable") + .withType( "JsonNullable<@Min(1) @Max(10) Integer>" ) + .toType() + .hasProperty("intMinNullable") + .withType( "JsonNullable<@Min(1) Integer>" ) + .toType() + .hasProperty("intMaxNullable") + .withType( "JsonNullable<@Max(10) Integer>" ) + .toType() + .hasProperty("numberMinMaxNullable") + .withType( "JsonNullable<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("numberMinNullable") + .withType( "JsonNullable<@DecimalMin(\"1\") BigDecimal>" ) + .toType() + .hasProperty("numberMaxNullable") + .withType( "JsonNullable<@DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("stringDefaultNullable") + .withType( "JsonNullable<@Size(max = 1) String>" ) + .toType() + .fileContains("stringDefaultNullable = JsonNullable.undefined();") + + .assertMethod("name") + .hasReturnType("Animal") + .bodyContainsLines("this.name = name;", "return this;") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setName") + .hasReturnType("void") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getName") + .hasReturnType("String") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("colors") + .hasReturnType("Animal") + .bodyContainsLines("this.colors = JsonNullable.of(colors);", "return this;") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setColors") + .hasReturnType("void") + .hasParameter("colors") + .withType("JsonNullable>") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getColors") + .hasReturnType("JsonNullable>") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("names") + .hasReturnType("Animal") + .bodyContainsLines("this.names = names;", "return this;") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setNames") + .hasReturnType("void") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getNames") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert(); + + assertJsonNullableMethod(javaFileAssert, Integer.class, "age", "JsonNullable"); + assertJsonNullableMethod(javaFileAssert, String.class, "alias", "JsonNullable"); + assertMethod(javaFileAssert, String.class, "color"); + + assertMethod(javaFileAssert, String.class, "stringPattern"); + assertMethod(javaFileAssert, String.class, "stringMaxMinLength"); + assertMethod(javaFileAssert, String.class, "stringMinLength"); + assertMethod(javaFileAssert, String.class, "stringMaxLength"); + assertMethod(javaFileAssert, String.class, "stringEmail"); + assertMethod(javaFileAssert, Integer.class, "intMinMax"); + assertMethod(javaFileAssert, Integer.class, "intMin"); + assertMethod(javaFileAssert, Integer.class, "intMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMin"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMax"); + assertMethod(javaFileAssert, "Zebra", "zebra"); + + assertJsonNullableMethod(javaFileAssert, String.class, "stringPatternNullable", "JsonNullable<@Pattern(regexp = \"[a-z]\") String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMaxMinLengthNullable", "JsonNullable<@Size(min = 1, max = 10) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMinLengthNullable", "JsonNullable<@Size(min = 1) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMaxLengthNullable", "JsonNullable<@Size(max = 1) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringEmailNullable", "JsonNullable<@jakarta.validation.constraints.Email String>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMinMaxNullable", "JsonNullable<@Min(1) @Max(10) Integer>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMinNullable", "JsonNullable<@Min(1) Integer>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMaxNullable", "JsonNullable<@Max(10) Integer>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMinMaxNullable", "JsonNullable<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMinNullable", "JsonNullable<@DecimalMin(\"1\") BigDecimal>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMaxNullable", "JsonNullable<@DecimalMax(\"10\") BigDecimal>"); + + } + + @Test + public void testModelsWithOptionalAndJsonNullable() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_14765.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOpenApiNullable(true); + codegen.setUseOptional(true); + codegen.setUseSpringBoot3(true); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + + JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/Animal.java")) + .hasImports("jakarta.validation.Valid") + .hasImports("jakarta.validation.constraints") + + .hasProperty("name") + .withType( "String" ) + .toType() + .hasProperty("age") + .withType( "JsonNullable" ) + .toType() + .hasProperty("alias") + .withType( "JsonNullable" ) + .toType() + .hasProperty("color") + .withType( "Optional" ) + .toType() + .hasProperty("names") + .withType( "List" ) + .toType() + .hasProperty("colors") + .withType( "JsonNullable>" ) + .toType() + .hasProperty("stringPattern") + .withType( "Optional<@Pattern(regexp = \"[a-z]\") String>" ) + .toType() + .hasProperty("stringMaxMinLength") + .withType( "Optional<@Size(min = 1, max = 10) String>" ) + .toType() + .hasProperty("stringMinLength") + .withType( "Optional<@Size(min = 1) String>" ) + .toType() + .hasProperty("stringMaxLength") + .withType( "Optional<@Size(max = 1) String>" ) + .toType() + .hasProperty("stringEmail") + .withType( "Optional<@jakarta.validation.constraints.Email String>" ) + .toType() + .hasProperty("intMinMax") + .withType( "Optional<@Min(1) @Max(10) Integer>" ) + .toType() + .hasProperty("intMin") + .withType( "Optional<@Min(1) Integer>" ) + .toType() + .hasProperty("intMax") + .withType( "Optional<@Max(10) Integer>" ) + .toType() + .hasProperty("numberMinMax") + .withType( "Optional<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("numberMin") + .withType( "Optional<@DecimalMin(\"1\") BigDecimal>" ) + .toType() + .hasProperty("numberMax") + .withType( "Optional<@DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("stringDefault") + .withType( "Optional<@Size(max = 1) String>" ) + .toType() + .fileContains("stringDefault = Optional.of(\"ABC\")") + .hasProperty("zebra") + .withType( "Optional" ) + .toType() + + .hasProperty("stringPatternNullable") + .withType( "JsonNullable<@Pattern(regexp = \"[a-z]\") String>" ) + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType( "JsonNullable<@Size(min = 1, max = 10) String>" ) + .toType() + .hasProperty("stringMinLengthNullable") + .withType( "JsonNullable<@Size(min = 1) String>" ) + .toType() + .hasProperty("stringMaxLengthNullable") + .withType( "JsonNullable<@Size(max = 1) String>" ) + .toType() + .hasProperty("intMinMaxNullable") + .withType( "JsonNullable<@Min(1) @Max(10) Integer>" ) + .toType() + .hasProperty("intMinNullable") + .withType( "JsonNullable<@Min(1) Integer>" ) + .toType() + .hasProperty("intMaxNullable") + .withType( "JsonNullable<@Max(10) Integer>" ) + .toType() + .hasProperty("numberMinMaxNullable") + .withType( "JsonNullable<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("numberMinNullable") + .withType( "JsonNullable<@DecimalMin(\"1\") BigDecimal>" ) + .toType() + .hasProperty("numberMaxNullable") + .withType( "JsonNullable<@DecimalMax(\"10\") BigDecimal>" ) + .toType() + .hasProperty("stringDefaultNullable") + .withType( "JsonNullable<@Size(max = 1) String>" ) + .toType() + .fileContains("stringDefaultNullable = JsonNullable.undefined();") + + .assertMethod("name") + .hasReturnType("Animal") + .bodyContainsLines("this.name = name;", "return this;") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setName") + .hasReturnType("void") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getName") + .hasReturnType("String") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("colors") + .hasReturnType("Animal") + .bodyContainsLines("this.colors = JsonNullable.of(colors);", "return this;") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setColors") + .hasReturnType("void") + .hasParameter("colors") + .withType("JsonNullable>") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getColors") + .hasReturnType("JsonNullable>") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("names") + .hasReturnType("Animal") + .bodyContainsLines("this.names = names;", "return this;") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setNames") + .hasReturnType("void") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getNames") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert(); + + assertJsonNullableMethod(javaFileAssert, String.class, "alias", "JsonNullable"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "age", "JsonNullable"); + assertOptionalMethod(javaFileAssert, String.class, "color", "Optional"); + + assertOptionalMethod(javaFileAssert, String.class, "stringPattern", "Optional<@Pattern(regexp = \"[a-z]\") String>"); + assertOptionalMethod(javaFileAssert, String.class, "stringMaxMinLength", "Optional<@Size(min = 1, max = 10) String>"); + assertOptionalMethod(javaFileAssert, String.class, "stringMinLength", "Optional<@Size(min = 1) String>"); + assertOptionalMethod(javaFileAssert, String.class, "stringMaxLength", "Optional<@Size(max = 1) String>"); + assertOptionalMethod(javaFileAssert, String.class, "stringEmail", "Optional<@jakarta.validation.constraints.Email String>"); + assertOptionalMethod(javaFileAssert, Integer.class, "intMinMax", "Optional<@Min(1) @Max(10) Integer>"); + assertOptionalMethod(javaFileAssert, Integer.class, "intMin", "Optional<@Min(1) Integer>"); + assertOptionalMethod(javaFileAssert, Integer.class, "intMax", "Optional<@Max(10) Integer>"); + assertOptionalMethod(javaFileAssert, BigDecimal.class, "numberMinMax", "Optional<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>"); + assertOptionalMethod(javaFileAssert, BigDecimal.class, "numberMin", "Optional<@DecimalMin(\"1\") BigDecimal>"); + assertOptionalMethod(javaFileAssert, BigDecimal.class, "numberMax", "Optional<@DecimalMax(\"10\") BigDecimal>"); + assertOptionalMethod(javaFileAssert,"Zebra", "zebra", "Optional"); + + assertJsonNullableMethod(javaFileAssert, String.class, "stringPatternNullable", "JsonNullable<@Pattern(regexp = \"[a-z]\") String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMaxMinLengthNullable", "JsonNullable<@Size(min = 1, max = 10) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMinLengthNullable", "JsonNullable<@Size(min = 1) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringMaxLengthNullable", "JsonNullable<@Size(max = 1) String>"); + assertJsonNullableMethod(javaFileAssert, String.class, "stringEmailNullable", "JsonNullable<@jakarta.validation.constraints.Email String>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMinMaxNullable", "JsonNullable<@Min(1) @Max(10) Integer>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMinNullable", "JsonNullable<@Min(1) Integer>"); + assertJsonNullableMethod(javaFileAssert, Integer.class, "intMaxNullable", "JsonNullable<@Max(10) Integer>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMinMaxNullable", "JsonNullable<@DecimalMin(\"1\") @DecimalMax(\"10\") BigDecimal>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMinNullable", "JsonNullable<@DecimalMin(\"1\") BigDecimal>"); + assertJsonNullableMethod(javaFileAssert, BigDecimal.class, "numberMaxNullable", "JsonNullable<@DecimalMax(\"10\") BigDecimal>"); + + } + + @Test + public void testModelsWithOptionalAndNoneJsonNullable() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_14765.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOpenApiNullable(false); + codegen.setUseOptional(true); + codegen.setUseSpringBoot3(true); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + + JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/Animal.java")) + .hasImports("jakarta.validation.Valid") + .hasImports("jakarta.validation.constraints") + + .hasProperty("name") + .withType( "String" ) + .toType() + .hasProperty("age") + .withType( "Integer" ) + .toType() + .hasProperty("alias") + .withType( "String" ) + .toType() + .hasProperty("color") + .withType( "String" ) + .toType() + .hasProperty("names") + .withType( "List" ) + .toType() + .hasProperty("colors") + .withType( "List" ) + .toType() + .hasProperty("stringPattern") + .withType( "String" ) + .toType() + .hasProperty("stringMaxMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMaxLength") + .withType( "String" ) + .toType() + .hasProperty("stringEmail") + .withType( "String" ) + .toType() + .hasProperty("intMinMax") + .withType( "Integer" ) + .toType() + .hasProperty("intMin") + .withType( "Integer" ) + .toType() + .hasProperty("intMax") + .withType( "Integer" ) + .toType() + .hasProperty("numberMinMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMin") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("stringDefault") + .withType( "String" ) + .toType() + .fileContains("stringDefault = \"ABC\"") + .hasProperty("zebra") + .withType( "Zebra" ) + .toType() + + .hasProperty("stringPatternNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMinLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMaxLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("intMinMaxNullable") + .withType( "Integer" ) + .toType() + .hasProperty("intMinNullable") + .withType( "Integer" ) + .toType() + .hasProperty("intMaxNullable") + .withType( "Integer" ) + .toType() + .hasProperty("numberMinMaxNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMinNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMaxNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("stringDefaultNullable") + .withType( "String" ) + .toType() + .fileContains("stringDefaultNullable = null;") + + .assertMethod("name") + .hasReturnType("Animal") + .bodyContainsLines("this.name = name;", "return this;") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setName") + .hasReturnType("void") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getName") + .hasReturnType("String") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("age") + .hasReturnType("Animal") + .bodyContainsLines("this.age = age;", "return this;") + .hasParameter("age") + .withType("Integer") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setAge") + .hasReturnType("void") + .hasParameter("age") + .withType("Integer") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getAge") + .hasReturnType("Integer") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("colors") + .hasReturnType("Animal") + .bodyContainsLines("this.colors = colors;", "return this;") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setColors") + .hasReturnType("void") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getColors") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("names") + .hasReturnType("Animal") + .bodyContainsLines("this.names = names;", "return this;") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setNames") + .hasReturnType("void") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getNames") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert(); + + assertMethod(javaFileAssert, String.class, "alias"); + assertMethod(javaFileAssert, String.class, "color"); + + assertMethod(javaFileAssert, String.class, "stringPattern"); + assertMethod(javaFileAssert, String.class, "stringMaxMinLength"); + assertMethod(javaFileAssert, String.class, "stringMinLength"); + assertMethod(javaFileAssert, String.class, "stringMaxLength"); + assertMethod(javaFileAssert, String.class, "stringEmail"); + assertMethod(javaFileAssert, Integer.class, "intMinMax"); + assertMethod(javaFileAssert, Integer.class, "intMin"); + assertMethod(javaFileAssert, Integer.class, "intMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMin"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMax"); + assertMethod(javaFileAssert, "Zebra", "zebra"); + + assertMethod(javaFileAssert, String.class, "stringPatternNullable"); + assertMethod(javaFileAssert, String.class, "stringMaxMinLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringMinLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringMaxLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringEmailNullable"); + assertMethod(javaFileAssert, Integer.class, "intMinMaxNullable"); + assertMethod(javaFileAssert, Integer.class, "intMinNullable"); + assertMethod(javaFileAssert, Integer.class, "intMaxNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinMaxNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMaxNullable"); + + } + + @Test + public void testModelsWithNoneOptionalAndNoneOpenApiNullable() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + String outputPath = output.getAbsolutePath().replace('\\', '/'); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/3_0/issue_14765.yaml", null, new ParseOptions()).getOpenAPI(); + + SpringCodegen codegen = new SpringCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.setOpenApiNullable(false); + codegen.setUseOptional(false); + codegen.setUseSpringBoot3(true); + + ClientOptInput input = new ClientOptInput(); + input.openAPI(openAPI); + input.config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + + generator.setGeneratorPropertyDefault(CodegenConstants.MODELS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_TESTS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.MODEL_DOCS, "false"); + generator.setGeneratorPropertyDefault(CodegenConstants.APIS, "true"); + generator.setGeneratorPropertyDefault(CodegenConstants.SUPPORTING_FILES, "false"); + generator.opts(input).generate(); + + + JavaFileAssert javaFileAssert = JavaFileAssert.assertThat(Paths.get(outputPath + "/src/main/java/org/openapitools/model/Animal.java")) + .hasImports("jakarta.validation.Valid") + .hasImports("jakarta.validation.constraints") + + .hasProperty("name") + .withType( "String" ) + .toType() + .hasProperty("age") + .withType( "Integer" ) + .toType() + .hasProperty("alias") + .withType( "String" ) + .toType() + .hasProperty("color") + .withType( "String" ) + .toType() + .hasProperty("names") + .withType( "List" ) + .toType() + .hasProperty("colors") + .withType( "List" ) + .toType() + .hasProperty("stringPattern") + .withType( "String" ) + .toType() + .hasProperty("stringMaxMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMinLength") + .withType( "String" ) + .toType() + .hasProperty("stringMaxLength") + .withType( "String" ) + .toType() + .hasProperty("stringEmail") + .withType( "String" ) + .toType() + .hasProperty("intMinMax") + .withType( "Integer" ) + .toType() + .hasProperty("intMin") + .withType( "Integer" ) + .toType() + .hasProperty("intMax") + .withType( "Integer" ) + .toType() + .hasProperty("numberMinMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMin") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMax") + .withType( "BigDecimal" ) + .toType() + .hasProperty("stringDefault") + .withType( "String" ) + .toType() + .fileContains("stringDefault = \"ABC\"") + .hasProperty("zebra") + .withType( "Zebra" ) + .toType() + + .hasProperty("stringPatternNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMaxMinLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMinLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("stringMaxLengthNullable") + .withType( "String" ) + .toType() + .hasProperty("intMinMaxNullable") + .withType( "Integer" ) + .toType() + .hasProperty("intMinNullable") + .withType( "Integer" ) + .toType() + .hasProperty("intMaxNullable") + .withType( "Integer" ) + .toType() + .hasProperty("numberMinMaxNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMinNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("numberMaxNullable") + .withType( "BigDecimal" ) + .toType() + .hasProperty("stringDefaultNullable") + .withType( "String" ) + .toType() + .fileContains("stringDefaultNullable = null;") + + .assertMethod("name") + .hasReturnType("Animal") + .bodyContainsLines("this.name = name;", "return this;") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setName") + .hasReturnType("void") + .hasParameter("name") + .withType("String") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getName") + .hasReturnType("String") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("age") + .hasReturnType("Animal") + .bodyContainsLines("this.age = age;", "return this;") + .hasParameter("age") + .withType("Integer") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setAge") + .hasReturnType("void") + .hasParameter("age") + .withType("Integer") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getAge") + .hasReturnType("Integer") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("colors") + .hasReturnType("Animal") + .bodyContainsLines("this.colors = colors;", "return this;") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setColors") + .hasReturnType("void") + .hasParameter("colors") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getColors") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert() + + .assertMethod("names") + .hasReturnType("Animal") + .bodyContainsLines("this.names = names;", "return this;") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("setNames") + .hasReturnType("void") + .hasParameter("names") + .withType("List") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("getNames") + .hasReturnType("List") + .doesNotHaveParameters() + .toFileAssert(); + + assertMethod(javaFileAssert, String.class, "alias"); + assertMethod(javaFileAssert, String.class, "color"); + + assertMethod(javaFileAssert, String.class, "stringPattern"); + assertMethod(javaFileAssert, String.class, "stringMaxMinLength"); + assertMethod(javaFileAssert, String.class, "stringMinLength"); + assertMethod(javaFileAssert, String.class, "stringMaxLength"); + assertMethod(javaFileAssert, String.class, "stringEmail"); + assertMethod(javaFileAssert, Integer.class, "intMinMax"); + assertMethod(javaFileAssert, Integer.class, "intMin"); + assertMethod(javaFileAssert, Integer.class, "intMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinMax"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMin"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMax"); + assertMethod(javaFileAssert, "Zebra", "zebra"); + + assertMethod(javaFileAssert, String.class, "stringPatternNullable"); + assertMethod(javaFileAssert, String.class, "stringMaxMinLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringMinLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringMaxLengthNullable"); + assertMethod(javaFileAssert, String.class, "stringEmailNullable"); + assertMethod(javaFileAssert, Integer.class, "intMinMaxNullable"); + assertMethod(javaFileAssert, Integer.class, "intMinNullable"); + assertMethod(javaFileAssert, Integer.class, "intMaxNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinMaxNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMinNullable"); + assertMethod(javaFileAssert, BigDecimal.class, "numberMaxNullable"); + + } + + private void assertOptionalMethod(JavaFileAssert javaFileAssert, Class type, String expectedName, String getterReturnType){ + assertOptionalMethod(javaFileAssert, type.getSimpleName(), expectedName, getterReturnType); + } + + private void assertOptionalMethod(JavaFileAssert javaFileAssert, String type, String expectedName, String getterReturnType){ + assertWrapperMethod(javaFileAssert, "Optional", type, expectedName, getterReturnType); + } + + private void assertJsonNullableMethod(JavaFileAssert javaFileAssert, Class type, String expectedName, String getterReturnType){ + assertJsonNullableMethod(javaFileAssert, type.getSimpleName(), expectedName, getterReturnType); + } + + private void assertJsonNullableMethod(JavaFileAssert javaFileAssert, String type, String expectedName, String getterReturnType){ + assertWrapperMethod(javaFileAssert, "JsonNullable", type, expectedName, getterReturnType); + } + + private void assertWrapperMethod(JavaFileAssert javaFileAssert, String wrapperType, String type, String expectedName, String getterReturnType){ + String methodName = StringUtils.capitalize(expectedName); + javaFileAssert.assertMethod(expectedName) + .hasReturnType("Animal") + .bodyContainsLines("this."+expectedName+" = "+wrapperType+".of("+expectedName+");", "return this;") + .hasParameter(expectedName) + .withType(type) + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("set"+methodName) + .hasReturnType("void") + .hasParameter(expectedName) + .withType(wrapperType+"<"+type+">") + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("get"+methodName) + .hasReturnType(getterReturnType) + .doesNotHaveParameters() + .toFileAssert(); + } + + private void assertMethod(JavaFileAssert javaFileAssert, String type, String expectedName){ + String methodName = StringUtils.capitalize(expectedName); + javaFileAssert.assertMethod(expectedName) + .hasReturnType("Animal") + .bodyContainsLines("this."+expectedName+" = "+ expectedName + ";", "return this;") + .hasParameter(expectedName) + .withType(type) + .toMethod() + .toFileAssert() + // Setter method assertions + .assertMethod("set"+methodName) + .hasReturnType("void") + .hasParameter(expectedName) + .withType(type) + .toMethod() + .toFileAssert() + // Getter method assertions + .assertMethod("get"+methodName) + .hasReturnType(type) + .doesNotHaveParameters() + .toFileAssert(); + } + + private void assertMethod(JavaFileAssert javaFileAssert, Class type, String expectedName){ + assertMethod(javaFileAssert,type.getSimpleName(), expectedName); + } + + @Test public void multiLineOperationDescription() throws IOException { Map additionalProperties = new HashMap<>(); @@ -3235,4 +4397,34 @@ public void givenMultipartForm_whenGenerateBlockedServer_thenParameterAreCreated assertFileContains(Paths.get(outputPath + "/src/main/java/org/openapitools/api/PetApi.java"), "@Valid @RequestParam(value = \"additionalMetadata\", required = false) String additionalMetadata"); } + + @Test + public void testMultiInheritanceParentRequiredParams_issue16797() throws IOException { + final Map output = generateFromContract("src/test/resources/3_0/spring/issue_16797.yaml", SPRING_BOOT); + // constructor should as + // public Object4(Type1 pageInfo, String responseType, String requestId, Boolean success) { + // super(responseType, requestId, success, pageInfo); + // } + JavaFileAssert.assertThat(output.get("Object4.java")) + .assertConstructor("Type1", "String", "String", "Boolean") + .hasParameter("responseType").toConstructor() + .hasParameter("requestId").toConstructor() + .hasParameter("success").toConstructor() + .hasParameter("pageInfo").toConstructor() + ; + } + + @Test + public void testMultiInheritanceParentRequiredParams_issue15796() throws IOException { + final Map output = generateFromContract("src/test/resources/3_0/spring/issue_15796.yaml", SPRING_BOOT); + // constructor should as this + //public Poodle(String race, String type) { + // super(race, type); + //} + JavaFileAssert.assertThat(output.get("Poodle.java")) + .assertConstructor("String", "String") + .hasParameter("type").toConstructor() + .hasParameter("race").toConstructor() + ; + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java index 8514e36b803c..7b5e0ca5de77 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/javascript/JavascriptClientCodegenTest.java @@ -169,4 +169,13 @@ public void testIsJsonIsXmlInProduces() throws Exception { } } + @Test(description = "test additional properties for code generation") + public void testAdditionalProperties() throws Exception { + final JavascriptClientCodegen codegen = new JavascriptClientCodegen(); + codegen.additionalProperties().put("customProperty", "customValue"); + codegen.processOpts(); + + Assert.assertEquals(codegen.additionalProperties().get("customProperty"), "customValue"); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java index 9f8a027907a5..35a92c66c5f6 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/kotlin/spring/KotlinSpringServerCodegenTest.java @@ -25,6 +25,9 @@ import java.nio.file.Paths; import java.util.Collections; import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; import static org.openapitools.codegen.TestUtils.assertFileContains; import static org.openapitools.codegen.TestUtils.assertFileNotContains; @@ -87,14 +90,14 @@ public void testNoRequestMappingAnnotation() throws IOException { codegen.setLibrary("spring-cloud"); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/feat13488_use_kotlinSpring_with_springCloud.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/feat13488_use_kotlinSpring_with_springCloud.yaml")) + .config(codegen)) + .generate(); // Check that the @RequestMapping annotation is not generated in the Api file assertFileNotContains( - Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1Api.kt"), - "@RequestMapping(\"\\${api.base-path" + Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1Api.kt"), + "@RequestMapping(\"\\${api.base-path" ); } @@ -214,18 +217,18 @@ public void delegateWithTags() throws Exception { codegen.additionalProperties().put(KotlinSpringServerCodegen.USE_TAGS, true); List files = new DefaultGenerator() - .opts( - new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue5497-use-tags-kotlin.yaml")) - .config(codegen) - ) - .generate(); + .opts( + new ClientOptInput() + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue5497-use-tags-kotlin.yaml")) + .config(codegen) + ) + .generate(); Helpers.assertContainsAllOf(files, - new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiController.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiController.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt") + new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiController.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiController.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt") ); } @@ -239,51 +242,51 @@ public void delegateReactiveWithTags() throws Exception { codegen.additionalProperties().put(KotlinSpringServerCodegen.USE_TAGS, true); List files = new DefaultGenerator() - .opts( - new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue7325-use-delegate-reactive-tags-kotlin.yaml")) - .config(codegen) - ) - .generate(); + .opts( + new ClientOptInput() + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue7325-use-delegate-reactive-tags-kotlin.yaml")) + .config(codegen) + ) + .generate(); Helpers.assertContainsAllOf(files, - new File(output, "src/main/kotlin/org/openapitools/api/TestV1Api.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiController.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV2Api.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiController.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV3Api.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV3ApiController.kt"), - new File(output, "src/main/kotlin/org/openapitools/api/TestV3ApiDelegate.kt") + new File(output, "src/main/kotlin/org/openapitools/api/TestV1Api.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiController.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV2Api.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiController.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV3Api.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV3ApiController.kt"), + new File(output, "src/main/kotlin/org/openapitools/api/TestV3ApiDelegate.kt") ); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1Api.kt"), - "suspend fun"); + "suspend fun"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1Api.kt"), - "exchange"); + "exchange"); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), - "suspend fun"); + "suspend fun"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV1ApiDelegate.kt"), - "ApiUtil"); + "ApiUtil"); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV2Api.kt"), - "import kotlinx.coroutines.flow.Flow", "ResponseEntity>"); + "import kotlinx.coroutines.flow.Flow", "ResponseEntity>"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV2Api.kt"), - "exchange"); + "exchange"); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt"), - "import kotlinx.coroutines.flow.Flow", "ResponseEntity>"); + "import kotlinx.coroutines.flow.Flow", "ResponseEntity>"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV2ApiDelegate.kt"), - "suspend fun", "ApiUtil"); + "suspend fun", "ApiUtil"); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV3Api.kt"), - "import kotlinx.coroutines.flow.Flow", "requestBody: Flow"); + "import kotlinx.coroutines.flow.Flow", "requestBody: Flow"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV3Api.kt"), - "exchange"); + "exchange"); assertFileContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV3ApiDelegate.kt"), - "import kotlinx.coroutines.flow.Flow", "suspend fun", "requestBody: Flow"); + "import kotlinx.coroutines.flow.Flow", "suspend fun", "requestBody: Flow"); assertFileNotContains(Paths.get(output + "/src/main/kotlin/org/openapitools/api/TestV3ApiDelegate.kt"), - "ApiUtil"); + "ApiUtil"); } @Test @@ -293,7 +296,7 @@ public void doNotGenerateRequestParamForObjectQueryParam() throws IOException { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/objectQueryParam.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/objectQueryParam.yaml", null, new ParseOptions()).getOpenAPI(); KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -323,7 +326,7 @@ public void doGenerateRequestParamForSimpleParam() throws IOException { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/issue_3248.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/issue_3248.yaml", null, new ParseOptions()).getOpenAPI(); KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -360,7 +363,7 @@ public void generateFormatForDateAndDateTimeQueryParam() throws IOException { String outputPath = output.getAbsolutePath().replace('\\', '/'); OpenAPI openAPI = new OpenAPIParser() - .readLocation("src/test/resources/3_0/issue_2053.yaml", null, new ParseOptions()).getOpenAPI(); + .readLocation("src/test/resources/3_0/issue_2053.yaml", null, new ParseOptions()).getOpenAPI(); KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); codegen.setOutputDir(output.getAbsolutePath()); @@ -380,12 +383,12 @@ public void generateFormatForDateAndDateTimeQueryParam() throws IOException { generator.opts(input).generate(); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ElephantsApiController.kt"), - "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ElephantsApiController.kt"), + "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE)" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ZebrasApiController.kt"), - "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ZebrasApiController.kt"), + "@org.springframework.format.annotation.DateTimeFormat(iso = org.springframework.format.annotation.DateTimeFormat.ISO.DATE_TIME)" ); } @@ -400,13 +403,13 @@ public void beanQualifiers() throws Exception { codegen.additionalProperties().put(KotlinSpringServerCodegen.BEAN_QUALIFIERS, true); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/bean-qualifiers.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/bean-qualifiers.yaml")) + .config(codegen)) + .generate(); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApiController.kt"), - "@RestController(\"org.openapitools.api.PingApiController\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApiController.kt"), + "@RestController(\"org.openapitools.api.PingApiController\")" ); } @@ -422,13 +425,13 @@ public void skipDefaultInterface() throws Exception { codegen.additionalProperties().put(KotlinSpringServerCodegen.SKIP_DEFAULT_INTERFACE, true); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/skip-default-interface.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/skip-default-interface.yaml")) + .config(codegen)) + .generate(); assertFileNotContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApi.kt"), - "return " + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApi.kt"), + "return " ); } @@ -443,21 +446,21 @@ public void useSpringBoot3() throws Exception { codegen.additionalProperties().put(KotlinSpringServerCodegen.USE_SPRING_BOOT3, true); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/feat13578_use_springboot3_jakarta_extension.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/feat13578_use_springboot3_jakarta_extension.yaml")) + .config(codegen)) + .generate(); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ApiUtil.kt"), - "import jakarta.servlet.http.HttpServletResponse" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/ApiUtil.kt"), + "import jakarta.servlet.http.HttpServletResponse" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/Exceptions.kt"), - "import jakarta.validation.ConstraintViolationException" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/Exceptions.kt"), + "import jakarta.validation.ConstraintViolationException" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApiController.kt"), - "import jakarta.validation.Valid" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/api/PingApiController.kt"), + "import jakarta.validation.Valid" ); } @@ -515,25 +518,25 @@ public void useTargetOnInterfaceAnnotations() throws IOException { codegen.setOutputDir(output.getAbsolutePath()); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue3596-use-correct-get-annotation-target.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue3596-use-correct-get-annotation-target.yaml")) + .config(codegen)) + .generate(); assertFileNotContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@Schema(example = \"null\", description = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@Schema(example = \"null\", description = \"\")" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@get:Schema(example = \"null\", description = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@get:Schema(example = \"null\", description = \"\")" ); assertFileNotContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@Schema(example = \"null\", requiredMode = Schema.RequiredMode.REQUIRED, description = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@Schema(example = \"null\", requiredMode = Schema.RequiredMode.REQUIRED, description = \"\")" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@get:Schema(example = \"null\", requiredMode = Schema.RequiredMode.REQUIRED, description = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@get:Schema(example = \"null\", requiredMode = Schema.RequiredMode.REQUIRED, description = \"\")" ); } @@ -549,25 +552,53 @@ public void useTargetOnInterfaceAnnotationsWithSwagger1() throws IOException { codegen.additionalProperties().put(DOCUMENTATION_PROVIDER, DocumentationProvider.SPRINGFOX.toCliOptValue()); new DefaultGenerator().opts(new ClientOptInput() - .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue3596-use-correct-get-annotation-target.yaml")) - .config(codegen)) - .generate(); + .openAPI(TestUtils.parseSpec("src/test/resources/3_0/kotlin/issue3596-use-correct-get-annotation-target.yaml")) + .config(codegen)) + .generate(); assertFileNotContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@ApiModelProperty(example = \"null\", value = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@ApiModelProperty(example = \"null\", value = \"\")" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@get:ApiModelProperty(example = \"null\", value = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@get:ApiModelProperty(example = \"null\", value = \"\")" ); assertFileNotContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@ApiModelProperty(example = \"null\", required = true, value = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@ApiModelProperty(example = \"null\", required = true, value = \"\")" ); assertFileContains( - Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), - "@get:ApiModelProperty(example = \"null\", required = true, value = \"\")" + Paths.get(outputPath + "/src/main/kotlin/org/openapitools/model/Animal.kt"), + "@get:ApiModelProperty(example = \"null\", required = true, value = \"\")" + ); + } + + @Test + public void useBeanValidationGenerateAnnotationsForRequestBody() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + + OpenAPI openAPI = new OpenAPIParser() + .readLocation("src/test/resources/bugs/issue_13932.yml", null, new ParseOptions()).getOpenAPI(); + KotlinSpringServerCodegen codegen = new KotlinSpringServerCodegen(); + codegen.setOutputDir(output.getAbsolutePath()); + codegen.additionalProperties().put(KotlinSpringServerCodegen.INTERFACE_ONLY, "true"); + codegen.additionalProperties().put(KotlinSpringServerCodegen.USE_BEANVALIDATION, "true"); + codegen.additionalProperties().put(CodegenConstants.MODEL_PACKAGE, "xyz.model"); + codegen.additionalProperties().put(CodegenConstants.API_PACKAGE, "xyz.controller"); + + ClientOptInput input = new ClientOptInput() + .openAPI(openAPI) + .config(codegen); + + DefaultGenerator generator = new DefaultGenerator(); + Map files = generator.opts(input).generate().stream() + .collect(Collectors.toMap(File::getName, Function.identity())); + + assertFileContains( + Paths.get(files.get("AddApi.kt").getAbsolutePath()), + "@Min(2)" ); } -} +} \ No newline at end of file diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java index ef8fa66558b9..830fd29a6c54 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/GoClientOptionsProvider.java @@ -36,6 +36,8 @@ public class GoClientOptionsProvider implements OptionsProvider { public static final boolean GENERATE_INTERFACES_VALUE = true; public static final boolean DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT_VALUE = true; public static final boolean USE_ONE_OF_DISCRIMINATOR_LOOKUP_VALUE = true; + public static final boolean WITH_GO_MOD_VALUE = true; + public static final boolean GENERATE_MARSHAL_JSON_VALUE = true; @Override public String getLanguage() { @@ -56,6 +58,8 @@ public Map createOptions() { .put(CodegenConstants.WITH_AWSV4_SIGNATURE_COMMENT, "true") .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") .put(CodegenConstants.USE_ONEOF_DISCRIMINATOR_LOOKUP, "true") + .put(CodegenConstants.WITH_GO_MOD, "true") + .put(CodegenConstants.GENERATE_MARSHAL_JSON, "true") .put("generateInterfaces", "true") .put("structPrefix", "true") .build(); diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java index 45a656dd3c3a..4578b058af70 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/RubyClientOptionsProvider.java @@ -36,6 +36,7 @@ public class RubyClientOptionsProvider implements OptionsProvider { public static final String GEM_SUMMARY_VALUE = "summary"; public static final String GEM_DESCRIPTION_VALUE = "description"; public static final String GEM_AUTHOR_VALUE = "foo"; + public static final String GEM_METADATA_VALUE = "{}"; public static final String GEM_AUTHOR_EMAIL_VALUE = "foo"; public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; @@ -61,6 +62,7 @@ public Map createOptions() { .put(RubyClientCodegen.GEM_SUMMARY, GEM_SUMMARY_VALUE) .put(RubyClientCodegen.GEM_AUTHOR, GEM_AUTHOR_VALUE) .put(RubyClientCodegen.GEM_AUTHOR_EMAIL, GEM_AUTHOR_EMAIL_VALUE) + .put(RubyClientCodegen.GEM_METADATA, GEM_METADATA_VALUE) .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaPekkoClientOptionsProvider.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaPekkoClientOptionsProvider.java new file mode 100644 index 000000000000..b04087101c0f --- /dev/null +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/options/ScalaPekkoClientOptionsProvider.java @@ -0,0 +1,69 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * Copyright 2018 SmartBear Software + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.codegen.options; + +import com.google.common.collect.ImmutableMap; +import org.openapitools.codegen.CodegenConstants; + +import java.util.Map; + +public class ScalaPekkoClientOptionsProvider implements OptionsProvider { + public static final String SOURCE_FOLDER_VALUE = "sourceFolder"; + public static final String MODEL_PACKAGE_VALUE = "package"; + public static final String API_PACKAGE_VALUE = "apiPackage"; + public static final String SORT_PARAMS_VALUE = "false"; + public static final String SORT_MODEL_PROPERTIES_VALUE = "false"; + public static final String ENSURE_UNIQUE_PARAMS_VALUE = "true"; + public static final String ALLOW_UNICODE_IDENTIFIERS_VALUE = "false"; + public static final String PREPEND_FORM_OR_BODY_PARAMETERS_VALUE = "true"; + public static final String MAIN_PACKAGE_VALUE = "net.test"; + public static final String MODEL_PROPERTY_NAMING = "camelCase"; + public static final String DATE_LIBRARY = "joda"; + public static final String ENUM_UNKNOWN_DEFAULT_CASE_VALUE = "false"; + + + @Override + public String getLanguage() { + return "scala-pekko"; + } + + @Override + public Map createOptions() { + ImmutableMap.Builder builder = new ImmutableMap.Builder(); + return builder.put(CodegenConstants.MODEL_PACKAGE, MODEL_PACKAGE_VALUE) + .put(CodegenConstants.API_PACKAGE, API_PACKAGE_VALUE) + .put(CodegenConstants.SORT_PARAMS_BY_REQUIRED_FLAG, SORT_PARAMS_VALUE) + .put(CodegenConstants.SORT_MODEL_PROPERTIES_BY_REQUIRED_FLAG, SORT_MODEL_PROPERTIES_VALUE) + .put(CodegenConstants.ENSURE_UNIQUE_PARAMS, ENSURE_UNIQUE_PARAMS_VALUE) + .put(CodegenConstants.SOURCE_FOLDER, SOURCE_FOLDER_VALUE) + .put(CodegenConstants.ALLOW_UNICODE_IDENTIFIERS, ALLOW_UNICODE_IDENTIFIERS_VALUE) + .put(CodegenConstants.PREPEND_FORM_OR_BODY_PARAMETERS, PREPEND_FORM_OR_BODY_PARAMETERS_VALUE) + .put("mainPackage", MAIN_PACKAGE_VALUE) + .put(CodegenConstants.MODEL_PROPERTY_NAMING, MODEL_PROPERTY_NAMING) + .put("dateLibrary", DATE_LIBRARY) + .put(CodegenConstants.LEGACY_DISCRIMINATOR_BEHAVIOR, "true") + .put(CodegenConstants.DISALLOW_ADDITIONAL_PROPERTIES_IF_NOT_PRESENT, "true") + .put(CodegenConstants.ENUM_UNKNOWN_DEFAULT_CASE, ENUM_UNKNOWN_DEFAULT_CASE_VALUE) + .build(); + } + + @Override + public boolean isServer() { + return false; + } +} diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/postman/PostmanCollectionCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/postman/PostmanCollectionCodegenTest.java index aa92b6a095fa..ba52c236057a 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/postman/PostmanCollectionCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/postman/PostmanCollectionCodegenTest.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.ObjectNode; +import io.swagger.v3.oas.models.tags.Tag; import org.junit.Assert; import org.junit.Test; import org.openapitools.codegen.*; @@ -16,6 +17,8 @@ import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashMap; import java.util.List; @@ -73,6 +76,8 @@ public void testBasicGeneration() throws IOException { // verify request name (from summary) assertFileContains(path, "\"name\": \"Get User\""); + // verify request endpoint + TestUtils.assertFileContains(path, "\"name\": \"/users/:userId\""); } @@ -155,6 +160,11 @@ public void testVariables() throws Exception { TestUtils.assertFileContains(path, "key\": \"groupId\", \"value\": \"1\", \"type\": \"number\""); + // verify request endpoint + TestUtils.assertFileContains(path, "\"name\": \"/users/:userId\""); + // verify path parameter value + TestUtils.assertFileContains(path, "key\": \"userId\", \"value\": \"{{userId}}\","); + } @Test @@ -187,6 +197,11 @@ public void testVariablesInRequestExample() throws Exception { assertFileContains(path, "{{MY_VAR_NAME}}"); + // verify request endpoint + TestUtils.assertFileContains(path, "\"name\": \"/users/:userId\""); + // verify path parameter value + TestUtils.assertFileContains(path, "key\": \"userId\", \"value\": \"{{userId}}\","); + } @Test @@ -292,7 +307,10 @@ public void testNamingRequestsWithUrl() throws Exception { Path path = Paths.get(output + "/postman.json"); assertFileExists(path); // verify request name (from path) - assertFileContains(path, "\"name\": \"/users/{{userId}}\""); + assertFileContains(path, "\"name\": \"/users/:userId\""); + // verify path parameter value + TestUtils.assertFileContains(path, "key\": \"userId\", \"value\": \"{{userId}}\","); + } @Test @@ -346,20 +364,6 @@ public void testSecuritySchemes() throws Exception { assertFileNotContains(path, "\"auth\": { \"type\": \"apikey\", \"apikey\": ["); } - @Test - public void doubleCurlyBraces() { - String str = "/api/{var}/archive"; - - assertEquals("/api/{{var}}/archive", new PostmanCollectionCodegen().doubleCurlyBraces(str)); - } - - @Test - public void doubleCurlyBracesNoChanges() { - String str = "/api/{{var}}/archive"; - - assertEquals("/api/{{var}}/archive", new PostmanCollectionCodegen().doubleCurlyBraces(str)); - } - @Test public void extractExampleByName() { String str = "#/components/examples/get-user-basic"; @@ -398,29 +402,6 @@ public void testJsonExampleIncludingValueWithCommas() throws Exception { assertFileContains(path, "\\\"acceptHeader\\\" : \\\"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8\\\""); } - @Test - public void testDeprecatedEndpoint() throws Exception { - - File output = Files.createTempDirectory("postmantest_").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("postman-collection") - .setInputSpec("src/test/resources/3_0/postman-collection/SampleProject.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(configurator.toClientOptInput()).generate(); - - System.out.println(files); - files.forEach(File::deleteOnExit); - - Path path = Paths.get(output + "/postman.json"); - assertFileExists(path); - // verify request name (from path) - assertFileContains(path, "(DEPRECATED)"); - } - @Test public void testGeneratedVariables() throws Exception { @@ -475,36 +456,6 @@ public void testSkipGeneratedVariables() throws IOException, Exception { } - @Test - public void testHeaderParameters() throws IOException { - - File output = Files.createTempDirectory("postmantest_").toFile(); - output.deleteOnExit(); - - final CodegenConfigurator configurator = new CodegenConfigurator() - .setGeneratorName("postman-collection") - .setInputSpec("./src/test/resources/SampleProject.yaml") - .setInputSpec("src/test/resources/3_0/postman-collection/SampleProject.yaml") - .setOutputDir(output.getAbsolutePath().replace("\\", "/")); - - final ClientOptInput clientOptInput = configurator.toClientOptInput(); - DefaultGenerator generator = new DefaultGenerator(); - List files = generator.opts(clientOptInput).generate(); - - files.forEach(File::deleteOnExit); - - Path path = Paths.get(output + "/postman.json"); - TestUtils.assertFileExists(path); - TestUtils.assertFileContains(path, "{ \"key\": \"Content-Type\", \"value\": \"application/json\""); - TestUtils.assertFileContains(path, "{ \"key\": \"Accept\", \"value\": \"application/json\""); - // header without default value (disabled: true) - TestUtils.assertFileContains(path, "{ \"key\": \"Custom-Header\", \"value\": \"\", \"disabled\": true"); - // header with default value (disabled: false) - TestUtils.assertFileContains(path, "{ \"key\": \"Another-Custom-Header\", \"value\": \"abc\", \"disabled\": false"); - - } - - @Test public void testFormatDescription() { @@ -682,4 +633,73 @@ public void convertNestedLinkedHashMapToJson() { } + @Test + public void testAddToList() { + + PostmanCollectionCodegen postmanCollectionCodegen = new PostmanCollectionCodegen(); + + CodegenOperation operationUsers = new CodegenOperation(); + operationUsers.path = "/users"; + postmanCollectionCodegen.addToList(operationUsers); + + CodegenOperation operationGroups = new CodegenOperation(); + operationGroups.path = "/groups"; + postmanCollectionCodegen.addToList(operationGroups); + + CodegenOperation operationUserId = new CodegenOperation(); + operationUserId.path = "/users/{id}"; + postmanCollectionCodegen.addToList(operationUserId); + + assertEquals(3, postmanCollectionCodegen.codegenOperationsList.size()); + // verify order + assertEquals("/groups", postmanCollectionCodegen.codegenOperationsList.get(0).path); + assertEquals("/users", postmanCollectionCodegen.codegenOperationsList.get(1).path); + assertEquals("/users/{id}", postmanCollectionCodegen.codegenOperationsList.get(2).path); + } + + @Test + public void testAddToMap() { + + PostmanCollectionCodegen postmanV2Generator = new PostmanCollectionCodegen(); + + CodegenOperation operationUsers = new CodegenOperation(); + operationUsers.path = "/users"; + operationUsers.tags = new ArrayList<>(Arrays.asList(new Tag().name("basic"))); + postmanV2Generator.addToMap(operationUsers); + + CodegenOperation operationGroups = new CodegenOperation(); + operationGroups.path = "/groups"; + operationGroups.tags = new ArrayList<>(Arrays.asList(new Tag().name("basic"))); + postmanV2Generator.addToMap(operationGroups); + + CodegenOperation operationUserId = new CodegenOperation(); + operationUserId.path = "/users/{id}"; + operationUserId.tags = new ArrayList<>(Arrays.asList(new Tag().name("basic"))); + postmanV2Generator.addToMap(operationUserId); + + // verify tag 'basic' + assertEquals(1, postmanV2Generator.codegenOperationsByTag.size()); + assertEquals(true, postmanV2Generator.codegenOperationsByTag.containsKey("basic")); + + List operations = postmanV2Generator.codegenOperationsByTag.get("basic"); + // verify order + assertEquals("/groups", operations.get(0).path); + assertEquals("/users", operations.get(1).path); + assertEquals("/users/{id}", operations.get(2).path); + } + + @Test + public void testAddToMapUsingDefaultTag() { + + PostmanCollectionCodegen postmanV2Generator = new PostmanCollectionCodegen(); + + CodegenOperation operationUsers = new CodegenOperation(); + operationUsers.path = "/users"; + postmanV2Generator.addToMap(operationUsers); + + // verify tag 'default' is used + assertEquals(1, postmanV2Generator.codegenOperationsByTag.size()); + assertEquals(true, postmanV2Generator.codegenOperationsByTag.containsKey("default")); + } + } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java index b0554c1ae856..63b3d0f6016f 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/python/PythonClientCodegenTest.java @@ -17,6 +17,7 @@ package org.openapitools.codegen.python; +import static org.junit.Assert.assertNotNull; import com.google.common.collect.Sets; import io.swagger.parser.OpenAPIParser; import io.swagger.v3.oas.models.OpenAPI; @@ -30,6 +31,7 @@ import static org.openapitools.codegen.TestUtils.assertFileContains; import static org.openapitools.codegen.TestUtils.assertFileExists; import org.openapitools.codegen.TestUtils; +import org.openapitools.codegen.java.assertions.JavaFileAssert; import org.testng.Assert; import org.testng.annotations.Test; import java.io.File; @@ -40,6 +42,9 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; public class PythonClientCodegenTest { @@ -501,4 +506,28 @@ public void modelTestDollarSign() { CodegenProperty property = vars.get(0); Assert.assertEquals(property.name, "dollar_value"); } + + @Test + public void testHandleConstantParams() throws IOException { + File output = Files.createTempDirectory("test").toFile().getCanonicalFile(); + output.deleteOnExit(); + final OpenAPI openAPI = TestUtils.parseFlattenSpec("src/test/resources/3_0/java/autoset_constant.yaml"); + final DefaultGenerator defaultGenerator = new DefaultGenerator(); + final ClientOptInput clientOptInput = new ClientOptInput(); + clientOptInput.openAPI(openAPI); + PythonClientCodegen pythonClientCodegen = new PythonClientCodegen(); + pythonClientCodegen.setOutputDir(output.getAbsolutePath()); + pythonClientCodegen.additionalProperties().put(CodegenConstants.AUTOSET_CONSTANTS, "true"); + pythonClientCodegen.setAutosetConstants(true); + clientOptInput.config(pythonClientCodegen); + defaultGenerator.opts(clientOptInput); + + Map files = defaultGenerator.generate().stream() + .collect(Collectors.toMap(File::getPath, Function.identity())); + + File apiFile = files + .get(Paths.get(output.getAbsolutePath(), "openapi_client", "api", "hello_example_api.py").toString()); + assertNotNull(apiFile); + assertFileContains(apiFile.toPath(), "_header_params['X-CUSTOM_CONSTANT_HEADER'] = 'CONSTANT_VALUE'"); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java index 7f600322de6c..0fe6656cce9e 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/ruby/RubyClientOptionsTest.java @@ -50,6 +50,7 @@ protected void verifyOptions() { verify(clientCodegen).setGemSummary(RubyClientOptionsProvider.GEM_SUMMARY_VALUE); verify(clientCodegen).setGemAuthor(RubyClientOptionsProvider.GEM_AUTHOR_VALUE); verify(clientCodegen).setGemAuthorEmail(RubyClientOptionsProvider.GEM_AUTHOR_EMAIL_VALUE); + verify(clientCodegen).setGemMetadata(RubyClientOptionsProvider.GEM_METADATA_VALUE); verify(clientCodegen).setEnumUnknownDefaultCase(Boolean.parseBoolean(RubyClientOptionsProvider.ENUM_UNKNOWN_DEFAULT_CASE_VALUE)); verify(clientCodegen).setUseAutoload(Boolean.parseBoolean(RubyClientOptionsProvider.USE_AUTOLOAD_VALUE)); } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/templating/mustache/IndentedLambdaTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/templating/mustache/IndentedLambdaTest.java index b88530344558..739d632daac5 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/templating/mustache/IndentedLambdaTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/templating/mustache/IndentedLambdaTest.java @@ -1,9 +1,13 @@ package org.openapitools.codegen.templating.mustache; +import static org.junit.Assert.assertEquals; + import java.util.Map; import org.testng.annotations.Test; +import com.samskivert.mustache.Mustache; + public class IndentedLambdaTest extends LambdaTest { String lineSeparator = "\n"; @@ -30,5 +34,13 @@ public void indentedCountTest() { "{{#indented}}first line" + lineSeparator + "second line{{/indented}}", ctx); } + @Test + public void lineBreaksPreservedTest() { + Map ctx = context("indented", new IndentedLambda(4, " ", true, true)); + String actual = execute(Mustache.compiler(), "{{#indented}}first line\nsecond line\n\nthird line\n\n\nfourth line\n\n{{/indented}}", ctx); + String expected = " first line\n second line\n\n third line\n\n\n fourth line\n\n"; + + assertEquals(expected, actual); + } } diff --git a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/URLPathUtilsTest.java b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/URLPathUtilsTest.java index f4fa3d68f6df..4242b3464078 100644 --- a/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/URLPathUtilsTest.java +++ b/modules/openapi-generator/src/test/java/org/openapitools/codegen/utils/URLPathUtilsTest.java @@ -111,8 +111,8 @@ public void testGetServerURLWithVariables() { Server s9 = new Server().url("https://{user}.example.com/{version}").variables( new ServerVariables().addServerVariable("version", new ServerVariable()._default("v1")) - .addServerVariable("user", new ServerVariable()._default("{user}"))); - Assert.assertEquals(URLPathUtils.getServerURL(s9, null).toString(), "https://{user}.example.com/v1"); + .addServerVariable("user", new ServerVariable()._default("another-user"))); + Assert.assertEquals(URLPathUtils.getServerURL(s9, null).toString(), "https://another-user.example.com/v1"); } private ServerVariables serverVariables(String... entries) { diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache index 5d45861acd8f..d50298967186 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/ApiClient.mustache @@ -551,7 +551,7 @@ public class ApiClient{{#jsr310}} extends JavaTimeFormatter{{/jsr310}} { List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) { + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache index 3297c77e49b2..021efbaeb5b5 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/JSON.mustache @@ -5,6 +5,7 @@ import org.threeten.bp.*; {{/threetenbp}} import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; {{#openApiNullable}} import org.openapitools.jackson.nullable.JsonNullableModule; {{/openApiNullable}} @@ -34,15 +35,16 @@ public class JSON implements ContextResolver { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .build(); {{#java8}} mapper.registerModule(new JavaTimeModule()); {{/java8}} diff --git a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache index 790aa68dbf3b..39ef67df983c 100644 --- a/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache +++ b/modules/openapi-generator/src/test/resources/2_0/templates/Java/libraries/jersey2/pom.mustache @@ -386,7 +386,7 @@ 1.3.5 {{/useJakartaEe}} {{#useBeanValidation}} - 2.0.2 + 2.0.2 {{/useBeanValidation}} 4.13.2 {{#hasHttpSignatureMethods}} diff --git a/modules/openapi-generator/src/test/resources/3_0/ada/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/ada/petstore.yaml index 3137152533ad..7e7b74ba4189 100644 --- a/modules/openapi-generator/src/test/resources/3_0/ada/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/ada/petstore.yaml @@ -784,3 +784,13 @@ components: type: string type_: type: string + AnotherStatus: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + + diff --git a/modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml b/modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml index a45d9d1cc2e5..873cc7a3788f 100644 --- a/modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/allOf_extension_parent.yaml @@ -96,4 +96,9 @@ components: mum_or_dad: type: string required: - - isParent \ No newline at end of file + - isParent + allOfWithSingleItem: + description: allOf with a single item + nullable: true + allOf: + - $ref: '#/components/schemas/AnotherParent' \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/allof_primitive.yaml b/modules/openapi-generator/src/test/resources/3_0/allof_primitive.yaml new file mode 100644 index 000000000000..849bbbf103ba --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/allof_primitive.yaml @@ -0,0 +1,36 @@ +openapi: 3.0.0 +info: + title: Foo + version: 1.0.0 +paths: + /foo: + get: + responses: + '200': + description: example + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Payment' +components: + schemas: + DateTime: + type: string + format: date-time + example: "2019-01-01T00:00:00" + # the following schema shouldn't be generated as model + AllOfDatetime: + allOf: + - $ref: '#/components/schemas/DateTime' + example: "2019-01-01 00:00:00" + Payment: + type: object + properties: + date: + $ref: '#/components/schemas/AllOfDatetime' + amount: + type: number + format: float + example: 625.0 \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/csharp-netcore/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/csharp-netcore/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 6d3946023a85..fba2c981d82c 100644 --- a/modules/openapi-generator/src/test/resources/3_0/csharp-netcore/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/csharp-netcore/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -961,6 +961,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1790,6 +1807,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/csharp/dates-api.yaml b/modules/openapi-generator/src/test/resources/3_0/csharp/dates-api.yaml new file mode 100644 index 000000000000..34fd6fa65d71 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/csharp/dates-api.yaml @@ -0,0 +1,25 @@ +openapi: 3.0.0 +info: + title: OpenAPI Dates + version: 1.0.0 + description: Thic spec contains endpoints with dates in different formats + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +paths: + /now: + get: + responses: + '200': + description: now dates + content: + application/json: + schema: + type: object + properties: + today: + type: string + format: date + now: + type: string + format: date-time diff --git a/modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 2fab0cbf5941..a238bd85bb29 100644 --- a/modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/csharp/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -213,6 +213,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] post: tags: - pet @@ -474,6 +475,13 @@ paths: '200': description: successful operation headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly X-Rate-Limit: description: calls per hour allowed by the user schema: @@ -531,6 +539,14 @@ paths: description: Invalid username supplied '404': description: User not found + '598': + description: Not a real HTTP status code + '599': + description: Not a real HTTP status code with a return object + content: + application/json: + schema: + $ref: '#/components/schemas/User' put: tags: - user @@ -958,6 +974,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1905,6 +1938,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string @@ -1983,6 +2020,266 @@ components: nullable: true type: string description: Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + RequiredClass: + type: object + properties: + required_nullable_integer_prop: + type: integer + nullable: true + required_notnullableinteger_prop: + type: integer + nullable: false + not_required_nullable_integer_prop: + type: integer + nullable: true + not_required_notnullableinteger_prop: + type: integer + nullable: false + + required_nullable_string_prop: + type: string + nullable: true + required_notnullable_string_prop: + type: string + nullable: false + notrequired_nullable_string_prop: + type: string + nullable: true + notrequired_notnullable_string_prop: + type: string + nullable: false + + required_nullable_boolean_prop: + type: boolean + nullable: true + required_notnullable_boolean_prop: + type: boolean + nullable: false + notrequired_nullable_boolean_prop: + type: boolean + nullable: true + notrequired_notnullable_boolean_prop: + type: boolean + nullable: false + + required_nullable_date_prop: + type: string + format: date + nullable: true + required_not_nullable_date_prop: + type: string + format: date + nullable: false + not_required_nullable_date_prop: + type: string + format: date + nullable: true + not_required_notnullable_date_prop: + type: string + format: date + nullable: false + + required_notnullable_datetime_prop: + type: string + format: date-time + nullable: false + required_nullable_datetime_prop: + type: string + format: date-time + nullable: true + notrequired_nullable_datetime_prop: + type: string + format: date-time + nullable: true + notrequired_notnullable_datetime_prop: + type: string + format: date-time + nullable: false + + required_nullable_enum_integer: + type: integer + format: int32 + nullable: true + enum: + - 1 + - -1 + required_notnullable_enum_integer: + type: integer + format: int32 + nullable: false + enum: + - 1 + - -1 + notrequired_nullable_enum_integer: + type: integer + format: int32 + nullable: true + enum: + - 1 + - -1 + notrequired_notnullable_enum_integer: + type: integer + format: int32 + nullable: false + enum: + - 1 + - -1 + + required_nullable_enum_integer_only: + type: integer + nullable: true + enum: + - 2 + - -2 + required_notnullable_enum_integer_only: + type: integer + nullable: false + enum: + - 2 + - -2 + notrequired_nullable_enum_integer_only: + type: integer + nullable: true + enum: + - 2 + - -2 + notrequired_notnullable_enum_integer_only: + type: integer + nullable: false + enum: + - 2 + - -2 + + required_notnullable_enum_string: + type: string + nullable: false + enum: + - UPPER + - lower + - '' + - "Value\twith tab" + - 'Value with " quote' + - 'Value with escaped \" quote' + - "Duplicate\nvalue" + - "Duplicate\r\nvalue" + required_nullable_enum_string: + type: string + nullable: true + enum: + - UPPER + - lower + - '' + - "Value\twith tab" + - 'Value with " quote' + - 'Value with escaped \" quote' + - "Duplicate\nvalue" + - "Duplicate\r\nvalue" + notrequired_nullable_enum_string: + type: string + nullable: true + enum: + - UPPER + - lower + - '' + - "Value\twith tab" + - 'Value with " quote' + - 'Value with escaped \" quote' + - "Duplicate\nvalue" + - "Duplicate\r\nvalue" + notrequired_notnullable_enum_string: + type: string + nullable: false + enum: + - UPPER + - lower + - '' + - "Value\twith tab" + - 'Value with " quote' + - 'Value with escaped \" quote' + - "Duplicate\nvalue" + - "Duplicate\r\nvalue" + + required_nullable_outerEnumDefaultValue: + nullable: true + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + required_notnullable_outerEnumDefaultValue: + nullable: false + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + notrequired_nullable_outerEnumDefaultValue: + nullable: true + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + notrequired_notnullable_outerEnumDefaultValue: + nullable: false + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + + required_nullable_uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + nullable: true + required_notnullable_uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + nullable: false + notrequired_nullable_uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + nullable: true + notrequired_notnullable_uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + nullable: false + + required_nullable_array_of_string: + type: array + nullable: true + items: + type: string + required_notnullable_array_of_string: + type: array + nullable: false + items: + type: string + notrequired_nullable_array_of_string: + type: array + nullable: true + items: + type: string + notrequired_notnullable_array_of_string: + type: array + nullable: false + items: + type: string + required: + - required_nullable_boolean_prop + - required_notnullable_boolean_prop + - required_nullable_string_prop + - required_notnullable_string_prop + - required_nullable_integer_prop + - required_notnullableinteger_prop + - required_nullable_date_prop + - required_not_nullable_date_prop + - required_notnullable_datetime_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_notnullable_enum_integer + - required_nullable_enum_integer_only + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_nullable_enum_string + - required_nullable_outerEnumDefaultValue + - required_notnullable_outerEnumDefaultValue + - required_nullable_uuid + - required_notnullable_uuid + - required_nullable_array_of_string + - required_notnullable_array_of_string NullableClass: type: object properties: @@ -2289,6 +2586,8 @@ components: enum: - ChildCat default: ChildCat + required: + - pet_type ArrayOfEnums: type: array items: diff --git a/modules/openapi-generator/src/test/resources/3_0/echo_api.yaml b/modules/openapi-generator/src/test/resources/3_0/echo_api.yaml index 9d9bbf3e85f1..e43c37e23871 100644 --- a/modules/openapi-generator/src/test/resources/3_0/echo_api.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/echo_api.yaml @@ -430,6 +430,22 @@ paths: application/json: schema: $ref: '#/components/schemas/Pet' + /echo/body/allOf/Pet: + post: + tags: + - body + summary: Test body parameter(s) + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + '200': + description: Successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' /echo/body/Pet/response_string: post: tags: @@ -497,6 +513,30 @@ paths: schema: type: string format: binary + # Single binary in multipart mime test + /body/application/octetstream/single_binary: + post: + tags: + - body + summary: Test single binary in multipart mime + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + my-file: + type: string + format: binary + responses: + '200': + description: Successful operation + content: + text/plain: + schema: + type: string # Array of binary in multipart mime tests /body/application/octetstream/array_of_binary: post: @@ -542,11 +582,31 @@ paths: text/plain: schema: type: string + # To test http bearer auth + /auth/http/bearer: + post: + tags: + - auth + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + '200': + description: Successful operation + content: + text/plain: + schema: + type: string components: securitySchemes: http_auth: type: http scheme: basic + http_bearer_auth: + type: http + scheme: bearer requestBodies: Pet: content: @@ -554,6 +614,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: diff --git a/modules/openapi-generator/src/test/resources/3_0/enum-and-inner-enum-uri.yaml b/modules/openapi-generator/src/test/resources/3_0/enum-and-inner-enum-uri.yaml new file mode 100644 index 000000000000..29bb3f4ceee6 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/enum-and-inner-enum-uri.yaml @@ -0,0 +1,38 @@ +openapi: 3.0.3 +info: + title: Example API + description: '' + version: v1 +servers: + - url: http://localhost + description: Global Endpoint +paths: + /v1/schemas: + get: + summary: Get a list of schemas + responses: + default: + description: List of schemas + content: + application/json: + schema: + type: object + properties: + data: + type: string + format: uri + default: https://example.com/v1/schema.json + enum: + - https://example.com/v1/schema.json + - https://example.com/v2/schema.json + metadata: + $ref: '#/components/schemas/Metadata' +components: + schemas: + Metadata: + type: string + format: uri + enum: + - https://example.com/v1/metadata.json + - https://example.com/v2/metadata.json + diff --git a/modules/openapi-generator/src/test/resources/3_0/example_generator_test.yaml b/modules/openapi-generator/src/test/resources/3_0/example_generator_test.yaml index c8f2187e69b7..d101a638c3eb 100644 --- a/modules/openapi-generator/src/test/resources/3_0/example_generator_test.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/example_generator_test.yaml @@ -26,6 +26,16 @@ paths: schema: type: string example: primitive type example value + /generate_from_response_schema_with_date_format: + get: + operationId: generateFromResponseSchemaWithDateFormat + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/DateSchema' /generate_from_response_schema_with_array_of_model: get: operationId: generateFromResponseSchemaWithArrayOfModel @@ -53,7 +63,7 @@ paths: example: primitive types example value /generate_from_response_schema_with_model: get: - operationId: generateFromResponseSchemaWithArrayOfPrimitiveTypes + operationId: generateFromResponseSchemaWithModel responses: '200': description: successful operation @@ -61,8 +71,48 @@ paths: application/json: schema: $ref: '#/components/schemas/ExampleSchema' + /generate_from_response_schema_with_allOf_composed_model: + get: + operationId: generateFromResponseSchemaWithAllOfModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ExampleAllOfSchema' + /generate_from_response_schema_with_anyOf_composed_model: + get: + operationId: generateFromResponseSchemaWithAnyOfModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ExampleAnyOfSchema' + /generate_from_response_schema_with_oneOf_composed_model: + get: + operationId: generateFromResponseSchemaWithOneOfModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ExampleOneOfSchema' components: schemas: + DateSchema: + type: object + properties: + date_with_example: + type: string + format: date + example: 2024-01-01 + date_without_example: + type: string + format: date StringSchema: type: string example: string schema example value @@ -72,3 +122,30 @@ components: example_schema_property: type: string example: example schema property value + ExampleAllOfSchema: + type: object + allOf: + - $ref: '#/components/schemas/ExampleSchema' + - type: object + properties: + example_schema_property_composed: + type: string + example: example schema property value composed + ExampleAnyOfSchema: + type: object + anyOf: + - $ref: '#/components/schemas/ExampleSchema' + - type: object + properties: + example_schema_property_composed: + type: string + example: example schema property value composed + ExampleOneOfSchema: + type: object + oneOf: + - $ref: '#/components/schemas/ExampleSchema' + - type: object + properties: + example_schema_property_composed: + type: string + example: example schema property value composed diff --git a/modules/openapi-generator/src/test/resources/3_0/go-server/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/go-server/petstore.yaml index fce2c52cbde4..78a7a1ec6cc5 100644 --- a/modules/openapi-generator/src/test/resources/3_0/go-server/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/go-server/petstore.yaml @@ -82,6 +82,24 @@ paths: description: Multiple status values can be provided with comma separated strings operationId: findPetsByStatus parameters: + - name: inlineEnumPath + in: path + description: Entity type + schema: + type: string + enum: + - "OPTION_1" + - "OPTION_2" + - "OPTION_3" + - name: inlineEnum + in: query + description: Entity type + schema: + type: string + enum: + - "OPTION_1" + - "OPTION_2" + - "OPTION_3" - name: status in: query description: Status values that need to be considered for filter @@ -117,6 +135,53 @@ paths: security: - petstore_auth: - 'read:pets' + /pet/searchPetWithManyFilters: + get: + tags: + - pet + summary: Search Pets by filters + description: >- + Search endpoint + operationId: searchPet + parameters: + - name: age + in: query + description: age of the pet + schema: + type: integer + format: int64 + nullable: true + - name: price + in: query + description: Price of the pet + schema: + type: number + nullable: true + - name: bornAfter + in: query + description: Find pets born after this date + style: form + explode: false + schema: + type: string + format: date-time + nullable: true + - description: Is the pet classified as old + in: query + name: old + schema: + type: boolean + nullable: true + style: form + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' /pet/findByTags: get: tags: @@ -137,6 +202,28 @@ paths: type: array items: type: string + - name: bornAfter + in: query + description: Find pets born after this date + required: true + style: form + explode: false + schema: + type: string + format: date-time + - name: bornBefore + in: query + description: Find pets born before this date + required: false + style: form + explode: false + schema: + type: string + format: date-time + - name: colour + in: query + schema: + $ref: '#/components/schemas/Colour' responses: '200': description: successful operation @@ -157,6 +244,52 @@ paths: - petstore_auth: - 'read:pets' deprecated: true + '/pet/filterPets/{gender}': + get: + tags: + - pet + summary: Finds Pets + operationId: filterPetsByCategory + parameters: + - name: gender + in: path + required: true + schema: + $ref: '#/components/schemas/Gender' + - name: species + in: query + description: Species to filter by + required: true + style: form + explode: false + schema: + $ref: '#/components/schemas/Species' + - name: notSpecies + in: query + description: Species to omit from results + required: false + style: form + explode: false + schema: + type: array + items: + $ref: '#/components/schemas/Species' + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid species value '/pet/{petId}': get: tags: @@ -282,10 +415,41 @@ paths: additionalMetadata: description: Additional data to pass to server type: string + extraOptionalMetadata: + description: More data to pass to server + type: array + items: + type: string file: description: file to upload type: string format: binary + get: + tags: + - pet + summary: Returns the image for the Pet that has been previously uploaded + description: Returns the image for the Pet that has been previously uploaded + operationId: getPetImageById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + image/jpeg: + schema: + type: string + format: binary + '400': + description: Invalid ID supplied + '404': + description: Pet not found /store/inventory: get: tags: @@ -579,6 +743,97 @@ paths: description: User not found security: - api_key: [] + '/fake/uploadImage/array of_file': + post: + tags: + - pet + summary: uploads images (array of files) + description: '' + operationId: uploadFileArrayOfFiles + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + files: + description: files to upload + type: array + items: + type: string + format: binary + /pets/boolean/parsing: + get: + tags: + - pet + summary: Get the pets by only using boolean query parameters + operationId: GetPetsUsingBooleanQueryParameters + parameters: + - in: query + name: expr + required: true + schema: + type: boolean + - in: query + name: grouping + required: false + schema: + type: boolean + - in: query + name: inactive + required: false + schema: + type: boolean + default: false + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + /pets/byTime/{createdTime}: + get: + tags: + - pet + summary: Get the pets by time + operationId: GetPetsByTime + parameters: + - in: path + name: createdTime + required: true + schema: + type: string + format: date-time + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' externalDocs: description: Find out more about Swagger url: 'http://swagger.io' @@ -810,6 +1065,26 @@ components: - sold xml: name: Pet + Species: + title: The species of a pet + type: string + enum: + - cat + - dog + - fish + - goat + - pig + Gender: + type: string + enum: + - male + - female + Colour: + type: string + nullable: true + enum: + - Blue + - White ApiResponse: title: An uploaded response description: Describes the result of uploading an image resource diff --git a/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 4c4b450e8067..bfab71284ea9 100644 --- a/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/go/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -946,6 +946,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1802,6 +1819,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/http-basic-test.yaml b/modules/openapi-generator/src/test/resources/3_0/http-basic-test.yaml new file mode 100644 index 000000000000..214092b3a9cd --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/http-basic-test.yaml @@ -0,0 +1,125 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - http_basic: [] + requestBody: + $ref: '#/components/requestBodies/Pet' + +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + securitySchemes: + http_basic: + type: http + scheme: basic + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet diff --git a/modules/openapi-generator/src/test/resources/3_0/issue-17367.yaml b/modules/openapi-generator/src/test/resources/3_0/issue-17367.yaml new file mode 100644 index 000000000000..cb3d4fd3e00f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue-17367.yaml @@ -0,0 +1,24 @@ +openapi: 3.0.0 +info: + version: 1.0.0 + title: Foo API +servers: + - url: http://127.0.0.1:8080/{basePath} + variables: + basePath: + default: v1 +paths: + /foo: + post: + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + bar: + type: string + format: binary + responses: + '200': + description: OK \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/issue-5676-enums.yaml b/modules/openapi-generator/src/test/resources/3_0/issue-5676-enums.yaml index 68746de926e5..901e159eef42 100644 --- a/modules/openapi-generator/src/test/resources/3_0/issue-5676-enums.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/issue-5676-enums.yaml @@ -218,4 +218,5 @@ components: allof-number-enum: allOf: - $ref: "#/components/schemas/NumberEnum" + deprecated: true diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_14765.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_14765.yaml new file mode 100644 index 000000000000..cb1cfb180b9f --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_14765.yaml @@ -0,0 +1,166 @@ +openapi: 3.0.0 +servers: + - url: 'localhost:8080' +info: + version: 1.0.0 + title: OpenAPI Zoo + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +paths: + /zebras: + get: + operationId: getZebras + responses: + '200': + description: OK + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Animal' + +components: + schemas: + Zebra: + required: + - name + - age + type: object + properties: + name: + type: string + example: 'Marty' + age: + type: integer + example: 15 + nullable: true + Animal: + required: + - name + - age + type: object + properties: + name: + type: string + example: 'Marty' + age: + type: integer + example: 15 + nullable: true + alias: + type: string + nullable: true + description: 'The stripy one' + example: 'Stripy' + color: + type: string + description: 'The color' + example: 'red' + + names: + type: array + items: + type: string + colors: + type: array + nullable: true + items: + type: string + + stringPattern: + type: string + pattern: "[a-z]" + stringMaxMinLength: + type: string + minLength: 1 + maxLength: 10 + stringMinLength: + type: string + minLength: 1 + stringMaxLength: + type: string + maxLength: 1 + stringEmail: + type: string + format: email + intMinMax: + type: integer + minimum: 1 + maximum: 10 + intMin: + type: integer + minimum: 1 + intMax: + type: integer + maximum: 10 + numberMinMax: + type: number + minimum: 1 + maximum: 10 + numberMin: + type: number + minimum: 1 + numberMax: + type: number + maximum: 10 + stringDefault: + type: string + maxLength: 1 + default: "ABC" + zebra: + $ref: '#/components/schemas/Zebra' + + stringPatternNullable: + nullable: true + type: string + pattern: "[a-z]" + stringMaxMinLengthNullable: + nullable: true + type: string + minLength: 1 + maxLength: 10 + stringMinLengthNullable: + nullable: true + type: string + minLength: 1 + stringMaxLengthNullable: + nullable: true + type: string + maxLength: 1 + stringEmailNullable: + nullable: true + type: string + format: email + intMinMaxNullable: + nullable: true + type: integer + minimum: 1 + maximum: 10 + intMinNullable: + nullable: true + type: integer + minimum: 1 + intMaxNullable: + nullable: true + type: integer + maximum: 10 + numberMinMaxNullable: + nullable: true + type: number + minimum: 1 + maximum: 10 + numberMinNullable: + nullable: true + type: number + minimum: 1 + numberMaxNullable: + nullable: true + type: number + maximum: 10 + stringDefaultNullable: + type: string + nullable: true + maxLength: 1 + default: "ABC" diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_17376.json b/modules/openapi-generator/src/test/resources/3_0/issue_17376.json new file mode 100644 index 000000000000..16c0ab40ef19 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_17376.json @@ -0,0 +1,43 @@ +{ + "openapi": "3.0.0", + "info": { + "title": "My API", + "version": "1.0.0" + }, + "paths": { + "/users": { + "get": { + "summary": "Get all users", + "responses": { + "200": { + "description": "Successful response" + } + }, + "operationId": "V1GetAllUsers", + "description": "Retrieve a users.", + "security": [ + { + "Our Identity service": [] + } + ], + "tags": [ + "Users" + ] + } + } + }, + "components": { + "securitySchemes": { + "Our Identity service": { + "type": "openIdConnect", + "description": "To authenticate your calls to the API...", + "openIdConnectUrl": "https://id-something.somewhere.com/.well-known/openid-configuration" + } + } + }, + "security": [ + { + "Our Identity service": [] + } + ] +} diff --git a/modules/openapi-generator/src/test/resources/3_0/issue_17555.yaml b/modules/openapi-generator/src/test/resources/3_0/issue_17555.yaml new file mode 100644 index 000000000000..158e3486e400 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/issue_17555.yaml @@ -0,0 +1,51 @@ +openapi: 3.0.0 +info: + description: My description + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: department + description: Everything about your Department +paths: + /api/department/{departmentId}/teams: + get: + tags: + - Department + summary: Find Department Teams + operationId: findDepartmentTeams + description: Find Department Teams + parameters: + - $ref: '#/components/parameters/departmentIdParam' + - $ref: '#/components/parameters/teamQueryParam' + responses: + '200': + description: OK +components: + schemas: + TeamCriteriaDTO: + type: object + title: TeamCriteriaDTO + properties: + key: + type: string + name: + type: string + parameters: + departmentIdParam: + name: departmentId + in: path + description: ID of the department to search + required: true + schema: + type: string + teamQueryParam: + name: filter + in: query + description: Fetch teams query + required: false + allowEmptyValue: true + schema: + $ref: '#/components/schemas/TeamCriteriaDTO' \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/java/native/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/java/native/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 035f90534ba0..40e38cde7200 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/native/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/native/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -944,6 +944,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1773,6 +1790,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml index 77bbc979e034..0fcc9905aae3 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-okhttp-gson.yaml @@ -920,6 +920,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1196,6 +1213,52 @@ paths: responses: 200: description: OK + /fake/null-request-body: + get: + tags: + - another_fake + summary: null request body + operationId: null-request-body + parameters: + - name: Accept-Language + in: header + schema: + type: string + example: application/json + requestBody: + content: + text/plain: + examples: + Generar Orden por External ID: + value: |- + { + "external_reference": "{{external_order_ref}}", + "notification_url": "www.yourserver.com/yourendpoint", + "sponsor_id": 446566691, + "items": [ + { + "title": "Papas frita", + "currency_id": "{{currency_id}}", + "unit_price": 6000, + "quantity": 1 + }, + { + "title": "Gaseosa", + "currency_id": "{{currency_id}}", + "unit_price": 3000, + "quantity": 1 + } + ]/*, + "taxes": [ + { + "value": 0, + "type": "IVA" + } + ]*/ + } + responses: + '200': + description: '' /values: get: tags: @@ -1829,6 +1892,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string @@ -1836,6 +1903,8 @@ components: - placed - approved - delivered + - s + - S OuterEnumInteger: type: integer enum: @@ -2429,3 +2498,26 @@ components: type: string type_: type: string + AllOfModelArrayAnyOf: + allOf: + - $ref: "#/components/schemas/Category" + - type: object + properties: + linkListColumn1: + type: object + properties: + value: + type: array + items: + anyOf: + - $ref: '#/components/schemas/User' + - $ref: '#/components/schemas/Tag' + required: + - value + attributes: + type: object + properties: + C: + oneOf: + - $ref: '#/components/schemas/Pet' + - $ref: '#/components/schemas/Order' diff --git a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index d85f71646286..29a142d7c42d 100644 --- a/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/java/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -924,6 +924,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1753,6 +1770,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml index 20c7e2f2684d..182df263da30 100644 --- a/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/javascript/petstore-with-fake-endpoints-models-for-testing.yaml @@ -959,6 +959,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1764,6 +1781,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/jmeter/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/jmeter/petstore.yaml new file mode 100644 index 000000000000..0876844df34d --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/jmeter/petstore.yaml @@ -0,0 +1,751 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + externalDocs: + url: "http://petstore.swagger.io/v2/doc/updatePet" + description: "API documentation for the updatePet operation" + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generate exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - api_key: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `api_key` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - api_key: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - api_key: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - api_key: [] + /fake/operation_id_dollar_sign: + get: + tags: + - fake + summary: operationId dollar sign + description: operationId dollar sign + operationId: operationId$DollarSign + responses: + '400': + description: Invalid username supplied +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/oneOf_twoPrimitives.yaml b/modules/openapi-generator/src/test/resources/3_0/oneOf_twoPrimitives.yaml new file mode 100644 index 000000000000..bb6ae880dbc5 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/oneOf_twoPrimitives.yaml @@ -0,0 +1,20 @@ +openapi: 3.0.3 +info: + title: oneOf two primitives + description: oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + version: 1.0.0 +paths: + /myExample: + post: + requestBody: + content: + application/json: + schema: + oneOf: + - type: string + format: ipv4 + - type: string + format: ipv6 + responses: + 200: + description: OK diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml new file mode 100644 index 000000000000..c300766b07a9 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-addpet-only.yaml @@ -0,0 +1,131 @@ +openapi: 3.0.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + schemas: + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-echo.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-echo.yaml new file mode 100644 index 000000000000..1ce0ac4c0273 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-echo.yaml @@ -0,0 +1,1993 @@ +openapi: 3.0.0 +info: + description: >- + This spec is mainly for testing Petstore server and contains fake endpoints, + models. Please do not use this for any other purpose. Special characters: " + \ + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +servers: + - url: http://localhost:3000/ +paths: + /foo: + get: + responses: + default: + description: response + content: + application/json: + schema: + type: object + properties: + string: + $ref: '#/components/schemas/Foo' + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: Successful operation + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + x-webclient-blocking: true + responses: + '200': + description: Successful operation + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + x-webclient-blocking: true + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + deprecated: true + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + x-webclient-blocking: true + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + uniqueItems: true + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + uniqueItems: true + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + uniqueItems: true + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + x-webclient-blocking: true + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: Successful operation + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: Successful operation + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: Successful operation + content: + text/plain: + schema: + type: string + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + x-webclient-blocking: false + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{order_id}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generate exceptions + operationId: getOrderById + parameters: + - name: order_id + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: order_id + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + /fake_classname_test: + patch: + tags: + - 'fake_classname_tags 123#$%^' + summary: To test class name in snake case + description: To test class name in snake case + operationId: testClassname + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + security: + - api_key_query: [] + requestBody: + $ref: '#/components/requestBodies/Client' + /fake: + patch: + tags: + - fake + summary: To test "client" model + description: To test "client" model + operationId: testClientModel + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + get: + tags: + - fake + summary: To test enum parameters + description: To test enum parameters + operationId: testEnumParameters + parameters: + - name: enum_header_string_array + in: header + description: Header parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_header_string + in: header + description: Header parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_string_array + in: query + description: Query parameter enum test (string array) + schema: + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + - name: enum_query_string + in: query + description: Query parameter enum test (string) + schema: + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + - name: enum_query_integer + in: query + description: Query parameter enum test (double) + schema: + type: integer + format: int32 + enum: + - 1 + - -2 + - name: enum_query_double + in: query + description: Query parameter enum test (double) + schema: + type: number + format: double + enum: + - 1.1 + - -1.2 + - name: enum_query_model_array + in: query + schema: + type: array + items: + $ref: '#/components/schemas/EnumClass' + responses: + '400': + description: Invalid request + '404': + description: Not found + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + enum_form_string_array: + description: Form parameter enum test (string array) + type: array + items: + type: string + default: $ + enum: + - '>' + - $ + enum_form_string: + description: Form parameter enum test (string) + type: string + enum: + - _abc + - '-efg' + - (xyz) + default: '-efg' + post: + tags: + - fake + summary: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + description: | + Fake endpoint for testing various parameters + 假端點 + 偽のエンドポイント + 가짜 엔드 포인트 + operationId: testEndpointParameters + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - http_basic_test: [] + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + integer: + description: None + type: integer + minimum: 10 + maximum: 100 + int32: + description: None + type: integer + format: int32 + minimum: 20 + maximum: 200 + int64: + description: None + type: integer + format: int64 + number: + description: None + type: number + minimum: 32.1 + maximum: 543.2 + float: + description: None + type: number + format: float + maximum: 987.6 + double: + description: None + type: number + format: double + minimum: 67.8 + maximum: 123.4 + string: + description: None + type: string + pattern: '/[a-z]/i' + pattern_without_delimiter: + description: None + type: string + pattern: '^[A-Z].*' + byte: + description: None + type: string + format: byte + binary: + description: None + type: string + format: binary + date: + description: None + type: string + format: date + dateTime: + description: None + type: string + format: date-time + password: + description: None + type: string + format: password + minLength: 10 + maxLength: 64 + callback: + description: None + type: string + required: + - number + - double + - pattern_without_delimiter + - byte + delete: + tags: + - fake + security: + - bearer_test: [] + summary: Fake endpoint to test group parameters (optional) + description: Fake endpoint to test group parameters (optional) + operationId: testGroupParameters + x-group-parameters: true + parameters: + - name: required_string_group + in: query + description: Required String in group parameters + required: true + schema: + type: integer + - name: required_boolean_group + in: header + description: Required Boolean in group parameters + required: true + schema: + type: boolean + - name: required_int64_group + in: query + description: Required Integer in group parameters + required: true + schema: + type: integer + format: int64 + - name: string_group + in: query + description: String in group parameters + schema: + type: integer + - name: boolean_group + in: header + description: Boolean in group parameters + schema: + type: boolean + - name: int64_group + in: query + description: Integer in group parameters + schema: + type: integer + format: int64 + responses: + '400': + description: Something wrong + /fake/outer/number: + post: + tags: + - fake + description: Test serialization of outer number types + operationId: fakeOuterNumberSerialize + responses: + '200': + description: Output number + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterNumber' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterNumber' + description: Input number as post body + /fake/property/enum-int: + post: + tags: + - fake + description: Test serialization of enum (int) properties with examples + operationId: fakePropertyEnumIntegerSerialize + responses: + '200': + description: Output enum (int) + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + requestBody: + required: true + content: + application/json: + schema: + $ref: '#/components/schemas/OuterObjectWithEnumProperty' + description: Input enum (int) as post body + /fake/outer/string: + post: + tags: + - fake + description: Test serialization of outer string types + operationId: fakeOuterStringSerialize + responses: + '200': + description: Output string + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterString' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterString' + description: Input string as post body + /fake/outer/boolean: + post: + tags: + - fake + description: Test serialization of outer boolean types + operationId: fakeOuterBooleanSerialize + responses: + '200': + description: Output boolean + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterBoolean' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterBoolean' + description: Input boolean as post body + /fake/outer/composite: + post: + tags: + - fake + description: Test serialization of object with outer number type + operationId: fakeOuterCompositeSerialize + responses: + '200': + description: Output composite + content: + '*/*': + schema: + $ref: '#/components/schemas/OuterComposite' + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/OuterComposite' + description: Input composite as post body + /fake/BigDecimalMap: + get: + tags: + - fake + description: for Java apache and Java native, test toUrlQueryString for maps with BegDecimal keys + operationId: fakeBigDecimalMap + responses: + '200': + description: successful operation + content: + '*/*': + schema: + type: object + properties: + someId: + type: number + someMap: + type: object + additionalProperties: + type: number + /fake/jsonFormData: + get: + tags: + - fake + summary: test json serialization of form data + description: '' + operationId: testJsonFormData + responses: + '200': + description: successful operation + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + param: + description: field1 + type: string + param2: + description: field2 + type: string + required: + - param + - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + /fake/inline-additionalProperties: + post: + tags: + - fake + summary: test inline additionalProperties + description: '' + operationId: testInlineAdditionalProperties + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + additionalProperties: + type: string + description: request body + required: true + /fake/inline-freeform-additionalProperties: + post: + tags: + - fake + summary: test inline free-form additionalProperties + description: '' + operationId: testInlineFreeformAdditionalProperties + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + type: object + properties: + someProperty: + type: string + additionalProperties: true + description: request body + required: true + /fake/nullable: + post: + tags: + - fake + summary: test nullable parent property + description: "" + operationId: testNullable + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/ChildWithNullable' + description: request body + required: true + responses: + "200": + description: successful operation + /fake/body-with-query-params: + put: + tags: + - fake + operationId: testBodyWithQueryParams + parameters: + - name: query + in: query + required: true + schema: + type: string + responses: + '200': + description: Success + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + required: true + /another-fake/dummy: + patch: + tags: + - $another-fake? + summary: To test special tags + description: To test special tags and operation ID starting with number + operationId: '123_test_@#$%_special_tags' + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + requestBody: + $ref: '#/components/requestBodies/Client' + /fake/body-with-file-schema: + put: + tags: + - fake + description: >- + For this test, the body for this request must reference a schema named + `File`. + operationId: testBodyWithFileSchema + responses: + '200': + description: Success + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FileSchemaTestClass' + required: true + /fake/body-with-binary: + put: + tags: + - fake + description: >- + For this test, the body has to be a binary file. + operationId: testBodyWithBinary + responses: + '200': + description: Success + requestBody: + content: + image/png: + schema: + type: string + nullable: true + format: binary + description: image to upload + required: true + /fake/test-query-parameters: + put: + tags: + - fake + description: To test the collection format in query parameters + operationId: testQueryParameterCollectionFormat + parameters: + - name: pipe + in: query + required: true + style: pipeDelimited + schema: + type: array + items: + type: string + - name: ioutil + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: http + in: query + required: true + style: spaceDelimited + schema: + type: array + items: + type: string + - name: url + in: query + required: true + style: form + explode: false + schema: + type: array + items: + type: string + - name: context + in: query + required: true + explode: true + schema: + type: array + items: + type: string + - name: language + in: query + required: false + schema: + type: object + additionalProperties: + type: string + format: string + - name: allowEmpty + in: query + required: true + allowEmptyValue: true + schema: + type: string + responses: + "200": + description: Success + '/fake/{petId}/uploadImageWithRequiredFile': + post: + tags: + - pet + summary: uploads an image (required) + description: '' + operationId: uploadFileWithRequiredFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + requiredFile: + description: file to upload + type: string + format: binary + required: + - requiredFile + /fake/health: + get: + tags: + - fake + summary: Health check endpoint + responses: + 200: + description: The instance started successfully + content: + application/json: + schema: + $ref: '#/components/schemas/HealthCheckResult' + /fake/http-signature-test: + get: + tags: + - fake + summary: test http signature authentication + operationId: fake-http-signature-test + parameters: + - name: query_1 + in: query + description: query parameter + required: optional + schema: + type: string + - name: header_1 + in: header + description: header parameter + required: optional + schema: + type: string + security: + - http_signature_test: [] + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + 200: + description: The instance started successfully +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Client: + content: + application/json: + schema: + $ref: '#/components/schemas/Client' + description: client model + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + api_key_query: + type: apiKey + name: api_key_query + in: query + http_basic_test: + type: http + scheme: basic + bearer_test: + type: http + scheme: bearer + bearerFormat: JWT + http_signature_test: + type: http + scheme: signature + schemas: + Foo: + type: object + properties: + bar: + $ref: '#/components/schemas/Bar' + Bar: + type: string + default: bar + Order: + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + type: object + required: + - name + properties: + id: + type: integer + format: int64 + name: + type: string + default: default-name + xml: + name: Category + User: + type: object + properties: + id: + type: integer + format: int64 + x-is-unique: true + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + x-is-unique: true + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + uniqueItems: true + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string + Return: + description: Model for testing reserved words + properties: + return: + type: integer + format: int32 + xml: + name: Return + Name: + description: Model for testing model name same as property name + required: + - name + properties: + name: + type: integer + format: int32 + snake_case: + readOnly: true + type: integer + format: int32 + property: + type: string + 123Number: + type: integer + readOnly: true + xml: + name: Name + 200_response: + description: Model for testing model name starting with number + properties: + name: + type: integer + format: int32 + class: + type: string + xml: + name: Name + ClassModel: + description: Model for testing model with "_class" property + properties: + _class: + type: string + Dog: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + breed: + type: string + Cat: + allOf: + - $ref: '#/components/schemas/Animal' + - type: object + properties: + declawed: + type: boolean + Animal: + type: object + discriminator: + propertyName: className + mapping: + DOG: '#/components/schemas/Dog' + CAT: '#/components/schemas/Cat' + required: + - className + properties: + className: + type: string + color: + type: string + default: red + AnimalFarm: + type: array + items: + $ref: '#/components/schemas/Animal' + format_test: + type: object + required: + - number + - byte + - date + - password + properties: + integer: + type: integer + maximum: 100 + minimum: 10 + int32: + type: integer + format: int32 + maximum: 200 + minimum: 20 + int64: + type: integer + format: int64 + number: + maximum: 543.2 + minimum: 32.1 + type: number + float: + type: number + format: float + maximum: 987.6 + minimum: 54.3 + double: + type: number + format: double + maximum: 123.4 + minimum: 67.8 + decimal: + type: string + format: number + string: + type: string + pattern: '/[a-z]/i' + byte: + type: string + format: byte + binary: + type: string + format: binary + date: + type: string + format: date + dateTime: + type: string + format: date-time + uuid: + type: string + format: uuid + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + password: + type: string + format: password + maxLength: 64 + minLength: 10 + pattern_with_digits: + description: A string that is a 10 digit number. Can have leading zeros. + type: string + pattern: '^\d{10}$' + pattern_with_digits_and_delimiter: + description: A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. + type: string + pattern: '/^image_\d{1,3}$/i' + EnumClass: + type: string + default: '-efg' + enum: + - _abc + - '-efg' + - (xyz) + Enum_Test: + type: object + required: + - enum_string_required + properties: + enum_string: + type: string + enum: + - UPPER + - lower + - '' + enum_string_required: + type: string + enum: + - UPPER + - lower + - '' + enum_integer: + type: integer + format: int32 + enum: + - 1 + - -1 + enum_number: + type: number + format: double + enum: + - 1.1 + - -1.2 + outerEnum: + $ref: '#/components/schemas/OuterEnum' + outerEnumInteger: + $ref: '#/components/schemas/OuterEnumInteger' + outerEnumDefaultValue: + $ref: '#/components/schemas/OuterEnumDefaultValue' + outerEnumIntegerDefaultValue: + $ref: '#/components/schemas/OuterEnumIntegerDefaultValue' + AdditionalPropertiesClass: + type: object + properties: + map_property: + type: object + additionalProperties: + type: string + map_of_map_property: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + MixedPropertiesAndAdditionalPropertiesClass: + type: object + properties: + uuid: + type: string + format: uuid + dateTime: + type: string + format: date-time + map: + type: object + additionalProperties: + $ref: '#/components/schemas/Animal' + List: + type: object + properties: + 123-list: + type: string + Client: + type: object + properties: + client: + type: string + ReadOnlyFirst: + type: object + properties: + bar: + type: string + readOnly: true + baz: + type: string + hasOnlyReadOnly: + type: object + properties: + bar: + type: string + readOnly: true + foo: + type: string + readOnly: true + Capitalization: + type: object + properties: + smallCamel: + type: string + CapitalCamel: + type: string + small_Snake: + type: string + Capital_Snake: + type: string + SCA_ETH_Flow_Points: + type: string + ATT_NAME: + description: | + Name of the pet + type: string + MapTest: + type: object + properties: + map_map_of_string: + type: object + additionalProperties: + type: object + additionalProperties: + type: string + map_of_enum_string: + type: object + additionalProperties: + type: string + enum: + - UPPER + - lower + direct_map: + type: object + additionalProperties: + type: boolean + indirect_map: + $ref: '#/components/schemas/StringBooleanMap' + ArrayTest: + type: object + properties: + array_of_string: + type: array + items: + type: string + minItems: 0 + maxItems: 3 + array_array_of_integer: + type: array + items: + type: array + items: + type: integer + format: int64 + array_array_of_model: + type: array + items: + type: array + items: + $ref: '#/components/schemas/ReadOnlyFirst' + NumberOnly: + type: object + properties: + JustNumber: + type: number + ArrayOfNumberOnly: + type: object + properties: + ArrayNumber: + type: array + items: + type: number + ArrayOfArrayOfNumberOnly: + type: object + properties: + ArrayArrayNumber: + type: array + items: + type: array + items: + type: number + EnumArrays: + type: object + properties: + just_symbol: + type: string + enum: + - '>=' + - $ + array_enum: + type: array + items: + type: string + enum: + - fish + - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true + OuterEnum: + nullable: true + type: string + enum: + - placed + - approved + - delivered + OuterEnumInteger: + type: integer + enum: + - 0 + - 1 + - 2 + example: 2 + OuterEnumDefaultValue: + type: string + enum: + - placed + - approved + - delivered + default: placed + OuterEnumIntegerDefaultValue: + type: integer + enum: + - 0 + - 1 + - 2 + default: 0 + OuterComposite: + type: object + properties: + my_number: + $ref: '#/components/schemas/OuterNumber' + my_string: + $ref: '#/components/schemas/OuterString' + my_boolean: + $ref: '#/components/schemas/OuterBoolean' + OuterNumber: + type: number + OuterString: + type: string + OuterBoolean: + type: boolean + x-codegen-body-parameter-name: boolean_post_body + ParentWithNullable: + type: object + discriminator: + propertyName: type + properties: + type: + type: string + enum: + - ChildWithNullable + nullableProperty: + type: string + nullable: true + ChildWithNullable: + allOf: + - $ref: '#/components/schemas/ParentWithNullable' + - type: object + properties: + otherProperty: + type: string + StringBooleanMap: + additionalProperties: + type: boolean + FileSchemaTestClass: + type: object + properties: + file: + $ref: '#/components/schemas/File' + files: + type: array + items: + $ref: '#/components/schemas/File' + File: + type: object + description: Must be named `File` for test. + properties: + sourceURI: + description: Test capitalization + type: string + _special_model.name_: + properties: + '$special[property.name]': + type: integer + format: int64 + xml: + name: '$special[model.name]' + HealthCheckResult: + type: object + properties: + NullableMessage: + nullable: true + type: string + description: Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + NullableClass: + type: object + properties: + integer_prop: + type: integer + nullable: true + number_prop: + type: number + nullable: true + boolean_prop: + type: boolean + nullable: true + string_prop: + type: string + nullable: true + date_prop: + type: string + format: date + nullable: true + datetime_prop: + type: string + format: date-time + nullable: true + array_nullable_prop: + type: array + nullable: true + items: + type: object + array_and_items_nullable_prop: + type: array + nullable: true + items: + type: object + nullable: true + array_items_nullable: + type: array + items: + type: object + nullable: true + object_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + object_and_items_nullable_prop: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + object_items_nullable: + type: object + additionalProperties: + type: object + nullable: true + additionalProperties: + type: object + nullable: true + OuterObjectWithEnumProperty: + type: object + example: + value: 2 + required: + - value + properties: + value: + $ref: '#/components/schemas/OuterEnumInteger' + DeprecatedObject: + type: object + deprecated: true + properties: + name: + type: string + ObjectWithDeprecatedFields: + type: object + properties: + uuid: + type: string + id: + type: number + deprecated: true + deprecatedRef: + $ref: '#/components/schemas/DeprecatedObject' + bars: + type: array + deprecated: true + items: + $ref: '#/components/schemas/Bar' + AllOfWithSingleRef: + type: object + properties: + username: + type: string + SingleRefType: + allOf: + - $ref: '#/components/schemas/SingleRefType' + SingleRefType: + type: string + title: SingleRefType + enum: + - admin + - user diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 707d452b494c..fd0450ad2b93 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -940,6 +940,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1738,6 +1755,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml index e9f73948e9ba..3004706c6bae 100644 --- a/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/petstore-with-fake-endpoints-models-for-testing.yaml @@ -995,6 +995,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1820,6 +1837,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml index e9f73948e9ba..3004706c6bae 100644 --- a/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/php-nextgen/petstore-with-fake-endpoints-models-for-testing.yaml @@ -995,6 +995,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1820,6 +1837,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml index c620afc8c988..56c2c88cd761 100644 --- a/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/php/petstore-with-fake-endpoints-models-for-testing.yaml @@ -995,6 +995,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1844,6 +1861,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/powershell/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/powershell/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index aecc1b8d4473..c4cbbb00f4df 100644 --- a/modules/openapi-generator/src/test/resources/3_0/powershell/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/powershell/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -925,6 +925,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1206,11 +1223,11 @@ components: 'read:pets': read your pets api_key: type: apiKey - name: api_key + name: api_key_name in: header api_key_query: type: apiKey - name: api_key_query + name: api_key_query_name in: query http_basic_test: type: http @@ -1754,6 +1771,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/python-fastapi/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/python-fastapi/petstore.yaml index 543c7327956e..7f5f20f5bc7e 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python-fastapi/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python-fastapi/petstore.yaml @@ -577,13 +577,13 @@ paths: description: '' operationId: fake_query_param_default parameters: - - name: has_default + - name: hasDefault in: query description: has default value schema: type: string default: Hello World - - name: no_default + - name: noDefault in: query description: no default value schema: diff --git a/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml b/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml index 3bd93b2b5fc0..2e1dc575517c 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python-prior/petstore-with-fake-endpoints-models-for-testing-with-http-signature.yaml @@ -1047,6 +1047,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -2077,6 +2094,10 @@ components: type: integer enum: - 0 + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true ObjectModelWithRefProps: description: a model that includes properties which should stay primitive (String + Boolean) and one which is defined as a class, NumberWithValidations type: object diff --git a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml index 6c6a10dc464c..c9eee7da1db2 100644 --- a/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/python/petstore-with-fake-endpoints-models-for-testing.yaml @@ -983,6 +983,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1063,6 +1080,49 @@ paths: schema: $ref: '#/components/schemas/User' required: true + /fake/empty_and_non_empty_responses: + post: + tags: + - fake + summary: test empty and non-empty responses + description: '' + operationId: testEmptyAndNonEmptyResponses + responses: + '204': + description: Success, but no response content + '206': + description: Partial response content + content: + text/plain: + schema: + type: string + /fake/error_responses_with_model: + post: + tags: + - fake + summary: test error responses with model + operationId: testErrorResponsesWithModel + responses: + '204': + description: Success, but no response content + '400': + description: '' + content: + application/json: + schema: + type: object + properties: + reason400: + type: string + '404': + description: '' + content: + application/json: + schema: + type: object + properties: + reason404: + type: string /another-fake/dummy: patch: tags: @@ -1322,6 +1382,19 @@ paths: type: array items: $ref: "#/components/schemas/ListOfObjects" + /fake/ref_enum_string: + get: + tags: + - fake + summary: test ref to enum string + operationId: fake_ref_enum_string + responses: + 200: + description: OK + content: + plain/text: + schema: + $ref: "#/components/schemas/EnumClass" servers: - url: 'http://{server}.swagger.io:{port}/v2' description: petstore server @@ -1899,6 +1972,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/ruby/petstore-with-fake-endpoints-models-for-testing.yaml b/modules/openapi-generator/src/test/resources/3_0/ruby/petstore-with-fake-endpoints-models-for-testing.yaml index c87242a6329e..a0fafbbcbf47 100644 --- a/modules/openapi-generator/src/test/resources/3_0/ruby/petstore-with-fake-endpoints-models-for-testing.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/ruby/petstore-with-fake-endpoints-models-for-testing.yaml @@ -1031,6 +1031,23 @@ paths: required: - param - param2 + /fake/additionalProperties-reference: + post: + tags: + - fake + summary: test referenced additionalProperties + description: '' + operationId: testAdditionalPropertiesReference + responses: + '200': + description: successful operation + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true /fake/inline-additionalProperties: post: tags: @@ -1296,7 +1313,7 @@ paths: operationId: getParameterNameMapping parameters: - name: _type - in: header + in: header description: _type required: true schema: @@ -1309,7 +1326,7 @@ paths: schema: type: string - name: type_ - in: header + in: header description: type_ required: true schema: @@ -1883,6 +1900,10 @@ components: enum: - fish - crab + FreeFormObject: + type: object + description: A schema consisting only of additional properties + additionalProperties: true OuterEnum: nullable: true type: string @@ -2070,6 +2091,9 @@ components: oneOf: - $ref: '#/components/schemas/whale' - $ref: '#/components/schemas/zebra' + mamal_with_enum: + oneOf: + - $ref: '#/components/schemas/cow' mammal: oneOf: - $ref: '#/components/schemas/whale' @@ -2101,9 +2125,14 @@ components: required: - classname additionalProperties: true + cow: + type: string + enum: + - BlackAndWhiteCow + - BrownCow PropertyNameMapping: - properties: - http_debug_operation: + properties: + http_debug_operation: type: string _type: type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml index 34eae5c8edef..af7ac951593f 100644 --- a/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/rust-server/openapi-v3.yaml @@ -639,6 +639,22 @@ components: items: type: string nullable: true + min_item_test: + type: array + items: + type: integer + minItems: 1 + max_item_test: + type: array + items: + type: integer + maxItems: 2 + min_max_item_test: + type: array + items: + type: integer + minItems: 1 + maxItems: 3 StringEnum: type: string enum: diff --git a/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml index 4f372bb7fd70..17ed5b4f0a84 100644 --- a/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_0/rust/petstore.yaml @@ -898,6 +898,22 @@ components: items: type: string enum: ["A", "B", "C"] + UniqueItemArrayTesting: + description: Test handling of enum array with unique items + type: object + required: + - unique_item_array + properties: + unique_item_array: + type: array + description: Helper object for the unique item array test + uniqueItems: true + items: + type: string + enum: + - unique_item_1 + - unique_item_2 + - unique_item_3 ArrayRefItem: description: Helper object for the array item ref test type: array diff --git a/modules/openapi-generator/src/test/resources/3_0/scala-pekko/petstore.yaml b/modules/openapi-generator/src/test/resources/3_0/scala-pekko/petstore.yaml new file mode 100644 index 000000000000..947376fc0082 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/scala-pekko/petstore.yaml @@ -0,0 +1,742 @@ +openapi: 3.0.0 +servers: + - url: 'https://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets + - name: store + description: Access to Petstore orders + - name: user + description: Operations about user +paths: + /pet: + post: + tags: + - pet + summary: Add a new pet to the store + description: '' + operationId: addPet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + put: + tags: + - pet + summary: Update an existing pet + description: '' + operationId: updatePet + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + '405': + description: Validation exception + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + $ref: '#/components/requestBodies/Pet' + /pet/findByStatus: + get: + tags: + - pet + summary: Finds Pets by status + description: Multiple status values can be provided with comma separated strings + operationId: findPetsByStatus + parameters: + - name: status + in: query + description: Status values that need to be considered for filter + required: true + style: form + explode: false + schema: + type: array + items: + type: string + enum: + - available + - pending + - sold + default: available + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid status value + security: + - petstore_auth: + - 'read:pets' + /pet/findByTags: + get: + tags: + - pet + summary: Finds Pets by tags + description: >- + Multiple tags can be provided with comma separated strings. Use tag1, + tag2, tag3 for testing. + operationId: findPetsByTags + parameters: + - name: tags + in: query + description: Tags to filter by + required: true + style: form + explode: false + schema: + type: array + items: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid tag value + security: + - petstore_auth: + - 'read:pets' + deprecated: true + '/pet/{petId}': + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + post: + tags: + - pet + summary: Updates a pet in the store with form data + description: '' + operationId: updatePetWithForm + parameters: + - name: petId + in: path + description: ID of pet that needs to be updated + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + '405': + description: Invalid input + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + application/x-www-form-urlencoded: + schema: + type: object + properties: + name: + description: Updated name of the pet + type: string + status: + description: Updated status of the pet + type: string + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + - name: petId + in: path + description: Pet id to delete + required: true + schema: + type: integer + format: int64 + responses: + '400': + description: Invalid pet value + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + '/pet/{petId}/uploadImage': + post: + tags: + - pet + summary: uploads an image + description: '' + operationId: uploadFile + parameters: + - name: petId + in: path + description: ID of pet to update + required: true + schema: + type: integer + format: int64 + responses: + '200': + description: successful operation + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + security: + - petstore_auth: + - 'write:pets' + - 'read:pets' + requestBody: + content: + multipart/form-data: + schema: + type: object + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + file: + description: file to upload + type: string + format: binary + /store/inventory: + get: + tags: + - store + summary: Returns pet inventories by status + description: Returns a map of status codes to quantities + operationId: getInventory + responses: + '200': + description: successful operation + content: + application/json: + schema: + type: object + additionalProperties: + type: integer + format: int32 + security: + - api_key: [] + /store/order: + post: + tags: + - store + summary: Place an order for a pet + description: '' + operationId: placeOrder + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid Order + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/Order' + description: order placed for purchasing the pet + required: true + '/store/order/{orderId}': + get: + tags: + - store + summary: Find purchase order by ID + description: >- + For valid response try integer IDs with value <= 5 or > 10. Other values + will generate exceptions + operationId: getOrderById + parameters: + - name: orderId + in: path + description: ID of pet that needs to be fetched + required: true + schema: + type: integer + format: int64 + minimum: 1 + maximum: 5 + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Order' + application/json: + schema: + $ref: '#/components/schemas/Order' + '400': + description: Invalid ID supplied + '404': + description: Order not found + delete: + tags: + - store + summary: Delete purchase order by ID + description: >- + For valid response try integer IDs with value < 1000. Anything above + 1000 or nonintegers will generate API errors + operationId: deleteOrder + parameters: + - name: orderId + in: path + description: ID of the order that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid ID supplied + '404': + description: Order not found + /user: + post: + tags: + - user + summary: Create user + description: This can only be done by the logged in user. + operationId: createUser + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Created user object + required: true + /user/createWithArray: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithArrayInput + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/createWithList: + post: + tags: + - user + summary: Creates list of users with given input array + description: '' + operationId: createUsersWithListInput + responses: + default: + description: successful operation + security: + - auth_cookie: [] + requestBody: + $ref: '#/components/requestBodies/UserArray' + /user/login: + get: + tags: + - user + summary: Logs user into the system + description: '' + operationId: loginUser + parameters: + - name: username + in: query + description: The user name for login + required: true + schema: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + - name: password + in: query + description: The password for login in clear text + required: true + schema: + type: string + responses: + '200': + description: successful operation + headers: + Set-Cookie: + description: >- + Cookie authentication key for use with the `auth_cookie` + apiKey authentication. + schema: + type: string + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + X-Rate-Limit: + description: calls per hour allowed by the user + schema: + type: integer + format: int32 + X-Expires-After: + description: date in UTC when token expires + schema: + type: string + format: date-time + content: + application/xml: + schema: + type: string + application/json: + schema: + type: string + '400': + description: Invalid username/password supplied + /user/logout: + get: + tags: + - user + summary: Logs out current logged in user session + description: '' + operationId: logoutUser + responses: + default: + description: successful operation + security: + - auth_cookie: [] + '/user/{username}': + get: + tags: + - user + summary: Get user by user name + description: '' + operationId: getUserByName + parameters: + - name: username + in: path + description: The name that needs to be fetched. Use user1 for testing. + required: true + schema: + type: string + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/User' + application/json: + schema: + $ref: '#/components/schemas/User' + '400': + description: Invalid username supplied + '404': + description: User not found + put: + tags: + - user + summary: Updated user + description: This can only be done by the logged in user. + operationId: updateUser + parameters: + - name: username + in: path + description: name that need to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid user supplied + '404': + description: User not found + security: + - auth_cookie: [] + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Updated user object + required: true + delete: + tags: + - user + summary: Delete user + description: This can only be done by the logged in user. + operationId: deleteUser + parameters: + - name: username + in: path + description: The name that needs to be deleted + required: true + schema: + type: string + responses: + '400': + description: Invalid username supplied + '404': + description: User not found + security: + - auth_cookie: [] +externalDocs: + description: Find out more about Swagger + url: 'http://swagger.io' +components: + requestBodies: + UserArray: + content: + application/json: + schema: + type: array + items: + $ref: '#/components/schemas/User' + description: List of user object + required: true + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + petstore_auth: + type: oauth2 + flows: + implicit: + authorizationUrl: 'http://petstore.swagger.io/api/oauth/dialog' + scopes: + 'write:pets': modify pets in your account + 'read:pets': read your pets + api_key: + type: apiKey + name: api_key + in: header + auth_cookie: + type: apiKey + name: AUTH_KEY + in: cookie + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/spring/issue_15796.yaml b/modules/openapi-generator/src/test/resources/3_0/spring/issue_15796.yaml new file mode 100644 index 000000000000..2b93af76afd0 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/spring/issue_15796.yaml @@ -0,0 +1,98 @@ +openapi: 3.0.0 +info: + title: My service + description: My service + version: 1.0.0 +servers: + - url: 'https://localhost' +paths: + /generator/test: + get: + summary: Get test generator models + responses: + 200: + description: Everything is fine +components: + schemas: + Pet: + type: object + required: + - type + properties: + name: + type: string + type: + type: string + discriminator: + propertyName: type + mapping: + CAT: '#/components/schemas/Cat' + DOG: '#/components/schemas/Dog' + Cat: + type: object + allOf: + - $ref: '#/components/schemas/Pet' + required: + - race + properties: + paws: + type: integer + race: + type: string + discriminator: + propertyName: race + mapping: + PERSIAN: '#/components/schemas/Persian' + MAINE_COON: '#/components/schemas/MaineCoon' + Dog: + type: object + allOf: + - $ref: '#/components/schemas/Pet' + required: + - race + properties: + tails: + type: integer + race: + type: string + discriminator: + propertyName: race + mapping: + POODLE: '#/components/schemas/Poodle' + LABRADOR: '#/components/schemas/Labrador' + Poodle: + type: object + allOf: + - $ref: '#/components/schemas/Dog' + properties: + hairType: + type: string + required: + - race + Labrador: + type: object + allOf: + - $ref: '#/components/schemas/Dog' + properties: + hairColor: + type: string + required: + - race + Persian: + type: object + allOf: + - $ref: '#/components/schemas/Cat' + properties: + hairType: + type: string + required: + - race + MaineCoon: + type: object + allOf: + - $ref: '#/components/schemas/Cat' + properties: + hairColor: + type: string + required: + - race diff --git a/modules/openapi-generator/src/test/resources/3_0/spring/issue_16797.yaml b/modules/openapi-generator/src/test/resources/3_0/spring/issue_16797.yaml new file mode 100644 index 000000000000..8201b6bd7483 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/spring/issue_16797.yaml @@ -0,0 +1,88 @@ +openapi: 3.0.1 +info: + title: OpenAPI definition + version: v0 +servers: + - url: / + - url: '{protocolAndBaseURL}' + variables: + protocolAndBaseURL: + default: 'https://localhost' +paths: + /user: + get: + tags: + - user + summary: Get User By Id + operationId: getUserById + parameters: + - in: query + name: id + description: Unique Id of an User + schema: + type: integer + default: 10 + responses: + default: + description: successful operation + content: + application/json: + schema: + $ref: "#/components/schemas/Object4" + +components: + schemas: + + Object1: + type: object + properties: + responseType: + type: string + requestId: + type: string + success: + type: boolean + default: true + required: + - responseType + - requestId + - success + discriminator: + propertyName: responseType + + Object2: + allOf: + - $ref: '#/components/schemas/Object1' + - type: object + + Type1: + type: object + properties: + pageSize: + minimum: 1 + type: integer + format: int32 + rowCount: + minimum: 0 + type: integer + format: int32 + required: + - pageSize + - rowCount + + Object3: + allOf: + - $ref: '#/components/schemas/Object2' + properties: + pageInfo: + $ref: '#/components/schemas/Type1' + required: + - pageInfo + + Object4: + allOf: + - $ref: '#/components/schemas/Object3' + - type: object + properties: + data: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_0/spring/issue_17150.yaml b/modules/openapi-generator/src/test/resources/3_0/spring/issue_17150.yaml new file mode 100644 index 000000000000..62968498b871 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_0/spring/issue_17150.yaml @@ -0,0 +1,161 @@ +openapi: 3.0.3 +info: + title: Test Issue + version: v1 +paths: + /test: + get: + responses: + '200': + description: default response + content: + '*/*': + schema: + $ref: '#/components/schemas/Foo' +components: + schemas: + Foo: + type: object + properties: + stringPattern: + type: array + uniqueItems: true + items: + type: string + pattern: "[a-z]" + stringMaxMinLength: + type: array + uniqueItems: true + items: + type: string + minLength: 1 + maxLength: 10 + maxItems: 10 + stringMinLength: + type: array + items: + type: string + minLength: 1 + maxItems: 10 + stringMaxLength: + type: array + uniqueItems: true + items: + type: string + maxLength: 1 + maxItems: 10 + + + stringEmail: + type: array + items: + type: string + format: email + intMinMax: + type: array + items: + type: integer + minimum: 1 + maximum: 10 + intMin: + type: array + items: + type: integer + minimum: 1 + intMax: + type: array + items: + type: integer + maximum: 10 + numberMinMax: + type: array + items: + type: number + minimum: 1 + maximum: 10 + numberMin: + type: array + items: + type: number + minimum: 1 + numberMax: + type: array + items: + type: number + maximum: 10 + + stringPatternNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + pattern: "[a-z]" + stringMaxMinLengthNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + minLength: 1 + maxLength: 10 + maxItems: 10 + stringMinLengthNullable: + nullable: true + type: array + items: + type: string + minLength: 1 + maxItems: 10 + stringMaxLengthNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + maxLength: 1 + maxItems: 10 + stringEmailNullable: + nullable: true + type: array + items: + type: string + format: email + intMinMaxNullable: + nullable: true + type: array + items: + type: integer + minimum: 1 + maximum: 10 + intMinNullable: + nullable: true + type: array + items: + type: integer + minimum: 1 + intMaxNullable: + nullable: true + type: array + items: + type: integer + maximum: 10 + numberMinMaxNullable: + nullable: true + type: array + items: + type: number + minimum: 1 + maximum: 10 + numberMinNullable: + nullable: true + type: array + items: + type: number + minimum: 1 + numberMaxNullable: + nullable: true + type: array + items: + type: number + maximum: 10 \ No newline at end of file diff --git a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/draft6/oneOf.json b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/draft6/oneOf.json index eeb7ae866ad6..c30a65c0d4f2 100755 --- a/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/draft6/oneOf.json +++ b/modules/openapi-generator/src/test/resources/3_0/unit_test_spec/draft6/oneOf.json @@ -203,7 +203,7 @@ } ] }, - { + { "description": "oneOf with missing optional property", "schema": { "oneOf": [ diff --git a/modules/openapi-generator/src/test/resources/3_1/common-parameters.yaml b/modules/openapi-generator/src/test/resources/3_1/common-parameters.yaml new file mode 100644 index 000000000000..6052f3d450f6 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/common-parameters.yaml @@ -0,0 +1,227 @@ +openapi: 3.1.0 +servers: + - url: 'http://petstore.swagger.io/v2' +info: + description: >- + This is a sample server Petstore server. For this sample, you can use the api key + `special-key` to test the authorization filters. + version: 1.0.0 + title: OpenAPI Petstore + license: + name: Apache-2.0 + url: 'https://www.apache.org/licenses/LICENSE-2.0.html' +tags: + - name: pet + description: Everything about your Pets +paths: + '/pet/{petId}': + parameters: + - name: petId + in: path + description: ID of pet to return + required: true + schema: + type: integer + format: int64 + get: + tags: + - pet + summary: Find pet by ID + description: Returns a single pet + operationId: getPetById + responses: + '200': + description: successful operation + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + '400': + description: Invalid ID supplied + '404': + description: Pet not found + security: + - api_key: [] + delete: + tags: + - pet + summary: Deletes a pet + description: '' + operationId: deletePet + parameters: + - name: api_key + in: header + required: false + schema: + type: string + responses: + '400': + description: Invalid pet value + security: + - api_key: [] + patch: + tags: + - pet + summary: Updates a pet + description: '' + operationId: updatePet + responses: + '400': + description: Invalid pet value + requestBody: + $ref: '#/components/requestBodies/Pet' + security: + - api_key: [] +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + securitySchemes: + api_key: + type: apiKey + name: api_key + in: header + schemas: + Order: + title: Pet Order + description: An order for a pets from the pet store + type: object + properties: + id: + type: integer + format: int64 + petId: + type: integer + format: int64 + quantity: + type: integer + format: int32 + shipDate: + type: string + format: date-time + status: + type: string + description: Order Status + enum: + - placed + - approved + - delivered + complete: + type: boolean + default: false + xml: + name: Order + Category: + title: Pet category + description: A category for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + pattern: '^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$' + xml: + name: Category + User: + title: a User + description: A User who is purchasing from the pet store + type: object + properties: + id: + type: integer + format: int64 + username: + type: string + firstName: + type: string + lastName: + type: string + email: + type: string + password: + type: string + phone: + type: string + userStatus: + type: integer + format: int32 + description: User Status + xml: + name: User + Tag: + title: Pet Tag + description: A tag for a pet + type: object + properties: + id: + type: integer + format: int64 + name: + type: string + xml: + name: Tag + Pet: + title: a Pet + description: A pet for sale in the pet store + type: object + required: + - name + - photoUrls + properties: + id: + type: integer + format: int64 + category: + $ref: '#/components/schemas/Category' + name: + type: string + example: doggie + photoUrls: + type: array + xml: + name: photoUrl + wrapped: true + items: + type: string + tags: + type: array + xml: + name: tag + wrapped: true + items: + $ref: '#/components/schemas/Tag' + status: + type: string + description: pet status in the store + deprecated: true + enum: + - available + - pending + - sold + xml: + name: Pet + ApiResponse: + title: An uploaded response + description: Describes the result of uploading an image resource + type: object + properties: + code: + type: integer + format: int32 + type: + type: string + message: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_1/java/petstore.yaml b/modules/openapi-generator/src/test/resources/3_1/java/petstore.yaml index 10bd7699fa2e..4f5478f77913 100644 --- a/modules/openapi-generator/src/test/resources/3_1/java/petstore.yaml +++ b/modules/openapi-generator/src/test/resources/3_1/java/petstore.yaml @@ -569,10 +569,60 @@ paths: description: User not found security: - api_key: [] + /no_ref: + get: + operationId: response_no_ref + tags: + - fake + responses: + '200': + description: required to pass validation + content: + text/plain: + schema: + type: string + + /ref/no_ref: + get: + operationId: response_ref_to_no_ref + tags: + - fake + responses: + '200': + $ref: '#/components/responses/no_ref' + + /ref/ref: + get: + operationId: response_ref_to_ref + tags: + - fake + responses: + '200': + $ref: '#/components/responses/ref' + /ref/ref_to_parameter: + get: + operationId: ref_to_ref_parameter + tags: + - fake + responses: + '200': + $ref: '#/components/responses/ref' + parameters: + - $ref: '#/components/parameters/ref_to_uuid' externalDocs: description: Find out more about Swagger url: 'http://swagger.io' components: + parameters: + ref_to_uuid: + description: to test ref to parameter (uuid) + name: ref_to_uuid + in: header + required: true + schema: + type: string + format: uuid + example: 61864654-6e6b-4152-a62f-795fdd606bc2 requestBodies: UserArray: content: @@ -593,6 +643,20 @@ components: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store required: true + responses: + no_ref: + description: required to pass validation + content: + text/plain: + schema: + type: string + + ref: + description: required to pass validation + content: + text/plain: + schema: + $ref: '#/components/schemas/simple_text' securitySchemes: petstore_auth: type: oauth2 @@ -773,3 +837,13 @@ components: color: type: string default: red + simple_text: + type: string + any_type_test: + properties: + any_type_property: {} + array_prop: + type: array + description: test array in 3.1 spec + items: + type: string diff --git a/modules/openapi-generator/src/test/resources/3_1/webhooks.yaml b/modules/openapi-generator/src/test/resources/3_1/webhooks.yaml new file mode 100644 index 000000000000..44fc73aaa917 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/3_1/webhooks.yaml @@ -0,0 +1,34 @@ +openapi: 3.1.0 +info: + title: Webhook Example + version: 1.0.0 +# Since OAS 3.1.0 the paths element isn't necessary. Now a valid OpenAPI Document can describe only paths, webhooks, or even only reusable components +webhooks: + # Each webhook needs a name + newPet: + # This is a Path Item Object, the only difference is that the request is initiated by the API provider + post: + requestBody: + description: Information about a new pet in the system + content: + application/json: + schema: + $ref: "#/components/schemas/Pet" + responses: + "200": + description: Return a 200 status to indicate that the data was received successfully + +components: + schemas: + Pet: + required: + - id + - name + properties: + id: + type: integer + format: int64 + name: + type: string + tag: + type: string diff --git a/modules/openapi-generator/src/test/resources/bugs/issue_4947.yaml b/modules/openapi-generator/src/test/resources/bugs/issue_4947.yaml new file mode 100644 index 000000000000..003ad599c992 --- /dev/null +++ b/modules/openapi-generator/src/test/resources/bugs/issue_4947.yaml @@ -0,0 +1,176 @@ +openapi: 3.0.3 +info: + title: Test Issue + version: v1 +paths: + /test: + get: + responses: + '200': + description: default response + content: + '*/*': + schema: + $ref: '#/components/schemas/Foo' +components: + schemas: + Foo: + type: object + properties: + stringPattern: + type: array + uniqueItems: true + items: + type: string + pattern: "[a-z]" + stringMaxMinLength: + type: array + uniqueItems: true + items: + type: string + minLength: 1 + maxLength: 10 + maxItems: 10 + stringMinLength: + type: array + items: + type: string + minLength: 1 + maxItems: 10 + stringMaxLength: + type: array + uniqueItems: true + items: + type: string + maxLength: 1 + maxItems: 10 + stringEmail: + type: array + items: + type: string + format: email + intMinMax: + type: array + items: + type: integer + minimum: 1 + maximum: 10 + intMin: + type: array + items: + type: integer + minimum: 1 + intMax: + type: array + items: + type: integer + maximum: 10 + numberMinMax: + type: array + items: + type: number + minimum: 1 + maximum: 10 + numberMin: + type: array + items: + type: number + minimum: 1 + numberMax: + type: array + items: + type: number + maximum: 10 + stringPatternWithMin: + nullable: true + type: array + uniqueItems: true + items: + type: string + minLength: 10 + pattern: '^\d{3}-\d{2}-\d{4}$' + stringPatternNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + pattern: '^\d{3}-\d{2}-\d{4}$' + stringMaxMinLengthNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + minLength: 1 + maxLength: 10 + maxItems: 10 + stringMinLengthNullable: + nullable: true + type: array + items: + type: string + minLength: 1 + maxItems: 10 + stringMaxLengthNullable: + nullable: true + type: array + uniqueItems: true + items: + type: string + maxLength: 1 + maxItems: 10 + stringNumbers: + type: array + uniqueItems: true + items: + type: string + format: number + minimum: 1 + maximum: 10 + maxItems: 10 + stringEmailNullable: + nullable: true + type: array + items: + type: string + format: email + intMinMaxNullable: + nullable: true + type: array + items: + type: integer + minimum: 1 + maximum: 10 + intMinNullable: + nullable: true + type: array + items: + type: integer + minimum: 1 + intMaxNullable: + nullable: true + type: array + items: + type: integer + maximum: 10 + numberMinMaxNullable: + nullable: true + type: array + items: + type: number + minimum: 1 + maximum: 10 + numberMinNullable: + nullable: true + type: array + items: + type: number + minimum: 1 + numberMaxNullable: + nullable: true + type: array + items: + type: number + maximum: 10 + exclusiveMaximum: true diff --git a/pom.xml b/pom.xml index a99ac8a7c027..77697243440d 100644 --- a/pom.xml +++ b/pom.xml @@ -13,7 +13,7 @@ pom openapi-generator-project - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT https://github.com/openapitools/openapi-generator @@ -1119,244 +1119,6 @@ samples/server/petstore/java-undertow - - samples - - - env - samples - - - - - - - - - - - - - samples/client/petstore/rust - samples/client/petstore/rust/hyper/petstore - samples/client/petstore/rust/reqwest/petstore - samples/client/petstore/rust/reqwest/petstore-async - samples/client/petstore/rust/reqwest/petstore-async-middleware - - - - - - samples.circleci - - - env - samples.circleci - - - - samples/client/petstore/ruby - samples/client/petstore/ruby-faraday - samples/client/petstore/ruby-httpx - samples/client/petstore/ruby-autoload - - - - samples.circleci.spring - - - env - samples.circleci.spring - - - - - samples/client/petstore/spring-cloud - - - - - samples.circleci.node3 - - - env - samples.circleci.node3 - - - - - samples/openapi3/client/petstore/python - samples/openapi3/client/petstore/python-pydantic-v1 - samples/openapi3/client/petstore/python-aiohttp - samples/openapi3/client/petstore/python-pydantic-v1-aiohttp - - - samples/client/others/typescript-angular - samples/client/petstore/typescript-angular-v12-provided-in-root - samples/client/petstore/typescript-angular-v13-provided-in-root - samples/client/petstore/typescript-angular-v14-provided-in-root - samples/client/petstore/typescript-angular-v15-provided-in-root - samples/client/petstore/typescript-angular-v16-provided-in-root - samples/openapi3/client/petstore/typescript/builds/default - samples/openapi3/client/petstore/typescript/tests/default - samples/openapi3/client/petstore/typescript/builds/jquery - samples/openapi3/client/petstore/typescript/tests/jquery - samples/openapi3/client/petstore/typescript/builds/object_params - samples/openapi3/client/petstore/typescript/tests/object_params - samples/openapi3/client/petstore/typescript/builds/inversify - - samples/openapi3/client/petstore/typescript/builds/browser - samples/openapi3/client/petstore/typescript/tests/browser - samples/client/petstore/typescript-fetch/builds/default - samples/client/petstore/typescript-fetch/builds/es6-target - samples/client/petstore/typescript-fetch/builds/with-npm-version - samples/client/petstore/typescript-fetch/tests/default - samples/client/petstore/typescript-node/npm - samples/client/petstore/typescript-rxjs/builds/with-npm-version - samples/client/petstore/typescript-axios/builds/with-npm-version - samples/client/petstore/typescript-axios/tests/default - samples/client/petstore/javascript-flowtyped - samples/client/petstore/javascript-es6 - samples/client/petstore/javascript-promise-es6 - - - - - samples.circleci.node4 - - - env - samples.circleci.node4 - - - - - - - - samples.circleci.others - - - env - samples.circleci.others - - - - - - samples/client/petstore/scala-akka - samples/client/petstore/scala-sttp - samples/client/petstore/scala-sttp4 - samples/client/petstore/clojure - samples/client/petstore/java/jersey2-java8 - samples/openapi3/client/petstore/java/jersey2-java8 - samples/client/petstore/java/jersey3 - samples/client/others/java/okhttp-gson-streaming - samples/client/petstore/java/okhttp-gson - samples/client/petstore/java/okhttp-gson-3.1 - samples/client/petstore/java/resteasy - samples/client/petstore/java-micronaut-client - samples/client/petstore/java/apache-httpclient - - samples/server/petstore/java-undertow - - - - - samples.misc - - - env - samples.misc - - - - - - - - - samples/client/petstore/go - samples/openapi3/client/petstore/go - - - - - samples.dart - - - env - samples.dart - - - - samples/openapi3/client/petstore/dart2/petstore_client_lib - samples/openapi3/client/petstore/dart-dio/oneof - samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance - samples/openapi3/client/petstore/dart-dio/oneof_primitive - samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake - samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable - - - - samples.ios - - - env - samples.ios - - - - - samples/client/petstore/swift5/alamofireLibrary - samples/client/petstore/swift5/combineLibrary - samples/client/petstore/swift5/default - samples/client/petstore/swift5/deprecated - samples/client/petstore/swift5/frozenEnums - samples/client/petstore/swift5/nonPublicApi - samples/client/petstore/swift5/objcCompatible - samples/client/petstore/swift5/promisekitLibrary - samples/client/petstore/swift5/readonlyProperties - samples/client/petstore/swift5/resultLibrary - samples/client/petstore/swift5/rxswiftLibrary - samples/client/petstore/swift5/urlsessionLibrary - - - - - - openapi-generator @@ -1449,17 +1211,17 @@ 1.0.2 4.9.10 3.0.9 - 31.1-jre + 32.1.3-jre 4.3.1 - 2.14.3 - 2.14.0 - 2.14.0 + 2.15.2 + 2.15.3 + 2.15.3 0.8.10 1.15 4.13.2 1.6.21 1.6.21 - 1.18.24 + 1.18.30 3.6.0 3.11.0 3.3.0 @@ -1469,7 +1231,7 @@ 4.0.0-M8 3.0.0 4.10.0 - 7.39.1 + 8.8.3 3.12.0 0.10.2 1.4 @@ -1477,7 +1239,7 @@ 1.7.36 3.1.12.2 io.swagger.parser.v3 - 2.1.14 + 2.1.19 7.5 1.34 3.4.3 diff --git a/run-in-docker.sh b/run-in-docker.sh index bdfa80b0ef53..077a9c972a56 100755 --- a/run-in-docker.sh +++ b/run-in-docker.sh @@ -15,10 +15,10 @@ docker run --rm -it \ -w /gen \ -e GEN_DIR=/gen \ -e MAVEN_CONFIG=/var/maven/.m2 \ - -e MAVEN_OPTS="-Dhttps.protocols=TLSv1.2 -Dmaven.repo.local=/var/maven/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true -Djacoco.skip=true" \ + -e MAVEN_OPTS="-Dmaven.repo.local=/var/maven/.m2/repository -Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=WARN -Dorg.slf4j.simpleLogger.showDateTime=true -Djava.awt.headless=true -Djacoco.skip=true" \ -u "$(id -u):$(id -g)" \ -v "${PWD}:/gen" \ -v "${PWD}/CI/run-in-docker-settings.xml:/var/maven/.m2/settings.xml" \ -v "${maven_cache_repo}:/var/maven/.m2/repository" \ --entrypoint /gen/docker-entrypoint.sh \ - maven:3-jdk-11 "$@" + maven:3-eclipse-temurin-17 "$@" diff --git a/samples/client/echo_api/csharp-restsharp/.openapi-generator/VERSION b/samples/client/echo_api/csharp-restsharp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/csharp-restsharp/.openapi-generator/VERSION +++ b/samples/client/echo_api/csharp-restsharp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/csharp-restsharp/README.md b/samples/client/echo_api/csharp-restsharp/README.md index 96bb4d4a50d6..c350eebaa413 100644 --- a/samples/client/echo_api/csharp-restsharp/README.md +++ b/samples/client/echo_api/csharp-restsharp/README.md @@ -117,9 +117,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**TestAuthHttpBasic**](docs/AuthApi.md#testauthhttpbasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**TestAuthHttpBearer**](docs/AuthApi.md#testauthhttpbearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**TestBinaryGif**](docs/BodyApi.md#testbinarygif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**TestBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testbodyapplicationoctetstreambinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**TestBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testbodymultipartformdataarrayofbinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**TestBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testbodymultipartformdatasinglebinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**TestEchoBodyAllOfPet**](docs/BodyApi.md#testechobodyallofpet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**TestEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testechobodyfreeformobjectresponsestring) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**TestEchoBodyPet**](docs/BodyApi.md#testechobodypet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**TestEchoBodyPetResponseString**](docs/BodyApi.md#testechobodypetresponsestring) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -164,3 +167,8 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer Authentication + diff --git a/samples/client/echo_api/csharp-restsharp/api/openapi.yaml b/samples/client/echo_api/csharp-restsharp/api/openapi.yaml index cef46d3ec210..e4f825722a4f 100644 --- a/samples/client/echo_api/csharp-restsharp/api/openapi.yaml +++ b/samples/client/echo_api/csharp-restsharp/api/openapi.yaml @@ -403,6 +403,22 @@ paths: summary: Test body parameter(s) tags: - body + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body /echo/body/Pet/response_string: post: description: Test empty response body @@ -470,6 +486,25 @@ paths: summary: Test binary (gif) response body tags: - body + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -505,6 +540,22 @@ paths: summary: To test HTTP basic authentication tags: - auth + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth components: requestBodies: Pet: @@ -513,6 +564,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -755,6 +813,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -769,4 +833,7 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/csharp-restsharp/docs/AuthApi.md b/samples/client/echo_api/csharp-restsharp/docs/AuthApi.md index cd93cd1eb3ac..04ec8ffa8f69 100644 --- a/samples/client/echo_api/csharp-restsharp/docs/AuthApi.md +++ b/samples/client/echo_api/csharp-restsharp/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* | Method | HTTP request | Description | |--------|--------------|-------------| | [**TestAuthHttpBasic**](AuthApi.md#testauthhttpbasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**TestAuthHttpBearer**](AuthApi.md#testauthhttpbearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | # **TestAuthHttpBasic** @@ -96,3 +97,92 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAuthHttpBearer** +> string TestAuthHttpBearer () + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAuthHttpBearerExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost:3000"; + // Configure Bearer token for authorization: http_bearer_auth + config.AccessToken = "YOUR_BEARER_TOKEN"; + + var apiInstance = new AuthApi(config); + + try + { + // To test HTTP bearer authentication + string result = apiInstance.TestAuthHttpBearer(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling AuthApi.TestAuthHttpBearer: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAuthHttpBearerWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // To test HTTP bearer authentication + ApiResponse response = apiInstance.TestAuthHttpBearerWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling AuthApi.TestAuthHttpBearerWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +**string** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/csharp-restsharp/docs/BodyApi.md b/samples/client/echo_api/csharp-restsharp/docs/BodyApi.md index 4d33c624608b..e1e031583b63 100644 --- a/samples/client/echo_api/csharp-restsharp/docs/BodyApi.md +++ b/samples/client/echo_api/csharp-restsharp/docs/BodyApi.md @@ -7,6 +7,8 @@ All URIs are relative to *http://localhost:3000* | [**TestBinaryGif**](BodyApi.md#testbinarygif) | **POST** /binary/gif | Test binary (gif) response body | | [**TestBodyApplicationOctetstreamBinary**](BodyApi.md#testbodyapplicationoctetstreambinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**TestBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testbodymultipartformdataarrayofbinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**TestBodyMultipartFormdataSingleBinary**](BodyApi.md#testbodymultipartformdatasinglebinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**TestEchoBodyAllOfPet**](BodyApi.md#testechobodyallofpet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**TestEchoBodyFreeFormObjectResponseString**](BodyApi.md#testechobodyfreeformobjectresponsestring) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**TestEchoBodyPet**](BodyApi.md#testechobodypet) | **POST** /echo/body/Pet | Test body parameter(s) | | [**TestEchoBodyPetResponseString**](BodyApi.md#testechobodypetresponsestring) | **POST** /echo/body/Pet/response_string | Test empty response body | @@ -273,6 +275,188 @@ No authorization required - **Accept**: text/plain +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestBodyMultipartFormdataSingleBinary** +> string TestBodyMultipartFormdataSingleBinary (System.IO.Stream? myFile = null) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestBodyMultipartFormdataSingleBinaryExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost:3000"; + var apiInstance = new BodyApi(config); + var myFile = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream? | (optional) + + try + { + // Test single binary in multipart mime + string result = apiInstance.TestBodyMultipartFormdataSingleBinary(myFile); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling BodyApi.TestBodyMultipartFormdataSingleBinary: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestBodyMultipartFormdataSingleBinaryWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Test single binary in multipart mime + ApiResponse response = apiInstance.TestBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling BodyApi.TestBodyMultipartFormdataSingleBinaryWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **myFile** | **System.IO.Stream?****System.IO.Stream?** | | [optional] | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **TestEchoBodyAllOfPet** +> Pet TestEchoBodyAllOfPet (Pet? pet = null) + +Test body parameter(s) + +Test body parameter(s) + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestEchoBodyAllOfPetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost:3000"; + var apiInstance = new BodyApi(config); + var pet = new Pet?(); // Pet? | Pet object that needs to be added to the store (optional) + + try + { + // Test body parameter(s) + Pet result = apiInstance.TestEchoBodyAllOfPet(pet); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling BodyApi.TestEchoBodyAllOfPet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestEchoBodyAllOfPetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // Test body parameter(s) + ApiResponse response = apiInstance.TestEchoBodyAllOfPetWithHttpInfo(pet); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling BodyApi.TestEchoBodyAllOfPetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **pet** | [**Pet?**](Pet?.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + + ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| diff --git a/samples/client/echo_api/csharp-restsharp/docs/QueryApi.md b/samples/client/echo_api/csharp-restsharp/docs/QueryApi.md index 681e00fa5fe6..227f3fa7494d 100644 --- a/samples/client/echo_api/csharp-restsharp/docs/QueryApi.md +++ b/samples/client/echo_api/csharp-restsharp/docs/QueryApi.md @@ -108,7 +108,7 @@ No authorization required # **TestQueryDatetimeDateString** -> string TestQueryDatetimeDateString (DateTime? datetimeQuery = null, DateTime? dateQuery = null, string? stringQuery = null) +> string TestQueryDatetimeDateString (DateTime? datetimeQuery = null, DateOnly? dateQuery = null, string? stringQuery = null) Test query parameter(s) @@ -132,7 +132,7 @@ namespace Example config.BasePath = "http://localhost:3000"; var apiInstance = new QueryApi(config); var datetimeQuery = DateTime.Parse("2013-10-20T19:20:30+01:00"); // DateTime? | (optional) - var dateQuery = DateTime.Parse("2013-10-20"); // DateTime? | (optional) + var dateQuery = DateOnly.Parse("2013-10-20"); // DateOnly? | (optional) var stringQuery = "stringQuery_example"; // string? | (optional) try @@ -177,7 +177,7 @@ catch (ApiException e) | Name | Type | Description | Notes | |------|------|-------------|-------| | **datetimeQuery** | **DateTime?** | | [optional] | -| **dateQuery** | **DateTime?** | | [optional] | +| **dateQuery** | **DateOnly?** | | [optional] | | **stringQuery** | **string?** | | [optional] | ### Return type diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/.editorconfig b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/.editorconfig new file mode 100644 index 000000000000..5ad6921484a1 --- /dev/null +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/.editorconfig @@ -0,0 +1,2 @@ +[*.cs] +dotnet_diagnostic.xUnit1031.severity = none diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index ebda386b94da..acda1cdef8ff 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/AuthApi.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/AuthApi.cs index 0e631350b5f4..19575017c5fb 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/AuthApi.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/AuthApi.cs @@ -47,6 +47,27 @@ public interface IAuthApiSync : IApiAccessor /// Index associated with the operation. /// ApiResponse of string ApiResponse TestAuthHttpBasicWithHttpInfo(int operationIndex = 0); + /// + /// To test HTTP bearer authentication + /// + /// + /// To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// string + string TestAuthHttpBearer(int operationIndex = 0); + + /// + /// To test HTTP bearer authentication + /// + /// + /// To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of string + ApiResponse TestAuthHttpBearerWithHttpInfo(int operationIndex = 0); #endregion Synchronous Operations } @@ -79,6 +100,29 @@ public interface IAuthApiAsync : IApiAccessor /// Cancellation Token to cancel the request. /// Task of ApiResponse (string) System.Threading.Tasks.Task> TestAuthHttpBasicWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// To test HTTP bearer authentication + /// + /// + /// To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task TestAuthHttpBearerAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// To test HTTP bearer authentication + /// + /// + /// To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> TestAuthHttpBearerWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); #endregion Asynchronous Operations } @@ -337,5 +381,143 @@ public Org.OpenAPITools.Client.ApiResponse TestAuthHttpBasicWithHttpInfo return localVarResponse; } + /// + /// To test HTTP bearer authentication To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// string + public string TestAuthHttpBearer(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestAuthHttpBearerWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// To test HTTP bearer authentication To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse TestAuthHttpBearerWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "text/plain" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "AuthApi.TestAuthHttpBearer"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_bearer_auth) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = this.Client.Post("/auth/http/bearer", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAuthHttpBearer", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// To test HTTP bearer authentication To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task TestAuthHttpBearerAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestAuthHttpBearerWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// To test HTTP bearer authentication To test HTTP bearer authentication + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> TestAuthHttpBearerWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "text/plain" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "AuthApi.TestAuthHttpBearer"; + localVarRequestOptions.OperationIndex = operationIndex; + + // authentication (http_bearer_auth) required + // bearer authentication required + if (!string.IsNullOrEmpty(this.Configuration.AccessToken) && !localVarRequestOptions.HeaderParameters.ContainsKey("Authorization")) + { + localVarRequestOptions.HeaderParameters.Add("Authorization", "Bearer " + this.Configuration.AccessToken); + } + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/auth/http/bearer", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAuthHttpBearer", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + } } diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/BodyApi.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/BodyApi.cs index abcd4a4071a7..11c028a2e0c6 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/BodyApi.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/BodyApi.cs @@ -95,6 +95,52 @@ public interface IBodyApiSync : IApiAccessor /// ApiResponse of string ApiResponse TestBodyMultipartFormdataArrayOfBinaryWithHttpInfo(List files, int operationIndex = 0); /// + /// Test single binary in multipart mime + /// + /// + /// Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// string + string TestBodyMultipartFormdataSingleBinary(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0); + + /// + /// Test single binary in multipart mime + /// + /// + /// Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// ApiResponse of string + ApiResponse TestBodyMultipartFormdataSingleBinaryWithHttpInfo(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0); + /// + /// Test body parameter(s) + /// + /// + /// Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Pet + Pet TestEchoBodyAllOfPet(Pet? pet = default(Pet?), int operationIndex = 0); + + /// + /// Test body parameter(s) + /// + /// + /// Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// ApiResponse of Pet + ApiResponse TestEchoBodyAllOfPetWithHttpInfo(Pet? pet = default(Pet?), int operationIndex = 0); + /// /// Test free form object /// /// @@ -269,6 +315,56 @@ public interface IBodyApiAsync : IApiAccessor /// Task of ApiResponse (string) System.Threading.Tasks.Task> TestBodyMultipartFormdataArrayOfBinaryWithHttpInfoAsync(List files, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// Test single binary in multipart mime + /// + /// + /// Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + System.Threading.Tasks.Task TestBodyMultipartFormdataSingleBinaryAsync(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Test single binary in multipart mime + /// + /// + /// Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + System.Threading.Tasks.Task> TestBodyMultipartFormdataSingleBinaryWithHttpInfoAsync(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// + /// Test body parameter(s) + /// + /// + /// Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Pet + System.Threading.Tasks.Task TestEchoBodyAllOfPetAsync(Pet? pet = default(Pet?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Test body parameter(s) + /// + /// + /// Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + System.Threading.Tasks.Task> TestEchoBodyAllOfPetWithHttpInfoAsync(Pet? pet = default(Pet?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// Test free form object /// /// @@ -900,6 +996,280 @@ public Org.OpenAPITools.Client.ApiResponse TestBodyMultipartFormdataArra return localVarResponse; } + /// + /// Test single binary in multipart mime Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// string + public string TestBodyMultipartFormdataSingleBinary(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile); + return localVarResponse.Data; + } + + /// + /// Test single binary in multipart mime Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// ApiResponse of string + public Org.OpenAPITools.Client.ApiResponse TestBodyMultipartFormdataSingleBinaryWithHttpInfo(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "text/plain" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (myFile != null) + { + localVarRequestOptions.FileParameters.Add("my-file", myFile); + } + + localVarRequestOptions.Operation = "BodyApi.TestBodyMultipartFormdataSingleBinary"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/body/application/octetstream/single_binary", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyMultipartFormdataSingleBinary", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test single binary in multipart mime Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of string + public async System.Threading.Tasks.Task TestBodyMultipartFormdataSingleBinaryAsync(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestBodyMultipartFormdataSingleBinaryWithHttpInfoAsync(myFile, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test single binary in multipart mime Test single binary in multipart mime + /// + /// Thrown when fails to make API call + /// (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (string) + public async System.Threading.Tasks.Task> TestBodyMultipartFormdataSingleBinaryWithHttpInfoAsync(System.IO.Stream? myFile = default(System.IO.Stream?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "multipart/form-data" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "text/plain" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + if (myFile != null) + { + localVarRequestOptions.FileParameters.Add("my-file", myFile); + } + + localVarRequestOptions.Operation = "BodyApi.TestBodyMultipartFormdataSingleBinary"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/body/application/octetstream/single_binary", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestBodyMultipartFormdataSingleBinary", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test body parameter(s) Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Pet + public Pet TestEchoBodyAllOfPet(Pet? pet = default(Pet?), int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = TestEchoBodyAllOfPetWithHttpInfo(pet); + return localVarResponse.Data; + } + + /// + /// Test body parameter(s) Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// ApiResponse of Pet + public Org.OpenAPITools.Client.ApiResponse TestEchoBodyAllOfPetWithHttpInfo(Pet? pet = default(Pet?), int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "BodyApi.TestEchoBodyAllOfPet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/echo/body/allOf/Pet", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEchoBodyAllOfPet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// Test body parameter(s) Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of Pet + public async System.Threading.Tasks.Task TestEchoBodyAllOfPetAsync(Pet? pet = default(Pet?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestEchoBodyAllOfPetWithHttpInfoAsync(pet, operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// Test body parameter(s) Test body parameter(s) + /// + /// Thrown when fails to make API call + /// Pet object that needs to be added to the store (optional) + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (Pet) + public async System.Threading.Tasks.Task> TestEchoBodyAllOfPetWithHttpInfoAsync(Pet? pet = default(Pet?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = pet; + + localVarRequestOptions.Operation = "BodyApi.TestEchoBodyAllOfPet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/echo/body/allOf/Pet", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestEchoBodyAllOfPet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// Test free form object Test free form object /// diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/QueryApi.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/QueryApi.cs index a19c0ef303cf..9b54b9048f60 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/QueryApi.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Api/QueryApi.cs @@ -64,7 +64,7 @@ public interface IQueryApiSync : IApiAccessor /// (optional) /// Index associated with the operation. /// string - string TestQueryDatetimeDateString(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0); + string TestQueryDatetimeDateString(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0); /// /// Test query parameter(s) @@ -78,7 +78,7 @@ public interface IQueryApiSync : IApiAccessor /// (optional) /// Index associated with the operation. /// ApiResponse of string - ApiResponse TestQueryDatetimeDateStringWithHttpInfo(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0); + ApiResponse TestQueryDatetimeDateStringWithHttpInfo(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0); /// /// Test query parameter(s) /// @@ -270,7 +270,7 @@ public interface IQueryApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of string - System.Threading.Tasks.Task TestQueryDatetimeDateStringAsync(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task TestQueryDatetimeDateStringAsync(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Test query parameter(s) @@ -285,7 +285,7 @@ public interface IQueryApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse (string) - System.Threading.Tasks.Task> TestQueryDatetimeDateStringWithHttpInfoAsync(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> TestQueryDatetimeDateStringWithHttpInfoAsync(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Test query parameter(s) /// @@ -719,7 +719,7 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory /// (optional) /// Index associated with the operation. /// string - public string TestQueryDatetimeDateString(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0) + public string TestQueryDatetimeDateString(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0) { Org.OpenAPITools.Client.ApiResponse localVarResponse = TestQueryDatetimeDateStringWithHttpInfo(datetimeQuery, dateQuery, stringQuery); return localVarResponse.Data; @@ -734,7 +734,7 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory /// (optional) /// Index associated with the operation. /// ApiResponse of string - public Org.OpenAPITools.Client.ApiResponse TestQueryDatetimeDateStringWithHttpInfo(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0) + public Org.OpenAPITools.Client.ApiResponse TestQueryDatetimeDateStringWithHttpInfo(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); @@ -799,7 +799,7 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of string - public async System.Threading.Tasks.Task TestQueryDatetimeDateStringAsync(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task TestQueryDatetimeDateStringAsync(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.ApiResponse localVarResponse = await TestQueryDatetimeDateStringWithHttpInfoAsync(datetimeQuery, dateQuery, stringQuery, operationIndex, cancellationToken).ConfigureAwait(false); return localVarResponse.Data; @@ -815,7 +815,7 @@ public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse (string) - public async System.Threading.Tasks.Task> TestQueryDatetimeDateStringWithHttpInfoAsync(DateTime? datetimeQuery = default(DateTime?), DateTime? dateQuery = default(DateTime?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> TestQueryDatetimeDateStringWithHttpInfoAsync(DateTime? datetimeQuery = default(DateTime?), DateOnly? dateQuery = default(DateOnly?), string? stringQuery = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs index a52908ef5df0..c569deebc531 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Client/ApiClient.cs @@ -548,7 +548,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; using (RestClient client = new RestClient(clientOptions, diff --git a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 89948381e2ee..addc6411ef6b 100644 --- a/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/echo_api/csharp-restsharp/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,7 +24,7 @@ - + diff --git a/samples/client/echo_api/go/.openapi-generator/VERSION b/samples/client/echo_api/go/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/go/.openapi-generator/VERSION +++ b/samples/client/echo_api/go/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/go/README.md b/samples/client/echo_api/go/README.md index f4b376bc3a82..2f5df82beb0a 100644 --- a/samples/client/echo_api/go/README.md +++ b/samples/client/echo_api/go/README.md @@ -13,20 +13,20 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat Install the following dependencies: -```shell +```sh go get github.com/stretchr/testify/assert go get golang.org/x/net/context ``` Put the package under your project folder and add the following in import: -```golang +```go import openapi "github.com/GIT_USER_ID/GIT_REPO_ID" ``` To use a proxy, set the environment variable `HTTP_PROXY`: -```golang +```go os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") ``` @@ -36,17 +36,17 @@ Default configuration comes with `Servers` field that contains server objects as ### Select Server Configuration -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. +For using other server than the one defined on index 0 set context value `openapi.ContextServerIndex` of type `int`. -```golang +```go ctx := context.WithValue(context.Background(), openapi.ContextServerIndex, 1) ``` ### Templated Server URL -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. +Templated server URL is formatted using default variables from configuration or from context value `openapi.ContextServerVariables` of type `map[string]string`. -```golang +```go ctx := context.WithValue(context.Background(), openapi.ContextServerVariables, map[string]string{ "basePath": "v2", }) @@ -58,9 +58,9 @@ Note, enum values are always validated and all unused variables are silently ign Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. +Similar rules for overriding default operation server index and variables applies by using `openapi.ContextOperationServerIndices` and `openapi.ContextOperationServerVariables` context maps. -```golang +```go ctx := context.WithValue(context.Background(), openapi.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -78,9 +78,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthAPI* | [**TestAuthHttpBasic**](docs/AuthAPI.md#testauthhttpbasic) | **Post** /auth/http/basic | To test HTTP basic authentication +*AuthAPI* | [**TestAuthHttpBearer**](docs/AuthAPI.md#testauthhttpbearer) | **Post** /auth/http/bearer | To test HTTP bearer authentication *BodyAPI* | [**TestBinaryGif**](docs/BodyAPI.md#testbinarygif) | **Post** /binary/gif | Test binary (gif) response body *BodyAPI* | [**TestBodyApplicationOctetstreamBinary**](docs/BodyAPI.md#testbodyapplicationoctetstreambinary) | **Post** /body/application/octetstream/binary | Test body parameter(s) *BodyAPI* | [**TestBodyMultipartFormdataArrayOfBinary**](docs/BodyAPI.md#testbodymultipartformdataarrayofbinary) | **Post** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyAPI* | [**TestBodyMultipartFormdataSingleBinary**](docs/BodyAPI.md#testbodymultipartformdatasinglebinary) | **Post** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyAPI* | [**TestEchoBodyAllOfPet**](docs/BodyAPI.md#testechobodyallofpet) | **Post** /echo/body/allOf/Pet | Test body parameter(s) *BodyAPI* | [**TestEchoBodyFreeFormObjectResponseString**](docs/BodyAPI.md#testechobodyfreeformobjectresponsestring) | **Post** /echo/body/FreeFormObject/response_string | Test free form object *BodyAPI* | [**TestEchoBodyPet**](docs/BodyAPI.md#testechobodypet) | **Post** /echo/body/Pet | Test body parameter(s) *BodyAPI* | [**TestEchoBodyPetResponseString**](docs/BodyAPI.md#testechobodypetresponsestring) | **Post** /echo/body/Pet/response_string | Test empty response body @@ -124,14 +127,25 @@ Authentication schemes defined for the API: Example -```golang -auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ - UserName: "username", - Password: "password", +```go +auth := context.WithValue(context.Background(), openapi.ContextBasicAuth, openapi.BasicAuth{ + UserName: "username", + Password: "password", }) r, err := client.Service.Operation(auth, args) ``` +### http_bearer_auth + +- **Type**: HTTP Bearer token authentication + +Example + +```go +auth := context.WithValue(context.Background(), openapi.ContextAccessToken, "BEARER_TOKEN_STRING") +r, err := client.Service.Operation(auth, args) +``` + ## Documentation for Utility Methods diff --git a/samples/client/echo_api/go/api/openapi.yaml b/samples/client/echo_api/go/api/openapi.yaml index 104784c4a235..bb31f3770bb4 100644 --- a/samples/client/echo_api/go/api/openapi.yaml +++ b/samples/client/echo_api/go/api/openapi.yaml @@ -403,6 +403,22 @@ paths: summary: Test body parameter(s) tags: - body + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body /echo/body/Pet/response_string: post: description: Test empty response body @@ -470,6 +486,25 @@ paths: summary: Test binary (gif) response body tags: - body + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -505,6 +540,22 @@ paths: summary: To test HTTP basic authentication tags: - auth + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth components: requestBodies: Pet: @@ -513,6 +564,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -755,6 +813,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -769,3 +833,6 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/go/api_auth.go b/samples/client/echo_api/go/api_auth.go index 0af21ce06031..d14f693e51f1 100644 --- a/samples/client/echo_api/go/api_auth.go +++ b/samples/client/echo_api/go/api_auth.go @@ -121,3 +121,102 @@ func (a *AuthAPIService) TestAuthHttpBasicExecute(r ApiTestAuthHttpBasicRequest) return localVarReturnValue, localVarHTTPResponse, nil } + +type ApiTestAuthHttpBearerRequest struct { + ctx context.Context + ApiService *AuthAPIService +} + +func (r ApiTestAuthHttpBearerRequest) Execute() (string, *http.Response, error) { + return r.ApiService.TestAuthHttpBearerExecute(r) +} + +/* +TestAuthHttpBearer To test HTTP bearer authentication + +To test HTTP bearer authentication + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestAuthHttpBearerRequest +*/ +func (a *AuthAPIService) TestAuthHttpBearer(ctx context.Context) ApiTestAuthHttpBearerRequest { + return ApiTestAuthHttpBearerRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return string +func (a *AuthAPIService) TestAuthHttpBearerExecute(r ApiTestAuthHttpBearerRequest) (string, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue string + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "AuthAPIService.TestAuthHttpBearer") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/auth/http/bearer" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"text/plain"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/samples/client/echo_api/go/api_body.go b/samples/client/echo_api/go/api_body.go index f06ffc274b65..7c4f82522d73 100644 --- a/samples/client/echo_api/go/api_body.go +++ b/samples/client/echo_api/go/api_body.go @@ -306,17 +306,138 @@ func (a *BodyAPIService) TestBodyMultipartFormdataArrayOfBinaryExecute(r ApiTest var filesLocalVarFileBytes []byte filesLocalVarFormFileName = "files" - - filesLocalVarFile := r.files if filesLocalVarFile != nil { - fbs, _ := io.ReadAll(filesLocalVarFile) + // loop through the array to prepare multiple files upload + for _, filesLocalVarFileValue := range filesLocalVarFile { + fbs, _ := io.ReadAll(filesLocalVarFileValue) + + filesLocalVarFileBytes = fbs + filesLocalVarFileName = filesLocalVarFileValue.Name() + filesLocalVarFileValue.Close() + formFiles = append(formFiles, formFile{fileBytes: filesLocalVarFileBytes, fileName: filesLocalVarFileName, formFileName: filesLocalVarFormFileName}) + } + } + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + +type ApiTestBodyMultipartFormdataSingleBinaryRequest struct { + ctx context.Context + ApiService *BodyAPIService + myFile *os.File +} + +func (r ApiTestBodyMultipartFormdataSingleBinaryRequest) MyFile(myFile *os.File) ApiTestBodyMultipartFormdataSingleBinaryRequest { + r.myFile = myFile + return r +} + +func (r ApiTestBodyMultipartFormdataSingleBinaryRequest) Execute() (string, *http.Response, error) { + return r.ApiService.TestBodyMultipartFormdataSingleBinaryExecute(r) +} + +/* +TestBodyMultipartFormdataSingleBinary Test single binary in multipart mime + +Test single binary in multipart mime + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestBodyMultipartFormdataSingleBinaryRequest +*/ +func (a *BodyAPIService) TestBodyMultipartFormdataSingleBinary(ctx context.Context) ApiTestBodyMultipartFormdataSingleBinaryRequest { + return ApiTestBodyMultipartFormdataSingleBinaryRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return string +func (a *BodyAPIService) TestBodyMultipartFormdataSingleBinaryExecute(r ApiTestBodyMultipartFormdataSingleBinaryRequest) (string, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue string + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "BodyAPIService.TestBodyMultipartFormdataSingleBinary") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/body/application/octetstream/single_binary" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"multipart/form-data"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"text/plain"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + var myFileLocalVarFormFileName string + var myFileLocalVarFileName string + var myFileLocalVarFileBytes []byte + + myFileLocalVarFormFileName = "my-file" + myFileLocalVarFile := r.myFile + + if myFileLocalVarFile != nil { + fbs, _ := io.ReadAll(myFileLocalVarFile) - filesLocalVarFileBytes = fbs - filesLocalVarFileName = filesLocalVarFile.Name() - filesLocalVarFile.Close() - formFiles = append(formFiles, formFile{fileBytes: filesLocalVarFileBytes, fileName: filesLocalVarFileName, formFileName: filesLocalVarFormFileName}) + myFileLocalVarFileBytes = fbs + myFileLocalVarFileName = myFileLocalVarFile.Name() + myFileLocalVarFile.Close() + formFiles = append(formFiles, formFile{fileBytes: myFileLocalVarFileBytes, fileName: myFileLocalVarFileName, formFileName: myFileLocalVarFormFileName}) } req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) if err != nil { @@ -355,6 +476,114 @@ func (a *BodyAPIService) TestBodyMultipartFormdataArrayOfBinaryExecute(r ApiTest return localVarReturnValue, localVarHTTPResponse, nil } +type ApiTestEchoBodyAllOfPetRequest struct { + ctx context.Context + ApiService *BodyAPIService + pet *Pet +} + +// Pet object that needs to be added to the store +func (r ApiTestEchoBodyAllOfPetRequest) Pet(pet Pet) ApiTestEchoBodyAllOfPetRequest { + r.pet = &pet + return r +} + +func (r ApiTestEchoBodyAllOfPetRequest) Execute() (*Pet, *http.Response, error) { + return r.ApiService.TestEchoBodyAllOfPetExecute(r) +} + +/* +TestEchoBodyAllOfPet Test body parameter(s) + +Test body parameter(s) + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestEchoBodyAllOfPetRequest +*/ +func (a *BodyAPIService) TestEchoBodyAllOfPet(ctx context.Context) ApiTestEchoBodyAllOfPetRequest { + return ApiTestEchoBodyAllOfPetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return Pet +func (a *BodyAPIService) TestEchoBodyAllOfPetExecute(r ApiTestEchoBodyAllOfPetRequest) (*Pet, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *Pet + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "BodyAPIService.TestEchoBodyAllOfPet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/echo/body/allOf/Pet" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.pet + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} + type ApiTestEchoBodyFreeFormObjectResponseStringRequest struct { ctx context.Context ApiService *BodyAPIService diff --git a/samples/client/echo_api/go/client.go b/samples/client/echo_api/go/client.go index 2c88423e340a..fba23f940742 100644 --- a/samples/client/echo_api/go/client.go +++ b/samples/client/echo_api/go/client.go @@ -36,8 +36,8 @@ import ( ) var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) ) @@ -431,6 +431,11 @@ func (c *APIClient) prepareRequest( localVarRequest.SetBasicAuth(auth.UserName, auth.Password) } + // AccessToken Authentication + if auth, ok := ctx.Value(ContextAccessToken).(string); ok { + localVarRequest.Header.Add("Authorization", "Bearer "+auth) + } + } for header, value := range c.cfg.DefaultHeader { @@ -457,7 +462,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = f.Seek(0, io.SeekStart) - err = os.Remove(f.Name()) return } if f, ok := v.(**os.File); ok { @@ -470,16 +474,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = (*f).Seek(0, io.SeekStart) - err = os.Remove((*f).Name()) return } - if xmlCheck.MatchString(contentType) { + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } - if jsonCheck.MatchString(contentType) { + if JsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { @@ -544,9 +547,9 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { + } else if XmlCheck.MatchString(contentType) { var bs []byte bs, err = xml.Marshal(body) if err == nil { diff --git a/samples/client/echo_api/go/configuration.go b/samples/client/echo_api/go/configuration.go index 43d6759c24f8..f0a872b31529 100644 --- a/samples/client/echo_api/go/configuration.go +++ b/samples/client/echo_api/go/configuration.go @@ -32,6 +32,9 @@ var ( // ContextBasicAuth takes BasicAuth as authentication for the request. ContextBasicAuth = contextKey("basic") + // ContextAccessToken takes a string oauth2 access token as authentication for the request. + ContextAccessToken = contextKey("accesstoken") + // ContextServerIndex uses a server configuration from the index. ContextServerIndex = contextKey("serverIndex") diff --git a/samples/client/echo_api/go/docs/AuthAPI.md b/samples/client/echo_api/go/docs/AuthAPI.md index e7bbfc23abd5..046104c5053c 100644 --- a/samples/client/echo_api/go/docs/AuthAPI.md +++ b/samples/client/echo_api/go/docs/AuthAPI.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* Method | HTTP request | Description ------------- | ------------- | ------------- [**TestAuthHttpBasic**](AuthAPI.md#TestAuthHttpBasic) | **Post** /auth/http/basic | To test HTTP basic authentication +[**TestAuthHttpBearer**](AuthAPI.md#TestAuthHttpBearer) | **Post** /auth/http/bearer | To test HTTP bearer authentication @@ -22,23 +23,23 @@ To test HTTP basic authentication package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.AuthAPI.TestAuthHttpBasic(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `AuthAPI.TestAuthHttpBasic``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestAuthHttpBasic`: string - fmt.Fprintf(os.Stdout, "Response from `AuthAPI.TestAuthHttpBasic`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.AuthAPI.TestAuthHttpBasic(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `AuthAPI.TestAuthHttpBasic``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestAuthHttpBasic`: string + fmt.Fprintf(os.Stdout, "Response from `AuthAPI.TestAuthHttpBasic`: %v\n", resp) } ``` @@ -68,3 +69,64 @@ Other parameters are passed through a pointer to a apiTestAuthHttpBasicRequest s [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +## TestAuthHttpBearer + +> string TestAuthHttpBearer(ctx).Execute() + +To test HTTP bearer authentication + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.AuthAPI.TestAuthHttpBearer(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `AuthAPI.TestAuthHttpBearer``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestAuthHttpBearer`: string + fmt.Fprintf(os.Stdout, "Response from `AuthAPI.TestAuthHttpBearer`: %v\n", resp) +} +``` + +### Path Parameters + +This endpoint does not need any parameter. + +### Other Parameters + +Other parameters are passed through a pointer to a apiTestAuthHttpBearerRequest struct via the builder pattern + + +### Return type + +**string** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/samples/client/echo_api/go/docs/BodyAPI.md b/samples/client/echo_api/go/docs/BodyAPI.md index 73b021cdcdea..7fafe50f258e 100644 --- a/samples/client/echo_api/go/docs/BodyAPI.md +++ b/samples/client/echo_api/go/docs/BodyAPI.md @@ -7,6 +7,8 @@ Method | HTTP request | Description [**TestBinaryGif**](BodyAPI.md#TestBinaryGif) | **Post** /binary/gif | Test binary (gif) response body [**TestBodyApplicationOctetstreamBinary**](BodyAPI.md#TestBodyApplicationOctetstreamBinary) | **Post** /body/application/octetstream/binary | Test body parameter(s) [**TestBodyMultipartFormdataArrayOfBinary**](BodyAPI.md#TestBodyMultipartFormdataArrayOfBinary) | **Post** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +[**TestBodyMultipartFormdataSingleBinary**](BodyAPI.md#TestBodyMultipartFormdataSingleBinary) | **Post** /body/application/octetstream/single_binary | Test single binary in multipart mime +[**TestEchoBodyAllOfPet**](BodyAPI.md#TestEchoBodyAllOfPet) | **Post** /echo/body/allOf/Pet | Test body parameter(s) [**TestEchoBodyFreeFormObjectResponseString**](BodyAPI.md#TestEchoBodyFreeFormObjectResponseString) | **Post** /echo/body/FreeFormObject/response_string | Test free form object [**TestEchoBodyPet**](BodyAPI.md#TestEchoBodyPet) | **Post** /echo/body/Pet | Test body parameter(s) [**TestEchoBodyPetResponseString**](BodyAPI.md#TestEchoBodyPetResponseString) | **Post** /echo/body/Pet/response_string | Test empty response body @@ -28,23 +30,23 @@ Test binary (gif) response body package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestBinaryGif(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBinaryGif``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestBinaryGif`: *os.File - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBinaryGif`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestBinaryGif(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBinaryGif``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestBinaryGif`: *os.File + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBinaryGif`: %v\n", resp) } ``` @@ -89,24 +91,24 @@ Test body parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := os.NewFile(1234, "some_file") // *os.File | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestBodyApplicationOctetstreamBinary(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBodyApplicationOctetstreamBinary``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestBodyApplicationOctetstreamBinary`: string - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBodyApplicationOctetstreamBinary`: %v\n", resp) + body := os.NewFile(1234, "some_file") // *os.File | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestBodyApplicationOctetstreamBinary(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBodyApplicationOctetstreamBinary``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestBodyApplicationOctetstreamBinary`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBodyApplicationOctetstreamBinary`: %v\n", resp) } ``` @@ -155,24 +157,24 @@ Test array of binary in multipart mime package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - files := []*os.File{"TODO"} // []*os.File | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestBodyMultipartFormdataArrayOfBinary(context.Background()).Files(files).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBodyMultipartFormdataArrayOfBinary``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestBodyMultipartFormdataArrayOfBinary`: string - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBodyMultipartFormdataArrayOfBinary`: %v\n", resp) + files := []*os.File{"TODO"} // []*os.File | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestBodyMultipartFormdataArrayOfBinary(context.Background()).Files(files).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBodyMultipartFormdataArrayOfBinary``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestBodyMultipartFormdataArrayOfBinary`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBodyMultipartFormdataArrayOfBinary`: %v\n", resp) } ``` @@ -207,6 +209,138 @@ No authorization required [[Back to README]](../README.md) +## TestBodyMultipartFormdataSingleBinary + +> string TestBodyMultipartFormdataSingleBinary(ctx).MyFile(myFile).Execute() + +Test single binary in multipart mime + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + myFile := os.NewFile(1234, "some_file") // *os.File | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestBodyMultipartFormdataSingleBinary(context.Background()).MyFile(myFile).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestBodyMultipartFormdataSingleBinary``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestBodyMultipartFormdataSingleBinary`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestBodyMultipartFormdataSingleBinary`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiTestBodyMultipartFormdataSingleBinaryRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **myFile** | ***os.File** | | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + +## TestEchoBodyAllOfPet + +> Pet TestEchoBodyAllOfPet(ctx).Pet(pet).Execute() + +Test body parameter(s) + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestEchoBodyAllOfPet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyAllOfPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEchoBodyAllOfPet`: Pet + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyAllOfPet`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiTestEchoBodyAllOfPetRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + ## TestEchoBodyFreeFormObjectResponseString > string TestEchoBodyFreeFormObjectResponseString(ctx).Body(body).Execute() @@ -221,24 +355,24 @@ Test free form object package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := map[string]interface{}{ ... } // map[string]interface{} | Free form object (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestEchoBodyFreeFormObjectResponseString(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyFreeFormObjectResponseString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestEchoBodyFreeFormObjectResponseString`: string - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyFreeFormObjectResponseString`: %v\n", resp) + body := map[string]interface{}{ ... } // map[string]interface{} | Free form object (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestEchoBodyFreeFormObjectResponseString(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyFreeFormObjectResponseString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEchoBodyFreeFormObjectResponseString`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyFreeFormObjectResponseString`: %v\n", resp) } ``` @@ -287,24 +421,24 @@ Test body parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestEchoBodyPet(context.Background()).Pet(pet).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyPet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestEchoBodyPet`: Pet - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyPet`: %v\n", resp) + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestEchoBodyPet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEchoBodyPet`: Pet + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyPet`: %v\n", resp) } ``` @@ -353,24 +487,24 @@ Test empty response body package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestEchoBodyPetResponseString(context.Background()).Pet(pet).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyPetResponseString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestEchoBodyPetResponseString`: string - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyPetResponseString`: %v\n", resp) + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestEchoBodyPetResponseString(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyPetResponseString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEchoBodyPetResponseString`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyPetResponseString`: %v\n", resp) } ``` @@ -419,24 +553,24 @@ Test empty json (request body) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - tag := *openapiclient.NewTag() // Tag | Tag object (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.BodyAPI.TestEchoBodyTagResponseString(context.Background()).Tag(tag).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyTagResponseString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestEchoBodyTagResponseString`: string - fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyTagResponseString`: %v\n", resp) + tag := *openapiclient.NewTag() // Tag | Tag object (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.BodyAPI.TestEchoBodyTagResponseString(context.Background()).Tag(tag).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `BodyAPI.TestEchoBodyTagResponseString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEchoBodyTagResponseString`: string + fmt.Fprintf(os.Stdout, "Response from `BodyAPI.TestEchoBodyTagResponseString`: %v\n", resp) } ``` diff --git a/samples/client/echo_api/go/docs/FormAPI.md b/samples/client/echo_api/go/docs/FormAPI.md index 7f3e725dc4a8..56d7d9921db0 100644 --- a/samples/client/echo_api/go/docs/FormAPI.md +++ b/samples/client/echo_api/go/docs/FormAPI.md @@ -23,26 +23,26 @@ Test form parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - integerForm := int32(56) // int32 | (optional) - booleanForm := true // bool | (optional) - stringForm := "stringForm_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FormAPI.TestFormIntegerBooleanString(context.Background()).IntegerForm(integerForm).BooleanForm(booleanForm).StringForm(stringForm).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FormAPI.TestFormIntegerBooleanString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestFormIntegerBooleanString`: string - fmt.Fprintf(os.Stdout, "Response from `FormAPI.TestFormIntegerBooleanString`: %v\n", resp) + integerForm := int32(56) // int32 | (optional) + booleanForm := true // bool | (optional) + stringForm := "stringForm_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FormAPI.TestFormIntegerBooleanString(context.Background()).IntegerForm(integerForm).BooleanForm(booleanForm).StringForm(stringForm).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FormAPI.TestFormIntegerBooleanString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestFormIntegerBooleanString`: string + fmt.Fprintf(os.Stdout, "Response from `FormAPI.TestFormIntegerBooleanString`: %v\n", resp) } ``` @@ -93,29 +93,29 @@ Test form parameter(s) for oneOf schema package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - form1 := "form1_example" // string | (optional) - form2 := int32(56) // int32 | (optional) - form3 := "form3_example" // string | (optional) - form4 := true // bool | (optional) - id := int64(789) // int64 | (optional) - name := "name_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FormAPI.TestFormOneof(context.Background()).Form1(form1).Form2(form2).Form3(form3).Form4(form4).Id(id).Name(name).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FormAPI.TestFormOneof``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestFormOneof`: string - fmt.Fprintf(os.Stdout, "Response from `FormAPI.TestFormOneof`: %v\n", resp) + form1 := "form1_example" // string | (optional) + form2 := int32(56) // int32 | (optional) + form3 := "form3_example" // string | (optional) + form4 := true // bool | (optional) + id := int64(789) // int64 | (optional) + name := "name_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FormAPI.TestFormOneof(context.Background()).Form1(form1).Form2(form2).Form3(form3).Form4(form4).Id(id).Name(name).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FormAPI.TestFormOneof``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestFormOneof`: string + fmt.Fprintf(os.Stdout, "Response from `FormAPI.TestFormOneof`: %v\n", resp) } ``` diff --git a/samples/client/echo_api/go/docs/HeaderAPI.md b/samples/client/echo_api/go/docs/HeaderAPI.md index 18c6b5bef617..859a1f9dd40f 100644 --- a/samples/client/echo_api/go/docs/HeaderAPI.md +++ b/samples/client/echo_api/go/docs/HeaderAPI.md @@ -22,28 +22,28 @@ Test header parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - integerHeader := int32(56) // int32 | (optional) - booleanHeader := true // bool | (optional) - stringHeader := "stringHeader_example" // string | (optional) - enumNonrefStringHeader := "enumNonrefStringHeader_example" // string | (optional) - enumRefStringHeader := openapiclient.StringEnumRef("success") // StringEnumRef | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.HeaderAPI.TestHeaderIntegerBooleanStringEnums(context.Background()).IntegerHeader(integerHeader).BooleanHeader(booleanHeader).StringHeader(stringHeader).EnumNonrefStringHeader(enumNonrefStringHeader).EnumRefStringHeader(enumRefStringHeader).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `HeaderAPI.TestHeaderIntegerBooleanStringEnums``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestHeaderIntegerBooleanStringEnums`: string - fmt.Fprintf(os.Stdout, "Response from `HeaderAPI.TestHeaderIntegerBooleanStringEnums`: %v\n", resp) + integerHeader := int32(56) // int32 | (optional) + booleanHeader := true // bool | (optional) + stringHeader := "stringHeader_example" // string | (optional) + enumNonrefStringHeader := "enumNonrefStringHeader_example" // string | (optional) + enumRefStringHeader := openapiclient.StringEnumRef("success") // StringEnumRef | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.HeaderAPI.TestHeaderIntegerBooleanStringEnums(context.Background()).IntegerHeader(integerHeader).BooleanHeader(booleanHeader).StringHeader(stringHeader).EnumNonrefStringHeader(enumNonrefStringHeader).EnumRefStringHeader(enumRefStringHeader).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `HeaderAPI.TestHeaderIntegerBooleanStringEnums``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestHeaderIntegerBooleanStringEnums`: string + fmt.Fprintf(os.Stdout, "Response from `HeaderAPI.TestHeaderIntegerBooleanStringEnums`: %v\n", resp) } ``` diff --git a/samples/client/echo_api/go/docs/PathAPI.md b/samples/client/echo_api/go/docs/PathAPI.md index 1b976a457e06..2ae33bb6e96a 100644 --- a/samples/client/echo_api/go/docs/PathAPI.md +++ b/samples/client/echo_api/go/docs/PathAPI.md @@ -22,27 +22,27 @@ Test path parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pathString := "pathString_example" // string | - pathInteger := int32(56) // int32 | - enumNonrefStringPath := "enumNonrefStringPath_example" // string | - enumRefStringPath := openapiclient.StringEnumRef("success") // StringEnumRef | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(context.Background(), pathString, pathInteger, enumNonrefStringPath, enumRefStringPath).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath`: string - fmt.Fprintf(os.Stdout, "Response from `PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath`: %v\n", resp) + pathString := "pathString_example" // string | + pathInteger := int32(56) // int32 | + enumNonrefStringPath := "enumNonrefStringPath_example" // string | + enumRefStringPath := openapiclient.StringEnumRef("success") // StringEnumRef | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(context.Background(), pathString, pathInteger, enumNonrefStringPath, enumRefStringPath).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath`: string + fmt.Fprintf(os.Stdout, "Response from `PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath`: %v\n", resp) } ``` diff --git a/samples/client/echo_api/go/docs/QueryAPI.md b/samples/client/echo_api/go/docs/QueryAPI.md index 815c9f9df9da..766c0c9ba8e8 100644 --- a/samples/client/echo_api/go/docs/QueryAPI.md +++ b/samples/client/echo_api/go/docs/QueryAPI.md @@ -29,25 +29,25 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - enumNonrefStringQuery := "enumNonrefStringQuery_example" // string | (optional) - enumRefStringQuery := openapiclient.StringEnumRef("success") // StringEnumRef | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestEnumRefString(context.Background()).EnumNonrefStringQuery(enumNonrefStringQuery).EnumRefStringQuery(enumRefStringQuery).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestEnumRefString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestEnumRefString`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestEnumRefString`: %v\n", resp) + enumNonrefStringQuery := "enumNonrefStringQuery_example" // string | (optional) + enumRefStringQuery := openapiclient.StringEnumRef("success") // StringEnumRef | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestEnumRefString(context.Background()).EnumNonrefStringQuery(enumNonrefStringQuery).EnumRefStringQuery(enumRefStringQuery).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestEnumRefString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestEnumRefString`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestEnumRefString`: %v\n", resp) } ``` @@ -97,27 +97,27 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" + "context" + "fmt" + "os" "time" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - datetimeQuery := time.Now() // time.Time | (optional) - dateQuery := time.Now() // string | (optional) - stringQuery := "stringQuery_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryDatetimeDateString(context.Background()).DatetimeQuery(datetimeQuery).DateQuery(dateQuery).StringQuery(stringQuery).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryDatetimeDateString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryDatetimeDateString`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryDatetimeDateString`: %v\n", resp) + datetimeQuery := time.Now() // time.Time | (optional) + dateQuery := time.Now() // string | (optional) + stringQuery := "stringQuery_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryDatetimeDateString(context.Background()).DatetimeQuery(datetimeQuery).DateQuery(dateQuery).StringQuery(stringQuery).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryDatetimeDateString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryDatetimeDateString`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryDatetimeDateString`: %v\n", resp) } ``` @@ -168,26 +168,26 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - integerQuery := int32(56) // int32 | (optional) - booleanQuery := true // bool | (optional) - stringQuery := "stringQuery_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryIntegerBooleanString(context.Background()).IntegerQuery(integerQuery).BooleanQuery(booleanQuery).StringQuery(stringQuery).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryIntegerBooleanString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryIntegerBooleanString`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryIntegerBooleanString`: %v\n", resp) + integerQuery := int32(56) // int32 | (optional) + booleanQuery := true // bool | (optional) + stringQuery := "stringQuery_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryIntegerBooleanString(context.Background()).IntegerQuery(integerQuery).BooleanQuery(booleanQuery).StringQuery(stringQuery).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryIntegerBooleanString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryIntegerBooleanString`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryIntegerBooleanString`: %v\n", resp) } ``` @@ -238,24 +238,24 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryObject := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject(context.Background()).QueryObject(queryObject).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryStyleDeepObjectExplodeTrueObject`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject`: %v\n", resp) + queryObject := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject(context.Background()).QueryObject(queryObject).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryStyleDeepObjectExplodeTrueObject`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObject`: %v\n", resp) } ``` @@ -304,24 +304,24 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryObject := *openapiclient.NewTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() // TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf(context.Background()).QueryObject(queryObject).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryStyleDeepObjectExplodeTrueObjectAllOf`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf`: %v\n", resp) + queryObject := *openapiclient.NewTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() // TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf(context.Background()).QueryObject(queryObject).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryStyleDeepObjectExplodeTrueObjectAllOf`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleDeepObjectExplodeTrueObjectAllOf`: %v\n", resp) } ``` @@ -370,24 +370,24 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryObject := *openapiclient.NewTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() // TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueArrayString(context.Background()).QueryObject(queryObject).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueArrayString``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryStyleFormExplodeTrueArrayString`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueArrayString`: %v\n", resp) + queryObject := *openapiclient.NewTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() // TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueArrayString(context.Background()).QueryObject(queryObject).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueArrayString``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryStyleFormExplodeTrueArrayString`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueArrayString`: %v\n", resp) } ``` @@ -436,24 +436,24 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryObject := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueObject(context.Background()).QueryObject(queryObject).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueObject``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryStyleFormExplodeTrueObject`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueObject`: %v\n", resp) + queryObject := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueObject(context.Background()).QueryObject(queryObject).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueObject``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryStyleFormExplodeTrueObject`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueObject`: %v\n", resp) } ``` @@ -502,24 +502,24 @@ Test query parameter(s) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryObject := *openapiclient.NewDataQuery() // DataQuery | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf(context.Background()).QueryObject(queryObject).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestQueryStyleFormExplodeTrueObjectAllOf`: string - fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf`: %v\n", resp) + queryObject := *openapiclient.NewDataQuery() // DataQuery | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf(context.Background()).QueryObject(queryObject).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestQueryStyleFormExplodeTrueObjectAllOf`: string + fmt.Fprintf(os.Stdout, "Response from `QueryAPI.TestQueryStyleFormExplodeTrueObjectAllOf`: %v\n", resp) } ``` diff --git a/samples/client/echo_api/go/model_pet.go b/samples/client/echo_api/go/model_pet.go index 62ed88418efe..13f24706dfd5 100644 --- a/samples/client/echo_api/go/model_pet.go +++ b/samples/client/echo_api/go/model_pet.go @@ -13,6 +13,8 @@ package openapi import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Pet type satisfies the MappedNullable interface at compile time @@ -29,6 +31,8 @@ type Pet struct { Status *string `json:"status,omitempty"` } +type _Pet Pet + // NewPet instantiates a new Pet object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -251,6 +255,44 @@ func (o Pet) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Pet) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + "photoUrls", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varPet := _Pet{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varPet) + + if err != nil { + return err + } + + *o = Pet(varPet) + + return err +} + type NullablePet struct { value *Pet isSet bool diff --git a/samples/client/echo_api/go/test/api_body_test.go b/samples/client/echo_api/go/test/api_body_test.go index fe706be23816..7bfd79b70ec6 100644 --- a/samples/client/echo_api/go/test/api_body_test.go +++ b/samples/client/echo_api/go/test/api_body_test.go @@ -11,10 +11,12 @@ package openapi import ( "context" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "os" "testing" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_openapi_BodyAPIService(t *testing.T) { @@ -24,19 +26,20 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestBinaryGif", func(t *testing.T) { - t.Skip("skip test") // remove to run test - resp, httpRes, err := apiClient.BodyAPI.TestBinaryGif(context.Background()).Execute() require.Nil(t, err) require.NotNil(t, resp) assert.Equal(t, 200, httpRes.StatusCode) + f, err := os.Stat(resp.Name()) + require.Nil(t, err) + require.Greater(t, f.Size(), int64(0)) }) t.Run("Test BodyAPIService TestBodyApplicationOctetstreamBinary", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestBodyApplicationOctetstreamBinary(context.Background()).Execute() @@ -48,7 +51,7 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestBodyMultipartFormdataArrayOfBinary", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestBodyMultipartFormdataArrayOfBinary(context.Background()).Execute() @@ -60,7 +63,7 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestEchoBodyFreeFormObjectResponseString", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestEchoBodyFreeFormObjectResponseString(context.Background()).Execute() @@ -72,7 +75,7 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestEchoBodyPet", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestEchoBodyPet(context.Background()).Execute() @@ -84,7 +87,7 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestEchoBodyPetResponseString", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestEchoBodyPetResponseString(context.Background()).Execute() @@ -96,7 +99,7 @@ func Test_openapi_BodyAPIService(t *testing.T) { t.Run("Test BodyAPIService TestEchoBodyTagResponseString", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test resp, httpRes, err := apiClient.BodyAPI.TestEchoBodyTagResponseString(context.Background()).Execute() diff --git a/samples/client/echo_api/go/test/api_header_test.go b/samples/client/echo_api/go/test/api_header_test.go index 7bf05f3fc01c..37ad22567fd8 100644 --- a/samples/client/echo_api/go/test/api_header_test.go +++ b/samples/client/echo_api/go/test/api_header_test.go @@ -11,10 +11,11 @@ package openapi import ( "context" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "testing" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_openapi_HeaderAPIService(t *testing.T) { @@ -24,9 +25,9 @@ func Test_openapi_HeaderAPIService(t *testing.T) { t.Run("Test HeaderAPIService TestHeaderIntegerBooleanString", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test - resp, httpRes, err := apiClient.HeaderAPI.TestHeaderIntegerBooleanString(context.Background()).Execute() + resp, httpRes, err := apiClient.HeaderAPI.TestHeaderIntegerBooleanStringEnums(context.Background()).Execute() require.Nil(t, err) require.NotNil(t, resp) diff --git a/samples/client/echo_api/go/test/api_path_test.go b/samples/client/echo_api/go/test/api_path_test.go index 43d6681938fa..5364670a18ca 100644 --- a/samples/client/echo_api/go/test/api_path_test.go +++ b/samples/client/echo_api/go/test/api_path_test.go @@ -11,10 +11,11 @@ package openapi import ( "context" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "testing" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) func Test_openapi_PathAPIService(t *testing.T) { @@ -24,12 +25,12 @@ func Test_openapi_PathAPIService(t *testing.T) { t.Run("Test PathAPIService TestsPathStringPathStringIntegerPathInteger", func(t *testing.T) { - t.Skip("skip test") // remove to run test + t.Skip("skip test") // remove to run test var pathString string var pathInteger int32 - resp, httpRes, err := apiClient.PathAPI.TestsPathStringPathStringIntegerPathInteger(context.Background(), pathString, pathInteger).Execute() + resp, httpRes, err := apiClient.PathAPI.TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(context.Background(), pathString, pathInteger, pathString, openapiclient.SUCCESS).Execute() require.Nil(t, err) require.NotNil(t, resp) diff --git a/samples/client/echo_api/java/apache-httpclient/.openapi-generator/VERSION b/samples/client/echo_api/java/apache-httpclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/java/apache-httpclient/.openapi-generator/VERSION +++ b/samples/client/echo_api/java/apache-httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/apache-httpclient/README.md b/samples/client/echo_api/java/apache-httpclient/README.md index c0f6067fdeb3..ed181eb376c2 100644 --- a/samples/client/echo_api/java/apache-httpclient/README.md +++ b/samples/client/echo_api/java/apache-httpclient/README.md @@ -111,9 +111,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**testAuthHttpBasic**](docs/AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**testBinaryGif**](docs/BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**testEchoBodyPet**](docs/BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyPetResponseString**](docs/BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -158,6 +161,12 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + + +- **Type**: HTTP Bearer Token authentication + ## Recommendation diff --git a/samples/client/echo_api/java/apache-httpclient/api/openapi.yaml b/samples/client/echo_api/java/apache-httpclient/api/openapi.yaml index de47c7b5e355..f5d4fc9abbde 100644 --- a/samples/client/echo_api/java/apache-httpclient/api/openapi.yaml +++ b/samples/client/echo_api/java/apache-httpclient/api/openapi.yaml @@ -421,6 +421,24 @@ paths: - body x-content-type: application/json x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json /echo/body/Pet/response_string: post: description: Test empty response body @@ -495,6 +513,27 @@ paths: tags: - body x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -533,6 +572,23 @@ paths: tags: - auth x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain components: requestBodies: Pet: @@ -541,6 +597,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -783,6 +846,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -797,4 +866,7 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/java/apache-httpclient/docs/AuthApi.md b/samples/client/echo_api/java/apache-httpclient/docs/AuthApi.md index 508c4c555cb9..de3353d43a2c 100644 --- a/samples/client/echo_api/java/apache-httpclient/docs/AuthApi.md +++ b/samples/client/echo_api/java/apache-httpclient/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* | Method | HTTP request | Description | |------------- | ------------- | -------------| | [**testAuthHttpBasic**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | @@ -75,3 +76,70 @@ This endpoint does not need any parameter. |-------------|-------------|------------------| | **200** | Successful operation | - | + +## testAuthHttpBearer + +> String testAuthHttpBearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBearer(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/apache-httpclient/docs/BodyApi.md b/samples/client/echo_api/java/apache-httpclient/docs/BodyApi.md index 9eecf09eb766..3cf2014e31f6 100644 --- a/samples/client/echo_api/java/apache-httpclient/docs/BodyApi.md +++ b/samples/client/echo_api/java/apache-httpclient/docs/BodyApi.md @@ -7,6 +7,8 @@ All URIs are relative to *http://localhost:3000* | [**testBinaryGif**](BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body | | [**testBodyApplicationOctetstreamBinary**](BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**testBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**testEchoBodyFreeFormObjectResponseString**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**testEchoBodyPet**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | | [**testEchoBodyPetResponseString**](BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body | @@ -208,6 +210,138 @@ No authorization required | **200** | Successful operation | - | +## testBodyMultipartFormdataSingleBinary + +> String testBodyMultipartFormdataSingleBinary(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyMultipartFormdataSingleBinary(myFile); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyAllOfPet + +> Pet testEchoBodyAllOfPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyAllOfPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + ## testEchoBodyFreeFormObjectResponseString > String testEchoBodyFreeFormObjectResponseString(body) diff --git a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java index 71e2d4d1ec10..c553e1554920 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java @@ -55,6 +55,7 @@ import java.util.Arrays; import java.util.ArrayList; import java.util.Date; +import java.util.function.Supplier; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -66,6 +67,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; @@ -77,6 +79,7 @@ import org.openapitools.client.auth.Authentication; import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class ApiClient extends JavaTimeFormatter { @@ -129,6 +132,7 @@ public ApiClient(CloseableHttpClient httpClient) { // Setup authentications (key: authentication name, value: authentication). authentications = new HashMap(); authentications.put("http_auth", new HttpBasicAuth()); + authentications.put("http_bearer_auth", new HttpBearerAuth("bearer")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); @@ -288,6 +292,35 @@ public String getTempFolderPath() { return tempFolderPath; } + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + * @return API client + */ + public ApiClient setBearerToken(String bearerToken) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(bearerToken); + return this; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier the token supplier function + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } /** * Helper method to set username for the first HTTP basic authentication. @@ -509,7 +542,7 @@ public List parameterToPairs(String collectionFormat, String name, Collect List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) { + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } @@ -671,7 +704,7 @@ public HttpEntity serialize(Object obj, Map formParams, ContentT String mimeType = contentType.getMimeType(); if (isJsonMime(mimeType)) { try { - return new StringEntity(objectMapper.writeValueAsString(obj), contentType); + return new StringEntity(objectMapper.writeValueAsString(obj), contentType.withCharset(StandardCharsets.UTF_8)); } catch (JsonProcessingException e) { throw new ApiException(e); } diff --git a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/AuthApi.java index f709addc0f6c..157cc87fe702 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/AuthApi.java +++ b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/AuthApi.java @@ -117,4 +117,71 @@ public String testAuthHttpBasic(Map additionalHeaders) throws Ap ); } + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return String + * @throws ApiException if fails to make API call + */ + public String testAuthHttpBearer() throws ApiException { + return this.testAuthHttpBearer(Collections.emptyMap()); + } + + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @param additionalHeaders additionalHeaders for this call + * @return String + * @throws ApiException if fails to make API call + */ + public String testAuthHttpBearer(Map additionalHeaders) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/auth/http/bearer"; + + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + localVarHeaderParams.putAll(additionalHeaders); + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_bearer_auth" }; + + TypeReference localVarReturnType = new TypeReference() {}; + return apiClient.invokeAPI( + localVarPath, + "POST", + localVarQueryParams, + localVarCollectionQueryParams, + localVarQueryStringJoiner.toString(), + localVarPostBody, + localVarHeaderParams, + localVarCookieParams, + localVarFormParams, + localVarAccept, + localVarContentType, + localVarAuthNames, + localVarReturnType + ); + } + } diff --git a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/BodyApi.java index f03255836397..272b2b2ddfcb 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/BodyApi.java +++ b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/api/BodyApi.java @@ -265,6 +265,146 @@ public String testBodyMultipartFormdataArrayOfBinary(List files, Map additionalHeaders) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/body/application/octetstream/single_binary"; + + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + localVarHeaderParams.putAll(additionalHeaders); + + + if (myFile != null) + localVarFormParams.put("my-file", myFile); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + TypeReference localVarReturnType = new TypeReference() {}; + return apiClient.invokeAPI( + localVarPath, + "POST", + localVarQueryParams, + localVarCollectionQueryParams, + localVarQueryStringJoiner.toString(), + localVarPostBody, + localVarHeaderParams, + localVarCookieParams, + localVarFormParams, + localVarAccept, + localVarContentType, + localVarAuthNames, + localVarReturnType + ); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet testEchoBodyAllOfPet(Pet pet) throws ApiException { + return this.testEchoBodyAllOfPet(pet, Collections.emptyMap()); + } + + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @param additionalHeaders additionalHeaders for this call + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet testEchoBodyAllOfPet(Pet pet, Map additionalHeaders) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/echo/body/allOf/Pet"; + + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + localVarHeaderParams.putAll(additionalHeaders); + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + TypeReference localVarReturnType = new TypeReference() {}; + return apiClient.invokeAPI( + localVarPath, + "POST", + localVarQueryParams, + localVarCollectionQueryParams, + localVarQueryStringJoiner.toString(), + localVarPostBody, + localVarHeaderParams, + localVarCookieParams, + localVarFormParams, + localVarAccept, + localVarContentType, + localVarAuthNames, + localVarReturnType + ); + } + /** * Test free form object * Test free form object diff --git a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 8c7cdd743e18..0f1f505b7de3 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/echo_api/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -15,13 +15,15 @@ import org.openapitools.client.Pair; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -33,7 +35,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -42,12 +44,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/echo_api/java/apache-httpclient/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/apache-httpclient/src/test/java/org/openapitools/client/api/AuthApiTest.java index ac4fa203fbc5..7fc2956fce23 100644 --- a/samples/client/echo_api/java/apache-httpclient/src/test/java/org/openapitools/client/api/AuthApiTest.java +++ b/samples/client/echo_api/java/apache-httpclient/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -28,7 +28,6 @@ /** * API tests for AuthApi */ -@Ignore public class AuthApiTest { private final AuthApi api = new AuthApi(); @@ -47,4 +46,23 @@ public void testAuthHttpBasicTest() throws ApiException { // TODO: test validations } + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBearerTest() throws ApiException { + String response; + api.getApiClient().setBearerToken("fixed token"); + response = api.testAuthHttpBearer(); + Assert.assertTrue(response.contains("Authorization: Bearer fixed token")); + + api.getApiClient().setBearerToken(() -> "dynamic token"); + response = api.testAuthHttpBearer(); + Assert.assertTrue(response.contains("Authorization: Bearer dynamic token")); + } } diff --git a/samples/client/echo_api/java/feign-gson/.openapi-generator/VERSION b/samples/client/echo_api/java/feign-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/java/feign-gson/.openapi-generator/VERSION +++ b/samples/client/echo_api/java/feign-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/feign-gson/api/openapi.yaml b/samples/client/echo_api/java/feign-gson/api/openapi.yaml index de47c7b5e355..f5d4fc9abbde 100644 --- a/samples/client/echo_api/java/feign-gson/api/openapi.yaml +++ b/samples/client/echo_api/java/feign-gson/api/openapi.yaml @@ -421,6 +421,24 @@ paths: - body x-content-type: application/json x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json /echo/body/Pet/response_string: post: description: Test empty response body @@ -495,6 +513,27 @@ paths: tags: - body x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -533,6 +572,23 @@ paths: tags: - auth x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain components: requestBodies: Pet: @@ -541,6 +597,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -783,6 +846,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -797,4 +866,7 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/java/feign-gson/pom.xml b/samples/client/echo_api/java/feign-gson/pom.xml index 3b52d0331b7b..d36b999efc39 100644 --- a/samples/client/echo_api/java/feign-gson/pom.xml +++ b/samples/client/echo_api/java/feign-gson/pom.xml @@ -267,7 +267,7 @@ ch.qos.logback logback-classic - 1.2.12 + 1.3.13 test diff --git a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/ApiClient.java index 9184a09164c1..c4f0909810ff 100644 --- a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -2,6 +2,7 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -42,6 +43,8 @@ public ApiClient(String[] authNames) { RequestInterceptor auth = null; if ("http_auth".equals(authName)) { auth = new HttpBasicAuth(); + } else if ("http_bearer_auth".equals(authName)) { + auth = new HttpBearerAuth("bearer"); } else { throw new RuntimeException("auth name \"" + authName + "\" not found in available auth names"); } @@ -153,6 +156,15 @@ public void setBearerToken(String bearerToken) { apiAuthorization.setBearerToken(bearerToken); } + /** + * Helper method to configure the supplier of bearer tokens. + * @param tokenSupplier the supplier of bearer tokens. + */ + public void setBearerToken(Supplier tokenSupplier) { + HttpBearerAuth apiAuthorization = getAuthorization(HttpBearerAuth.class); + apiAuthorization.setBearerToken(tokenSupplier); + } + /** * Helper method to configure the first api key found * @param apiKey API key diff --git a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/AuthApi.java index 2c2524805f0f..900372cdd34b 100644 --- a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/AuthApi.java +++ b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/AuthApi.java @@ -39,4 +39,29 @@ public interface AuthApi extends ApiClient.Api { ApiResponse testAuthHttpBasicWithHttpInfo(); + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return String + */ + @RequestLine("POST /auth/http/bearer") + @Headers({ + "Accept: text/plain", + }) + String testAuthHttpBearer(); + + /** + * To test HTTP bearer authentication + * Similar to testAuthHttpBearer but it also returns the http response headers . + * To test HTTP bearer authentication + * @return A ApiResponse that wraps the response boyd and the http headers. + */ + @RequestLine("POST /auth/http/bearer") + @Headers({ + "Accept: text/plain", + }) + ApiResponse testAuthHttpBearerWithHttpInfo(); + + } diff --git a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/BodyApi.java index fbc19a32eb69..2b9bb7c413c5 100644 --- a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/BodyApi.java +++ b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/api/BodyApi.java @@ -101,6 +101,64 @@ public interface BodyApi extends ApiClient.Api { + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return String + */ + @RequestLine("POST /body/application/octetstream/single_binary") + @Headers({ + "Content-Type: multipart/form-data", + "Accept: text/plain", + }) + String testBodyMultipartFormdataSingleBinary(@Param("my-file") File myFile); + + /** + * Test single binary in multipart mime + * Similar to testBodyMultipartFormdataSingleBinary but it also returns the http response headers . + * Test single binary in multipart mime + * @param myFile (optional) + * @return A ApiResponse that wraps the response boyd and the http headers. + */ + @RequestLine("POST /body/application/octetstream/single_binary") + @Headers({ + "Content-Type: multipart/form-data", + "Accept: text/plain", + }) + ApiResponse testBodyMultipartFormdataSingleBinaryWithHttpInfo(@Param("my-file") File myFile); + + + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + */ + @RequestLine("POST /echo/body/allOf/Pet") + @Headers({ + "Content-Type: application/json", + "Accept: application/json", + }) + Pet testEchoBodyAllOfPet(Pet pet); + + /** + * Test body parameter(s) + * Similar to testEchoBodyAllOfPet but it also returns the http response headers . + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return A ApiResponse that wraps the response boyd and the http headers. + */ + @RequestLine("POST /echo/body/allOf/Pet") + @Headers({ + "Content-Type: application/json", + "Accept: application/json", + }) + ApiResponse testEchoBodyAllOfPetWithHttpInfo(Pet pet); + + + /** * Test free form object * Test free form object diff --git a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index d4c9cbe6361e..43c1a722ad9f 100644 --- a/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/echo_api/java/feign-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -2,13 +2,15 @@ import feign.RequestInterceptor; import feign.RequestTemplate; +import java.util.Optional; +import java.util.function.Supplier; /** * An interceptor that adds the request header needed to use HTTP bearer authentication. */ public class HttpBearerAuth implements RequestInterceptor { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -16,21 +18,35 @@ public HttpBearerAuth(String scheme) { /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void apply(RequestTemplate template) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/echo_api/java/feign-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/feign-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java index 2c33d9c32dce..f53e1f75b5df 100644 --- a/samples/client/echo_api/java/feign-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java +++ b/samples/client/echo_api/java/feign-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -1,5 +1,7 @@ package org.openapitools.client.api; +import feign.codec.StringDecoder; +import org.junit.jupiter.api.Assertions; import org.openapitools.client.ApiClient; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.BeforeEach; @@ -37,4 +39,28 @@ void testAuthHttpBasicTest() { } + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + */ + @Test + void testAuthHttpBearerTest() { + ApiClient client = new ApiClient("http_bearer_auth"); + client.getFeignBuilder().decoder(new StringDecoder()); + { + client.setBearerToken("fixed token"); + AuthApi api = client.buildClient(AuthApi.class); + String response = api.testAuthHttpBearer(); + Assertions.assertTrue(response.contains("Authorization: Bearer fixed token")); + } + { + client.setBearerToken(() -> "dynamic token"); + AuthApi api = client.buildClient(AuthApi.class); + String response = api.testAuthHttpBearer(); + Assertions.assertTrue(response.contains("Authorization: Bearer dynamic token")); + } + } + + } diff --git a/samples/client/echo_api/java/native/.openapi-generator/VERSION b/samples/client/echo_api/java/native/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/java/native/.openapi-generator/VERSION +++ b/samples/client/echo_api/java/native/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/native/README.md b/samples/client/echo_api/java/native/README.md index 6caea3a23da1..4c8dec19ee26 100644 --- a/samples/client/echo_api/java/native/README.md +++ b/samples/client/echo_api/java/native/README.md @@ -106,12 +106,18 @@ Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**testAuthHttpBasic**](docs/AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication *AuthApi* | [**testAuthHttpBasicWithHttpInfo**](docs/AuthApi.md#testAuthHttpBasicWithHttpInfo) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*AuthApi* | [**testAuthHttpBearerWithHttpInfo**](docs/AuthApi.md#testAuthHttpBearerWithHttpInfo) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**testBinaryGif**](docs/BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**testBinaryGifWithHttpInfo**](docs/BodyApi.md#testBinaryGifWithHttpInfo) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**testBodyApplicationOctetstreamBinaryWithHttpInfo**](docs/BodyApi.md#testBodyApplicationOctetstreamBinaryWithHttpInfo) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime *BodyApi* | [**testBodyMultipartFormdataArrayOfBinaryWithHttpInfo**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinaryWithHttpInfo) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinaryWithHttpInfo**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinaryWithHttpInfo) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*BodyApi* | [**testEchoBodyAllOfPetWithHttpInfo**](docs/BodyApi.md#testEchoBodyAllOfPetWithHttpInfo) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**testEchoBodyFreeFormObjectResponseStringWithHttpInfo**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseStringWithHttpInfo) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**testEchoBodyPet**](docs/BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) @@ -172,6 +178,12 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + + +- **Type**: HTTP Bearer Token authentication + ## Recommendation diff --git a/samples/client/echo_api/java/native/api/openapi.yaml b/samples/client/echo_api/java/native/api/openapi.yaml index de47c7b5e355..f5d4fc9abbde 100644 --- a/samples/client/echo_api/java/native/api/openapi.yaml +++ b/samples/client/echo_api/java/native/api/openapi.yaml @@ -421,6 +421,24 @@ paths: - body x-content-type: application/json x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json /echo/body/Pet/response_string: post: description: Test empty response body @@ -495,6 +513,27 @@ paths: tags: - body x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -533,6 +572,23 @@ paths: tags: - auth x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain components: requestBodies: Pet: @@ -541,6 +597,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -783,6 +846,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -797,4 +866,7 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/java/native/docs/AuthApi.md b/samples/client/echo_api/java/native/docs/AuthApi.md index 6d679e7bf945..7c1c77adca9e 100644 --- a/samples/client/echo_api/java/native/docs/AuthApi.md +++ b/samples/client/echo_api/java/native/docs/AuthApi.md @@ -6,6 +6,8 @@ All URIs are relative to *http://localhost:3000* |------------- | ------------- | -------------| | [**testAuthHttpBasic**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | | [**testAuthHttpBasicWithHttpInfo**](AuthApi.md#testAuthHttpBasicWithHttpInfo) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | +| [**testAuthHttpBearerWithHttpInfo**](AuthApi.md#testAuthHttpBearerWithHttpInfo) | **POST** /auth/http/bearer | To test HTTP bearer authentication | @@ -146,3 +148,139 @@ ApiResponse<**String**> |-------------|-------------|------------------| | **200** | Successful operation | - | + +## testAuthHttpBearer + +> String testAuthHttpBearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBearer(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +## testAuthHttpBearerWithHttpInfo + +> ApiResponse testAuthHttpBearer testAuthHttpBearerWithHttpInfo() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + ApiResponse response = apiInstance.testAuthHttpBearerWithHttpInfo(); + System.out.println("Status code: " + response.getStatusCode()); + System.out.println("Response headers: " + response.getHeaders()); + System.out.println("Response body: " + response.getData()); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Response headers: " + e.getResponseHeaders()); + System.err.println("Reason: " + e.getResponseBody()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +ApiResponse<**String**> + + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/native/docs/BodyApi.md b/samples/client/echo_api/java/native/docs/BodyApi.md index 3661d666b2f7..8e5f878bac0e 100644 --- a/samples/client/echo_api/java/native/docs/BodyApi.md +++ b/samples/client/echo_api/java/native/docs/BodyApi.md @@ -10,6 +10,10 @@ All URIs are relative to *http://localhost:3000* | [**testBodyApplicationOctetstreamBinaryWithHttpInfo**](BodyApi.md#testBodyApplicationOctetstreamBinaryWithHttpInfo) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**testBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | | [**testBodyMultipartFormdataArrayOfBinaryWithHttpInfo**](BodyApi.md#testBodyMultipartFormdataArrayOfBinaryWithHttpInfo) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinaryWithHttpInfo**](BodyApi.md#testBodyMultipartFormdataSingleBinaryWithHttpInfo) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | +| [**testEchoBodyAllOfPetWithHttpInfo**](BodyApi.md#testEchoBodyAllOfPetWithHttpInfo) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**testEchoBodyFreeFormObjectResponseString**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**testEchoBodyFreeFormObjectResponseStringWithHttpInfo**](BodyApi.md#testEchoBodyFreeFormObjectResponseStringWithHttpInfo) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**testEchoBodyPet**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | @@ -415,6 +419,274 @@ No authorization required | **200** | Successful operation | - | +## testBodyMultipartFormdataSingleBinary + +> String testBodyMultipartFormdataSingleBinary(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyMultipartFormdataSingleBinary(myFile); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +**String** + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +## testBodyMultipartFormdataSingleBinaryWithHttpInfo + +> ApiResponse testBodyMultipartFormdataSingleBinary testBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + ApiResponse response = apiInstance.testBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile); + System.out.println("Status code: " + response.getStatusCode()); + System.out.println("Response headers: " + response.getHeaders()); + System.out.println("Response body: " + response.getData()); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Response headers: " + e.getResponseHeaders()); + System.err.println("Reason: " + e.getResponseBody()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +ApiResponse<**String**> + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyAllOfPet + +> Pet testEchoBodyAllOfPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyAllOfPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + +## testEchoBodyAllOfPetWithHttpInfo + +> ApiResponse testEchoBodyAllOfPet testEchoBodyAllOfPetWithHttpInfo(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + ApiResponse response = apiInstance.testEchoBodyAllOfPetWithHttpInfo(pet); + System.out.println("Status code: " + response.getStatusCode()); + System.out.println("Response headers: " + response.getHeaders()); + System.out.println("Response body: " + response.getData()); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Response headers: " + e.getResponseHeaders()); + System.err.println("Reason: " + e.getResponseBody()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +ApiResponse<[**Pet**](Pet.md)> + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + ## testEchoBodyFreeFormObjectResponseString > String testEchoBodyFreeFormObjectResponseString(body) diff --git a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/JSON.java b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/JSON.java index 1ce1e47b4fb6..5c966f6fa4a9 100644 --- a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/JSON.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; import org.openapitools.jackson.nullable.JsonNullableModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.client.model.*; @@ -17,16 +18,17 @@ public class JSON { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .build(); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); } diff --git a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/AuthApi.java index 530872704725..d22bfe292788 100644 --- a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/AuthApi.java +++ b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/AuthApi.java @@ -144,6 +144,79 @@ private HttpRequest.Builder testAuthHttpBasicRequestBuilder() throws ApiExceptio localVarRequestBuilder.header("Accept", "text/plain"); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return String + * @throws ApiException if fails to make API call + */ + public String testAuthHttpBearer() throws ApiException { + ApiResponse localVarResponse = testAuthHttpBearerWithHttpInfo(); + return localVarResponse.getData(); + } + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return ApiResponse<String> + * @throws ApiException if fails to make API call + */ + public ApiResponse testAuthHttpBearerWithHttpInfo() throws ApiException { + HttpRequest.Builder localVarRequestBuilder = testAuthHttpBearerRequestBuilder(); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testAuthHttpBearer", localVarResponse); + } + // for plain text response + if (localVarResponse.headers().map().containsKey("Content-Type") && + "text/plain".equalsIgnoreCase(localVarResponse.headers().map().get("Content-Type").get(0).split(";")[0].trim())) { + java.util.Scanner s = new java.util.Scanner(localVarResponse.body()).useDelimiter("\\A"); + String responseBodyText = s.hasNext() ? s.next() : ""; + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBodyText + ); + } else { + throw new RuntimeException("Error! The response Content-Type is supposed to be `text/plain` but it's not: " + localVarResponse); + } + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder testAuthHttpBearerRequestBuilder() throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/auth/http/bearer"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "text/plain"); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.noBody()); if (memberVarReadTimeout != null) { localVarRequestBuilder.timeout(memberVarReadTimeout); diff --git a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/BodyApi.java index 78f0991205bd..4807d5adb293 100644 --- a/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/BodyApi.java +++ b/samples/client/echo_api/java/native/src/main/java/org/openapitools/client/api/BodyApi.java @@ -349,6 +349,187 @@ private HttpRequest.Builder testBodyMultipartFormdataArrayOfBinaryRequestBuilder } return localVarRequestBuilder; } + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return String + * @throws ApiException if fails to make API call + */ + public String testBodyMultipartFormdataSingleBinary(File myFile) throws ApiException { + ApiResponse localVarResponse = testBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile); + return localVarResponse.getData(); + } + + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return ApiResponse<String> + * @throws ApiException if fails to make API call + */ + public ApiResponse testBodyMultipartFormdataSingleBinaryWithHttpInfo(File myFile) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = testBodyMultipartFormdataSingleBinaryRequestBuilder(myFile); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testBodyMultipartFormdataSingleBinary", localVarResponse); + } + // for plain text response + if (localVarResponse.headers().map().containsKey("Content-Type") && + "text/plain".equalsIgnoreCase(localVarResponse.headers().map().get("Content-Type").get(0).split(";")[0].trim())) { + java.util.Scanner s = new java.util.Scanner(localVarResponse.body()).useDelimiter("\\A"); + String responseBodyText = s.hasNext() ? s.next() : ""; + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + responseBodyText + ); + } else { + throw new RuntimeException("Error! The response Content-Type is supposed to be `text/plain` but it's not: " + localVarResponse); + } + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder testBodyMultipartFormdataSingleBinaryRequestBuilder(File myFile) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/body/application/octetstream/single_binary"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Accept", "text/plain"); + + MultipartEntityBuilder multiPartBuilder = MultipartEntityBuilder.create(); + boolean hasFiles = false; + multiPartBuilder.addBinaryBody("my-file", myFile); + hasFiles = true; + HttpEntity entity = multiPartBuilder.build(); + HttpRequest.BodyPublisher formDataPublisher; + if (hasFiles) { + Pipe pipe; + try { + pipe = Pipe.open(); + } catch (IOException e) { + throw new RuntimeException(e); + } + new Thread(() -> { + try (OutputStream outputStream = Channels.newOutputStream(pipe.sink())) { + entity.writeTo(outputStream); + } catch (IOException e) { + e.printStackTrace(); + } + }).start(); + formDataPublisher = HttpRequest.BodyPublishers.ofInputStream(() -> Channels.newInputStream(pipe.source())); + } else { + ByteArrayOutputStream formOutputStream = new ByteArrayOutputStream(); + try { + entity.writeTo(formOutputStream); + } catch (IOException e) { + throw new RuntimeException(e); + } + formDataPublisher = HttpRequest.BodyPublishers + .ofInputStream(() -> new ByteArrayInputStream(formOutputStream.toByteArray())); + } + localVarRequestBuilder + .header("Content-Type", entity.getContentType().getValue()) + .method("POST", formDataPublisher); + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + * @throws ApiException if fails to make API call + */ + public Pet testEchoBodyAllOfPet(Pet pet) throws ApiException { + ApiResponse localVarResponse = testEchoBodyAllOfPetWithHttpInfo(pet); + return localVarResponse.getData(); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return ApiResponse<Pet> + * @throws ApiException if fails to make API call + */ + public ApiResponse testEchoBodyAllOfPetWithHttpInfo(Pet pet) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = testEchoBodyAllOfPetRequestBuilder(pet); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testEchoBodyAllOfPet", localVarResponse); + } + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + localVarResponse.body() == null ? null : memberVarObjectMapper.readValue(localVarResponse.body(), new TypeReference() {}) // closes the InputStream + ); + } finally { + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder testEchoBodyAllOfPetRequestBuilder(Pet pet) throws ApiException { + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/echo/body/allOf/Pet"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(pet); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } /** * Test free form object * Test free form object diff --git a/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/CustomTest.java b/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/CustomTest.java index 92c7966b05c8..0eb53fa61b18 100644 --- a/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/CustomTest.java +++ b/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/CustomTest.java @@ -60,6 +60,28 @@ public void testEchoBodyPet() throws ApiException { Assert.assertNull(p2); } + /** + * Test allOf body parameter(s) + *

              + * Test allOf body parameter(s) + * + * @throws ApiException if the Api call fails + */ + @Test + public void testEchoBodyAllOfPet() throws ApiException { + Pet queryObject = new Pet().id(12345L).name("Hello World"). + photoUrls(Arrays.asList(new String[]{"http://a.com", "http://b.com"})).category(new Category().id(987L).name("new category")); + + Pet p = bodyApi.testEchoBodyAllOfPet(queryObject); + Assert.assertNotNull(p); + Assert.assertEquals("Hello World", p.getName()); + Assert.assertEquals(Long.valueOf(12345L), p.getId()); + + // response is empty body + Pet p2 = bodyApi.testEchoBodyPet(null); + Assert.assertNull(p2); + } + /** * Test query parameter(s) *

              diff --git a/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/api/AuthApiTest.java index 3e6f3a79b758..35d1b0316c71 100644 --- a/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/api/AuthApiTest.java +++ b/samples/client/echo_api/java/native/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -49,4 +49,20 @@ public void testAuthHttpBasicTest() throws ApiException { // TODO: test validations } + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBearerTest() throws ApiException { + String response = + api.testAuthHttpBearer(); + + // TODO: test validations + } + } diff --git a/samples/client/echo_api/java/okhttp-gson/.openapi-generator/VERSION b/samples/client/echo_api/java/okhttp-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/java/okhttp-gson/.openapi-generator/VERSION +++ b/samples/client/echo_api/java/okhttp-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/okhttp-gson/README.md b/samples/client/echo_api/java/okhttp-gson/README.md index 155878f2f8ca..3f0a774aff82 100644 --- a/samples/client/echo_api/java/okhttp-gson/README.md +++ b/samples/client/echo_api/java/okhttp-gson/README.md @@ -119,9 +119,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**testAuthHttpBasic**](docs/AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**testBinaryGif**](docs/BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**testEchoBodyPet**](docs/BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyPetResponseString**](docs/BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -165,6 +168,11 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: HTTP Bearer Token authentication + ## Recommendation diff --git a/samples/client/echo_api/java/okhttp-gson/api/openapi.yaml b/samples/client/echo_api/java/okhttp-gson/api/openapi.yaml index de47c7b5e355..f5d4fc9abbde 100644 --- a/samples/client/echo_api/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/echo_api/java/okhttp-gson/api/openapi.yaml @@ -421,6 +421,24 @@ paths: - body x-content-type: application/json x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json /echo/body/Pet/response_string: post: description: Test empty response body @@ -495,6 +513,27 @@ paths: tags: - body x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain /body/application/octetstream/array_of_binary: post: description: Test array of binary in multipart mime @@ -533,6 +572,23 @@ paths: tags: - auth x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain components: requestBodies: Pet: @@ -541,6 +597,13 @@ components: schema: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store Tag: content: application/json: @@ -783,6 +846,12 @@ components: allOf: - $ref: '#/components/schemas/Bird' - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object test_body_multipart_formdata_array_of_binary_request: properties: files: @@ -797,4 +866,7 @@ components: http_auth: scheme: basic type: http + http_bearer_auth: + scheme: bearer + type: http diff --git a/samples/client/echo_api/java/okhttp-gson/build.gradle b/samples/client/echo_api/java/okhttp-gson/build.gradle index 12e5cc914535..ea04a997bd8d 100644 --- a/samples/client/echo_api/java/okhttp-gson/build.gradle +++ b/samples/client/echo_api/java/okhttp-gson/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/echo_api/java/okhttp-gson/build.sbt b/samples/client/echo_api/java/okhttp-gson/build.sbt index 57000c7d4704..8ba4919fe3c7 100644 --- a/samples/client/echo_api/java/okhttp-gson/build.sbt +++ b/samples/client/echo_api/java/okhttp-gson/build.sbt @@ -17,7 +17,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "jsr311-api" % "1.1.1", "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/echo_api/java/okhttp-gson/docs/AuthApi.md b/samples/client/echo_api/java/okhttp-gson/docs/AuthApi.md index 5a691fcb6f46..387a0f3dcbd1 100644 --- a/samples/client/echo_api/java/okhttp-gson/docs/AuthApi.md +++ b/samples/client/echo_api/java/okhttp-gson/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* | Method | HTTP request | Description | |------------- | ------------- | -------------| | [**testAuthHttpBasic**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | @@ -71,3 +72,66 @@ This endpoint does not need any parameter. |-------------|-------------|------------------| | **200** | Successful operation | - | + +# **testAuthHttpBearer** +> String testAuthHttpBearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBearer(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/okhttp-gson/docs/BodyApi.md b/samples/client/echo_api/java/okhttp-gson/docs/BodyApi.md index 39348a00e2f3..c5694eaaf2b8 100644 --- a/samples/client/echo_api/java/okhttp-gson/docs/BodyApi.md +++ b/samples/client/echo_api/java/okhttp-gson/docs/BodyApi.md @@ -7,6 +7,8 @@ All URIs are relative to *http://localhost:3000* | [**testBinaryGif**](BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body | | [**testBodyApplicationOctetstreamBinary**](BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**testBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**testEchoBodyFreeFormObjectResponseString**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**testEchoBodyPet**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | | [**testEchoBodyPetResponseString**](BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body | @@ -195,6 +197,130 @@ No authorization required |-------------|-------------|------------------| | **200** | Successful operation | - | + +# **testBodyMultipartFormdataSingleBinary** +> String testBodyMultipartFormdataSingleBinary(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyMultipartFormdataSingleBinary(myFile); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +# **testEchoBodyAllOfPet** +> Pet testEchoBodyAllOfPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyAllOfPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + # **testEchoBodyFreeFormObjectResponseString** > String testEchoBodyFreeFormObjectResponseString(body) diff --git a/samples/client/echo_api/java/okhttp-gson/pom.xml b/samples/client/echo_api/java/okhttp-gson/pom.xml index c5bdc3e7ed8c..066de6c9ec37 100644 --- a/samples/client/echo_api/java/okhttp-gson/pom.xml +++ b/samples/client/echo_api/java/okhttp-gson/pom.xml @@ -328,7 +328,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 3d952c96bf8a..faac0e455a78 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -47,6 +47,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -100,6 +101,7 @@ public ApiClient() { // Setup authentications (key: authentication name, value: authentication). authentications.put("http_auth", new HttpBasicAuth()); + authentications.put("http_bearer_auth", new HttpBearerAuth("bearer")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -116,6 +118,7 @@ public ApiClient(OkHttpClient client) { // Setup authentications (key: authentication name, value: authentication). authentications.put("http_auth", new HttpBasicAuth()); + authentications.put("http_bearer_auth", new HttpBearerAuth("bearer")); // Prevent the authentications from being modified. authentications = Collections.unmodifiableMap(authentications); } @@ -384,6 +387,28 @@ public Authentication getAuthentication(String authName) { return authentications.get(authName); } + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } /** * Helper method to set username for the first HTTP basic authentication. diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/AuthApi.java index dc87a48f8588..f0e208cbc610 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/AuthApi.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/AuthApi.java @@ -184,4 +184,117 @@ public okhttp3.Call testAuthHttpBasicAsync(final ApiCallback _callback) localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } + /** + * Build call for testAuthHttpBearer + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testAuthHttpBearerCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/auth/http/bearer"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { "http_bearer_auth" }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testAuthHttpBearerValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return testAuthHttpBearerCall(_callback); + + } + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public String testAuthHttpBearer() throws ApiException { + ApiResponse localVarResp = testAuthHttpBearerWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public ApiResponse testAuthHttpBearerWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = testAuthHttpBearerValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * To test HTTP bearer authentication (asynchronously) + * To test HTTP bearer authentication + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testAuthHttpBearerAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testAuthHttpBearerValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/BodyApi.java index 413daf159798..e344d508d10c 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/BodyApi.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/api/BodyApi.java @@ -432,6 +432,246 @@ public okhttp3.Call testBodyMultipartFormdataArrayOfBinaryAsync(List files localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); return localVarCall; } + /** + * Build call for testBodyMultipartFormdataSingleBinary + * @param myFile (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testBodyMultipartFormdataSingleBinaryCall(File myFile, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/body/application/octetstream/single_binary"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (myFile != null) { + localVarFormParams.put("my-file", myFile); + } + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testBodyMultipartFormdataSingleBinaryValidateBeforeCall(File myFile, final ApiCallback _callback) throws ApiException { + return testBodyMultipartFormdataSingleBinaryCall(myFile, _callback); + + } + + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public String testBodyMultipartFormdataSingleBinary(File myFile) throws ApiException { + ApiResponse localVarResp = testBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile); + return localVarResp.getData(); + } + + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public ApiResponse testBodyMultipartFormdataSingleBinaryWithHttpInfo(File myFile) throws ApiException { + okhttp3.Call localVarCall = testBodyMultipartFormdataSingleBinaryValidateBeforeCall(myFile, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Test single binary in multipart mime (asynchronously) + * Test single binary in multipart mime + * @param myFile (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testBodyMultipartFormdataSingleBinaryAsync(File myFile, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testBodyMultipartFormdataSingleBinaryValidateBeforeCall(myFile, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for testEchoBodyAllOfPet + * @param pet Pet object that needs to be added to the store (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testEchoBodyAllOfPetCall(Pet pet, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/echo/body/allOf/Pet"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testEchoBodyAllOfPetValidateBeforeCall(Pet pet, final ApiCallback _callback) throws ApiException { + return testEchoBodyAllOfPetCall(pet, _callback); + + } + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public Pet testEchoBodyAllOfPet(Pet pet) throws ApiException { + ApiResponse localVarResp = testEchoBodyAllOfPetWithHttpInfo(pet); + return localVarResp.getData(); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return ApiResponse<Pet> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public ApiResponse testEchoBodyAllOfPetWithHttpInfo(Pet pet) throws ApiException { + okhttp3.Call localVarCall = testEchoBodyAllOfPetValidateBeforeCall(pet, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * Test body parameter(s) (asynchronously) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 Successful operation -
              + */ + public okhttp3.Call testEchoBodyAllOfPetAsync(Pet pet, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testEchoBodyAllOfPetValidateBeforeCall(pet, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } /** * Build call for testEchoBodyFreeFormObjectResponseString * @param body Free form object (optional) diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 7eb3566fcce9..5147daf61c0e 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 26b94f38e4d2..e86aa2961e45 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Bird.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Bird.java index f8a88a604b07..472d77535a88 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Bird.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Bird.java @@ -63,7 +63,6 @@ public Bird() { } public Bird size(String size) { - this.size = size; return this; } @@ -77,14 +76,12 @@ public String getSize() { return size; } - public void setSize(String size) { this.size = size; } public Bird color(String color) { - this.color = color; return this; } @@ -98,7 +95,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java index 240826b0c7a3..71d231979025 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DataQuery.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DataQuery.java index 934f739ee40c..ff4a29d43ea7 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DataQuery.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DataQuery.java @@ -71,7 +71,6 @@ public DataQuery() { } public DataQuery suffix(String suffix) { - this.suffix = suffix; return this; } @@ -85,14 +84,12 @@ public String getSuffix() { return suffix; } - public void setSuffix(String suffix) { this.suffix = suffix; } public DataQuery text(String text) { - this.text = text; return this; } @@ -106,14 +103,12 @@ public String getText() { return text; } - public void setText(String text) { this.text = text; } public DataQuery date(OffsetDateTime date) { - this.date = date; return this; } @@ -127,7 +122,6 @@ public OffsetDateTime getDate() { return date; } - public void setDate(OffsetDateTime date) { this.date = date; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DefaultValue.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DefaultValue.java index a9d92978920d..244dd32a0e3d 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DefaultValue.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/DefaultValue.java @@ -106,6 +106,11 @@ public ArrayStringEnumDefaultEnum read(final JsonReader jsonReader) throws IOExc return ArrayStringEnumDefaultEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ArrayStringEnumDefaultEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ARRAY_STRING_ENUM_DEFAULT = "array_string_enum_default"; @@ -140,7 +145,6 @@ public DefaultValue() { } public DefaultValue arrayStringEnumRefDefault(List arrayStringEnumRefDefault) { - this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; return this; } @@ -162,14 +166,12 @@ public List getArrayStringEnumRefDefault() { return arrayStringEnumRefDefault; } - public void setArrayStringEnumRefDefault(List arrayStringEnumRefDefault) { this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; } public DefaultValue arrayStringEnumDefault(List arrayStringEnumDefault) { - this.arrayStringEnumDefault = arrayStringEnumDefault; return this; } @@ -191,14 +193,12 @@ public List getArrayStringEnumDefault() { return arrayStringEnumDefault; } - public void setArrayStringEnumDefault(List arrayStringEnumDefault) { this.arrayStringEnumDefault = arrayStringEnumDefault; } public DefaultValue arrayStringDefault(List arrayStringDefault) { - this.arrayStringDefault = arrayStringDefault; return this; } @@ -220,14 +220,12 @@ public List getArrayStringDefault() { return arrayStringDefault; } - public void setArrayStringDefault(List arrayStringDefault) { this.arrayStringDefault = arrayStringDefault; } public DefaultValue arrayIntegerDefault(List arrayIntegerDefault) { - this.arrayIntegerDefault = arrayIntegerDefault; return this; } @@ -249,14 +247,12 @@ public List getArrayIntegerDefault() { return arrayIntegerDefault; } - public void setArrayIntegerDefault(List arrayIntegerDefault) { this.arrayIntegerDefault = arrayIntegerDefault; } public DefaultValue arrayString(List arrayString) { - this.arrayString = arrayString; return this; } @@ -278,14 +274,12 @@ public List getArrayString() { return arrayString; } - public void setArrayString(List arrayString) { this.arrayString = arrayString; } public DefaultValue arrayStringNullable(List arrayStringNullable) { - this.arrayStringNullable = arrayStringNullable; return this; } @@ -307,14 +301,12 @@ public List getArrayStringNullable() { return arrayStringNullable; } - public void setArrayStringNullable(List arrayStringNullable) { this.arrayStringNullable = arrayStringNullable; } public DefaultValue arrayStringExtensionNullable(List arrayStringExtensionNullable) { - this.arrayStringExtensionNullable = arrayStringExtensionNullable; return this; } @@ -336,14 +328,12 @@ public List getArrayStringExtensionNullable() { return arrayStringExtensionNullable; } - public void setArrayStringExtensionNullable(List arrayStringExtensionNullable) { this.arrayStringExtensionNullable = arrayStringExtensionNullable; } public DefaultValue stringNullable(String stringNullable) { - this.stringNullable = stringNullable; return this; } @@ -357,7 +347,6 @@ public String getStringNullable() { return stringNullable; } - public void setStringNullable(String stringNullable) { this.stringNullable = stringNullable; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java index b304917e74a0..9e41ee189994 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java @@ -68,7 +68,6 @@ public NumberPropertiesOnly() { } public NumberPropertiesOnly number(BigDecimal number) { - this.number = number; return this; } @@ -82,14 +81,12 @@ public BigDecimal getNumber() { return number; } - public void setNumber(BigDecimal number) { this.number = number; } public NumberPropertiesOnly _float(Float _float) { - this._float = _float; return this; } @@ -103,14 +100,12 @@ public Float getFloat() { return _float; } - public void setFloat(Float _float) { this._float = _float; } public NumberPropertiesOnly _double(Double _double) { - this._double = _double; return this; } @@ -126,7 +121,6 @@ public Double getDouble() { return _double; } - public void setDouble(Double _double) { this._double = _double; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java index 44a73022face..cabce13af96a 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -132,7 +137,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -146,14 +150,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet name(String name) { - this.name = name; return this; } @@ -167,14 +169,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet category(Category category) { - this.category = category; return this; } @@ -188,14 +188,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -217,14 +215,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -246,14 +242,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -267,7 +261,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -399,6 +392,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Query.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Query.java index 7daca5795f00..31a7af02acaa 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Query.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Query.java @@ -104,6 +104,11 @@ public OutcomesEnum read(final JsonReader jsonReader) throws IOException { return OutcomesEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OutcomesEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_OUTCOMES = "outcomes"; @@ -114,7 +119,6 @@ public Query() { } public Query id(Long id) { - this.id = id; return this; } @@ -128,14 +132,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Query outcomes(List outcomes) { - this.outcomes = outcomes; return this; } @@ -157,7 +159,6 @@ public List getOutcomes() { return outcomes; } - public void setOutcomes(List outcomes) { this.outcomes = outcomes; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/StringEnumRef.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/StringEnumRef.java index fbd954c9d6ee..c786ac6c8423 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/StringEnumRef.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/StringEnumRef.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public StringEnumRef read(final JsonReader jsonReader) throws IOException { return StringEnumRef.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StringEnumRef.fromValue(value); + } } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java index 8f2dca745387..b52b66131466 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java index 532843528e89..41e90d09eb06 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java @@ -71,7 +71,6 @@ public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() { } public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter size(String size) { - this.size = size; return this; } @@ -85,14 +84,12 @@ public String getSize() { return size; } - public void setSize(String size) { this.size = size; } public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter color(String color) { - this.color = color; return this; } @@ -106,14 +103,12 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter id(Long id) { - this.id = id; return this; } @@ -127,14 +122,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter name(String name) { - this.name = name; return this; } @@ -148,7 +141,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java index 055b13ac8987..d2a89f3e6d59 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java +++ b/samples/client/echo_api/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java @@ -61,7 +61,6 @@ public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() { } public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter values(List values) { - this.values = values; return this; } @@ -83,7 +82,6 @@ public List getValues() { return values; } - public void setValues(List values) { this.values = values; } diff --git a/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java index 7d5e92b75a50..69083155b5af 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java +++ b/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -13,6 +13,8 @@ package org.openapitools.client.api; +import org.junit.Assert; +import org.junit.jupiter.api.Assertions; import org.openapitools.client.ApiException; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @@ -21,11 +23,11 @@ import java.util.HashMap; import java.util.List; import java.util.Map; +import org.openapitools.client.ApiResponse; /** * API tests for AuthApi */ -@Disabled public class AuthApiTest { private final AuthApi api = new AuthApi(); @@ -43,4 +45,23 @@ public void testAuthHttpBasicTest() throws ApiException { // TODO: test validations } + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + * + * @throws ApiException if the Api call fails + */ + @Test + public void testAuthHttpBearerTest() throws ApiException { + String response; + api.getApiClient().setBearerToken("fixed token"); + response = api.testAuthHttpBearer(); + Assertions.assertTrue(response.contains("Authorization: Bearer fixed token")); + + api.getApiClient().setBearerToken(() -> "dynamic token"); + response = api.testAuthHttpBearer(); + Assertions.assertTrue(response.contains("Authorization: Bearer dynamic token")); + } + } diff --git a/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/model/BirdAndCategoryTest.java b/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/model/BirdAndCategoryTest.java index 205f5cff0cda..9237871cfb7f 100644 --- a/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/model/BirdAndCategoryTest.java +++ b/samples/client/echo_api/java/okhttp-gson/src/test/java/org/openapitools/client/model/BirdAndCategoryTest.java @@ -34,7 +34,7 @@ public class BirdAndCategoryTest { */ @Test public void testBirdAndCategory() { - // TODO: test BirdAndCategory + } /** @@ -42,7 +42,7 @@ public void testBirdAndCategory() { */ @Test public void sizeTest() { - // TODO: test size + } /** diff --git a/samples/client/echo_api/java/resteasy/.github/workflows/maven.yml b/samples/client/echo_api/java/resteasy/.github/workflows/maven.yml new file mode 100644 index 000000000000..aa75c116424b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build Echo Server API + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/echo_api/java/resteasy/.gitignore b/samples/client/echo_api/java/resteasy/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/openapi3/server/petstore/python-flask/.openapi-generator-ignore b/samples/client/echo_api/java/resteasy/.openapi-generator-ignore similarity index 100% rename from samples/openapi3/server/petstore/python-flask/.openapi-generator-ignore rename to samples/client/echo_api/java/resteasy/.openapi-generator-ignore diff --git a/samples/client/echo_api/java/resteasy/.openapi-generator/FILES b/samples/client/echo_api/java/resteasy/.openapi-generator/FILES new file mode 100644 index 000000000000..2ff641b20af8 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/.openapi-generator/FILES @@ -0,0 +1,64 @@ +.github/workflows/maven.yml +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/AuthApi.md +docs/Bird.md +docs/BodyApi.md +docs/Category.md +docs/DataQuery.md +docs/DefaultValue.md +docs/FormApi.md +docs/HeaderApi.md +docs/NumberPropertiesOnly.md +docs/PathApi.md +docs/Pet.md +docs/Query.md +docs/QueryApi.md +docs/StringEnumRef.md +docs/Tag.md +docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/JavaTimeFormatter.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/AuthApi.java +src/main/java/org/openapitools/client/api/BodyApi.java +src/main/java/org/openapitools/client/api/FormApi.java +src/main/java/org/openapitools/client/api/HeaderApi.java +src/main/java/org/openapitools/client/api/PathApi.java +src/main/java/org/openapitools/client/api/QueryApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/Bird.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/DataQuery.java +src/main/java/org/openapitools/client/model/DefaultValue.java +src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/Query.java +src/main/java/org/openapitools/client/model/StringEnumRef.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java +src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java diff --git a/samples/client/echo_api/java/resteasy/.openapi-generator/VERSION b/samples/client/echo_api/java/resteasy/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/resteasy/.travis.yml b/samples/client/echo_api/java/resteasy/.travis.yml new file mode 100644 index 000000000000..1b6741c083c7 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/echo_api/java/resteasy/README.md b/samples/client/echo_api/java/resteasy/README.md new file mode 100644 index 000000000000..2c53ad7593f9 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/README.md @@ -0,0 +1,185 @@ +# petstore-resteasy-echo + +Echo Server API + +- API version: 0.1.0 + +Echo Server API + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + petstore-resteasy-echo + 0.1.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'petstore-resteasy-echo' jar has been published to maven central. + mavenLocal() // Needed if the 'petstore-resteasy-echo' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:petstore-resteasy-echo:0.1.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/petstore-resteasy-echo-0.1.0.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AuthApi; + +public class AuthApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP basic authorization: http_auth + HttpBasicAuth http_auth = (HttpBasicAuth) defaultClient.getAuthentication("http_auth"); + http_auth.setUsername("YOUR USERNAME"); + http_auth.setPassword("YOUR PASSWORD"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBasic(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBasic"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:3000* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AuthApi* | [**testAuthHttpBasic**](docs/AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*BodyApi* | [**testBinaryGif**](docs/BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body +*BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +*BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +*BodyApi* | [**testEchoBodyPet**](docs/BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) +*BodyApi* | [**testEchoBodyPetResponseString**](docs/BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body +*BodyApi* | [**testEchoBodyTagResponseString**](docs/BodyApi.md#testEchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +*FormApi* | [**testFormIntegerBooleanString**](docs/FormApi.md#testFormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) +*FormApi* | [**testFormOneof**](docs/FormApi.md#testFormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema +*HeaderApi* | [**testHeaderIntegerBooleanStringEnums**](docs/HeaderApi.md#testHeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) +*PathApi* | [**testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](docs/PathApi.md#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) +*QueryApi* | [**testEnumRefString**](docs/QueryApi.md#testEnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) +*QueryApi* | [**testQueryDatetimeDateString**](docs/QueryApi.md#testQueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) +*QueryApi* | [**testQueryIntegerBooleanString**](docs/QueryApi.md#testQueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) +*QueryApi* | [**testQueryStyleDeepObjectExplodeTrueObject**](docs/QueryApi.md#testQueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +*QueryApi* | [**testQueryStyleDeepObjectExplodeTrueObjectAllOf**](docs/QueryApi.md#testQueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueArrayString**](docs/QueryApi.md#testQueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueObject**](docs/QueryApi.md#testQueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueObjectAllOf**](docs/QueryApi.md#testQueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + +## Documentation for Models + + - [Bird](docs/Bird.md) + - [Category](docs/Category.md) + - [DataQuery](docs/DataQuery.md) + - [DefaultValue](docs/DefaultValue.md) + - [NumberPropertiesOnly](docs/NumberPropertiesOnly.md) + - [Pet](docs/Pet.md) + - [Query](docs/Query.md) + - [StringEnumRef](docs/StringEnumRef.md) + - [Tag](docs/Tag.md) + - [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter](docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md) + - [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter](docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### http_auth + + +- **Type**: HTTP basic authentication + + +### http_bearer_auth + + +- **Type**: HTTP Bearer Token authentication + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +team@openapitools.org + diff --git a/samples/client/echo_api/java/resteasy/api/openapi.yaml b/samples/client/echo_api/java/resteasy/api/openapi.yaml new file mode 100644 index 000000000000..f5d4fc9abbde --- /dev/null +++ b/samples/client/echo_api/java/resteasy/api/openapi.yaml @@ -0,0 +1,872 @@ +openapi: 3.0.3 +info: + contact: + email: team@openapitools.org + description: Echo Server API + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + title: Echo Server API + version: 0.1.0 +servers: +- url: http://localhost:3000/ +paths: + /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}: + get: + description: Test path parameter(s) + operationId: "tests/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}" + parameters: + - explode: false + in: path + name: path_string + required: true + schema: + type: string + style: simple + - explode: false + in: path + name: path_integer + required: true + schema: + type: integer + style: simple + - explode: false + in: path + name: enum_nonref_string_path + required: true + schema: + enum: + - success + - failure + - unclassified + type: string + style: simple + - explode: false + in: path + name: enum_ref_string_path + required: true + schema: + $ref: '#/components/schemas/StringEnumRef' + style: simple + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test path parameter(s) + tags: + - path + x-accepts: text/plain + /form/integer/boolean/string: + post: + description: Test form parameter(s) + operationId: test/form/integer/boolean/string + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/test_form_integer_boolean_string_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test form parameter(s) + tags: + - form + x-content-type: application/x-www-form-urlencoded + x-accepts: text/plain + /form/oneof: + post: + description: Test form parameter(s) for oneOf schema + operationId: test/form/oneof + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/test_form_oneof_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test form parameter(s) for oneOf schema + tags: + - form + x-content-type: application/x-www-form-urlencoded + x-accepts: text/plain + /header/integer/boolean/string/enums: + get: + description: Test header parameter(s) + operationId: test/header/integer/boolean/string/enums + parameters: + - explode: true + in: header + name: integer_header + required: false + schema: + type: integer + style: form + - explode: true + in: header + name: boolean_header + required: false + schema: + type: boolean + style: form + - explode: true + in: header + name: string_header + required: false + schema: + type: string + style: form + - explode: true + in: header + name: enum_nonref_string_header + required: false + schema: + enum: + - success + - failure + - unclassified + type: string + style: form + - explode: true + in: header + name: enum_ref_string_header + required: false + schema: + $ref: '#/components/schemas/StringEnumRef' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test header parameter(s) + tags: + - header + x-accepts: text/plain + /query/enum_ref_string: + get: + description: Test query parameter(s) + operationId: test/enum_ref_string + parameters: + - explode: true + in: query + name: enum_nonref_string_query + required: false + schema: + enum: + - success + - failure + - unclassified + type: string + style: form + - explode: true + in: query + name: enum_ref_string_query + required: false + schema: + $ref: '#/components/schemas/StringEnumRef' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/datetime/date/string: + get: + description: Test query parameter(s) + operationId: test/query/datetime/date/string + parameters: + - explode: true + in: query + name: datetime_query + required: false + schema: + format: date-time + type: string + style: form + - explode: true + in: query + name: date_query + required: false + schema: + format: date + type: string + style: form + - explode: true + in: query + name: string_query + required: false + schema: + type: string + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/integer/boolean/string: + get: + description: Test query parameter(s) + operationId: test/query/integer/boolean/string + parameters: + - explode: true + in: query + name: integer_query + required: false + schema: + type: integer + style: form + - explode: true + in: query + name: boolean_query + required: false + schema: + type: boolean + style: form + - explode: true + in: query + name: string_query + required: false + schema: + type: string + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/array_string: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/array_string + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/test_query_style_form_explode_true_array_string_query_object_parameter' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/object: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/object + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/Pet' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/object/allOf: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/object/allOf + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/DataQuery' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_deepObject/explode_true/object: + get: + description: Test query parameter(s) + operationId: test/query/style_deepObject/explode_true/object + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/Pet' + style: deepObject + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_deepObject/explode_true/object/allOf: + get: + description: Test query parameter(s) + operationId: test/query/style_deepObject/explode_true/object/allOf + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/test_query_style_deepObject_explode_true_object_allOf_query_object_parameter' + style: deepObject + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /body/application/octetstream/binary: + post: + description: Test body parameter(s) + operationId: test/body/application/octetstream/binary + requestBody: + content: + application/octet-stream: + schema: + format: binary + type: string + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/octet-stream + x-accepts: text/plain + /echo/body/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/Pet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json + /echo/body/Pet/response_string: + post: + description: Test empty response body + operationId: test/echo/body/Pet/response_string + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test empty response body + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /echo/body/Tag/response_string: + post: + description: Test empty json (request body) + operationId: test/echo/body/Tag/response_string + requestBody: + $ref: '#/components/requestBodies/Tag' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test empty json (request body) + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /echo/body/FreeFormObject/response_string: + post: + description: Test free form object + operationId: test/echo/body/FreeFormObject/response_string + requestBody: + content: + application/json: + schema: + type: object + description: Free form object + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test free form object + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /binary/gif: + post: + description: Test binary (gif) response body + operationId: test/binary/gif + responses: + "200": + content: + image/gif: + schema: + format: binary + type: string + description: Successful operation + summary: Test binary (gif) response body + tags: + - body + x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain + /body/application/octetstream/array_of_binary: + post: + description: Test array of binary in multipart mime + operationId: test/body/multipart/formdata/array_of_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_array_of_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test array of binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain + /auth/http/basic: + post: + description: To test HTTP basic authentication + operationId: test/auth/http/basic + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_auth: [] + summary: To test HTTP basic authentication + tags: + - auth + x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + Tag: + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + description: Tag object + schemas: + Category: + example: + name: Dogs + id: 1 + properties: + id: + example: 1 + format: int64 + type: integer + name: + example: Dogs + type: string + type: object + xml: + name: category + Tag: + example: + name: name + id: 0 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 10 + category: + name: Dogs + id: 1 + tags: + - name: name + id: 0 + - name: name + id: 0 + status: available + properties: + id: + example: 10 + format: int64 + type: integer + name: + example: doggie + type: string + category: + $ref: '#/components/schemas/Category' + photoUrls: + items: + type: string + xml: + name: photoUrl + type: array + xml: + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: pet + StringEnumRef: + enum: + - success + - failure + - unclassified + type: string + DefaultValue: + description: to test the default value of properties + properties: + array_string_enum_ref_default: + default: + - success + - failure + items: + $ref: '#/components/schemas/StringEnumRef' + type: array + array_string_enum_default: + default: + - success + - failure + items: + enum: + - success + - failure + - unclassified + type: string + type: array + array_string_default: + default: + - failure + - skipped + items: + type: string + type: array + array_integer_default: + default: + - 1 + - 3 + items: + type: integer + type: array + array_string: + items: + type: string + type: array + array_string_nullable: + items: + type: string + nullable: true + type: array + array_string_extension_nullable: + items: + type: string + type: array + x-nullable: true + string_nullable: + nullable: true + type: string + type: object + Bird: + properties: + size: + type: string + color: + type: string + type: object + Query: + properties: + id: + description: Query + format: int64 + type: integer + outcomes: + default: + - SUCCESS + - FAILURE + items: + enum: + - SUCCESS + - FAILURE + - SKIPPED + type: string + type: array + type: object + x-parent: true + DataQuery: + allOf: + - properties: + suffix: + description: test suffix + type: string + text: + description: Some text containing white spaces + example: Some text + type: string + date: + description: A date + format: date-time + type: string + type: object + - $ref: '#/components/schemas/Query' + NumberPropertiesOnly: + properties: + number: + type: number + float: + format: float + type: number + double: + format: double + maximum: 50.2 + minimum: 0.8 + type: number + type: object + test_form_integer_boolean_string_request: + properties: + integer_form: + type: integer + boolean_form: + type: boolean + string_form: + type: string + type: object + test_form_oneof_request_oneOf: + properties: + form1: + type: string + form2: + type: integer + type: object + test_form_oneof_request_oneOf_1: + properties: + form3: + type: string + form4: + type: boolean + type: object + test_form_oneof_request: + oneOf: + - $ref: '#/components/schemas/test_form_oneof_request_oneOf' + - $ref: '#/components/schemas/test_form_oneof_request_oneOf_1' + - $ref: '#/components/schemas/Tag' + type: object + test_query_style_form_explode_true_array_string_query_object_parameter: + properties: + values: + items: + type: string + type: array + type: object + test_query_style_deepObject_explode_true_object_allOf_query_object_parameter: + allOf: + - $ref: '#/components/schemas/Bird' + - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object + test_body_multipart_formdata_array_of_binary_request: + properties: + files: + items: + format: binary + type: string + type: array + required: + - files + type: object + securitySchemes: + http_auth: + scheme: basic + type: http + http_bearer_auth: + scheme: bearer + type: http + diff --git a/samples/client/echo_api/java/resteasy/build.gradle b/samples/client/echo_api/java/resteasy/build.gradle new file mode 100644 index 000000000000..62d43afabd02 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/build.gradle @@ -0,0 +1,124 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '0.1.0' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + mavenCentral() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 23 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDirectory + task.destinationDirectory = project.file("${project.buildDir}/outputs/jar") + task.archiveFileName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven-publish' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + publishing { + publications { + maven(MavenPublication) { + artifactId = 'petstore-resteasy-echo' + from components.java + } + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + swagger_annotations_version = "1.6.3" + jackson_version = "2.13.4" + jackson_databind_version = "2.13.4.2" + jackson_databind_nullable_version = "0.2.6" + jakarta_annotation_version = "1.3.5" + threetenbp_version = "2.9.10" + resteasy_version = "4.5.11.Final" + junit_version = "4.13" +} + +dependencies { + implementation "io.swagger:swagger-annotations:$swagger_annotations_version" + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation "org.jboss.resteasy:resteasy-client:$resteasy_version" + implementation "org.jboss.resteasy:resteasy-multipart-provider:$resteasy_version" + implementation "org.jboss.resteasy:resteasy-jackson2-provider:$resteasy_version" + implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + implementation "com.github.joschi.jackson:jackson-datatype-threetenbp:$threetenbp_version" + implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation "junit:junit:$junit_version" +} diff --git a/samples/client/echo_api/java/resteasy/build.sbt b/samples/client/echo_api/java/resteasy/build.sbt new file mode 100644 index 000000000000..0c31d90292c0 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/build.sbt @@ -0,0 +1,25 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "petstore-resteasy-echo", + version := "0.1.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.5.22" % "compile", + "org.jboss.resteasy" % "resteasy-client" % "3.1.3.Final" % "compile", + "org.jboss.resteasy" % "resteasy-multipart-provider" % "4.5.11.Final" % "compile", + "org.jboss.resteasy" % "resteasy-jackson2-provider" % "4.5.11.Final" % "compile", + "com.fasterxml.jackson.core" % "jackson-core" % "2.13.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-annotations" % "2.13.4" % "compile", + "com.fasterxml.jackson.core" % "jackson-databind" % "2.13.4.2" % "compile", + "com.github.joschi.jackson" % "jackson-datatype-threetenbp" % "2.9.10" % "compile", + "com.fasterxml.jackson.datatype" % "jackson-datatype-jsr310" % "2.9.10" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "junit" % "junit" % "4.13" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test" + ) + ) diff --git a/samples/client/echo_api/java/resteasy/docs/AuthApi.md b/samples/client/echo_api/java/resteasy/docs/AuthApi.md new file mode 100644 index 000000000000..de3353d43a2c --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/AuthApi.md @@ -0,0 +1,145 @@ +# AuthApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testAuthHttpBasic**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | + + + +## testAuthHttpBasic + +> String testAuthHttpBasic() + +To test HTTP basic authentication + +To test HTTP basic authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP basic authorization: http_auth + HttpBasicAuth http_auth = (HttpBasicAuth) defaultClient.getAuthentication("http_auth"); + http_auth.setUsername("YOUR USERNAME"); + http_auth.setPassword("YOUR PASSWORD"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBasic(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBasic"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testAuthHttpBearer + +> String testAuthHttpBearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBearer(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/Bird.md b/samples/client/echo_api/java/resteasy/docs/Bird.md new file mode 100644 index 000000000000..2a6f8a660d65 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/Bird.md @@ -0,0 +1,14 @@ + + +# Bird + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**size** | **String** | | [optional] | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/BodyApi.md b/samples/client/echo_api/java/resteasy/docs/BodyApi.md new file mode 100644 index 000000000000..3cf2014e31f6 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/BodyApi.md @@ -0,0 +1,607 @@ +# BodyApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testBinaryGif**](BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body | +| [**testBodyApplicationOctetstreamBinary**](BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | +| [**testBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | +| [**testEchoBodyFreeFormObjectResponseString**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | +| [**testEchoBodyPet**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | +| [**testEchoBodyPetResponseString**](BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body | +| [**testEchoBodyTagResponseString**](BodyApi.md#testEchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) | + + + +## testBinaryGif + +> File testBinaryGif() + +Test binary (gif) response body + +Test binary (gif) response body + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + try { + File result = apiInstance.testBinaryGif(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBinaryGif"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**File**](File.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/gif + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyApplicationOctetstreamBinary + +> String testBodyApplicationOctetstreamBinary(body) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File body = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyApplicationOctetstreamBinary(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyApplicationOctetstreamBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/octet-stream +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyMultipartFormdataArrayOfBinary + +> String testBodyMultipartFormdataArrayOfBinary(files) + +Test array of binary in multipart mime + +Test array of binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + List files = Arrays.asList(); // List | + try { + String result = apiInstance.testBodyMultipartFormdataArrayOfBinary(files); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataArrayOfBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **files** | **List<File>**| | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyMultipartFormdataSingleBinary + +> String testBodyMultipartFormdataSingleBinary(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyMultipartFormdataSingleBinary(myFile); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyAllOfPet + +> Pet testEchoBodyAllOfPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyAllOfPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyFreeFormObjectResponseString + +> String testEchoBodyFreeFormObjectResponseString(body) + +Test free form object + +Test free form object + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Object body = null; // Object | Free form object + try { + String result = apiInstance.testEchoBodyFreeFormObjectResponseString(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyFreeFormObjectResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **Object**| Free form object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyPet + +> Pet testEchoBodyPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyPetResponseString + +> String testEchoBodyPetResponseString(pet) + +Test empty response body + +Test empty response body + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + String result = apiInstance.testEchoBodyPetResponseString(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyPetResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyTagResponseString + +> String testEchoBodyTagResponseString(tag) + +Test empty json (request body) + +Test empty json (request body) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Tag tag = new Tag(); // Tag | Tag object + try { + String result = apiInstance.testEchoBodyTagResponseString(tag); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyTagResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **tag** | [**Tag**](Tag.md)| Tag object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/Category.md b/samples/client/echo_api/java/resteasy/docs/Category.md new file mode 100644 index 000000000000..7289ebf585bb --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/DataQuery.md b/samples/client/echo_api/java/resteasy/docs/DataQuery.md new file mode 100644 index 000000000000..338c467b2d56 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/DataQuery.md @@ -0,0 +1,15 @@ + + +# DataQuery + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**suffix** | **String** | test suffix | [optional] | +|**text** | **String** | Some text containing white spaces | [optional] | +|**date** | **OffsetDateTime** | A date | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/DefaultValue.md b/samples/client/echo_api/java/resteasy/docs/DefaultValue.md new file mode 100644 index 000000000000..20a9b8ee2508 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/DefaultValue.md @@ -0,0 +1,31 @@ + + +# DefaultValue + +to test the default value of properties + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayStringEnumRefDefault** | **List<StringEnumRef>** | | [optional] | +|**arrayStringEnumDefault** | [**List<ArrayStringEnumDefaultEnum>**](#List<ArrayStringEnumDefaultEnum>) | | [optional] | +|**arrayStringDefault** | **List<String>** | | [optional] | +|**arrayIntegerDefault** | **List<Integer>** | | [optional] | +|**arrayString** | **List<String>** | | [optional] | +|**arrayStringNullable** | **List<String>** | | [optional] | +|**arrayStringExtensionNullable** | **List<String>** | | [optional] | +|**stringNullable** | **String** | | [optional] | + + + +## Enum: List<ArrayStringEnumDefaultEnum> + +| Name | Value | +|---- | -----| +| SUCCESS | "success" | +| FAILURE | "failure" | +| UNCLASSIFIED | "unclassified" | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/FormApi.md b/samples/client/echo_api/java/resteasy/docs/FormApi.md new file mode 100644 index 000000000000..1f3ad73e9384 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/FormApi.md @@ -0,0 +1,156 @@ +# FormApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testFormIntegerBooleanString**](FormApi.md#testFormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) | +| [**testFormOneof**](FormApi.md#testFormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema | + + + +## testFormIntegerBooleanString + +> String testFormIntegerBooleanString(integerForm, booleanForm, stringForm) + +Test form parameter(s) + +Test form parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FormApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + FormApi apiInstance = new FormApi(defaultClient); + Integer integerForm = 56; // Integer | + Boolean booleanForm = true; // Boolean | + String stringForm = "stringForm_example"; // String | + try { + String result = apiInstance.testFormIntegerBooleanString(integerForm, booleanForm, stringForm); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FormApi#testFormIntegerBooleanString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerForm** | **Integer**| | [optional] | +| **booleanForm** | **Boolean**| | [optional] | +| **stringForm** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testFormOneof + +> String testFormOneof(form1, form2, form3, form4, id, name) + +Test form parameter(s) for oneOf schema + +Test form parameter(s) for oneOf schema + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FormApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + FormApi apiInstance = new FormApi(defaultClient); + String form1 = "form1_example"; // String | + Integer form2 = 56; // Integer | + String form3 = "form3_example"; // String | + Boolean form4 = true; // Boolean | + Long id = 56L; // Long | + String name = "name_example"; // String | + try { + String result = apiInstance.testFormOneof(form1, form2, form3, form4, id, name); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FormApi#testFormOneof"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **form1** | **String**| | [optional] | +| **form2** | **Integer**| | [optional] | +| **form3** | **String**| | [optional] | +| **form4** | **Boolean**| | [optional] | +| **id** | **Long**| | [optional] | +| **name** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/HeaderApi.md b/samples/client/echo_api/java/resteasy/docs/HeaderApi.md new file mode 100644 index 000000000000..e30880043fac --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/HeaderApi.md @@ -0,0 +1,83 @@ +# HeaderApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testHeaderIntegerBooleanStringEnums**](HeaderApi.md#testHeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) | + + + +## testHeaderIntegerBooleanStringEnums + +> String testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader) + +Test header parameter(s) + +Test header parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.HeaderApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + HeaderApi apiInstance = new HeaderApi(defaultClient); + Integer integerHeader = 56; // Integer | + Boolean booleanHeader = true; // Boolean | + String stringHeader = "stringHeader_example"; // String | + String enumNonrefStringHeader = "success"; // String | + StringEnumRef enumRefStringHeader = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling HeaderApi#testHeaderIntegerBooleanStringEnums"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerHeader** | **Integer**| | [optional] | +| **booleanHeader** | **Boolean**| | [optional] | +| **stringHeader** | **String**| | [optional] | +| **enumNonrefStringHeader** | **String**| | [optional] [enum: success, failure, unclassified] | +| **enumRefStringHeader** | [**StringEnumRef**](.md)| | [optional] [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/NumberPropertiesOnly.md b/samples/client/echo_api/java/resteasy/docs/NumberPropertiesOnly.md new file mode 100644 index 000000000000..7e153538475a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/NumberPropertiesOnly.md @@ -0,0 +1,15 @@ + + +# NumberPropertiesOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**number** | **BigDecimal** | | [optional] | +|**_float** | **Float** | | [optional] | +|**_double** | **Double** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/PathApi.md b/samples/client/echo_api/java/resteasy/docs/PathApi.md new file mode 100644 index 000000000000..e9a539e8c3e4 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/PathApi.md @@ -0,0 +1,81 @@ +# PathApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](PathApi.md#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) | + + + +## testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath + +> String testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath) + +Test path parameter(s) + +Test path parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PathApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + PathApi apiInstance = new PathApi(defaultClient); + String pathString = "pathString_example"; // String | + Integer pathInteger = 56; // Integer | + String enumNonrefStringPath = "success"; // String | + StringEnumRef enumRefStringPath = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PathApi#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pathString** | **String**| | | +| **pathInteger** | **Integer**| | | +| **enumNonrefStringPath** | **String**| | [enum: success, failure, unclassified] | +| **enumRefStringPath** | [**StringEnumRef**](.md)| | [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/Pet.md b/samples/client/echo_api/java/resteasy/docs/Pet.md new file mode 100644 index 000000000000..82aa8a25ed7c --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**category** | [**Category**](Category.md) | | [optional] | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/Query.md b/samples/client/echo_api/java/resteasy/docs/Query.md new file mode 100644 index 000000000000..99c6fd6faa5d --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/Query.md @@ -0,0 +1,24 @@ + + +# Query + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | Query | [optional] | +|**outcomes** | [**List<OutcomesEnum>**](#List<OutcomesEnum>) | | [optional] | + + + +## Enum: List<OutcomesEnum> + +| Name | Value | +|---- | -----| +| SUCCESS | "SUCCESS" | +| FAILURE | "FAILURE" | +| SKIPPED | "SKIPPED" | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/QueryApi.md b/samples/client/echo_api/java/resteasy/docs/QueryApi.md new file mode 100644 index 000000000000..2606c8e62ca9 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/QueryApi.md @@ -0,0 +1,554 @@ +# QueryApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testEnumRefString**](QueryApi.md#testEnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) | +| [**testQueryDatetimeDateString**](QueryApi.md#testQueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) | +| [**testQueryIntegerBooleanString**](QueryApi.md#testQueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) | +| [**testQueryStyleDeepObjectExplodeTrueObject**](QueryApi.md#testQueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) | +| [**testQueryStyleDeepObjectExplodeTrueObjectAllOf**](QueryApi.md#testQueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueArrayString**](QueryApi.md#testQueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueObject**](QueryApi.md#testQueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueObjectAllOf**](QueryApi.md#testQueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) | + + + +## testEnumRefString + +> String testEnumRefString(enumNonrefStringQuery, enumRefStringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + String enumNonrefStringQuery = "success"; // String | + StringEnumRef enumRefStringQuery = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testEnumRefString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **enumNonrefStringQuery** | **String**| | [optional] [enum: success, failure, unclassified] | +| **enumRefStringQuery** | [**StringEnumRef**](.md)| | [optional] [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryDatetimeDateString + +> String testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + OffsetDateTime datetimeQuery = OffsetDateTime.now(); // OffsetDateTime | + LocalDate dateQuery = LocalDate.now(); // LocalDate | + String stringQuery = "stringQuery_example"; // String | + try { + String result = apiInstance.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryDatetimeDateString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **datetimeQuery** | **OffsetDateTime**| | [optional] | +| **dateQuery** | **LocalDate**| | [optional] | +| **stringQuery** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryIntegerBooleanString + +> String testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Integer integerQuery = 56; // Integer | + Boolean booleanQuery = true; // Boolean | + String stringQuery = "stringQuery_example"; // String | + try { + String result = apiInstance.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryIntegerBooleanString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerQuery** | **Integer**| | [optional] | +| **booleanQuery** | **Boolean**| | [optional] | +| **stringQuery** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleDeepObjectExplodeTrueObject + +> String testQueryStyleDeepObjectExplodeTrueObject(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Pet queryObject = new Pet(); // Pet | + try { + String result = apiInstance.testQueryStyleDeepObjectExplodeTrueObject(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleDeepObjectExplodeTrueObject"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**Pet**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleDeepObjectExplodeTrueObjectAllOf + +> String testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject = new TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(); // TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | + try { + String result = apiInstance.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleDeepObjectExplodeTrueObjectAllOf"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueArrayString + +> String testQueryStyleFormExplodeTrueArrayString(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject = new TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(); // TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueArrayString(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueArrayString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueObject + +> String testQueryStyleFormExplodeTrueObject(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Pet queryObject = new Pet(); // Pet | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueObject(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueObject"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**Pet**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueObjectAllOf + +> String testQueryStyleFormExplodeTrueObjectAllOf(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + DataQuery queryObject = new DataQuery(); // DataQuery | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueObjectAllOf(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueObjectAllOf"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**DataQuery**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resteasy/docs/StringEnumRef.md b/samples/client/echo_api/java/resteasy/docs/StringEnumRef.md new file mode 100644 index 000000000000..dff22ecf074b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/StringEnumRef.md @@ -0,0 +1,15 @@ + + +# StringEnumRef + +## Enum + + +* `SUCCESS` (value: `"success"`) + +* `FAILURE` (value: `"failure"`) + +* `UNCLASSIFIED` (value: `"unclassified"`) + + + diff --git a/samples/client/echo_api/java/resteasy/docs/Tag.md b/samples/client/echo_api/java/resteasy/docs/Tag.md new file mode 100644 index 000000000000..5088b2dd1c31 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/java/resteasy/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md new file mode 100644 index 000000000000..a756a343e8a8 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -0,0 +1,16 @@ + + +# TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**size** | **String** | | [optional] | +|**color** | **String** | | [optional] | +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resteasy/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/java/resteasy/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md new file mode 100644 index 000000000000..9235e80fb823 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -0,0 +1,13 @@ + + +# TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**values** | **List<String>** | | [optional] | + + + diff --git a/samples/openapi3/server/petstore/python-flask/git_push.sh b/samples/client/echo_api/java/resteasy/git_push.sh similarity index 100% rename from samples/openapi3/server/petstore/python-flask/git_push.sh rename to samples/client/echo_api/java/resteasy/git_push.sh diff --git a/samples/client/echo_api/java/resteasy/gradle.properties b/samples/client/echo_api/java/resteasy/gradle.properties new file mode 100644 index 000000000000..a3408578278a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.jar b/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..7454180f2ae8 Binary files /dev/null and b/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.properties b/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..ffed3a254e91 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/echo_api/java/resteasy/gradlew b/samples/client/echo_api/java/resteasy/gradlew new file mode 100644 index 000000000000..005bcde04284 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/echo_api/java/resteasy/gradlew.bat b/samples/client/echo_api/java/resteasy/gradlew.bat new file mode 100644 index 000000000000..6a68175eb70f --- /dev/null +++ b/samples/client/echo_api/java/resteasy/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/echo_api/java/resteasy/pom.xml b/samples/client/echo_api/java/resteasy/pom.xml new file mode 100644 index 000000000000..67f2e7229e85 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/pom.xml @@ -0,0 +1,260 @@ + + 4.0.0 + org.openapitools + petstore-resteasy-echo + jar + petstore-resteasy-echo + 0.1.0 + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.12 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 1.10 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 2.5.1 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.2 + + none + 1.8 + + + + attach-javadocs + + jar + + + + + + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + org.jboss.resteasy + resteasy-client + ${resteasy-version} + + + org.jboss.resteasy + resteasy-jaxrs-services + + + net.jcip + jcip-annotations + + + + + org.jboss.resteasy + resteasy-multipart-provider + ${resteasy-version} + + + com.sun.xml.bind + jaxb-impl + + + com.sun.mail + javax.mail + + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + org.jboss.resteasy + resteasy-jackson2-provider + ${resteasy-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + com.github.joschi.jackson + jackson-datatype-threetenbp + ${threetenbp-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 4.7.6.Final + 2.15.2 + 2.15.2 + 0.2.6 + 1.3.5 + 2.9.10 + 1.0.0 + 4.13 + + diff --git a/samples/client/echo_api/java/resteasy/settings.gradle b/samples/client/echo_api/java/resteasy/settings.gradle new file mode 100644 index 000000000000..256d4b61e16d --- /dev/null +++ b/samples/client/echo_api/java/resteasy/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "petstore-resteasy-echo" \ No newline at end of file diff --git a/samples/client/echo_api/java/resteasy/src/main/AndroidManifest.xml b/samples/client/echo_api/java/resteasy/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..44a553eb4d5a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,747 @@ +package org.openapitools.client; + +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.time.OffsetDateTime; + +import javax.ws.rs.client.Client; +import javax.ws.rs.client.ClientBuilder; +import javax.ws.rs.client.Entity; +import javax.ws.rs.client.Invocation; +import javax.ws.rs.client.WebTarget; +import javax.ws.rs.core.Form; +import javax.ws.rs.core.GenericEntity; +import javax.ws.rs.core.GenericType; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.Response; +import javax.ws.rs.core.Response.Status; + +import org.jboss.logging.Logger; +import org.jboss.resteasy.client.jaxrs.internal.ClientConfiguration; +import org.jboss.resteasy.plugins.providers.multipart.MultipartFormDataOutput; +import org.jboss.resteasy.spi.ResteasyProviderFactory; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiClient extends JavaTimeFormatter { + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String basePath = "http://localhost:3000"; + private boolean debugging = false; + + private Client httpClient; + private JSON json; + private String tempFolderPath = null; + + private Map authentications; + + private int statusCode; + private Map> responseHeaders; + + private DateFormat dateFormat; + + public ApiClient() { + json = new JSON(); + httpClient = buildHttpClient(debugging); + + this.dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX", Locale.ROOT); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + this.json.setDateFormat((DateFormat) dateFormat.clone()); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/0.1.0/java"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("http_auth", new HttpBasicAuth()); + authentications.put("http_bearer_auth", new HttpBearerAuth("bearer")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Gets the JSON instance to do JSON serialization and deserialization. + * @return the JSON utility class + */ + public JSON getJSON() { + return json; + } + + public Client getHttpClient() { + return httpClient; + } + + public ApiClient setHttpClient(Client httpClient) { + this.httpClient = httpClient; + return this; + } + + public String getBasePath() { + return basePath; + } + + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Gets the status code of the previous request + * @return the status code of the previous request + */ + public int getStatusCode() { + return statusCode; + } + + /** + * Gets the response headers of the previous request + * @return the response headers of the previous request + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * @return the authentications + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set username for the first HTTP basic authentication. + * @param username the username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password the password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * @param apiKey the API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * @param apiKeyPrefix the API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * @param userAgent the User-Agent header value + * @return this {@code ApiClient} + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return this {@code ApiClient} + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return {@code true} if debugging is enabled for this API client + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return this {@code ApiClient} + */ + public ApiClient setDebugging(boolean debugging) { + this.debugging = debugging; + // Rebuild HTTP Client according to the new "debugging" value. + this.httpClient = buildHttpClient(debugging); + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default temporary folder. + * + * @return the temporary folder path + * @see createTempFile + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get the date format used to parse/format date parameters. + * @return the date format used to parse/format date parameters + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat a date format used to parse/format date parameters + * @return this {@code ApiClient} + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + // also set the date format for model (de)serialization with Date properties + this.json.setDateFormat((DateFormat) dateFormat.clone()); + return this; + } + + /** + * Parse the given string into Date object. + * @param str a string to parse + * @return a {@code Date} object + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (java.text.ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * @param date a {@code Date} object to format + * @return the {@code String} version of the {@code Date} object + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * @param param an object to format + * @return the {@code String} version of the object + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate((Date) param); + } else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for(Object o : (Collection)param) { + if(b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /* + Format to {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Object value){ + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null) return params; + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(new Pair(name, parameterToString(value))); + return params; + } + + if (valueCollection.isEmpty()){ + return params; + } + + // get the collection format + collectionFormat = (collectionFormat == null || collectionFormat.isEmpty() ? "csv" : collectionFormat); // default: csv + + // create the params based on the collection format + if (collectionFormat.equals("multi")) { + for (Object item : valueCollection) { + params.add(new Pair(name, parameterToString(item))); + } + + return params; + } + + String delimiter = ","; + + if (collectionFormat.equals("csv")) { + delimiter = ","; + } else if (collectionFormat.equals("ssv")) { + delimiter = " "; + } else if (collectionFormat.equals("tsv")) { + delimiter = "\t"; + } else if (collectionFormat.equals("pipes")) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : valueCollection) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + params.add(new Pair(name, sb.substring(1))); + + return params; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return "application/json"; + } + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * @param str a {@code String} to escape + * @return the escaped version of the {@code String} + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Serialize the given Java object into string entity according the given + * Content-Type (only JSON is supported for now). + * @param obj the object to serialize + * @param formParams the form parameters + * @param contentType the content type + * @return an {@code Entity} + * @throws ApiException on failure to serialize + */ + public Entity serialize(Object obj, Map formParams, String contentType) throws ApiException { + Entity entity = null; + if (contentType.startsWith("multipart/form-data")) { + MultipartFormDataOutput multipart = new MultipartFormDataOutput(); + //MultiPart multiPart = new MultiPart(); + for (Entry param: formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + try { + multipart.addFormData(param.getKey(),new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM_TYPE, file.getName()); + } catch (FileNotFoundException e) { + throw new ApiException("Could not serialize multipart/form-data "+e.getMessage()); + } + } else { + multipart.addFormData(param.getKey(),param.getValue().toString(),MediaType.APPLICATION_OCTET_STREAM_TYPE); + } + } + GenericEntity genericEntity = new GenericEntity(multipart) { }; + entity = Entity.entity(genericEntity, MediaType.MULTIPART_FORM_DATA_TYPE); + } else if (contentType.startsWith("application/x-www-form-urlencoded")) { + Form form = new Form(); + for (Entry param: formParams.entrySet()) { + form.param(param.getKey(), parameterToString(param.getValue())); + } + entity = Entity.entity(form, MediaType.APPLICATION_FORM_URLENCODED_TYPE); + } else { + // We let jersey handle the serialization + entity = Entity.entity(obj, contentType); + } + return entity; + } + + /** + * Deserialize response body to Java object according to the Content-Type. + * @param a Java type parameter + * @param response the response body to deserialize + * @param returnType a Java type to deserialize into + * @return a deserialized Java object + * @throws ApiException on failure to deserialize + */ + public T deserialize(Response response, GenericType returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + return (T) response.readEntity(byte[].class); + } else if (returnType.equals(File.class)) { + // Handle file downloading. + @SuppressWarnings("unchecked") + T file = (T) downloadFileFromResponse(response); + return file; + } + + String contentType = null; + List contentTypes = response.getHeaders().get("Content-Type"); + if (contentTypes != null && !contentTypes.isEmpty()) + contentType = String.valueOf(contentTypes.get(0)); + if (contentType == null) + throw new ApiException(500, "missing Content-Type in response"); + + return response.readEntity(returnType); + } + + /** + * Download file from the given response. + * @param response a response + * @return a file from the given response + * @throws ApiException If fail to read file content from response and write to disk + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + Files.copy(response.readEntity(InputStream.class), file.toPath()); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = (String) response.getHeaders().getFirst("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) + filename = matcher.group(1); + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param a Java type parameter + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "POST", "PUT", "HEAD" and "DELETE" + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return The response body in type of string + * @throws ApiException if the invocation failed + */ + public T invokeAPI(String path, String method, List queryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String accept, String contentType, String[] authNames, GenericType returnType) throws ApiException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + // Not using `.target(this.basePath).path(path)` below, + // to support (constant) query string in `path`, e.g. "/posts?draft=1" + WebTarget target = httpClient.target(this.basePath + path); + + if (queryParams != null) { + for (Pair queryParam : queryParams) { + if (queryParam.getValue() != null) { + target = target.queryParam(queryParam.getName(), queryParam.getValue()); + } + } + } + + Invocation.Builder invocationBuilder = target.request().accept(accept); + + for (Entry headerParamsEntry : headerParams.entrySet()) { + String value = headerParamsEntry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(headerParamsEntry.getKey(), value); + } + } + + for (Entry defaultHeaderEntry: defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(defaultHeaderEntry.getKey())) { + String value = defaultHeaderEntry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.header(defaultHeaderEntry.getKey(), value); + } + } + } + + for (Entry cookieParamsEntry : cookieParams.entrySet()) { + String value = cookieParamsEntry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(cookieParamsEntry.getKey(), value); + } + } + + for (Entry defaultCookieEntry: defaultHeaderMap.entrySet()) { + if (!cookieParams.containsKey(defaultCookieEntry.getKey())) { + String value = defaultCookieEntry.getValue(); + if (value != null) { + invocationBuilder = invocationBuilder.cookie(defaultCookieEntry.getKey(), value); + } + } + } + + Entity entity = serialize(body, formParams, contentType); + + try (Response response = invoke(invocationBuilder, method, entity)) { + statusCode = response.getStatusInfo().getStatusCode(); + responseHeaders = buildResponseHeaders(response); + + if (response.getStatus() == Status.NO_CONTENT.getStatusCode()) { + return null; + } else if (response.getStatusInfo().getFamily().equals(Status.Family.SUCCESSFUL)) { + if (returnType == null) + return null; + else + return deserialize(response, returnType); + } else { + String message = "error"; + String respBody = null; + if (response.hasEntity()) { + try { + respBody = String.valueOf(response.readEntity(String.class)); + message = respBody; + } catch (RuntimeException e) { + // e.printStackTrace(); + } + } + throw new ApiException( + response.getStatus(), + message, + buildResponseHeaders(response), + respBody); + } + } + } + + private Response invoke(Invocation.Builder invocationBuilder, String method, Entity entity) throws ApiException { + Response response = null; + + if ("GET".equals(method)) { + response = invocationBuilder.get(); + } else if ("POST".equals(method)) { + response = invocationBuilder.post(entity); + } else if ("PUT".equals(method)) { + response = invocationBuilder.put(entity); + } else if ("DELETE".equals(method)) { + response = invocationBuilder.method("DELETE", entity); + } else if ("PATCH".equals(method)) { + response = invocationBuilder.method("PATCH", entity); + } else if ("HEAD".equals(method)) { + response = invocationBuilder.head(); + } else if ("OPTIONS".equals(method)) { + response = invocationBuilder.options(); + } else if ("TRACE".equals(method)) { + response = invocationBuilder.trace(); + } else { + throw new ApiException(500, "unknown method type " + method); + } + + return response; + } + + /** + * Build the Client used to make HTTP requests. + */ + private Client buildHttpClient(boolean debugging) { + final ClientConfiguration clientConfig = new ClientConfiguration(ResteasyProviderFactory.getInstance()); + clientConfig.register(json); + if(debugging){ + clientConfig.register(Logger.class); + } + return ClientBuilder.newClient(clientConfig); + } + private Map> buildResponseHeaders(Response response) { + Map> responseHeaders = new HashMap>(); + for (Entry> entry: response.getHeaders().entrySet()) { + List values = entry.getValue(); + List headers = new ArrayList(); + for (Object o : values) { + headers.add(String.valueOf(o)); + } + responseHeaders.put(entry.getKey(), headers); + } + return responseHeaders; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + */ + private void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, Map cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) throw new RuntimeException("Authentication undefined: " + authName); + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiException.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..53d011b4ce5c --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,100 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + public ApiException() {} + + public ApiException(Throwable throwable) { + super(throwable); + } + + public ApiException(String message) { + super(message); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + @Override + public String toString() { + return "ApiException{" + + "code=" + code + + ", responseHeaders=" + responseHeaders + + ", responseBody='" + responseBody + '\'' + + '}'; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Configuration.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..73125b18c8f2 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,41 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Configuration { + public static final String VERSION = "0.1.0"; + + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JSON.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..85ff9ce7928a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,42 @@ +package org.openapitools.client; + +import com.fasterxml.jackson.annotation.*; +import com.fasterxml.jackson.databind.*; +import org.openapitools.jackson.nullable.JsonNullableModule; +import com.fasterxml.jackson.datatype.jsr310.*; + +import java.text.DateFormat; + +import javax.ws.rs.ext.ContextResolver; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JSON implements ContextResolver { + private ObjectMapper mapper; + + public JSON() { + mapper = new ObjectMapper(); + mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); + mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, false); + mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); + mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); + mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); + mapper.setDateFormat(new RFC3339DateFormat()); + JsonNullableModule jnm = new JsonNullableModule(); + mapper.registerModule(jnm); + mapper.registerModule(new JavaTimeModule()); + } + + /** + * Set the date format for JSON (de)serialization with Date properties. + * @param dateFormat the date format to set + */ + public void setDateFormat(DateFormat dateFormat) { + mapper.setDateFormat(dateFormat); + } + + @Override + public ObjectMapper getContext(Class type) { + return mapper; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JavaTimeFormatter.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JavaTimeFormatter.java new file mode 100644 index 000000000000..b51199a21b06 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/JavaTimeFormatter.java @@ -0,0 +1,64 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Pair.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..6518a0948d8a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,57 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + return true; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 000000000000..22bbe68c49f4 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..59edc528a446 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..c2f13e216662 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..d6c3fc8a9687 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

              + * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

              + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/AuthApi.java new file mode 100644 index 000000000000..b054205b206f --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/AuthApi.java @@ -0,0 +1,110 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AuthApi { + private ApiClient apiClient; + + public AuthApi() { + this(Configuration.getDefaultApiClient()); + } + + public AuthApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test HTTP basic authentication + * To test HTTP basic authentication + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testAuthHttpBasic() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/auth/http/basic".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testAuthHttpBearer() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/auth/http/bearer".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_bearer_auth" }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/BodyApi.java new file mode 100644 index 000000000000..fde7ad5e99cc --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/BodyApi.java @@ -0,0 +1,389 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + +import java.io.File; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class BodyApi { + private ApiClient apiClient; + + public BodyApi() { + this(Configuration.getDefaultApiClient()); + } + + public BodyApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test binary (gif) response body + * Test binary (gif) response body + * @return a {@code File} + * @throws ApiException if fails to make API call + */ + public File testBinaryGif() throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/binary/gif".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "image/gif" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + * @param body (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testBodyApplicationOctetstreamBinary(File body) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/body/application/octetstream/binary".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/octet-stream" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test array of binary in multipart mime + * Test array of binary in multipart mime + * @param files (required) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testBodyMultipartFormdataArrayOfBinary(List files) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'files' is set + if (files == null) { + throw new ApiException(400, "Missing the required parameter 'files' when calling testBodyMultipartFormdataArrayOfBinary"); + } + + // create path and map variables + String localVarPath = "/body/application/octetstream/array_of_binary".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + if (files != null) + localVarFormParams.put("files", files); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + * @param myFile (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testBodyMultipartFormdataSingleBinary(File myFile) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/body/application/octetstream/single_binary".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + if (myFile != null) + localVarFormParams.put("my-file", myFile); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return a {@code Pet} + * @throws ApiException if fails to make API call + */ + public Pet testEchoBodyAllOfPet(Pet pet) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/echo/body/allOf/Pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test free form object + * Test free form object + * @param body Free form object (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testEchoBodyFreeFormObjectResponseString(Object body) throws ApiException { + Object localVarPostBody = body; + + // create path and map variables + String localVarPath = "/echo/body/FreeFormObject/response_string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + * @param pet Pet object that needs to be added to the store (optional) + * @return a {@code Pet} + * @throws ApiException if fails to make API call + */ + public Pet testEchoBodyPet(Pet pet) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/echo/body/Pet".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "application/json" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test empty response body + * Test empty response body + * @param pet Pet object that needs to be added to the store (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testEchoBodyPetResponseString(Pet pet) throws ApiException { + Object localVarPostBody = pet; + + // create path and map variables + String localVarPath = "/echo/body/Pet/response_string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test empty json (request body) + * Test empty json (request body) + * @param tag Tag object (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testEchoBodyTagResponseString(Tag tag) throws ApiException { + Object localVarPostBody = tag; + + // create path and map variables + String localVarPath = "/echo/body/Tag/response_string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/FormApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/FormApi.java new file mode 100644 index 000000000000..f30385ee8c97 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/FormApi.java @@ -0,0 +1,137 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class FormApi { + private ApiClient apiClient; + + public FormApi() { + this(Configuration.getDefaultApiClient()); + } + + public FormApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test form parameter(s) + * Test form parameter(s) + * @param integerForm (optional) + * @param booleanForm (optional) + * @param stringForm (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testFormIntegerBooleanString(Integer integerForm, Boolean booleanForm, String stringForm) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/form/integer/boolean/string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + if (integerForm != null) + localVarFormParams.put("integer_form", integerForm); +if (booleanForm != null) + localVarFormParams.put("boolean_form", booleanForm); +if (stringForm != null) + localVarFormParams.put("string_form", stringForm); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test form parameter(s) for oneOf schema + * Test form parameter(s) for oneOf schema + * @param form1 (optional) + * @param form2 (optional) + * @param form3 (optional) + * @param form4 (optional) + * @param id (optional) + * @param name (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testFormOneof(String form1, Integer form2, String form3, Boolean form4, Long id, String name) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/form/oneof".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + if (form1 != null) + localVarFormParams.put("form1", form1); +if (form2 != null) + localVarFormParams.put("form2", form2); +if (form3 != null) + localVarFormParams.put("form3", form3); +if (form4 != null) + localVarFormParams.put("form4", form4); +if (id != null) + localVarFormParams.put("id", id); +if (name != null) + localVarFormParams.put("name", name); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/HeaderApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/HeaderApi.java new file mode 100644 index 000000000000..1541ee5a4027 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/HeaderApi.java @@ -0,0 +1,89 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + +import org.openapitools.client.model.StringEnumRef; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HeaderApi { + private ApiClient apiClient; + + public HeaderApi() { + this(Configuration.getDefaultApiClient()); + } + + public HeaderApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test header parameter(s) + * Test header parameter(s) + * @param integerHeader (optional) + * @param booleanHeader (optional) + * @param stringHeader (optional) + * @param enumNonrefStringHeader (optional) + * @param enumRefStringHeader (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testHeaderIntegerBooleanStringEnums(Integer integerHeader, Boolean booleanHeader, String stringHeader, String enumNonrefStringHeader, StringEnumRef enumRefStringHeader) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/header/integer/boolean/string/enums".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + if (integerHeader != null) + localVarHeaderParams.put("integer_header", apiClient.parameterToString(integerHeader)); +if (booleanHeader != null) + localVarHeaderParams.put("boolean_header", apiClient.parameterToString(booleanHeader)); +if (stringHeader != null) + localVarHeaderParams.put("string_header", apiClient.parameterToString(stringHeader)); +if (enumNonrefStringHeader != null) + localVarHeaderParams.put("enum_nonref_string_header", apiClient.parameterToString(enumNonrefStringHeader)); +if (enumRefStringHeader != null) + localVarHeaderParams.put("enum_ref_string_header", apiClient.parameterToString(enumRefStringHeader)); + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/PathApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/PathApi.java new file mode 100644 index 000000000000..5ab77cba67ec --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/PathApi.java @@ -0,0 +1,102 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + +import org.openapitools.client.model.StringEnumRef; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class PathApi { + private ApiClient apiClient; + + public PathApi() { + this(Configuration.getDefaultApiClient()); + } + + public PathApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test path parameter(s) + * Test path parameter(s) + * @param pathString (required) + * @param pathInteger (required) + * @param enumNonrefStringPath (required) + * @param enumRefStringPath (required) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(String pathString, Integer pathInteger, String enumNonrefStringPath, StringEnumRef enumRefStringPath) throws ApiException { + Object localVarPostBody = null; + + // verify the required parameter 'pathString' is set + if (pathString == null) { + throw new ApiException(400, "Missing the required parameter 'pathString' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'pathInteger' is set + if (pathInteger == null) { + throw new ApiException(400, "Missing the required parameter 'pathInteger' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'enumNonrefStringPath' is set + if (enumNonrefStringPath == null) { + throw new ApiException(400, "Missing the required parameter 'enumNonrefStringPath' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'enumRefStringPath' is set + if (enumRefStringPath == null) { + throw new ApiException(400, "Missing the required parameter 'enumRefStringPath' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // create path and map variables + String localVarPath = "/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}".replaceAll("\\{format\\}","json") + .replaceAll("\\{" + "path_string" + "\\}", apiClient.escapeString(pathString.toString())) + .replaceAll("\\{" + "path_integer" + "\\}", apiClient.escapeString(pathInteger.toString())) + .replaceAll("\\{" + "enum_nonref_string_path" + "\\}", apiClient.escapeString(enumNonrefStringPath.toString())) + .replaceAll("\\{" + "enum_ref_string_path" + "\\}", apiClient.escapeString(enumRefStringPath.toString())); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/QueryApi.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/QueryApi.java new file mode 100644 index 000000000000..56dca02c018b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/api/QueryApi.java @@ -0,0 +1,365 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiClient; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; + +import javax.ws.rs.core.GenericType; + +import org.openapitools.client.model.DataQuery; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.client.model.TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter; +import org.openapitools.client.model.TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class QueryApi { + private ApiClient apiClient; + + public QueryApi() { + this(Configuration.getDefaultApiClient()); + } + + public QueryApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test query parameter(s) + * Test query parameter(s) + * @param enumNonrefStringQuery (optional) + * @param enumRefStringQuery (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testEnumRefString(String enumNonrefStringQuery, StringEnumRef enumRefStringQuery) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/enum_ref_string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_nonref_string_query", enumNonrefStringQuery)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "enum_ref_string_query", enumRefStringQuery)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param datetimeQuery (optional) + * @param dateQuery (optional) + * @param stringQuery (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryDatetimeDateString(OffsetDateTime datetimeQuery, LocalDate dateQuery, String stringQuery) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/datetime/date/string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "datetime_query", datetimeQuery)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "date_query", dateQuery)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "string_query", stringQuery)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param integerQuery (optional) + * @param booleanQuery (optional) + * @param stringQuery (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryIntegerBooleanString(Integer integerQuery, Boolean booleanQuery, String stringQuery) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/integer/boolean/string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "integer_query", integerQuery)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "boolean_query", booleanQuery)); + localVarQueryParams.addAll(apiClient.parameterToPairs("", "string_query", stringQuery)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param queryObject (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryStyleDeepObjectExplodeTrueObject(Pet queryObject) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/style_deepObject/explode_true/object".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "query_object", queryObject)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param queryObject (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryStyleDeepObjectExplodeTrueObjectAllOf(TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/style_deepObject/explode_true/object/allOf".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "query_object", queryObject)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param queryObject (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryStyleFormExplodeTrueArrayString(TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/style_form/explode_true/array_string".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "query_object", queryObject)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param queryObject (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryStyleFormExplodeTrueObject(Pet queryObject) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/style_form/explode_true/object".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "query_object", queryObject)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + * @param queryObject (optional) + * @return a {@code String} + * @throws ApiException if fails to make API call + */ + public String testQueryStyleFormExplodeTrueObjectAllOf(DataQuery queryObject) throws ApiException { + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/query/style_form/explode_true/object/allOf".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + localVarQueryParams.addAll(apiClient.parameterToPairs("", "query_object", queryObject)); + + + + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + GenericType localVarReturnType = new GenericType() {}; + return apiClient.invokeAPI(localVarPath, "GET", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..3e77c69480d4 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,77 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..4df1c672327a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,30 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams); +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..09f92fecfbc3 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,53 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.Base64; +import java.nio.charset.StandardCharsets; + +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.put("Authorization", "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..0f1f505b7de3 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,72 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; + +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Bird.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Bird.java new file mode 100644 index 000000000000..1e3195e9bdda --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Bird.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Bird + */ +@JsonPropertyOrder({ + Bird.JSON_PROPERTY_SIZE, + Bird.JSON_PROPERTY_COLOR +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Bird { + public static final String JSON_PROPERTY_SIZE = "size"; + private String size; + + public static final String JSON_PROPERTY_COLOR = "color"; + private String color; + + public Bird() { + } + + public Bird size(String size) { + + this.size = size; + return this; + } + + /** + * Get size + * @return size + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSize() { + return size; + } + + + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSize(String size) { + this.size = size; + } + + + public Bird color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getColor() { + return color; + } + + + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setColor(String color) { + this.color = color; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Bird bird = (Bird) o; + return Objects.equals(this.size, bird.size) && + Objects.equals(this.color, bird.color); + } + + @Override + public int hashCode() { + return Objects.hash(size, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Bird {\n"); + sb.append(" size: ").append(toIndentedString(size)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Category.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 000000000000..29d956d6cb75 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Category + */ +@JsonPropertyOrder({ + Category.JSON_PROPERTY_ID, + Category.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Category { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public Category() { + } + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DataQuery.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DataQuery.java new file mode 100644 index 000000000000..5f1c039d516a --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DataQuery.java @@ -0,0 +1,187 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Query; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * DataQuery + */ +@JsonPropertyOrder({ + DataQuery.JSON_PROPERTY_SUFFIX, + DataQuery.JSON_PROPERTY_TEXT, + DataQuery.JSON_PROPERTY_DATE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataQuery extends Query { + public static final String JSON_PROPERTY_SUFFIX = "suffix"; + private String suffix; + + public static final String JSON_PROPERTY_TEXT = "text"; + private String text; + + public static final String JSON_PROPERTY_DATE = "date"; + private OffsetDateTime date; + + public DataQuery() { + + } + + public DataQuery suffix(String suffix) { + + this.suffix = suffix; + return this; + } + + /** + * test suffix + * @return suffix + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SUFFIX) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSuffix() { + return suffix; + } + + + @JsonProperty(JSON_PROPERTY_SUFFIX) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSuffix(String suffix) { + this.suffix = suffix; + } + + + public DataQuery text(String text) { + + this.text = text; + return this; + } + + /** + * Some text containing white spaces + * @return text + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TEXT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getText() { + return text; + } + + + @JsonProperty(JSON_PROPERTY_TEXT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setText(String text) { + this.text = text; + } + + + public DataQuery date(OffsetDateTime date) { + + this.date = date; + return this; + } + + /** + * A date + * @return date + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public OffsetDateTime getDate() { + return date; + } + + + @JsonProperty(JSON_PROPERTY_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDate(OffsetDateTime date) { + this.date = date; + } + + @Override + public DataQuery id(Long id) { + this.setId(id); + return this; + } + + @Override + public DataQuery outcomes(List outcomes) { + this.setOutcomes(outcomes); + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataQuery dataQuery = (DataQuery) o; + return Objects.equals(this.suffix, dataQuery.suffix) && + Objects.equals(this.text, dataQuery.text) && + Objects.equals(this.date, dataQuery.date) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(suffix, text, date, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataQuery {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" suffix: ").append(toIndentedString(suffix)).append("\n"); + sb.append(" text: ").append(toIndentedString(text)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DefaultValue.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DefaultValue.java new file mode 100644 index 000000000000..1365a5fcb045 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/DefaultValue.java @@ -0,0 +1,471 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * to test the default value of properties + */ +@JsonPropertyOrder({ + DefaultValue.JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_INTEGER_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_NULLABLE, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE, + DefaultValue.JSON_PROPERTY_STRING_NULLABLE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DefaultValue { + public static final String JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT = "array_string_enum_ref_default"; + private List arrayStringEnumRefDefault = new ArrayList<>(Arrays.asList(StringEnumRef.SUCCESS, StringEnumRef.FAILURE)); + + /** + * Gets or Sets arrayStringEnumDefault + */ + public enum ArrayStringEnumDefaultEnum { + SUCCESS("success"), + + FAILURE("failure"), + + UNCLASSIFIED("unclassified"); + + private String value; + + ArrayStringEnumDefaultEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayStringEnumDefaultEnum fromValue(String value) { + for (ArrayStringEnumDefaultEnum b : ArrayStringEnumDefaultEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT = "array_string_enum_default"; + private List arrayStringEnumDefault = new ArrayList<>(Arrays.asList(ArrayStringEnumDefaultEnum.SUCCESS, ArrayStringEnumDefaultEnum.FAILURE)); + + public static final String JSON_PROPERTY_ARRAY_STRING_DEFAULT = "array_string_default"; + private List arrayStringDefault = new ArrayList<>(Arrays.asList("failure", "skipped")); + + public static final String JSON_PROPERTY_ARRAY_INTEGER_DEFAULT = "array_integer_default"; + private List arrayIntegerDefault = new ArrayList<>(Arrays.asList(1, 3)); + + public static final String JSON_PROPERTY_ARRAY_STRING = "array_string"; + private List arrayString; + + public static final String JSON_PROPERTY_ARRAY_STRING_NULLABLE = "array_string_nullable"; + private JsonNullable> arrayStringNullable = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE = "array_string_extension_nullable"; + private JsonNullable> arrayStringExtensionNullable = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_STRING_NULLABLE = "string_nullable"; + private JsonNullable stringNullable = JsonNullable.undefined(); + + public DefaultValue() { + } + + public DefaultValue arrayStringEnumRefDefault(List arrayStringEnumRefDefault) { + + this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; + return this; + } + + public DefaultValue addArrayStringEnumRefDefaultItem(StringEnumRef arrayStringEnumRefDefaultItem) { + if (this.arrayStringEnumRefDefault == null) { + this.arrayStringEnumRefDefault = new ArrayList<>(Arrays.asList(StringEnumRef.SUCCESS, StringEnumRef.FAILURE)); + } + this.arrayStringEnumRefDefault.add(arrayStringEnumRefDefaultItem); + return this; + } + + /** + * Get arrayStringEnumRefDefault + * @return arrayStringEnumRefDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringEnumRefDefault() { + return arrayStringEnumRefDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringEnumRefDefault(List arrayStringEnumRefDefault) { + this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; + } + + + public DefaultValue arrayStringEnumDefault(List arrayStringEnumDefault) { + + this.arrayStringEnumDefault = arrayStringEnumDefault; + return this; + } + + public DefaultValue addArrayStringEnumDefaultItem(ArrayStringEnumDefaultEnum arrayStringEnumDefaultItem) { + if (this.arrayStringEnumDefault == null) { + this.arrayStringEnumDefault = new ArrayList<>(Arrays.asList(ArrayStringEnumDefaultEnum.SUCCESS, ArrayStringEnumDefaultEnum.FAILURE)); + } + this.arrayStringEnumDefault.add(arrayStringEnumDefaultItem); + return this; + } + + /** + * Get arrayStringEnumDefault + * @return arrayStringEnumDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringEnumDefault() { + return arrayStringEnumDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringEnumDefault(List arrayStringEnumDefault) { + this.arrayStringEnumDefault = arrayStringEnumDefault; + } + + + public DefaultValue arrayStringDefault(List arrayStringDefault) { + + this.arrayStringDefault = arrayStringDefault; + return this; + } + + public DefaultValue addArrayStringDefaultItem(String arrayStringDefaultItem) { + if (this.arrayStringDefault == null) { + this.arrayStringDefault = new ArrayList<>(Arrays.asList("failure", "skipped")); + } + this.arrayStringDefault.add(arrayStringDefaultItem); + return this; + } + + /** + * Get arrayStringDefault + * @return arrayStringDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringDefault() { + return arrayStringDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringDefault(List arrayStringDefault) { + this.arrayStringDefault = arrayStringDefault; + } + + + public DefaultValue arrayIntegerDefault(List arrayIntegerDefault) { + + this.arrayIntegerDefault = arrayIntegerDefault; + return this; + } + + public DefaultValue addArrayIntegerDefaultItem(Integer arrayIntegerDefaultItem) { + if (this.arrayIntegerDefault == null) { + this.arrayIntegerDefault = new ArrayList<>(Arrays.asList(1, 3)); + } + this.arrayIntegerDefault.add(arrayIntegerDefaultItem); + return this; + } + + /** + * Get arrayIntegerDefault + * @return arrayIntegerDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_INTEGER_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayIntegerDefault() { + return arrayIntegerDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_INTEGER_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayIntegerDefault(List arrayIntegerDefault) { + this.arrayIntegerDefault = arrayIntegerDefault; + } + + + public DefaultValue arrayString(List arrayString) { + + this.arrayString = arrayString; + return this; + } + + public DefaultValue addArrayStringItem(String arrayStringItem) { + if (this.arrayString == null) { + this.arrayString = new ArrayList<>(); + } + this.arrayString.add(arrayStringItem); + return this; + } + + /** + * Get arrayString + * @return arrayString + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayString() { + return arrayString; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayString(List arrayString) { + this.arrayString = arrayString; + } + + + public DefaultValue arrayStringNullable(List arrayStringNullable) { + this.arrayStringNullable = JsonNullable.>of(arrayStringNullable); + + return this; + } + + public DefaultValue addArrayStringNullableItem(String arrayStringNullableItem) { + if (this.arrayStringNullable == null || !this.arrayStringNullable.isPresent()) { + this.arrayStringNullable = JsonNullable.>of(new ArrayList<>()); + } + try { + this.arrayStringNullable.get().add(arrayStringNullableItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get arrayStringNullable + * @return arrayStringNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public List getArrayStringNullable() { + return arrayStringNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable> getArrayStringNullable_JsonNullable() { + return arrayStringNullable; + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_NULLABLE) + public void setArrayStringNullable_JsonNullable(JsonNullable> arrayStringNullable) { + this.arrayStringNullable = arrayStringNullable; + } + + public void setArrayStringNullable(List arrayStringNullable) { + this.arrayStringNullable = JsonNullable.>of(arrayStringNullable); + } + + + public DefaultValue arrayStringExtensionNullable(List arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = JsonNullable.>of(arrayStringExtensionNullable); + + return this; + } + + public DefaultValue addArrayStringExtensionNullableItem(String arrayStringExtensionNullableItem) { + if (this.arrayStringExtensionNullable == null || !this.arrayStringExtensionNullable.isPresent()) { + this.arrayStringExtensionNullable = JsonNullable.>of(new ArrayList<>()); + } + try { + this.arrayStringExtensionNullable.get().add(arrayStringExtensionNullableItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get arrayStringExtensionNullable + * @return arrayStringExtensionNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public List getArrayStringExtensionNullable() { + return arrayStringExtensionNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable> getArrayStringExtensionNullable_JsonNullable() { + return arrayStringExtensionNullable; + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE) + public void setArrayStringExtensionNullable_JsonNullable(JsonNullable> arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = arrayStringExtensionNullable; + } + + public void setArrayStringExtensionNullable(List arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = JsonNullable.>of(arrayStringExtensionNullable); + } + + + public DefaultValue stringNullable(String stringNullable) { + this.stringNullable = JsonNullable.of(stringNullable); + + return this; + } + + /** + * Get stringNullable + * @return stringNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public String getStringNullable() { + return stringNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_STRING_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable getStringNullable_JsonNullable() { + return stringNullable; + } + + @JsonProperty(JSON_PROPERTY_STRING_NULLABLE) + public void setStringNullable_JsonNullable(JsonNullable stringNullable) { + this.stringNullable = stringNullable; + } + + public void setStringNullable(String stringNullable) { + this.stringNullable = JsonNullable.of(stringNullable); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DefaultValue defaultValue = (DefaultValue) o; + return Objects.equals(this.arrayStringEnumRefDefault, defaultValue.arrayStringEnumRefDefault) && + Objects.equals(this.arrayStringEnumDefault, defaultValue.arrayStringEnumDefault) && + Objects.equals(this.arrayStringDefault, defaultValue.arrayStringDefault) && + Objects.equals(this.arrayIntegerDefault, defaultValue.arrayIntegerDefault) && + Objects.equals(this.arrayString, defaultValue.arrayString) && + equalsNullable(this.arrayStringNullable, defaultValue.arrayStringNullable) && + equalsNullable(this.arrayStringExtensionNullable, defaultValue.arrayStringExtensionNullable) && + equalsNullable(this.stringNullable, defaultValue.stringNullable); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(arrayStringEnumRefDefault, arrayStringEnumDefault, arrayStringDefault, arrayIntegerDefault, arrayString, hashCodeNullable(arrayStringNullable), hashCodeNullable(arrayStringExtensionNullable), hashCodeNullable(stringNullable)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DefaultValue {\n"); + sb.append(" arrayStringEnumRefDefault: ").append(toIndentedString(arrayStringEnumRefDefault)).append("\n"); + sb.append(" arrayStringEnumDefault: ").append(toIndentedString(arrayStringEnumDefault)).append("\n"); + sb.append(" arrayStringDefault: ").append(toIndentedString(arrayStringDefault)).append("\n"); + sb.append(" arrayIntegerDefault: ").append(toIndentedString(arrayIntegerDefault)).append("\n"); + sb.append(" arrayString: ").append(toIndentedString(arrayString)).append("\n"); + sb.append(" arrayStringNullable: ").append(toIndentedString(arrayStringNullable)).append("\n"); + sb.append(" arrayStringExtensionNullable: ").append(toIndentedString(arrayStringExtensionNullable)).append("\n"); + sb.append(" stringNullable: ").append(toIndentedString(stringNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java new file mode 100644 index 000000000000..96de851944c1 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java @@ -0,0 +1,170 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * NumberPropertiesOnly + */ +@JsonPropertyOrder({ + NumberPropertiesOnly.JSON_PROPERTY_NUMBER, + NumberPropertiesOnly.JSON_PROPERTY_FLOAT, + NumberPropertiesOnly.JSON_PROPERTY_DOUBLE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class NumberPropertiesOnly { + public static final String JSON_PROPERTY_NUMBER = "number"; + private BigDecimal number; + + public static final String JSON_PROPERTY_FLOAT = "float"; + private Float _float; + + public static final String JSON_PROPERTY_DOUBLE = "double"; + private Double _double; + + public NumberPropertiesOnly() { + } + + public NumberPropertiesOnly number(BigDecimal number) { + + this.number = number; + return this; + } + + /** + * Get number + * @return number + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NUMBER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public BigDecimal getNumber() { + return number; + } + + + @JsonProperty(JSON_PROPERTY_NUMBER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNumber(BigDecimal number) { + this.number = number; + } + + + public NumberPropertiesOnly _float(Float _float) { + + this._float = _float; + return this; + } + + /** + * Get _float + * @return _float + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FLOAT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Float getFloat() { + return _float; + } + + + @JsonProperty(JSON_PROPERTY_FLOAT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFloat(Float _float) { + this._float = _float; + } + + + public NumberPropertiesOnly _double(Double _double) { + + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 0.8 + * maximum: 50.2 + * @return _double + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DOUBLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Double getDouble() { + return _double; + } + + + @JsonProperty(JSON_PROPERTY_DOUBLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDouble(Double _double) { + this._double = _double; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberPropertiesOnly numberPropertiesOnly = (NumberPropertiesOnly) o; + return Objects.equals(this.number, numberPropertiesOnly.number) && + Objects.equals(this._float, numberPropertiesOnly._float) && + Objects.equals(this._double, numberPropertiesOnly._double); + } + + @Override + public int hashCode() { + return Objects.hash(number, _float, _double); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberPropertiesOnly {\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 000000000000..4daf4511bb04 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,321 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Pet + */ +@JsonPropertyOrder({ + Pet.JSON_PROPERTY_ID, + Pet.JSON_PROPERTY_NAME, + Pet.JSON_PROPERTY_CATEGORY, + Pet.JSON_PROPERTY_PHOTO_URLS, + Pet.JSON_PROPERTY_TAGS, + Pet.JSON_PROPERTY_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pet { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + private Category category; + + public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; + private List photoUrls = new ArrayList<>(); + + public static final String JSON_PROPERTY_TAGS = "tags"; + private List tags; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + public Pet() { + } + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Category getCategory() { + return category; + } + + + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCategory(Category category) { + this.category = category; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @javax.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getPhotoUrls() { + return photoUrls; + } + + + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getTags() { + return tags; + } + + + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, category, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Query.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Query.java new file mode 100644 index 000000000000..5e110710d726 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Query.java @@ -0,0 +1,183 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Query + */ +@JsonPropertyOrder({ + Query.JSON_PROPERTY_ID, + Query.JSON_PROPERTY_OUTCOMES +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Query { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + /** + * Gets or Sets outcomes + */ + public enum OutcomesEnum { + SUCCESS("SUCCESS"), + + FAILURE("FAILURE"), + + SKIPPED("SKIPPED"); + + private String value; + + OutcomesEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OutcomesEnum fromValue(String value) { + for (OutcomesEnum b : OutcomesEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_OUTCOMES = "outcomes"; + private List outcomes = new ArrayList<>(Arrays.asList(OutcomesEnum.SUCCESS, OutcomesEnum.FAILURE)); + + public Query() { + } + + public Query id(Long id) { + + this.id = id; + return this; + } + + /** + * Query + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Query outcomes(List outcomes) { + + this.outcomes = outcomes; + return this; + } + + public Query addOutcomesItem(OutcomesEnum outcomesItem) { + if (this.outcomes == null) { + this.outcomes = new ArrayList<>(Arrays.asList(OutcomesEnum.SUCCESS, OutcomesEnum.FAILURE)); + } + this.outcomes.add(outcomesItem); + return this; + } + + /** + * Get outcomes + * @return outcomes + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_OUTCOMES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getOutcomes() { + return outcomes; + } + + + @JsonProperty(JSON_PROPERTY_OUTCOMES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOutcomes(List outcomes) { + this.outcomes = outcomes; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Query query = (Query) o; + return Objects.equals(this.id, query.id) && + Objects.equals(this.outcomes, query.outcomes); + } + + @Override + public int hashCode() { + return Objects.hash(id, outcomes); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Query {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" outcomes: ").append(toIndentedString(outcomes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/StringEnumRef.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/StringEnumRef.java new file mode 100644 index 000000000000..6e706b20d44c --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/StringEnumRef.java @@ -0,0 +1,61 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets StringEnumRef + */ +public enum StringEnumRef { + + SUCCESS("success"), + + FAILURE("failure"), + + UNCLASSIFIED("unclassified"); + + private String value; + + StringEnumRef(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StringEnumRef fromValue(String value) { + for (StringEnumRef b : StringEnumRef.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 000000000000..794d3457040b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Tag + */ +@JsonPropertyOrder({ + Tag.JSON_PROPERTY_ID, + Tag.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Tag { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public Tag() { + } + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java new file mode 100644 index 000000000000..95ee4725f1a3 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java @@ -0,0 +1,200 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ +@JsonPropertyOrder({ + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_SIZE, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_COLOR, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_ID, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_NAME +}) +@JsonTypeName("test_query_style_deepObject_explode_true_object_allOf_query_object_parameter") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter { + public static final String JSON_PROPERTY_SIZE = "size"; + private String size; + + public static final String JSON_PROPERTY_COLOR = "color"; + private String color; + + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() { + } + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter size(String size) { + + this.size = size; + return this; + } + + /** + * Get size + * @return size + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSize() { + return size; + } + + + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSize(String size) { + this.size = size; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getColor() { + return color; + } + + + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setColor(String color) { + this.color = color; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter = (TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter) o; + return Objects.equals(this.size, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.size) && + Objects.equals(this.color, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.color) && + Objects.equals(this.id, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.id) && + Objects.equals(this.name, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.name); + } + + @Override + public int hashCode() { + return Objects.hash(size, color, id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter {\n"); + sb.append(" size: ").append(toIndentedString(size)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java new file mode 100644 index 000000000000..a28cc79320db --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java @@ -0,0 +1,115 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ +@JsonPropertyOrder({ + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.JSON_PROPERTY_VALUES +}) +@JsonTypeName("test_query_style_form_explode_true_array_string_query_object_parameter") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter { + public static final String JSON_PROPERTY_VALUES = "values"; + private List values; + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() { + } + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter values(List values) { + + this.values = values; + return this; + } + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter addValuesItem(String valuesItem) { + if (this.values == null) { + this.values = new ArrayList<>(); + } + this.values.add(valuesItem); + return this; + } + + /** + * Get values + * @return values + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_VALUES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getValues() { + return values; + } + + + @JsonProperty(JSON_PROPERTY_VALUES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setValues(List values) { + this.values = values; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter testQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = (TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter) o; + return Objects.equals(this.values, testQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.values); + } + + @Override + public int hashCode() { + return Objects.hash(values); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter {\n"); + sb.append(" values: ").append(toIndentedString(values)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/CustomTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/CustomTest.java new file mode 100644 index 000000000000..1ffbe4ace092 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/CustomTest.java @@ -0,0 +1,73 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.io.File; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * API tests + */ +public class CustomTest { + + private final BodyApi api = new BodyApi(); + + /** + * Test single binary in multipart mime + * + * @see + * #17367 + */ + @Test + public void testBodyMultipartFormdataSingleBinaryTest() throws ApiException, IOException { + File myFile = new File("test.txt"); + if (!myFile.exists()){ + assertTrue(myFile.createNewFile()); + } + FileWriter fw = new FileWriter(myFile); + fw.write("testing only"); + fw.close(); + myFile.deleteOnExit(); + + String response = + api.testBodyMultipartFormdataSingleBinary(myFile); + + EchoServerResponseParser parser = + new EchoServerResponseParser(response); + + String contentDisposition = parser.headers.get("Content-Disposition"); + + assertThat(contentDisposition, containsString( + "form-data; name=\"my-file\"; filename=\"test.txt\"" + )); + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/EchoServerResponseParser.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/EchoServerResponseParser.java new file mode 100644 index 000000000000..35a6999aab43 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/EchoServerResponseParser.java @@ -0,0 +1,51 @@ +/* + * Copyright 2018 OpenAPI-Generator Contributors (https://openapi-generator.tech) + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * https://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package org.openapitools.client.api; + +public class EchoServerResponseParser { + public String method; // e.g. GET + public String path; // e.g. /query/style_form/explode_true/object?id=12345 + public String protocol; // e.g. HTTP/1.1 + public java.util.HashMap headers = new java.util.HashMap<>(); + + public EchoServerResponseParser(String response) { + if (response == null) { + throw new RuntimeException("Echo server response cannot be null"); + } + + String[] lines = response.split("\n"); + boolean firstLine = true; + + for (String line : lines) { + if (firstLine) { + String[] items = line.split(" "); + this.method = items[0]; + this.path = items[1]; + this.protocol = items[2]; + firstLine = false; + continue; + } + + // store the header key-value pair in headers + String[] keyValue = line.split(": "); + if (keyValue.length == 2) { // skip blank line, non key-value pair + this.headers.put(keyValue[0], keyValue[1]); + } + } + + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/AuthApiTest.java new file mode 100644 index 000000000000..17e790b76173 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -0,0 +1,65 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for AuthApi + */ +public class AuthApiTest { + + private final AuthApi api = new AuthApi(); + + /** + * To test HTTP basic authentication + * + * To test HTTP basic authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBasicTest() throws ApiException { + // + //String response = api.testAuthHttpBasic(); + + // TODO: test validations + } + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBearerTest() throws ApiException { + // + //String response = api.testAuthHttpBearer(); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/BodyApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/BodyApiTest.java new file mode 100644 index 000000000000..3d2102e4643b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/BodyApiTest.java @@ -0,0 +1,210 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import java.io.File; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.io.FileWriter; +import java.io.IOException; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.MatcherAssert.assertThat; +import static org.junit.Assert.assertTrue; + +/** + * API tests for BodyApi + */ +public class BodyApiTest { + + private final BodyApi api = new BodyApi(); + + /** + * Test binary (gif) response body + * + * Test binary (gif) response body + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBinaryGifTest() throws ApiException { + // + //File response = api.testBinaryGif(); + + // TODO: test validations + } + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyApplicationOctetstreamBinaryTest() throws ApiException { + // + //File body = null; + // + //String response = api.testBodyApplicationOctetstreamBinary(body); + + // TODO: test validations + } + /** + * Test array of binary in multipart mime + * + * Test array of binary in multipart mime + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyMultipartFormdataArrayOfBinaryTest() throws ApiException { + // + //List files = null; + // + //String response = api.testBodyMultipartFormdataArrayOfBinary(files); + + // TODO: test validations + } + + /** + * Test single binary in multipart mime + * + * @see + * #17367 + */ + @Test + public void testBodyMultipartFormdataSingleBinaryTest() + throws ApiException, IOException { + File myFile = new File("test.txt"); + if (!myFile.exists()){ + assertTrue(myFile.createNewFile()); + } + FileWriter fw = new FileWriter(myFile); + fw.write("testing only"); + fw.close(); + myFile.deleteOnExit(); + + String response = + api.testBodyMultipartFormdataSingleBinary(myFile); + + EchoServerResponseParser parser = + new EchoServerResponseParser(response); + + String contentDisposition = parser.headers.get("Content-Disposition"); + + assertThat(contentDisposition, containsString( + "form-data; name=\"my-file\"; filename=\"test.txt\"" + )); + } + + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyAllOfPetTest() throws ApiException { + // + //Pet pet = null; + // + //Pet response = api.testEchoBodyAllOfPet(pet); + + // TODO: test validations + } + /** + * Test free form object + * + * Test free form object + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyFreeFormObjectResponseStringTest() throws ApiException { + // + //Object body = null; + // + //String response = api.testEchoBodyFreeFormObjectResponseString(body); + + // TODO: test validations + } + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyPetTest() throws ApiException { + // + //Pet pet = null; + // + //Pet response = api.testEchoBodyPet(pet); + + // TODO: test validations + } + /** + * Test empty response body + * + * Test empty response body + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyPetResponseStringTest() throws ApiException { + // + //Pet pet = null; + // + //String response = api.testEchoBodyPetResponseString(pet); + + // TODO: test validations + } + /** + * Test empty json (request body) + * + * Test empty json (request body) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyTagResponseStringTest() throws ApiException { + // + //Tag tag = null; + // + //String response = api.testEchoBodyTagResponseString(tag); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/FormApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/FormApiTest.java new file mode 100644 index 000000000000..df8fae9511d6 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/FormApiTest.java @@ -0,0 +1,83 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FormApi + */ +public class FormApiTest { + + private final FormApi api = new FormApi(); + + /** + * Test form parameter(s) + * + * Test form parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testFormIntegerBooleanStringTest() throws ApiException { + // + //Integer integerForm = null; + // + //Boolean booleanForm = null; + // + //String stringForm = null; + // + //String response = api.testFormIntegerBooleanString(integerForm, booleanForm, stringForm); + + // TODO: test validations + } + /** + * Test form parameter(s) for oneOf schema + * + * Test form parameter(s) for oneOf schema + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testFormOneofTest() throws ApiException { + // + //String form1 = null; + // + //Integer form2 = null; + // + //String form3 = null; + // + //Boolean form4 = null; + // + //Long id = null; + // + //String name = null; + // + //String response = api.testFormOneof(form1, form2, form3, form4, id, name); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/HeaderApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/HeaderApiTest.java new file mode 100644 index 000000000000..9132aeb9b781 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/HeaderApiTest.java @@ -0,0 +1,61 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.StringEnumRef; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for HeaderApi + */ +public class HeaderApiTest { + + private final HeaderApi api = new HeaderApi(); + + /** + * Test header parameter(s) + * + * Test header parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testHeaderIntegerBooleanStringEnumsTest() throws ApiException { + // + //Integer integerHeader = null; + // + //Boolean booleanHeader = null; + // + //String stringHeader = null; + // + //String enumNonrefStringHeader = null; + // + //StringEnumRef enumRefStringHeader = null; + // + //String response = api.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/PathApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/PathApiTest.java new file mode 100644 index 000000000000..a48fb9c3bf3f --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/PathApiTest.java @@ -0,0 +1,59 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.StringEnumRef; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PathApi + */ +public class PathApiTest { + + private final PathApi api = new PathApi(); + + /** + * Test path parameter(s) + * + * Test path parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathTest() throws ApiException { + // + //String pathString = null; + // + //Integer pathInteger = null; + // + //String enumNonrefStringPath = null; + // + //StringEnumRef enumRefStringPath = null; + // + //String response = api.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/QueryApiTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/QueryApiTest.java new file mode 100644 index 000000000000..a2bd6f65721b --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/api/QueryApiTest.java @@ -0,0 +1,188 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.DataQuery; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.client.model.TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter; +import org.openapitools.client.model.TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter; +import org.junit.Test; +import org.junit.Ignore; +import org.junit.Assert; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for QueryApi + */ +public class QueryApiTest { + + private final QueryApi api = new QueryApi(); + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumRefStringTest() throws ApiException { + // + //String enumNonrefStringQuery = null; + // + //StringEnumRef enumRefStringQuery = null; + // + //String response = api.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryDatetimeDateStringTest() throws ApiException { + // + //OffsetDateTime datetimeQuery = null; + // + //LocalDate dateQuery = null; + // + //String stringQuery = null; + // + //String response = api.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryIntegerBooleanStringTest() throws ApiException { + // + //Integer integerQuery = null; + // + //Boolean booleanQuery = null; + // + //String stringQuery = null; + // + //String response = api.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleDeepObjectExplodeTrueObjectTest() throws ApiException { + // + //Pet queryObject = null; + // + //String response = api.testQueryStyleDeepObjectExplodeTrueObject(queryObject); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleDeepObjectExplodeTrueObjectAllOfTest() throws ApiException { + // + //TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject = null; + // + //String response = api.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueArrayStringTest() throws ApiException { + // + //TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject = null; + // + //String response = api.testQueryStyleFormExplodeTrueArrayString(queryObject); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueObjectTest() throws ApiException { + // + //Pet queryObject = null; + // + //String response = api.testQueryStyleFormExplodeTrueObject(queryObject); + + // TODO: test validations + } + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueObjectAllOfTest() throws ApiException { + // + //DataQuery queryObject = null; + // + //String response = api.testQueryStyleFormExplodeTrueObjectAllOf(queryObject); + + // TODO: test validations + } +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/BirdTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/BirdTest.java new file mode 100644 index 000000000000..3e82e9d75535 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/BirdTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Bird + */ +public class BirdTest { + private final Bird model = new Bird(); + + /** + * Model tests for Bird + */ + @Test + public void testBird() { + // TODO: test Bird + } + + /** + * Test the property 'size' + */ + @Test + public void sizeTest() { + // TODO: test size + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 000000000000..5b6a08fd6773 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DataQueryTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DataQueryTest.java new file mode 100644 index 000000000000..d08082e114ed --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DataQueryTest.java @@ -0,0 +1,84 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Query; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for DataQuery + */ +public class DataQueryTest { + private final DataQuery model = new DataQuery(); + + /** + * Model tests for DataQuery + */ + @Test + public void testDataQuery() { + // TODO: test DataQuery + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'outcomes' + */ + @Test + public void outcomesTest() { + // TODO: test outcomes + } + + /** + * Test the property 'suffix' + */ + @Test + public void suffixTest() { + // TODO: test suffix + } + + /** + * Test the property 'text' + */ + @Test + public void textTest() { + // TODO: test text + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DefaultValueTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DefaultValueTest.java new file mode 100644 index 000000000000..843a43b28d72 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/DefaultValueTest.java @@ -0,0 +1,111 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for DefaultValue + */ +public class DefaultValueTest { + private final DefaultValue model = new DefaultValue(); + + /** + * Model tests for DefaultValue + */ + @Test + public void testDefaultValue() { + // TODO: test DefaultValue + } + + /** + * Test the property 'arrayStringEnumRefDefault' + */ + @Test + public void arrayStringEnumRefDefaultTest() { + // TODO: test arrayStringEnumRefDefault + } + + /** + * Test the property 'arrayStringEnumDefault' + */ + @Test + public void arrayStringEnumDefaultTest() { + // TODO: test arrayStringEnumDefault + } + + /** + * Test the property 'arrayStringDefault' + */ + @Test + public void arrayStringDefaultTest() { + // TODO: test arrayStringDefault + } + + /** + * Test the property 'arrayIntegerDefault' + */ + @Test + public void arrayIntegerDefaultTest() { + // TODO: test arrayIntegerDefault + } + + /** + * Test the property 'arrayString' + */ + @Test + public void arrayStringTest() { + // TODO: test arrayString + } + + /** + * Test the property 'arrayStringNullable' + */ + @Test + public void arrayStringNullableTest() { + // TODO: test arrayStringNullable + } + + /** + * Test the property 'arrayStringExtensionNullable' + */ + @Test + public void arrayStringExtensionNullableTest() { + // TODO: test arrayStringExtensionNullable + } + + /** + * Test the property 'stringNullable' + */ + @Test + public void stringNullableTest() { + // TODO: test stringNullable + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java new file mode 100644 index 000000000000..80e515fd707e --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java @@ -0,0 +1,64 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for NumberPropertiesOnly + */ +public class NumberPropertiesOnlyTest { + private final NumberPropertiesOnly model = new NumberPropertiesOnly(); + + /** + * Model tests for NumberPropertiesOnly + */ + @Test + public void testNumberPropertiesOnly() { + // TODO: test NumberPropertiesOnly + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..30e1991c7e32 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,92 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/QueryTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/QueryTest.java new file mode 100644 index 000000000000..3ae0ecb7b70d --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/QueryTest.java @@ -0,0 +1,58 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Query + */ +public class QueryTest { + private final Query model = new Query(); + + /** + * Model tests for Query + */ + @Test + public void testQuery() { + // TODO: test Query + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'outcomes' + */ + @Test + public void outcomesTest() { + // TODO: test outcomes + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/StringEnumRefTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/StringEnumRefTest.java new file mode 100644 index 000000000000..81bf17732bda --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/StringEnumRefTest.java @@ -0,0 +1,32 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for StringEnumRef + */ +public class StringEnumRefTest { + /** + * Model tests for StringEnumRef + */ + @Test + public void testStringEnumRef() { + // TODO: test StringEnumRef + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 000000000000..073b7aca33c1 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java new file mode 100644 index 000000000000..8ab39f47d766 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java @@ -0,0 +1,71 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ +public class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest { + private final TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter model = new TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(); + + /** + * Model tests for TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + @Test + public void testTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() { + // TODO: test TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + } + + /** + * Test the property 'size' + */ + @Test + public void sizeTest() { + // TODO: test size + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java new file mode 100644 index 000000000000..f3e020346fa0 --- /dev/null +++ b/samples/client/echo_api/java/resteasy/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java @@ -0,0 +1,50 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ +public class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest { + private final TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter model = new TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(); + + /** + * Model tests for TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ + @Test + public void testTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() { + // TODO: test TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + } + + /** + * Test the property 'values' + */ + @Test + public void valuesTest() { + // TODO: test values + } + +} diff --git a/samples/client/echo_api/java/resttemplate/.github/workflows/maven.yml b/samples/client/echo_api/java/resttemplate/.github/workflows/maven.yml new file mode 100644 index 000000000000..aa75c116424b --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build Echo Server API + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/echo_api/java/resttemplate/.gitignore b/samples/client/echo_api/java/resttemplate/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/echo_api/java/resttemplate/.openapi-generator-ignore b/samples/client/echo_api/java/resttemplate/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/echo_api/java/resttemplate/.openapi-generator/FILES b/samples/client/echo_api/java/resttemplate/.openapi-generator/FILES new file mode 100644 index 000000000000..7086d5ac3443 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.openapi-generator/FILES @@ -0,0 +1,59 @@ +.github/workflows/maven.yml +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/AuthApi.md +docs/Bird.md +docs/BodyApi.md +docs/Category.md +docs/DataQuery.md +docs/DefaultValue.md +docs/FormApi.md +docs/HeaderApi.md +docs/NumberPropertiesOnly.md +docs/PathApi.md +docs/Pet.md +docs/Query.md +docs/QueryApi.md +docs/StringEnumRef.md +docs/Tag.md +docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/JavaTimeFormatter.java +src/main/java/org/openapitools/client/RFC3339DateFormat.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/api/AuthApi.java +src/main/java/org/openapitools/client/api/BodyApi.java +src/main/java/org/openapitools/client/api/FormApi.java +src/main/java/org/openapitools/client/api/HeaderApi.java +src/main/java/org/openapitools/client/api/PathApi.java +src/main/java/org/openapitools/client/api/QueryApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/Bird.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/DataQuery.java +src/main/java/org/openapitools/client/model/DefaultValue.java +src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/Query.java +src/main/java/org/openapitools/client/model/StringEnumRef.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java +src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java diff --git a/samples/client/echo_api/java/resttemplate/.openapi-generator/VERSION b/samples/client/echo_api/java/resttemplate/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/java/resttemplate/.travis.yml b/samples/client/echo_api/java/resttemplate/.travis.yml new file mode 100644 index 000000000000..1b6741c083c7 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/echo_api/java/resttemplate/README.md b/samples/client/echo_api/java/resttemplate/README.md new file mode 100644 index 000000000000..3950c9c3273b --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/README.md @@ -0,0 +1,185 @@ +# echo-api-resttemplate + +Echo Server API + +- API version: 0.1.0 + +Echo Server API + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: + +1. Java 1.8+ +2. Maven/Gradle + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + echo-api-resttemplate + 0.1.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'echo-api-resttemplate' jar has been published to maven central. + mavenLocal() // Needed if the 'echo-api-resttemplate' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:echo-api-resttemplate:0.1.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +- `target/echo-api-resttemplate-0.1.0.jar` +- `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +import org.openapitools.client.*; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.api.AuthApi; + +public class AuthApiExample { + + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP basic authorization: http_auth + HttpBasicAuth http_auth = (HttpBasicAuth) defaultClient.getAuthentication("http_auth"); + http_auth.setUsername("YOUR USERNAME"); + http_auth.setPassword("YOUR PASSWORD"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBasic(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBasic"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:3000* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AuthApi* | [**testAuthHttpBasic**](docs/AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*BodyApi* | [**testBinaryGif**](docs/BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body +*BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +*BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +*BodyApi* | [**testEchoBodyPet**](docs/BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) +*BodyApi* | [**testEchoBodyPetResponseString**](docs/BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body +*BodyApi* | [**testEchoBodyTagResponseString**](docs/BodyApi.md#testEchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +*FormApi* | [**testFormIntegerBooleanString**](docs/FormApi.md#testFormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) +*FormApi* | [**testFormOneof**](docs/FormApi.md#testFormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema +*HeaderApi* | [**testHeaderIntegerBooleanStringEnums**](docs/HeaderApi.md#testHeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) +*PathApi* | [**testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](docs/PathApi.md#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) +*QueryApi* | [**testEnumRefString**](docs/QueryApi.md#testEnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) +*QueryApi* | [**testQueryDatetimeDateString**](docs/QueryApi.md#testQueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) +*QueryApi* | [**testQueryIntegerBooleanString**](docs/QueryApi.md#testQueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) +*QueryApi* | [**testQueryStyleDeepObjectExplodeTrueObject**](docs/QueryApi.md#testQueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +*QueryApi* | [**testQueryStyleDeepObjectExplodeTrueObjectAllOf**](docs/QueryApi.md#testQueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueArrayString**](docs/QueryApi.md#testQueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueObject**](docs/QueryApi.md#testQueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +*QueryApi* | [**testQueryStyleFormExplodeTrueObjectAllOf**](docs/QueryApi.md#testQueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + +## Documentation for Models + + - [Bird](docs/Bird.md) + - [Category](docs/Category.md) + - [DataQuery](docs/DataQuery.md) + - [DefaultValue](docs/DefaultValue.md) + - [NumberPropertiesOnly](docs/NumberPropertiesOnly.md) + - [Pet](docs/Pet.md) + - [Query](docs/Query.md) + - [StringEnumRef](docs/StringEnumRef.md) + - [Tag](docs/Tag.md) + - [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter](docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md) + - [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter](docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### http_auth + + +- **Type**: HTTP basic authentication + + +### http_bearer_auth + + +- **Type**: HTTP Bearer Token authentication + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + +team@openapitools.org + diff --git a/samples/client/echo_api/java/resttemplate/api/openapi.yaml b/samples/client/echo_api/java/resttemplate/api/openapi.yaml new file mode 100644 index 000000000000..f5d4fc9abbde --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/api/openapi.yaml @@ -0,0 +1,872 @@ +openapi: 3.0.3 +info: + contact: + email: team@openapitools.org + description: Echo Server API + license: + name: Apache 2.0 + url: http://www.apache.org/licenses/LICENSE-2.0.html + title: Echo Server API + version: 0.1.0 +servers: +- url: http://localhost:3000/ +paths: + /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}: + get: + description: Test path parameter(s) + operationId: "tests/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}" + parameters: + - explode: false + in: path + name: path_string + required: true + schema: + type: string + style: simple + - explode: false + in: path + name: path_integer + required: true + schema: + type: integer + style: simple + - explode: false + in: path + name: enum_nonref_string_path + required: true + schema: + enum: + - success + - failure + - unclassified + type: string + style: simple + - explode: false + in: path + name: enum_ref_string_path + required: true + schema: + $ref: '#/components/schemas/StringEnumRef' + style: simple + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test path parameter(s) + tags: + - path + x-accepts: text/plain + /form/integer/boolean/string: + post: + description: Test form parameter(s) + operationId: test/form/integer/boolean/string + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/test_form_integer_boolean_string_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test form parameter(s) + tags: + - form + x-content-type: application/x-www-form-urlencoded + x-accepts: text/plain + /form/oneof: + post: + description: Test form parameter(s) for oneOf schema + operationId: test/form/oneof + requestBody: + content: + application/x-www-form-urlencoded: + schema: + $ref: '#/components/schemas/test_form_oneof_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test form parameter(s) for oneOf schema + tags: + - form + x-content-type: application/x-www-form-urlencoded + x-accepts: text/plain + /header/integer/boolean/string/enums: + get: + description: Test header parameter(s) + operationId: test/header/integer/boolean/string/enums + parameters: + - explode: true + in: header + name: integer_header + required: false + schema: + type: integer + style: form + - explode: true + in: header + name: boolean_header + required: false + schema: + type: boolean + style: form + - explode: true + in: header + name: string_header + required: false + schema: + type: string + style: form + - explode: true + in: header + name: enum_nonref_string_header + required: false + schema: + enum: + - success + - failure + - unclassified + type: string + style: form + - explode: true + in: header + name: enum_ref_string_header + required: false + schema: + $ref: '#/components/schemas/StringEnumRef' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test header parameter(s) + tags: + - header + x-accepts: text/plain + /query/enum_ref_string: + get: + description: Test query parameter(s) + operationId: test/enum_ref_string + parameters: + - explode: true + in: query + name: enum_nonref_string_query + required: false + schema: + enum: + - success + - failure + - unclassified + type: string + style: form + - explode: true + in: query + name: enum_ref_string_query + required: false + schema: + $ref: '#/components/schemas/StringEnumRef' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/datetime/date/string: + get: + description: Test query parameter(s) + operationId: test/query/datetime/date/string + parameters: + - explode: true + in: query + name: datetime_query + required: false + schema: + format: date-time + type: string + style: form + - explode: true + in: query + name: date_query + required: false + schema: + format: date + type: string + style: form + - explode: true + in: query + name: string_query + required: false + schema: + type: string + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/integer/boolean/string: + get: + description: Test query parameter(s) + operationId: test/query/integer/boolean/string + parameters: + - explode: true + in: query + name: integer_query + required: false + schema: + type: integer + style: form + - explode: true + in: query + name: boolean_query + required: false + schema: + type: boolean + style: form + - explode: true + in: query + name: string_query + required: false + schema: + type: string + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/array_string: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/array_string + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/test_query_style_form_explode_true_array_string_query_object_parameter' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/object: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/object + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/Pet' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_form/explode_true/object/allOf: + get: + description: Test query parameter(s) + operationId: test/query/style_form/explode_true/object/allOf + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/DataQuery' + style: form + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_deepObject/explode_true/object: + get: + description: Test query parameter(s) + operationId: test/query/style_deepObject/explode_true/object + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/Pet' + style: deepObject + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /query/style_deepObject/explode_true/object/allOf: + get: + description: Test query parameter(s) + operationId: test/query/style_deepObject/explode_true/object/allOf + parameters: + - explode: true + in: query + name: query_object + required: false + schema: + $ref: '#/components/schemas/test_query_style_deepObject_explode_true_object_allOf_query_object_parameter' + style: deepObject + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test query parameter(s) + tags: + - query + x-accepts: text/plain + /body/application/octetstream/binary: + post: + description: Test body parameter(s) + operationId: test/body/application/octetstream/binary + requestBody: + content: + application/octet-stream: + schema: + format: binary + type: string + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/octet-stream + x-accepts: text/plain + /echo/body/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/Pet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json + /echo/body/allOf/Pet: + post: + description: Test body parameter(s) + operationId: test/echo/body/allOf/Pet + requestBody: + $ref: '#/components/requestBodies/AllOfPet' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Successful operation + summary: Test body parameter(s) + tags: + - body + x-content-type: application/json + x-accepts: application/json + /echo/body/Pet/response_string: + post: + description: Test empty response body + operationId: test/echo/body/Pet/response_string + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test empty response body + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /echo/body/Tag/response_string: + post: + description: Test empty json (request body) + operationId: test/echo/body/Tag/response_string + requestBody: + $ref: '#/components/requestBodies/Tag' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test empty json (request body) + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /echo/body/FreeFormObject/response_string: + post: + description: Test free form object + operationId: test/echo/body/FreeFormObject/response_string + requestBody: + content: + application/json: + schema: + type: object + description: Free form object + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test free form object + tags: + - body + x-content-type: application/json + x-accepts: text/plain + /binary/gif: + post: + description: Test binary (gif) response body + operationId: test/binary/gif + responses: + "200": + content: + image/gif: + schema: + format: binary + type: string + description: Successful operation + summary: Test binary (gif) response body + tags: + - body + x-accepts: image/gif + /body/application/octetstream/single_binary: + post: + description: Test single binary in multipart mime + operationId: test/body/multipart/formdata/single_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_single_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test single binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain + /body/application/octetstream/array_of_binary: + post: + description: Test array of binary in multipart mime + operationId: test/body/multipart/formdata/array_of_binary + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/test_body_multipart_formdata_array_of_binary_request' + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + summary: Test array of binary in multipart mime + tags: + - body + x-content-type: multipart/form-data + x-accepts: text/plain + /auth/http/basic: + post: + description: To test HTTP basic authentication + operationId: test/auth/http/basic + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_auth: [] + summary: To test HTTP basic authentication + tags: + - auth + x-accepts: text/plain + /auth/http/bearer: + post: + description: To test HTTP bearer authentication + operationId: test/auth/http/bearer + responses: + "200": + content: + text/plain: + schema: + type: string + description: Successful operation + security: + - http_bearer_auth: [] + summary: To test HTTP bearer authentication + tags: + - auth + x-accepts: text/plain +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + AllOfPet: + content: + application/json: + schema: + allOf: + - $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + Tag: + content: + application/json: + schema: + $ref: '#/components/schemas/Tag' + description: Tag object + schemas: + Category: + example: + name: Dogs + id: 1 + properties: + id: + example: 1 + format: int64 + type: integer + name: + example: Dogs + type: string + type: object + xml: + name: category + Tag: + example: + name: name + id: 0 + properties: + id: + format: int64 + type: integer + name: + type: string + type: object + xml: + name: tag + Pet: + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 10 + category: + name: Dogs + id: 1 + tags: + - name: name + id: 0 + - name: name + id: 0 + status: available + properties: + id: + example: 10 + format: int64 + type: integer + name: + example: doggie + type: string + category: + $ref: '#/components/schemas/Category' + photoUrls: + items: + type: string + xml: + name: photoUrl + type: array + xml: + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + wrapped: true + status: + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + type: object + xml: + name: pet + StringEnumRef: + enum: + - success + - failure + - unclassified + type: string + DefaultValue: + description: to test the default value of properties + properties: + array_string_enum_ref_default: + default: + - success + - failure + items: + $ref: '#/components/schemas/StringEnumRef' + type: array + array_string_enum_default: + default: + - success + - failure + items: + enum: + - success + - failure + - unclassified + type: string + type: array + array_string_default: + default: + - failure + - skipped + items: + type: string + type: array + array_integer_default: + default: + - 1 + - 3 + items: + type: integer + type: array + array_string: + items: + type: string + type: array + array_string_nullable: + items: + type: string + nullable: true + type: array + array_string_extension_nullable: + items: + type: string + type: array + x-nullable: true + string_nullable: + nullable: true + type: string + type: object + Bird: + properties: + size: + type: string + color: + type: string + type: object + Query: + properties: + id: + description: Query + format: int64 + type: integer + outcomes: + default: + - SUCCESS + - FAILURE + items: + enum: + - SUCCESS + - FAILURE + - SKIPPED + type: string + type: array + type: object + x-parent: true + DataQuery: + allOf: + - properties: + suffix: + description: test suffix + type: string + text: + description: Some text containing white spaces + example: Some text + type: string + date: + description: A date + format: date-time + type: string + type: object + - $ref: '#/components/schemas/Query' + NumberPropertiesOnly: + properties: + number: + type: number + float: + format: float + type: number + double: + format: double + maximum: 50.2 + minimum: 0.8 + type: number + type: object + test_form_integer_boolean_string_request: + properties: + integer_form: + type: integer + boolean_form: + type: boolean + string_form: + type: string + type: object + test_form_oneof_request_oneOf: + properties: + form1: + type: string + form2: + type: integer + type: object + test_form_oneof_request_oneOf_1: + properties: + form3: + type: string + form4: + type: boolean + type: object + test_form_oneof_request: + oneOf: + - $ref: '#/components/schemas/test_form_oneof_request_oneOf' + - $ref: '#/components/schemas/test_form_oneof_request_oneOf_1' + - $ref: '#/components/schemas/Tag' + type: object + test_query_style_form_explode_true_array_string_query_object_parameter: + properties: + values: + items: + type: string + type: array + type: object + test_query_style_deepObject_explode_true_object_allOf_query_object_parameter: + allOf: + - $ref: '#/components/schemas/Bird' + - $ref: '#/components/schemas/Category' + test_body_multipart_formdata_single_binary_request: + properties: + my-file: + format: binary + type: string + type: object + test_body_multipart_formdata_array_of_binary_request: + properties: + files: + items: + format: binary + type: string + type: array + required: + - files + type: object + securitySchemes: + http_auth: + scheme: basic + type: http + http_bearer_auth: + scheme: bearer + type: http + diff --git a/samples/client/echo_api/java/resttemplate/build.gradle b/samples/client/echo_api/java/resttemplate/build.gradle new file mode 100644 index 000000000000..a3f880a047c1 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/build.gradle @@ -0,0 +1,121 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' + +group = 'org.openapitools' +version = '0.1.0' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:1.5.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:1.3' + } +} + +repositories { + mavenCentral() +} + + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 23 + buildToolsVersion '23.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 22 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDirectory + task.destinationDirectory = project.file("${project.buildDir}/outputs/jar") + task.archiveFileName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task); + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + archiveClassifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven-publish' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + publishing { + publications { + maven(MavenPublication) { + artifactId = 'echo-api-resttemplate' + from components.java + } + } + } + + task execute(type:JavaExec) { + mainClass = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + jackson_version = "2.14.2" + jackson_databind_version = "2.15.1" + jackson_databind_nullable_version = "0.2.6" + spring_web_version = "5.3.24" + jakarta_annotation_version = "1.3.5" + jodatime_version = "2.9.9" + junit_version = "4.13.2" +} + +dependencies { + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation "org.springframework:spring-web:$spring_web_version" + implementation "org.springframework:spring-context:$spring_web_version" + implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-annotations:$jackson_version" + implementation "com.fasterxml.jackson.core:jackson-databind:$jackson_databind_version" + implementation "com.fasterxml.jackson.jaxrs:jackson-jaxrs-json-provider:$jackson_version" + implementation "org.openapitools:jackson-databind-nullable:$jackson_databind_nullable_version" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:$jackson_version" + implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation "junit:junit:$junit_version" +} diff --git a/samples/client/echo_api/java/resttemplate/build.sbt b/samples/client/echo_api/java/resttemplate/build.sbt new file mode 100644 index 000000000000..464090415c47 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/build.sbt @@ -0,0 +1 @@ +# TODO diff --git a/samples/client/echo_api/java/resttemplate/docs/AuthApi.md b/samples/client/echo_api/java/resttemplate/docs/AuthApi.md new file mode 100644 index 000000000000..de3353d43a2c --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/AuthApi.md @@ -0,0 +1,145 @@ +# AuthApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testAuthHttpBasic**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | + + + +## testAuthHttpBasic + +> String testAuthHttpBasic() + +To test HTTP basic authentication + +To test HTTP basic authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP basic authorization: http_auth + HttpBasicAuth http_auth = (HttpBasicAuth) defaultClient.getAuthentication("http_auth"); + http_auth.setUsername("YOUR USERNAME"); + http_auth.setPassword("YOUR PASSWORD"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBasic(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBasic"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testAuthHttpBearer + +> String testAuthHttpBearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AuthApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + // Configure HTTP bearer authorization: http_bearer_auth + HttpBearerAuth http_bearer_auth = (HttpBearerAuth) defaultClient.getAuthentication("http_bearer_auth"); + http_bearer_auth.setBearerToken("BEARER TOKEN"); + + AuthApi apiInstance = new AuthApi(defaultClient); + try { + String result = apiInstance.testAuthHttpBearer(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling AuthApi#testAuthHttpBearer"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/Bird.md b/samples/client/echo_api/java/resttemplate/docs/Bird.md new file mode 100644 index 000000000000..2a6f8a660d65 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/Bird.md @@ -0,0 +1,14 @@ + + +# Bird + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**size** | **String** | | [optional] | +|**color** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/BodyApi.md b/samples/client/echo_api/java/resttemplate/docs/BodyApi.md new file mode 100644 index 000000000000..3cf2014e31f6 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/BodyApi.md @@ -0,0 +1,607 @@ +# BodyApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testBinaryGif**](BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body | +| [**testBodyApplicationOctetstreamBinary**](BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | +| [**testBodyMultipartFormdataArrayOfBinary**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | +| [**testEchoBodyFreeFormObjectResponseString**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | +| [**testEchoBodyPet**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | +| [**testEchoBodyPetResponseString**](BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body | +| [**testEchoBodyTagResponseString**](BodyApi.md#testEchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) | + + + +## testBinaryGif + +> File testBinaryGif() + +Test binary (gif) response body + +Test binary (gif) response body + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + try { + File result = apiInstance.testBinaryGif(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBinaryGif"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**File**](File.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/gif + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyApplicationOctetstreamBinary + +> String testBodyApplicationOctetstreamBinary(body) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File body = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyApplicationOctetstreamBinary(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyApplicationOctetstreamBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/octet-stream +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyMultipartFormdataArrayOfBinary + +> String testBodyMultipartFormdataArrayOfBinary(files) + +Test array of binary in multipart mime + +Test array of binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + List files = Arrays.asList(); // List | + try { + String result = apiInstance.testBodyMultipartFormdataArrayOfBinary(files); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataArrayOfBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **files** | **List<File>**| | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testBodyMultipartFormdataSingleBinary + +> String testBodyMultipartFormdataSingleBinary(myFile) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + File myFile = new File("/path/to/file"); // File | + try { + String result = apiInstance.testBodyMultipartFormdataSingleBinary(myFile); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testBodyMultipartFormdataSingleBinary"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myFile** | **File**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyAllOfPet + +> Pet testEchoBodyAllOfPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyAllOfPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyAllOfPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyFreeFormObjectResponseString + +> String testEchoBodyFreeFormObjectResponseString(body) + +Test free form object + +Test free form object + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Object body = null; // Object | Free form object + try { + String result = apiInstance.testEchoBodyFreeFormObjectResponseString(body); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyFreeFormObjectResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **body** | **Object**| Free form object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyPet + +> Pet testEchoBodyPet(pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.testEchoBodyPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyPetResponseString + +> String testEchoBodyPetResponseString(pet) + +Test empty response body + +Test empty response body + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + String result = apiInstance.testEchoBodyPetResponseString(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyPetResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testEchoBodyTagResponseString + +> String testEchoBodyTagResponseString(tag) + +Test empty json (request body) + +Test empty json (request body) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.BodyApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + BodyApi apiInstance = new BodyApi(defaultClient); + Tag tag = new Tag(); // Tag | Tag object + try { + String result = apiInstance.testEchoBodyTagResponseString(tag); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling BodyApi#testEchoBodyTagResponseString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **tag** | [**Tag**](Tag.md)| Tag object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/Category.md b/samples/client/echo_api/java/resttemplate/docs/Category.md new file mode 100644 index 000000000000..7289ebf585bb --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/Category.md @@ -0,0 +1,14 @@ + + +# Category + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/DataQuery.md b/samples/client/echo_api/java/resttemplate/docs/DataQuery.md new file mode 100644 index 000000000000..338c467b2d56 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/DataQuery.md @@ -0,0 +1,15 @@ + + +# DataQuery + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**suffix** | **String** | test suffix | [optional] | +|**text** | **String** | Some text containing white spaces | [optional] | +|**date** | **OffsetDateTime** | A date | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/DefaultValue.md b/samples/client/echo_api/java/resttemplate/docs/DefaultValue.md new file mode 100644 index 000000000000..20a9b8ee2508 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/DefaultValue.md @@ -0,0 +1,31 @@ + + +# DefaultValue + +to test the default value of properties + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**arrayStringEnumRefDefault** | **List<StringEnumRef>** | | [optional] | +|**arrayStringEnumDefault** | [**List<ArrayStringEnumDefaultEnum>**](#List<ArrayStringEnumDefaultEnum>) | | [optional] | +|**arrayStringDefault** | **List<String>** | | [optional] | +|**arrayIntegerDefault** | **List<Integer>** | | [optional] | +|**arrayString** | **List<String>** | | [optional] | +|**arrayStringNullable** | **List<String>** | | [optional] | +|**arrayStringExtensionNullable** | **List<String>** | | [optional] | +|**stringNullable** | **String** | | [optional] | + + + +## Enum: List<ArrayStringEnumDefaultEnum> + +| Name | Value | +|---- | -----| +| SUCCESS | "success" | +| FAILURE | "failure" | +| UNCLASSIFIED | "unclassified" | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/FormApi.md b/samples/client/echo_api/java/resttemplate/docs/FormApi.md new file mode 100644 index 000000000000..1f3ad73e9384 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/FormApi.md @@ -0,0 +1,156 @@ +# FormApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testFormIntegerBooleanString**](FormApi.md#testFormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) | +| [**testFormOneof**](FormApi.md#testFormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema | + + + +## testFormIntegerBooleanString + +> String testFormIntegerBooleanString(integerForm, booleanForm, stringForm) + +Test form parameter(s) + +Test form parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FormApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + FormApi apiInstance = new FormApi(defaultClient); + Integer integerForm = 56; // Integer | + Boolean booleanForm = true; // Boolean | + String stringForm = "stringForm_example"; // String | + try { + String result = apiInstance.testFormIntegerBooleanString(integerForm, booleanForm, stringForm); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FormApi#testFormIntegerBooleanString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerForm** | **Integer**| | [optional] | +| **booleanForm** | **Boolean**| | [optional] | +| **stringForm** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testFormOneof + +> String testFormOneof(form1, form2, form3, form4, id, name) + +Test form parameter(s) for oneOf schema + +Test form parameter(s) for oneOf schema + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FormApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + FormApi apiInstance = new FormApi(defaultClient); + String form1 = "form1_example"; // String | + Integer form2 = 56; // Integer | + String form3 = "form3_example"; // String | + Boolean form4 = true; // Boolean | + Long id = 56L; // Long | + String name = "name_example"; // String | + try { + String result = apiInstance.testFormOneof(form1, form2, form3, form4, id, name); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FormApi#testFormOneof"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **form1** | **String**| | [optional] | +| **form2** | **Integer**| | [optional] | +| **form3** | **String**| | [optional] | +| **form4** | **Boolean**| | [optional] | +| **id** | **Long**| | [optional] | +| **name** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/HeaderApi.md b/samples/client/echo_api/java/resttemplate/docs/HeaderApi.md new file mode 100644 index 000000000000..e30880043fac --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/HeaderApi.md @@ -0,0 +1,83 @@ +# HeaderApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testHeaderIntegerBooleanStringEnums**](HeaderApi.md#testHeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) | + + + +## testHeaderIntegerBooleanStringEnums + +> String testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader) + +Test header parameter(s) + +Test header parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.HeaderApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + HeaderApi apiInstance = new HeaderApi(defaultClient); + Integer integerHeader = 56; // Integer | + Boolean booleanHeader = true; // Boolean | + String stringHeader = "stringHeader_example"; // String | + String enumNonrefStringHeader = "success"; // String | + StringEnumRef enumRefStringHeader = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling HeaderApi#testHeaderIntegerBooleanStringEnums"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerHeader** | **Integer**| | [optional] | +| **booleanHeader** | **Boolean**| | [optional] | +| **stringHeader** | **String**| | [optional] | +| **enumNonrefStringHeader** | **String**| | [optional] [enum: success, failure, unclassified] | +| **enumRefStringHeader** | [**StringEnumRef**](.md)| | [optional] [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/NumberPropertiesOnly.md b/samples/client/echo_api/java/resttemplate/docs/NumberPropertiesOnly.md new file mode 100644 index 000000000000..7e153538475a --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/NumberPropertiesOnly.md @@ -0,0 +1,15 @@ + + +# NumberPropertiesOnly + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**number** | **BigDecimal** | | [optional] | +|**_float** | **Float** | | [optional] | +|**_double** | **Double** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/PathApi.md b/samples/client/echo_api/java/resttemplate/docs/PathApi.md new file mode 100644 index 000000000000..e9a539e8c3e4 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/PathApi.md @@ -0,0 +1,81 @@ +# PathApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](PathApi.md#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) | + + + +## testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath + +> String testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath) + +Test path parameter(s) + +Test path parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PathApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + PathApi apiInstance = new PathApi(defaultClient); + String pathString = "pathString_example"; // String | + Integer pathInteger = 56; // Integer | + String enumNonrefStringPath = "success"; // String | + StringEnumRef enumRefStringPath = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PathApi#testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pathString** | **String**| | | +| **pathInteger** | **Integer**| | | +| **enumNonrefStringPath** | **String**| | [enum: success, failure, unclassified] | +| **enumRefStringPath** | [**StringEnumRef**](.md)| | [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/Pet.md b/samples/client/echo_api/java/resttemplate/docs/Pet.md new file mode 100644 index 000000000000..82aa8a25ed7c --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/Pet.md @@ -0,0 +1,28 @@ + + +# Pet + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**category** | [**Category**](Category.md) | | [optional] | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/Query.md b/samples/client/echo_api/java/resttemplate/docs/Query.md new file mode 100644 index 000000000000..99c6fd6faa5d --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/Query.md @@ -0,0 +1,24 @@ + + +# Query + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | Query | [optional] | +|**outcomes** | [**List<OutcomesEnum>**](#List<OutcomesEnum>) | | [optional] | + + + +## Enum: List<OutcomesEnum> + +| Name | Value | +|---- | -----| +| SUCCESS | "SUCCESS" | +| FAILURE | "FAILURE" | +| SKIPPED | "SKIPPED" | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/QueryApi.md b/samples/client/echo_api/java/resttemplate/docs/QueryApi.md new file mode 100644 index 000000000000..2606c8e62ca9 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/QueryApi.md @@ -0,0 +1,554 @@ +# QueryApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**testEnumRefString**](QueryApi.md#testEnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) | +| [**testQueryDatetimeDateString**](QueryApi.md#testQueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) | +| [**testQueryIntegerBooleanString**](QueryApi.md#testQueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) | +| [**testQueryStyleDeepObjectExplodeTrueObject**](QueryApi.md#testQueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) | +| [**testQueryStyleDeepObjectExplodeTrueObjectAllOf**](QueryApi.md#testQueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueArrayString**](QueryApi.md#testQueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueObject**](QueryApi.md#testQueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) | +| [**testQueryStyleFormExplodeTrueObjectAllOf**](QueryApi.md#testQueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) | + + + +## testEnumRefString + +> String testEnumRefString(enumNonrefStringQuery, enumRefStringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + String enumNonrefStringQuery = "success"; // String | + StringEnumRef enumRefStringQuery = StringEnumRef.fromValue("success"); // StringEnumRef | + try { + String result = apiInstance.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testEnumRefString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **enumNonrefStringQuery** | **String**| | [optional] [enum: success, failure, unclassified] | +| **enumRefStringQuery** | [**StringEnumRef**](.md)| | [optional] [enum: success, failure, unclassified] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryDatetimeDateString + +> String testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + OffsetDateTime datetimeQuery = OffsetDateTime.now(); // OffsetDateTime | + LocalDate dateQuery = LocalDate.now(); // LocalDate | + String stringQuery = "stringQuery_example"; // String | + try { + String result = apiInstance.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryDatetimeDateString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **datetimeQuery** | **OffsetDateTime**| | [optional] | +| **dateQuery** | **LocalDate**| | [optional] | +| **stringQuery** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryIntegerBooleanString + +> String testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Integer integerQuery = 56; // Integer | + Boolean booleanQuery = true; // Boolean | + String stringQuery = "stringQuery_example"; // String | + try { + String result = apiInstance.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryIntegerBooleanString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **integerQuery** | **Integer**| | [optional] | +| **booleanQuery** | **Boolean**| | [optional] | +| **stringQuery** | **String**| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleDeepObjectExplodeTrueObject + +> String testQueryStyleDeepObjectExplodeTrueObject(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Pet queryObject = new Pet(); // Pet | + try { + String result = apiInstance.testQueryStyleDeepObjectExplodeTrueObject(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleDeepObjectExplodeTrueObject"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**Pet**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleDeepObjectExplodeTrueObjectAllOf + +> String testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject = new TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(); // TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | + try { + String result = apiInstance.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleDeepObjectExplodeTrueObjectAllOf"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueArrayString + +> String testQueryStyleFormExplodeTrueArrayString(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject = new TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(); // TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueArrayString(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueArrayString"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueObject + +> String testQueryStyleFormExplodeTrueObject(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + Pet queryObject = new Pet(); // Pet | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueObject(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueObject"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**Pet**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + + +## testQueryStyleFormExplodeTrueObjectAllOf + +> String testQueryStyleFormExplodeTrueObjectAllOf(queryObject) + +Test query parameter(s) + +Test query parameter(s) + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.QueryApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost:3000"); + + QueryApi apiInstance = new QueryApi(defaultClient); + DataQuery queryObject = new DataQuery(); // DataQuery | + try { + String result = apiInstance.testQueryStyleFormExplodeTrueObjectAllOf(queryObject); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling QueryApi#testQueryStyleFormExplodeTrueObjectAllOf"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **queryObject** | [**DataQuery**](.md)| | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | Successful operation | - | + diff --git a/samples/client/echo_api/java/resttemplate/docs/StringEnumRef.md b/samples/client/echo_api/java/resttemplate/docs/StringEnumRef.md new file mode 100644 index 000000000000..dff22ecf074b --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/StringEnumRef.md @@ -0,0 +1,15 @@ + + +# StringEnumRef + +## Enum + + +* `SUCCESS` (value: `"success"`) + +* `FAILURE` (value: `"failure"`) + +* `UNCLASSIFIED` (value: `"unclassified"`) + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/Tag.md b/samples/client/echo_api/java/resttemplate/docs/Tag.md new file mode 100644 index 000000000000..5088b2dd1c31 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/Tag.md @@ -0,0 +1,14 @@ + + +# Tag + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md new file mode 100644 index 000000000000..a756a343e8a8 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -0,0 +1,16 @@ + + +# TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**size** | **String** | | [optional] | +|**color** | **String** | | [optional] | +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md new file mode 100644 index 000000000000..9235e80fb823 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -0,0 +1,13 @@ + + +# TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**values** | **List<String>** | | [optional] | + + + diff --git a/samples/client/echo_api/java/resttemplate/git_push.sh b/samples/client/echo_api/java/resttemplate/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/echo_api/java/resttemplate/gradle.properties b/samples/client/echo_api/java/resttemplate/gradle.properties new file mode 100644 index 000000000000..a3408578278a --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.jar b/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..7454180f2ae8 Binary files /dev/null and b/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.properties b/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..ffed3a254e91 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/echo_api/java/resttemplate/gradlew b/samples/client/echo_api/java/resttemplate/gradlew new file mode 100644 index 000000000000..005bcde04284 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/echo_api/java/resttemplate/gradlew.bat b/samples/client/echo_api/java/resttemplate/gradlew.bat new file mode 100644 index 000000000000..6a68175eb70f --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/echo_api/java/resttemplate/pom.xml b/samples/client/echo_api/java/resttemplate/pom.xml new file mode 100644 index 000000000000..49ebb1b37502 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/pom.xml @@ -0,0 +1,276 @@ + + 4.0.0 + org.openapitools + echo-api-resttemplate + jar + echo-api-resttemplate + 0.1.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://www.apache.org/licenses/LICENSE-2.0.html + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.4.0 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.1.2 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + pertest + true + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.4.0 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.11.0 + + 1.8 + 1.8 + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.5.0 + + none + + + + attach-javadocs + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.3.0 + + + attach-sources + + jar-no-fork + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 1.5 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + + + org.springframework + spring-web + ${spring-web-version} + + + org.springframework + spring-context + ${spring-web-version} + + + + + com.fasterxml.jackson.core + jackson-core + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson-version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson-databind-version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-json-provider + ${jackson-version} + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + + + junit + junit + ${junit-version} + test + + + + UTF-8 + 5.3.24 + 2.15.2 + 2.15.2 + 0.2.6 + 1.3.5 + 4.13.2 + + diff --git a/samples/client/echo_api/java/resttemplate/settings.gradle b/samples/client/echo_api/java/resttemplate/settings.gradle new file mode 100644 index 000000000000..5b9c824d855e --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "echo-api-resttemplate" \ No newline at end of file diff --git a/samples/client/echo_api/java/resttemplate/src/main/AndroidManifest.xml b/samples/client/echo_api/java/resttemplate/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..8f37424cbecc --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,858 @@ +package org.openapitools.client; + +import org.apache.commons.logging.Log; +import org.apache.commons.logging.LogFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpRequest; +import org.springframework.http.HttpStatus; +import org.springframework.http.InvalidMediaTypeException; +import org.springframework.http.MediaType; +import org.springframework.http.RequestEntity; +import org.springframework.http.RequestEntity.BodyBuilder; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestExecution; +import org.springframework.http.client.ClientHttpRequestInterceptor; +import org.springframework.http.client.ClientHttpResponse; +import org.springframework.stereotype.Component; +import org.springframework.util.CollectionUtils; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; +import org.springframework.web.util.DefaultUriBuilderFactory; +import org.openapitools.jackson.nullable.JsonNullableModule; + + +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URLEncoder; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.ParseException; +import java.util.Arrays; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.Date; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; +import java.util.TimeZone; +import java.util.function.Supplier; +import java.time.OffsetDateTime; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiClient extends JavaTimeFormatter { + public enum CollectionFormat { + CSV(","), TSV("\t"), SSV(" "), PIPES("|"), MULTI(null); + + private final String separator; + + private CollectionFormat(String separator) { + this.separator = separator; + } + + private String collectionToString(Collection collection) { + return StringUtils.collectionToDelimitedString(collection, separator); + } + } + + private boolean debugging = false; + + private HttpHeaders defaultHeaders = new HttpHeaders(); + private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + + private String basePath = "http://localhost:3000"; + + private RestTemplate restTemplate; + + private Map authentications; + + private DateFormat dateFormat; + + public ApiClient() { + this.restTemplate = buildRestTemplate(); + init(); + } + + public ApiClient(RestTemplate restTemplate) { + this.restTemplate = restTemplate; + init(); + } + + protected void init() { + // Use RFC3339 format for date and datetime. + // See http://xml2rfc.ietf.org/public/rfc/html/rfc3339.html#anchor14 + this.dateFormat = new RFC3339DateFormat(); + + // Use UTC as the default time zone. + this.dateFormat.setTimeZone(TimeZone.getTimeZone("UTC")); + + // Set default User-Agent. + setUserAgent("Java-SDK"); + + // Setup authentications (key: authentication name, value: authentication). + authentications = new HashMap(); + authentications.put("http_auth", new HttpBasicAuth()); + authentications.put("http_bearer_auth", new HttpBearerAuth("bearer")); + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Get the current base path + * + * @return String the base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set the base path, which should include the host + * + * @param basePath the base path + * @return ApiClient this client + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + return this; + } + + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map the currently configured authentication types + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + /** + * Helper method to set access token for the first Bearer authentication. + * + * @param bearerToken Bearer token + */ + public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } + + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + + + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent the user agent string + * @return ApiClient this client + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param name The header's name + * @param value The header's value + * @return ApiClient this client + */ + public ApiClient addDefaultHeader(String name, String value) { + if (defaultHeaders.containsKey(name)) { + defaultHeaders.remove(name); + } + defaultHeaders.add(name, value); + return this; + } + + /** + * Add a default cookie. + * + * @param name The cookie's name + * @param value The cookie's value + * @return ApiClient this client + */ + public ApiClient addDefaultCookie(String name, String value) { + if (defaultCookies.containsKey(name)) { + defaultCookies.remove(name); + } + defaultCookies.add(name, value); + return this; + } + + public void setDebugging(boolean debugging) { + List currentInterceptors = this.restTemplate.getInterceptors(); + if (debugging) { + if (currentInterceptors == null) { + currentInterceptors = new ArrayList(); + } + ClientHttpRequestInterceptor interceptor = new ApiClientHttpRequestInterceptor(); + currentInterceptors.add(interceptor); + this.restTemplate.setInterceptors(currentInterceptors); + } else { + if (currentInterceptors != null && !currentInterceptors.isEmpty()) { + Iterator iter = currentInterceptors.iterator(); + while (iter.hasNext()) { + ClientHttpRequestInterceptor interceptor = iter.next(); + if (interceptor instanceof ApiClientHttpRequestInterceptor) { + iter.remove(); + } + } + this.restTemplate.setInterceptors(currentInterceptors); + } + } + this.debugging = debugging; + } + + /** + * Check that whether debugging is enabled for this API client. + * @return boolean true if this client is enabled for debugging, false otherwise + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Get the date format used to parse/format date parameters. + * @return DateFormat format + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + * Set the date format used to parse/format date parameters. + * @param dateFormat Date format + * @return API client + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + return this; + } + + /** + * Parse the given string into Date object. + * + * @param str the string to parse + * @return the Date parsed from the string + */ + public Date parseDate(String str) { + try { + return dateFormat.parse(str); + } catch (ParseException e) { + throw new RuntimeException(e); + } + } + + /** + * Format the given Date object into string. + * + * @param date the date to format + * @return the formatted date as string + */ + public String formatDate(Date date) { + return dateFormat.format(date); + } + + /** + * Format the given parameter object into string. + * + * @param param the object to convert + * @return String the parameter represented as a String + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date) { + return formatDate( (Date) param); + } else if (param instanceof OffsetDateTime) { + return formatOffsetDateTime((OffsetDateTime) param); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(String.valueOf(o)); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param values The values of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(CollectionFormat collectionFormat, Collection values) { + // create the value based on the collection format + if (CollectionFormat.MULTI.equals(collectionFormat)) { + // not valid for path params + return parameterToString(values); + } + + // collectionFormat is assumed to be "csv" by default + if (collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + return collectionFormat.collectionToString(values); + } + + /** + * Converts a parameter to a {@link MultiValueMap} for use in REST requests + * + * @param collectionFormat The format to convert to + * @param name The name of the parameter + * @param value The parameter's value + * @return a Map containing the String value(s) of the input parameter + */ + public MultiValueMap parameterToMultiValueMap(CollectionFormat collectionFormat, String name, Object value) { + final MultiValueMap params = new LinkedMultiValueMap(); + + if (name == null || name.isEmpty() || value == null) { + return params; + } + + if (collectionFormat == null) { + collectionFormat = CollectionFormat.CSV; + } + + if (value instanceof Map) { + @SuppressWarnings("unchecked") + final Map valuesMap = (Map) value; + for (final Entry entry : valuesMap.entrySet()) { + params.add(entry.getKey(), parameterToString(entry.getValue())); + } + return params; + } + + Collection valueCollection = null; + if (value instanceof Collection) { + valueCollection = (Collection) value; + } else { + params.add(name, parameterToString(value)); + return params; + } + + if (valueCollection.isEmpty()) { + return params; + } + + if (collectionFormat.equals(CollectionFormat.MULTI)) { + for (Object item : valueCollection) { + params.add(name, parameterToString(item)); + } + return params; + } + + List values = new ArrayList(); + for (Object o : valueCollection) { + values.add(parameterToString(o)); + } + params.add(name, collectionFormat.collectionToString(values)); + + return params; + } + + /** + * Check if the given {@code String} is a JSON MIME. + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(String mediaType) { + // "* / *" is default to JSON + if ("*/*".equals(mediaType)) { + return true; + } + + try { + return isJsonMime(MediaType.parseMediaType(mediaType)); + } catch (InvalidMediaTypeException e) { + } + return false; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents JSON, false otherwise + */ + public boolean isJsonMime(MediaType mediaType) { + return mediaType != null && (MediaType.APPLICATION_JSON.isCompatibleWith(mediaType) || mediaType.getSubtype().matches("^.*\\+json[;]?\\s*$")); + } + + /** + * Check if the given {@code String} is a Problem JSON MIME (RFC-7807). + * + * @param mediaType the input MediaType + * @return boolean true if the MediaType represents Problem JSON, false otherwise + */ + public boolean isProblemJsonMime(String mediaType) { + return "application/problem+json".equalsIgnoreCase(mediaType); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return List The list of MediaTypes to use for the Accept header + */ + public List selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + MediaType mediaType = MediaType.parseMediaType(accept); + if (isJsonMime(mediaType) && !isProblemJsonMime(accept)) { + return Collections.singletonList(mediaType); + } + } + return MediaType.parseMediaTypes(StringUtils.arrayToCommaDelimitedString(accepts)); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return MediaType The Content-Type header to use. If the given array is empty, JSON will be used. + */ + public MediaType selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return MediaType.APPLICATION_JSON; + } + for (String contentType : contentTypes) { + MediaType mediaType = MediaType.parseMediaType(contentType); + if (isJsonMime(mediaType)) { + return mediaType; + } + } + return MediaType.parseMediaType(contentTypes[0]); + } + + /** + * Select the body to use for the request + * + * @param obj the body object + * @param formParams the form parameters + * @param contentType the content type of the request + * @return Object the selected body + */ + protected Object selectBody(Object obj, MultiValueMap formParams, MediaType contentType) { + boolean isForm = MediaType.MULTIPART_FORM_DATA.isCompatibleWith(contentType) || MediaType.APPLICATION_FORM_URLENCODED.isCompatibleWith(contentType); + return isForm ? formParams : obj; + } + + /** + * Expand path template with variables + * + * @param pathTemplate path template with placeholders + * @param variables variables to replace + * @return path with placeholders replaced by variables + */ + public String expandPath(String pathTemplate, Map variables) { + return restTemplate.getUriTemplateHandler().expand(pathTemplate, variables).toString(); + } + + /** + * Include queryParams in uriParams taking into account the paramName + * + * @param queryParams The query parameters + * @param uriParams The path parameters + * return templatized query string + */ + public String generateQueryUri(MultiValueMap queryParams, Map uriParams) { + StringBuilder queryBuilder = new StringBuilder(); + queryParams.forEach((name, values) -> { + try { + final String encodedName = URLEncoder.encode(name.toString(), "UTF-8"); + if (CollectionUtils.isEmpty(values)) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + } else { + int valueItemCounter = 0; + for (Object value : values) { + if (queryBuilder.length() != 0) { + queryBuilder.append('&'); + } + queryBuilder.append(encodedName); + if (value != null) { + String templatizedKey = encodedName + valueItemCounter++; + uriParams.put(templatizedKey, value.toString()); + queryBuilder.append('=').append("{").append(templatizedKey).append("}"); + } + } + } + } catch (UnsupportedEncodingException e) { + + } + }); + return queryBuilder.toString(); + + } + + /** + * Invoke API by sending HTTP request with the given options. + * + * @param the return type to use + * @param path The sub-path of the HTTP URL + * @param method The request method + * @param pathParams The path parameters + * @param queryParams The query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param accept The request's Accept header + * @param contentType The request's Content-Type header + * @param authNames The authentications to apply + * @param returnType The return type into which to deserialize the response + * @return ResponseEntity<T> The response of the chosen type + */ + public ResponseEntity invokeAPI(String path, HttpMethod method, Map pathParams, MultiValueMap queryParams, Object body, HttpHeaders headerParams, MultiValueMap cookieParams, MultiValueMap formParams, List accept, MediaType contentType, String[] authNames, ParameterizedTypeReference returnType) throws RestClientException { + updateParamsForAuth(authNames, queryParams, headerParams, cookieParams); + + Map uriParams = new HashMap<>(); + uriParams.putAll(pathParams); + + String finalUri = path; + + if (queryParams != null && !queryParams.isEmpty()) { + //Include queryParams in uriParams taking into account the paramName + String queryUri = generateQueryUri(queryParams, uriParams); + //Append to finalUri the templatized query string like "?param1={param1Value}&....... + finalUri += "?" + queryUri; + } + String expandedPath = this.expandPath(finalUri, uriParams); + final UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(basePath).path(expandedPath); + + URI uri; + try { + uri = new URI(builder.build().toUriString()); + } catch (URISyntaxException ex) { + throw new RestClientException("Could not build URL: " + builder.toUriString(), ex); + } + + final BodyBuilder requestBuilder = RequestEntity.method(method, UriComponentsBuilder.fromHttpUrl(basePath).toUriString() + finalUri, uriParams); + if (accept != null) { + requestBuilder.accept(accept.toArray(new MediaType[accept.size()])); + } + if (contentType != null) { + requestBuilder.contentType(contentType); + } + + addHeadersToRequest(headerParams, requestBuilder); + addHeadersToRequest(defaultHeaders, requestBuilder); + addCookiesToRequest(cookieParams, requestBuilder); + addCookiesToRequest(defaultCookies, requestBuilder); + + RequestEntity requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); + + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } + + if (responseEntity.getStatusCode().is2xxSuccessful()) { + return responseEntity; + } else { + // The error handler built into the RestTemplate should handle 400 and 500 series errors. + throw new RestClientException("API returned " + responseEntity.getStatusCode() + " and it wasn't handled by the RestTemplate error handler"); + } + } + + /** + * Add headers to the request that is being built + * @param headers The headers to add + * @param requestBuilder The current request + */ + protected void addHeadersToRequest(HttpHeaders headers, BodyBuilder requestBuilder) { + for (Entry> entry : headers.entrySet()) { + List values = entry.getValue(); + for (String value : values) { + if (value != null) { + requestBuilder.header(entry.getKey(), value); + } + } + } + } + + /** + * Add cookies to the request that is being built + * + * @param cookies The cookies to add + * @param requestBuilder The current request + */ + protected void addCookiesToRequest(MultiValueMap cookies, BodyBuilder requestBuilder) { + if (!cookies.isEmpty()) { + requestBuilder.header("Cookie", buildCookieHeader(cookies)); + } + } + + /** + * Build cookie header. Keeps a single value per cookie (as per + * RFC6265 section 5.3). + * + * @param cookies map all cookies + * @return header string for cookies. + */ + private String buildCookieHeader(MultiValueMap cookies) { + final StringBuilder cookieValue = new StringBuilder(); + String delimiter = ""; + for (final Map.Entry> entry : cookies.entrySet()) { + final String value = entry.getValue().get(entry.getValue().size() - 1); + cookieValue.append(String.format("%s%s=%s", delimiter, entry.getKey(), value)); + delimiter = "; "; + } + return cookieValue.toString(); + } + + /** + * Build the RestTemplate used to make HTTP requests. + * @return RestTemplate + */ + protected RestTemplate buildRestTemplate() { + RestTemplate restTemplate = new RestTemplate(); + // This allows us to read the response more than once - Necessary for debugging. + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(restTemplate.getRequestFactory())); + + // disable default URL encoding + DefaultUriBuilderFactory uriBuilderFactory = new DefaultUriBuilderFactory(); + uriBuilderFactory.setEncodingMode(DefaultUriBuilderFactory.EncodingMode.VALUES_ONLY); + restTemplate.setUriTemplateHandler(uriBuilderFactory); + return restTemplate; + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams The query parameters + * @param headerParams The header parameters + */ + protected void updateParamsForAuth(String[] authNames, MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RestClientException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams); + } + } + + private class ApiClientHttpRequestInterceptor implements ClientHttpRequestInterceptor { + private final Log log = LogFactory.getLog(ApiClientHttpRequestInterceptor.class); + + @Override + public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException { + logRequest(request, body); + ClientHttpResponse response = execution.execute(request, body); + logResponse(response); + return response; + } + + private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEncodingException { + log.info("URI: " + request.getURI()); + log.info("HTTP Method: " + request.getMethod()); + log.info("HTTP Headers: " + headersToString(request.getHeaders())); + log.info("Request Body: " + new String(body, StandardCharsets.UTF_8)); + } + + private void logResponse(ClientHttpResponse response) throws IOException { + log.info("HTTP Status Code: " + response.getStatusCode().value()); + log.info("Status Text: " + response.getStatusText()); + log.info("HTTP Headers: " + headersToString(response.getHeaders())); + log.info("Response Body: " + bodyToString(response.getBody())); + } + + private String headersToString(HttpHeaders headers) { + if(headers == null || headers.isEmpty()) { + return ""; + } + StringBuilder builder = new StringBuilder(); + for (Entry> entry : headers.entrySet()) { + builder.append(entry.getKey()).append("=["); + for (String value : entry.getValue()) { + builder.append(value).append(","); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + builder.append("],"); + } + builder.setLength(builder.length() - 1); // Get rid of trailing comma + return builder.toString(); + } + + private String bodyToString(InputStream body) throws IOException { + StringBuilder builder = new StringBuilder(); + BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(body, StandardCharsets.UTF_8)); + String line = bufferedReader.readLine(); + while (line != null) { + builder.append(line).append(System.lineSeparator()); + line = bufferedReader.readLine(); + } + bufferedReader.close(); + return builder.toString(); + } + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/JavaTimeFormatter.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/JavaTimeFormatter.java new file mode 100644 index 000000000000..b51199a21b06 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/JavaTimeFormatter.java @@ -0,0 +1,64 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.time.format.DateTimeParseException; + +/** + * Class that add parsing/formatting support for Java 8+ {@code OffsetDateTime} class. + * It's generated for java clients when {@code AbstractJavaCodegen#dateLibrary} specified as {@code java8}. + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class JavaTimeFormatter { + + private DateTimeFormatter offsetDateTimeFormatter = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + + /** + * Get the date format used to parse/format {@code OffsetDateTime} parameters. + * @return DateTimeFormatter + */ + public DateTimeFormatter getOffsetDateTimeFormatter() { + return offsetDateTimeFormatter; + } + + /** + * Set the date format used to parse/format {@code OffsetDateTime} parameters. + * @param offsetDateTimeFormatter {@code DateTimeFormatter} + */ + public void setOffsetDateTimeFormatter(DateTimeFormatter offsetDateTimeFormatter) { + this.offsetDateTimeFormatter = offsetDateTimeFormatter; + } + + /** + * Parse the given string into {@code OffsetDateTime} object. + * @param str String + * @return {@code OffsetDateTime} + */ + public OffsetDateTime parseOffsetDateTime(String str) { + try { + return OffsetDateTime.parse(str, offsetDateTimeFormatter); + } catch (DateTimeParseException e) { + throw new RuntimeException(e); + } + } + /** + * Format the given {@code OffsetDateTime} object into string. + * @param offsetDateTime {@code OffsetDateTime} + * @return {@code OffsetDateTime} in string format + */ + public String formatOffsetDateTime(OffsetDateTime offsetDateTime) { + return offsetDateTimeFormatter.format(offsetDateTime); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java new file mode 100644 index 000000000000..22bbe68c49f4 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/RFC3339DateFormat.java @@ -0,0 +1,57 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client; + +import com.fasterxml.jackson.databind.util.StdDateFormat; + +import java.text.DateFormat; +import java.text.FieldPosition; +import java.text.ParsePosition; +import java.util.Date; +import java.text.DecimalFormat; +import java.util.GregorianCalendar; +import java.util.TimeZone; + +public class RFC3339DateFormat extends DateFormat { + private static final long serialVersionUID = 1L; + private static final TimeZone TIMEZONE_Z = TimeZone.getTimeZone("UTC"); + + private final StdDateFormat fmt = new StdDateFormat() + .withTimeZone(TIMEZONE_Z) + .withColonInTimeZone(true); + + public RFC3339DateFormat() { + this.calendar = new GregorianCalendar(); + this.numberFormat = new DecimalFormat(); + } + + @Override + public Date parse(String source) { + return parse(source, new ParsePosition(0)); + } + + @Override + public Date parse(String source, ParsePosition pos) { + return fmt.parse(source, pos); + } + + @Override + public StringBuffer format(Date date, StringBuffer toAppendTo, FieldPosition fieldPosition) { + return fmt.format(date, toAppendTo, fieldPosition); + } + + @Override + public Object clone() { + return super.clone(); + } +} \ No newline at end of file diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..59edc528a446 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..c2f13e216662 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/AuthApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/AuthApi.java new file mode 100644 index 000000000000..109f35c294aa --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/AuthApi.java @@ -0,0 +1,125 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AuthApi { + private ApiClient apiClient; + + public AuthApi() { + this(new ApiClient()); + } + + public AuthApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * To test HTTP basic authentication + * To test HTTP basic authentication + *

              200 - Successful operation + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testAuthHttpBasic() throws RestClientException { + return testAuthHttpBasicWithHttpInfo().getBody(); + } + + /** + * To test HTTP basic authentication + * To test HTTP basic authentication + *

              200 - Successful operation + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testAuthHttpBasicWithHttpInfo() throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_auth" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/auth/http/basic", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + *

              200 - Successful operation + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testAuthHttpBearer() throws RestClientException { + return testAuthHttpBearerWithHttpInfo().getBody(); + } + + /** + * To test HTTP bearer authentication + * To test HTTP bearer authentication + *

              200 - Successful operation + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testAuthHttpBearerWithHttpInfo() throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { "http_bearer_auth" }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/auth/http/bearer", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/BodyApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/BodyApi.java new file mode 100644 index 000000000000..572f8586b5cc --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/BodyApi.java @@ -0,0 +1,444 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + +import java.io.File; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class BodyApi { + private ApiClient apiClient; + + public BodyApi() { + this(new ApiClient()); + } + + public BodyApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test binary (gif) response body + * Test binary (gif) response body + *

              200 - Successful operation + * @return File + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public File testBinaryGif() throws RestClientException { + return testBinaryGifWithHttpInfo().getBody(); + } + + /** + * Test binary (gif) response body + * Test binary (gif) response body + *

              200 - Successful operation + * @return ResponseEntity<File> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testBinaryGifWithHttpInfo() throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "image/gif" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/binary/gif", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param body (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testBodyApplicationOctetstreamBinary(File body) throws RestClientException { + return testBodyApplicationOctetstreamBinaryWithHttpInfo(body).getBody(); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param body (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testBodyApplicationOctetstreamBinaryWithHttpInfo(File body) throws RestClientException { + Object localVarPostBody = body; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/octet-stream" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/body/application/octetstream/binary", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test array of binary in multipart mime + * Test array of binary in multipart mime + *

              200 - Successful operation + * @param files (required) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testBodyMultipartFormdataArrayOfBinary(List files) throws RestClientException { + return testBodyMultipartFormdataArrayOfBinaryWithHttpInfo(files).getBody(); + } + + /** + * Test array of binary in multipart mime + * Test array of binary in multipart mime + *

              200 - Successful operation + * @param files (required) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testBodyMultipartFormdataArrayOfBinaryWithHttpInfo(List files) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'files' is set + if (files == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'files' when calling testBodyMultipartFormdataArrayOfBinary"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + if (files != null) + localVarFormParams.addAll("files", files.stream().map(FileSystemResource::new).collect(Collectors.toList())); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/body/application/octetstream/array_of_binary", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + *

              200 - Successful operation + * @param myFile (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testBodyMultipartFormdataSingleBinary(File myFile) throws RestClientException { + return testBodyMultipartFormdataSingleBinaryWithHttpInfo(myFile).getBody(); + } + + /** + * Test single binary in multipart mime + * Test single binary in multipart mime + *

              200 - Successful operation + * @param myFile (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testBodyMultipartFormdataSingleBinaryWithHttpInfo(File myFile) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + if (myFile != null) + localVarFormParams.add("my-file", new FileSystemResource(myFile)); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "multipart/form-data" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/body/application/octetstream/single_binary", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet testEchoBodyAllOfPet(Pet pet) throws RestClientException { + return testEchoBodyAllOfPetWithHttpInfo(pet).getBody(); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return ResponseEntity<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEchoBodyAllOfPetWithHttpInfo(Pet pet) throws RestClientException { + Object localVarPostBody = pet; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/echo/body/allOf/Pet", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test free form object + * Test free form object + *

              200 - Successful operation + * @param body Free form object (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testEchoBodyFreeFormObjectResponseString(Object body) throws RestClientException { + return testEchoBodyFreeFormObjectResponseStringWithHttpInfo(body).getBody(); + } + + /** + * Test free form object + * Test free form object + *

              200 - Successful operation + * @param body Free form object (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEchoBodyFreeFormObjectResponseStringWithHttpInfo(Object body) throws RestClientException { + Object localVarPostBody = body; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/echo/body/FreeFormObject/response_string", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return Pet + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public Pet testEchoBodyPet(Pet pet) throws RestClientException { + return testEchoBodyPetWithHttpInfo(pet).getBody(); + } + + /** + * Test body parameter(s) + * Test body parameter(s) + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return ResponseEntity<Pet> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEchoBodyPetWithHttpInfo(Pet pet) throws RestClientException { + Object localVarPostBody = pet; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "application/json" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/echo/body/Pet", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test empty response body + * Test empty response body + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testEchoBodyPetResponseString(Pet pet) throws RestClientException { + return testEchoBodyPetResponseStringWithHttpInfo(pet).getBody(); + } + + /** + * Test empty response body + * Test empty response body + *

              200 - Successful operation + * @param pet Pet object that needs to be added to the store (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEchoBodyPetResponseStringWithHttpInfo(Pet pet) throws RestClientException { + Object localVarPostBody = pet; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/echo/body/Pet/response_string", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test empty json (request body) + * Test empty json (request body) + *

              200 - Successful operation + * @param tag Tag object (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testEchoBodyTagResponseString(Tag tag) throws RestClientException { + return testEchoBodyTagResponseStringWithHttpInfo(tag).getBody(); + } + + /** + * Test empty json (request body) + * Test empty json (request body) + *

              200 - Successful operation + * @param tag Tag object (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEchoBodyTagResponseStringWithHttpInfo(Tag tag) throws RestClientException { + Object localVarPostBody = tag; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/echo/body/Tag/response_string", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/FormApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/FormApi.java new file mode 100644 index 000000000000..9befcecfbaf6 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/FormApi.java @@ -0,0 +1,167 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class FormApi { + private ApiClient apiClient; + + public FormApi() { + this(new ApiClient()); + } + + public FormApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test form parameter(s) + * Test form parameter(s) + *

              200 - Successful operation + * @param integerForm (optional) + * @param booleanForm (optional) + * @param stringForm (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testFormIntegerBooleanString(Integer integerForm, Boolean booleanForm, String stringForm) throws RestClientException { + return testFormIntegerBooleanStringWithHttpInfo(integerForm, booleanForm, stringForm).getBody(); + } + + /** + * Test form parameter(s) + * Test form parameter(s) + *

              200 - Successful operation + * @param integerForm (optional) + * @param booleanForm (optional) + * @param stringForm (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testFormIntegerBooleanStringWithHttpInfo(Integer integerForm, Boolean booleanForm, String stringForm) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + if (integerForm != null) + localVarFormParams.add("integer_form", integerForm); + if (booleanForm != null) + localVarFormParams.add("boolean_form", booleanForm); + if (stringForm != null) + localVarFormParams.add("string_form", stringForm); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/form/integer/boolean/string", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test form parameter(s) for oneOf schema + * Test form parameter(s) for oneOf schema + *

              200 - Successful operation + * @param form1 (optional) + * @param form2 (optional) + * @param form3 (optional) + * @param form4 (optional) + * @param id (optional) + * @param name (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testFormOneof(String form1, Integer form2, String form3, Boolean form4, Long id, String name) throws RestClientException { + return testFormOneofWithHttpInfo(form1, form2, form3, form4, id, name).getBody(); + } + + /** + * Test form parameter(s) for oneOf schema + * Test form parameter(s) for oneOf schema + *

              200 - Successful operation + * @param form1 (optional) + * @param form2 (optional) + * @param form3 (optional) + * @param form4 (optional) + * @param id (optional) + * @param name (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testFormOneofWithHttpInfo(String form1, Integer form2, String form3, Boolean form4, Long id, String name) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + if (form1 != null) + localVarFormParams.add("form1", form1); + if (form2 != null) + localVarFormParams.add("form2", form2); + if (form3 != null) + localVarFormParams.add("form3", form3); + if (form4 != null) + localVarFormParams.add("form4", form4); + if (id != null) + localVarFormParams.add("id", id); + if (name != null) + localVarFormParams.add("name", name); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/x-www-form-urlencoded" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/form/oneof", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/HeaderApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/HeaderApi.java new file mode 100644 index 000000000000..121f8875a722 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/HeaderApi.java @@ -0,0 +1,108 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.StringEnumRef; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HeaderApi { + private ApiClient apiClient; + + public HeaderApi() { + this(new ApiClient()); + } + + public HeaderApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test header parameter(s) + * Test header parameter(s) + *

              200 - Successful operation + * @param integerHeader (optional) + * @param booleanHeader (optional) + * @param stringHeader (optional) + * @param enumNonrefStringHeader (optional) + * @param enumRefStringHeader (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testHeaderIntegerBooleanStringEnums(Integer integerHeader, Boolean booleanHeader, String stringHeader, String enumNonrefStringHeader, StringEnumRef enumRefStringHeader) throws RestClientException { + return testHeaderIntegerBooleanStringEnumsWithHttpInfo(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader).getBody(); + } + + /** + * Test header parameter(s) + * Test header parameter(s) + *

              200 - Successful operation + * @param integerHeader (optional) + * @param booleanHeader (optional) + * @param stringHeader (optional) + * @param enumNonrefStringHeader (optional) + * @param enumRefStringHeader (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testHeaderIntegerBooleanStringEnumsWithHttpInfo(Integer integerHeader, Boolean booleanHeader, String stringHeader, String enumNonrefStringHeader, StringEnumRef enumRefStringHeader) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + if (integerHeader != null) + localVarHeaderParams.add("integer_header", apiClient.parameterToString(integerHeader)); + if (booleanHeader != null) + localVarHeaderParams.add("boolean_header", apiClient.parameterToString(booleanHeader)); + if (stringHeader != null) + localVarHeaderParams.add("string_header", apiClient.parameterToString(stringHeader)); + if (enumNonrefStringHeader != null) + localVarHeaderParams.add("enum_nonref_string_header", apiClient.parameterToString(enumNonrefStringHeader)); + if (enumRefStringHeader != null) + localVarHeaderParams.add("enum_ref_string_header", apiClient.parameterToString(enumRefStringHeader)); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/header/integer/boolean/string/enums", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/PathApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/PathApi.java new file mode 100644 index 000000000000..764808413412 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/PathApi.java @@ -0,0 +1,121 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.StringEnumRef; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class PathApi { + private ApiClient apiClient; + + public PathApi() { + this(new ApiClient()); + } + + public PathApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test path parameter(s) + * Test path parameter(s) + *

              200 - Successful operation + * @param pathString (required) + * @param pathInteger (required) + * @param enumNonrefStringPath (required) + * @param enumRefStringPath (required) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(String pathString, Integer pathInteger, String enumNonrefStringPath, StringEnumRef enumRefStringPath) throws RestClientException { + return testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathWithHttpInfo(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath).getBody(); + } + + /** + * Test path parameter(s) + * Test path parameter(s) + *

              200 - Successful operation + * @param pathString (required) + * @param pathInteger (required) + * @param enumNonrefStringPath (required) + * @param enumRefStringPath (required) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathWithHttpInfo(String pathString, Integer pathInteger, String enumNonrefStringPath, StringEnumRef enumRefStringPath) throws RestClientException { + Object localVarPostBody = null; + + // verify the required parameter 'pathString' is set + if (pathString == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'pathString' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'pathInteger' is set + if (pathInteger == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'pathInteger' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'enumNonrefStringPath' is set + if (enumNonrefStringPath == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'enumNonrefStringPath' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // verify the required parameter 'enumRefStringPath' is set + if (enumRefStringPath == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'enumRefStringPath' when calling testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath"); + } + + // create path and map variables + final Map uriVariables = new HashMap(); + uriVariables.put("path_string", pathString); + uriVariables.put("path_integer", pathInteger); + uriVariables.put("enum_nonref_string_path", enumNonrefStringPath); + uriVariables.put("enum_ref_string_path", enumRefStringPath); + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}", HttpMethod.GET, uriVariables, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/QueryApi.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/QueryApi.java new file mode 100644 index 000000000000..d30cd1b058e4 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/api/QueryApi.java @@ -0,0 +1,437 @@ +package org.openapitools.client.api; + +import org.openapitools.client.ApiClient; + +import org.openapitools.client.model.DataQuery; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.client.model.TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter; +import org.openapitools.client.model.TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter; + +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.stream.Collectors; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import org.springframework.util.LinkedMultiValueMap; +import org.springframework.util.MultiValueMap; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.core.io.FileSystemResource; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class QueryApi { + private ApiClient apiClient; + + public QueryApi() { + this(new ApiClient()); + } + + public QueryApi(ApiClient apiClient) { + this.apiClient = apiClient; + } + + public ApiClient getApiClient() { + return apiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.apiClient = apiClient; + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param enumNonrefStringQuery (optional) + * @param enumRefStringQuery (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testEnumRefString(String enumNonrefStringQuery, StringEnumRef enumRefStringQuery) throws RestClientException { + return testEnumRefStringWithHttpInfo(enumNonrefStringQuery, enumRefStringQuery).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param enumNonrefStringQuery (optional) + * @param enumRefStringQuery (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testEnumRefStringWithHttpInfo(String enumNonrefStringQuery, StringEnumRef enumRefStringQuery) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_nonref_string_query", enumNonrefStringQuery)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_ref_string_query", enumRefStringQuery)); + + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/enum_ref_string", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param datetimeQuery (optional) + * @param dateQuery (optional) + * @param stringQuery (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryDatetimeDateString(OffsetDateTime datetimeQuery, LocalDate dateQuery, String stringQuery) throws RestClientException { + return testQueryDatetimeDateStringWithHttpInfo(datetimeQuery, dateQuery, stringQuery).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param datetimeQuery (optional) + * @param dateQuery (optional) + * @param stringQuery (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryDatetimeDateStringWithHttpInfo(OffsetDateTime datetimeQuery, LocalDate dateQuery, String stringQuery) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "datetime_query", datetimeQuery)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "date_query", dateQuery)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_query", stringQuery)); + + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/datetime/date/string", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param integerQuery (optional) + * @param booleanQuery (optional) + * @param stringQuery (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryIntegerBooleanString(Integer integerQuery, Boolean booleanQuery, String stringQuery) throws RestClientException { + return testQueryIntegerBooleanStringWithHttpInfo(integerQuery, booleanQuery, stringQuery).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param integerQuery (optional) + * @param booleanQuery (optional) + * @param stringQuery (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryIntegerBooleanStringWithHttpInfo(Integer integerQuery, Boolean booleanQuery, String stringQuery) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "integer_query", integerQuery)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "boolean_query", booleanQuery)); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_query", stringQuery)); + + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/integer/boolean/string", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryStyleDeepObjectExplodeTrueObject(Pet queryObject) throws RestClientException { + return testQueryStyleDeepObjectExplodeTrueObjectWithHttpInfo(queryObject).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryStyleDeepObjectExplodeTrueObjectWithHttpInfo(Pet queryObject) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + + if (queryObject != null) { + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "id", queryObject.getId())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", queryObject.getName())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "category", queryObject.getCategory())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "photoUrls", queryObject.getPhotoUrls())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "tags", queryObject.getTags())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "status", queryObject.getStatus())); + } + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/style_deepObject/explode_true/object", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryStyleDeepObjectExplodeTrueObjectAllOf(TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject) throws RestClientException { + return testQueryStyleDeepObjectExplodeTrueObjectAllOfWithHttpInfo(queryObject).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryStyleDeepObjectExplodeTrueObjectAllOfWithHttpInfo(TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_object", queryObject)); + + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/style_deepObject/explode_true/object/allOf", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryStyleFormExplodeTrueArrayString(TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject) throws RestClientException { + return testQueryStyleFormExplodeTrueArrayStringWithHttpInfo(queryObject).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryStyleFormExplodeTrueArrayStringWithHttpInfo(TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + + if (queryObject != null) { + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "values", queryObject.getValues())); + } + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/style_form/explode_true/array_string", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryStyleFormExplodeTrueObject(Pet queryObject) throws RestClientException { + return testQueryStyleFormExplodeTrueObjectWithHttpInfo(queryObject).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryStyleFormExplodeTrueObjectWithHttpInfo(Pet queryObject) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + + if (queryObject != null) { + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "id", queryObject.getId())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "name", queryObject.getName())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "category", queryObject.getCategory())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "photoUrls", queryObject.getPhotoUrls())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "tags", queryObject.getTags())); + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "status", queryObject.getStatus())); + } + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/style_form/explode_true/object", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return String + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public String testQueryStyleFormExplodeTrueObjectAllOf(DataQuery queryObject) throws RestClientException { + return testQueryStyleFormExplodeTrueObjectAllOfWithHttpInfo(queryObject).getBody(); + } + + /** + * Test query parameter(s) + * Test query parameter(s) + *

              200 - Successful operation + * @param queryObject (optional) + * @return ResponseEntity<String> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testQueryStyleFormExplodeTrueObjectAllOfWithHttpInfo(DataQuery queryObject) throws RestClientException { + Object localVarPostBody = null; + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_object", queryObject)); + + + final String[] localVarAccepts = { + "text/plain" + }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/query/style_form/explode_true/object/allOf", HttpMethod.GET, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..9e9f3733160e --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,62 @@ +package org.openapitools.client.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if (location.equals("query")) { + queryParams.add(paramName, value); + } else if (location.equals("header")) { + headerParams.add(paramName, value); + } else if (location.equals("cookie")) { + cookieParams.add(paramName, value); + } + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..4f9a14ebd7c3 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,14 @@ +package org.openapitools.client.auth; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +public interface Authentication { + /** + * Apply authentication settings to header and / or query parameters. + * @param queryParams The query parameters for the request + * @param headerParams The header parameters for the request + * @param cookieParams The cookie parameters for the request + */ + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams); +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..81de07ee04f5 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,38 @@ +package org.openapitools.client.auth; + +import java.nio.charset.StandardCharsets; +import java.util.Base64; + +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + if (username == null && password == null) { + return; + } + String str = (username == null ? "" : username) + ":" + (password == null ? "" : password); + headerParams.add(HttpHeaders.AUTHORIZATION, "Basic " + Base64.getEncoder().encodeToString(str.getBytes(StandardCharsets.UTF_8))); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..4678c06efd7c --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,56 @@ +package org.openapitools.client.auth; + +import java.util.Optional; +import java.util.function.Supplier; +import org.springframework.http.HttpHeaders; +import org.springframework.util.MultiValueMap; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(MultiValueMap queryParams, HttpHeaders headerParams, MultiValueMap cookieParams) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + headerParams.add(HttpHeaders.AUTHORIZATION, (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Bird.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Bird.java new file mode 100644 index 000000000000..1e3195e9bdda --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Bird.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Bird + */ +@JsonPropertyOrder({ + Bird.JSON_PROPERTY_SIZE, + Bird.JSON_PROPERTY_COLOR +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Bird { + public static final String JSON_PROPERTY_SIZE = "size"; + private String size; + + public static final String JSON_PROPERTY_COLOR = "color"; + private String color; + + public Bird() { + } + + public Bird size(String size) { + + this.size = size; + return this; + } + + /** + * Get size + * @return size + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSize() { + return size; + } + + + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSize(String size) { + this.size = size; + } + + + public Bird color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getColor() { + return color; + } + + + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setColor(String color) { + this.color = color; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Bird bird = (Bird) o; + return Objects.equals(this.size, bird.size) && + Objects.equals(this.color, bird.color); + } + + @Override + public int hashCode() { + return Objects.hash(size, color); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Bird {\n"); + sb.append(" size: ").append(toIndentedString(size)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 000000000000..29d956d6cb75 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Category + */ +@JsonPropertyOrder({ + Category.JSON_PROPERTY_ID, + Category.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Category { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public Category() { + } + + public Category id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Category name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DataQuery.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DataQuery.java new file mode 100644 index 000000000000..5f1c039d516a --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DataQuery.java @@ -0,0 +1,187 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Query; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * DataQuery + */ +@JsonPropertyOrder({ + DataQuery.JSON_PROPERTY_SUFFIX, + DataQuery.JSON_PROPERTY_TEXT, + DataQuery.JSON_PROPERTY_DATE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DataQuery extends Query { + public static final String JSON_PROPERTY_SUFFIX = "suffix"; + private String suffix; + + public static final String JSON_PROPERTY_TEXT = "text"; + private String text; + + public static final String JSON_PROPERTY_DATE = "date"; + private OffsetDateTime date; + + public DataQuery() { + + } + + public DataQuery suffix(String suffix) { + + this.suffix = suffix; + return this; + } + + /** + * test suffix + * @return suffix + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SUFFIX) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSuffix() { + return suffix; + } + + + @JsonProperty(JSON_PROPERTY_SUFFIX) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSuffix(String suffix) { + this.suffix = suffix; + } + + + public DataQuery text(String text) { + + this.text = text; + return this; + } + + /** + * Some text containing white spaces + * @return text + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TEXT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getText() { + return text; + } + + + @JsonProperty(JSON_PROPERTY_TEXT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setText(String text) { + this.text = text; + } + + + public DataQuery date(OffsetDateTime date) { + + this.date = date; + return this; + } + + /** + * A date + * @return date + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public OffsetDateTime getDate() { + return date; + } + + + @JsonProperty(JSON_PROPERTY_DATE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDate(OffsetDateTime date) { + this.date = date; + } + + @Override + public DataQuery id(Long id) { + this.setId(id); + return this; + } + + @Override + public DataQuery outcomes(List outcomes) { + this.setOutcomes(outcomes); + return this; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DataQuery dataQuery = (DataQuery) o; + return Objects.equals(this.suffix, dataQuery.suffix) && + Objects.equals(this.text, dataQuery.text) && + Objects.equals(this.date, dataQuery.date) && + super.equals(o); + } + + @Override + public int hashCode() { + return Objects.hash(suffix, text, date, super.hashCode()); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DataQuery {\n"); + sb.append(" ").append(toIndentedString(super.toString())).append("\n"); + sb.append(" suffix: ").append(toIndentedString(suffix)).append("\n"); + sb.append(" text: ").append(toIndentedString(text)).append("\n"); + sb.append(" date: ").append(toIndentedString(date)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DefaultValue.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DefaultValue.java new file mode 100644 index 000000000000..1365a5fcb045 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/DefaultValue.java @@ -0,0 +1,471 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * to test the default value of properties + */ +@JsonPropertyOrder({ + DefaultValue.JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_INTEGER_DEFAULT, + DefaultValue.JSON_PROPERTY_ARRAY_STRING, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_NULLABLE, + DefaultValue.JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE, + DefaultValue.JSON_PROPERTY_STRING_NULLABLE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class DefaultValue { + public static final String JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT = "array_string_enum_ref_default"; + private List arrayStringEnumRefDefault = new ArrayList<>(Arrays.asList(StringEnumRef.SUCCESS, StringEnumRef.FAILURE)); + + /** + * Gets or Sets arrayStringEnumDefault + */ + public enum ArrayStringEnumDefaultEnum { + SUCCESS("success"), + + FAILURE("failure"), + + UNCLASSIFIED("unclassified"); + + private String value; + + ArrayStringEnumDefaultEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static ArrayStringEnumDefaultEnum fromValue(String value) { + for (ArrayStringEnumDefaultEnum b : ArrayStringEnumDefaultEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT = "array_string_enum_default"; + private List arrayStringEnumDefault = new ArrayList<>(Arrays.asList(ArrayStringEnumDefaultEnum.SUCCESS, ArrayStringEnumDefaultEnum.FAILURE)); + + public static final String JSON_PROPERTY_ARRAY_STRING_DEFAULT = "array_string_default"; + private List arrayStringDefault = new ArrayList<>(Arrays.asList("failure", "skipped")); + + public static final String JSON_PROPERTY_ARRAY_INTEGER_DEFAULT = "array_integer_default"; + private List arrayIntegerDefault = new ArrayList<>(Arrays.asList(1, 3)); + + public static final String JSON_PROPERTY_ARRAY_STRING = "array_string"; + private List arrayString; + + public static final String JSON_PROPERTY_ARRAY_STRING_NULLABLE = "array_string_nullable"; + private JsonNullable> arrayStringNullable = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE = "array_string_extension_nullable"; + private JsonNullable> arrayStringExtensionNullable = JsonNullable.>undefined(); + + public static final String JSON_PROPERTY_STRING_NULLABLE = "string_nullable"; + private JsonNullable stringNullable = JsonNullable.undefined(); + + public DefaultValue() { + } + + public DefaultValue arrayStringEnumRefDefault(List arrayStringEnumRefDefault) { + + this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; + return this; + } + + public DefaultValue addArrayStringEnumRefDefaultItem(StringEnumRef arrayStringEnumRefDefaultItem) { + if (this.arrayStringEnumRefDefault == null) { + this.arrayStringEnumRefDefault = new ArrayList<>(Arrays.asList(StringEnumRef.SUCCESS, StringEnumRef.FAILURE)); + } + this.arrayStringEnumRefDefault.add(arrayStringEnumRefDefaultItem); + return this; + } + + /** + * Get arrayStringEnumRefDefault + * @return arrayStringEnumRefDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringEnumRefDefault() { + return arrayStringEnumRefDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_REF_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringEnumRefDefault(List arrayStringEnumRefDefault) { + this.arrayStringEnumRefDefault = arrayStringEnumRefDefault; + } + + + public DefaultValue arrayStringEnumDefault(List arrayStringEnumDefault) { + + this.arrayStringEnumDefault = arrayStringEnumDefault; + return this; + } + + public DefaultValue addArrayStringEnumDefaultItem(ArrayStringEnumDefaultEnum arrayStringEnumDefaultItem) { + if (this.arrayStringEnumDefault == null) { + this.arrayStringEnumDefault = new ArrayList<>(Arrays.asList(ArrayStringEnumDefaultEnum.SUCCESS, ArrayStringEnumDefaultEnum.FAILURE)); + } + this.arrayStringEnumDefault.add(arrayStringEnumDefaultItem); + return this; + } + + /** + * Get arrayStringEnumDefault + * @return arrayStringEnumDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringEnumDefault() { + return arrayStringEnumDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_ENUM_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringEnumDefault(List arrayStringEnumDefault) { + this.arrayStringEnumDefault = arrayStringEnumDefault; + } + + + public DefaultValue arrayStringDefault(List arrayStringDefault) { + + this.arrayStringDefault = arrayStringDefault; + return this; + } + + public DefaultValue addArrayStringDefaultItem(String arrayStringDefaultItem) { + if (this.arrayStringDefault == null) { + this.arrayStringDefault = new ArrayList<>(Arrays.asList("failure", "skipped")); + } + this.arrayStringDefault.add(arrayStringDefaultItem); + return this; + } + + /** + * Get arrayStringDefault + * @return arrayStringDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayStringDefault() { + return arrayStringDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayStringDefault(List arrayStringDefault) { + this.arrayStringDefault = arrayStringDefault; + } + + + public DefaultValue arrayIntegerDefault(List arrayIntegerDefault) { + + this.arrayIntegerDefault = arrayIntegerDefault; + return this; + } + + public DefaultValue addArrayIntegerDefaultItem(Integer arrayIntegerDefaultItem) { + if (this.arrayIntegerDefault == null) { + this.arrayIntegerDefault = new ArrayList<>(Arrays.asList(1, 3)); + } + this.arrayIntegerDefault.add(arrayIntegerDefaultItem); + return this; + } + + /** + * Get arrayIntegerDefault + * @return arrayIntegerDefault + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_INTEGER_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayIntegerDefault() { + return arrayIntegerDefault; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_INTEGER_DEFAULT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayIntegerDefault(List arrayIntegerDefault) { + this.arrayIntegerDefault = arrayIntegerDefault; + } + + + public DefaultValue arrayString(List arrayString) { + + this.arrayString = arrayString; + return this; + } + + public DefaultValue addArrayStringItem(String arrayStringItem) { + if (this.arrayString == null) { + this.arrayString = new ArrayList<>(); + } + this.arrayString.add(arrayStringItem); + return this; + } + + /** + * Get arrayString + * @return arrayString + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ARRAY_STRING) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getArrayString() { + return arrayString; + } + + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setArrayString(List arrayString) { + this.arrayString = arrayString; + } + + + public DefaultValue arrayStringNullable(List arrayStringNullable) { + this.arrayStringNullable = JsonNullable.>of(arrayStringNullable); + + return this; + } + + public DefaultValue addArrayStringNullableItem(String arrayStringNullableItem) { + if (this.arrayStringNullable == null || !this.arrayStringNullable.isPresent()) { + this.arrayStringNullable = JsonNullable.>of(new ArrayList<>()); + } + try { + this.arrayStringNullable.get().add(arrayStringNullableItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get arrayStringNullable + * @return arrayStringNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public List getArrayStringNullable() { + return arrayStringNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable> getArrayStringNullable_JsonNullable() { + return arrayStringNullable; + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_NULLABLE) + public void setArrayStringNullable_JsonNullable(JsonNullable> arrayStringNullable) { + this.arrayStringNullable = arrayStringNullable; + } + + public void setArrayStringNullable(List arrayStringNullable) { + this.arrayStringNullable = JsonNullable.>of(arrayStringNullable); + } + + + public DefaultValue arrayStringExtensionNullable(List arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = JsonNullable.>of(arrayStringExtensionNullable); + + return this; + } + + public DefaultValue addArrayStringExtensionNullableItem(String arrayStringExtensionNullableItem) { + if (this.arrayStringExtensionNullable == null || !this.arrayStringExtensionNullable.isPresent()) { + this.arrayStringExtensionNullable = JsonNullable.>of(new ArrayList<>()); + } + try { + this.arrayStringExtensionNullable.get().add(arrayStringExtensionNullableItem); + } catch (java.util.NoSuchElementException e) { + // this can never happen, as we make sure above that the value is present + } + return this; + } + + /** + * Get arrayStringExtensionNullable + * @return arrayStringExtensionNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public List getArrayStringExtensionNullable() { + return arrayStringExtensionNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable> getArrayStringExtensionNullable_JsonNullable() { + return arrayStringExtensionNullable; + } + + @JsonProperty(JSON_PROPERTY_ARRAY_STRING_EXTENSION_NULLABLE) + public void setArrayStringExtensionNullable_JsonNullable(JsonNullable> arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = arrayStringExtensionNullable; + } + + public void setArrayStringExtensionNullable(List arrayStringExtensionNullable) { + this.arrayStringExtensionNullable = JsonNullable.>of(arrayStringExtensionNullable); + } + + + public DefaultValue stringNullable(String stringNullable) { + this.stringNullable = JsonNullable.of(stringNullable); + + return this; + } + + /** + * Get stringNullable + * @return stringNullable + **/ + @javax.annotation.Nullable + @JsonIgnore + + public String getStringNullable() { + return stringNullable.orElse(null); + } + + @JsonProperty(JSON_PROPERTY_STRING_NULLABLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public JsonNullable getStringNullable_JsonNullable() { + return stringNullable; + } + + @JsonProperty(JSON_PROPERTY_STRING_NULLABLE) + public void setStringNullable_JsonNullable(JsonNullable stringNullable) { + this.stringNullable = stringNullable; + } + + public void setStringNullable(String stringNullable) { + this.stringNullable = JsonNullable.of(stringNullable); + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + DefaultValue defaultValue = (DefaultValue) o; + return Objects.equals(this.arrayStringEnumRefDefault, defaultValue.arrayStringEnumRefDefault) && + Objects.equals(this.arrayStringEnumDefault, defaultValue.arrayStringEnumDefault) && + Objects.equals(this.arrayStringDefault, defaultValue.arrayStringDefault) && + Objects.equals(this.arrayIntegerDefault, defaultValue.arrayIntegerDefault) && + Objects.equals(this.arrayString, defaultValue.arrayString) && + equalsNullable(this.arrayStringNullable, defaultValue.arrayStringNullable) && + equalsNullable(this.arrayStringExtensionNullable, defaultValue.arrayStringExtensionNullable) && + equalsNullable(this.stringNullable, defaultValue.stringNullable); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(arrayStringEnumRefDefault, arrayStringEnumDefault, arrayStringDefault, arrayIntegerDefault, arrayString, hashCodeNullable(arrayStringNullable), hashCodeNullable(arrayStringExtensionNullable), hashCodeNullable(stringNullable)); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class DefaultValue {\n"); + sb.append(" arrayStringEnumRefDefault: ").append(toIndentedString(arrayStringEnumRefDefault)).append("\n"); + sb.append(" arrayStringEnumDefault: ").append(toIndentedString(arrayStringEnumDefault)).append("\n"); + sb.append(" arrayStringDefault: ").append(toIndentedString(arrayStringDefault)).append("\n"); + sb.append(" arrayIntegerDefault: ").append(toIndentedString(arrayIntegerDefault)).append("\n"); + sb.append(" arrayString: ").append(toIndentedString(arrayString)).append("\n"); + sb.append(" arrayStringNullable: ").append(toIndentedString(arrayStringNullable)).append("\n"); + sb.append(" arrayStringExtensionNullable: ").append(toIndentedString(arrayStringExtensionNullable)).append("\n"); + sb.append(" stringNullable: ").append(toIndentedString(stringNullable)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java new file mode 100644 index 000000000000..96de851944c1 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/NumberPropertiesOnly.java @@ -0,0 +1,170 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * NumberPropertiesOnly + */ +@JsonPropertyOrder({ + NumberPropertiesOnly.JSON_PROPERTY_NUMBER, + NumberPropertiesOnly.JSON_PROPERTY_FLOAT, + NumberPropertiesOnly.JSON_PROPERTY_DOUBLE +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class NumberPropertiesOnly { + public static final String JSON_PROPERTY_NUMBER = "number"; + private BigDecimal number; + + public static final String JSON_PROPERTY_FLOAT = "float"; + private Float _float; + + public static final String JSON_PROPERTY_DOUBLE = "double"; + private Double _double; + + public NumberPropertiesOnly() { + } + + public NumberPropertiesOnly number(BigDecimal number) { + + this.number = number; + return this; + } + + /** + * Get number + * @return number + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NUMBER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public BigDecimal getNumber() { + return number; + } + + + @JsonProperty(JSON_PROPERTY_NUMBER) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setNumber(BigDecimal number) { + this.number = number; + } + + + public NumberPropertiesOnly _float(Float _float) { + + this._float = _float; + return this; + } + + /** + * Get _float + * @return _float + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_FLOAT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Float getFloat() { + return _float; + } + + + @JsonProperty(JSON_PROPERTY_FLOAT) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setFloat(Float _float) { + this._float = _float; + } + + + public NumberPropertiesOnly _double(Double _double) { + + this._double = _double; + return this; + } + + /** + * Get _double + * minimum: 0.8 + * maximum: 50.2 + * @return _double + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_DOUBLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Double getDouble() { + return _double; + } + + + @JsonProperty(JSON_PROPERTY_DOUBLE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setDouble(Double _double) { + this._double = _double; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberPropertiesOnly numberPropertiesOnly = (NumberPropertiesOnly) o; + return Objects.equals(this.number, numberPropertiesOnly.number) && + Objects.equals(this._float, numberPropertiesOnly._float) && + Objects.equals(this._double, numberPropertiesOnly._double); + } + + @Override + public int hashCode() { + return Objects.hash(number, _float, _double); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class NumberPropertiesOnly {\n"); + sb.append(" number: ").append(toIndentedString(number)).append("\n"); + sb.append(" _float: ").append(toIndentedString(_float)).append("\n"); + sb.append(" _double: ").append(toIndentedString(_double)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 000000000000..35aa2634a420 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,321 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Pet + */ +@JsonPropertyOrder({ + Pet.JSON_PROPERTY_ID, + Pet.JSON_PROPERTY_NAME, + Pet.JSON_PROPERTY_CATEGORY, + Pet.JSON_PROPERTY_PHOTO_URLS, + Pet.JSON_PROPERTY_TAGS, + Pet.JSON_PROPERTY_STATUS +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pet { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public static final String JSON_PROPERTY_CATEGORY = "category"; + private Category category; + + public static final String JSON_PROPERTY_PHOTO_URLS = "photoUrls"; + private List photoUrls; + + public static final String JSON_PROPERTY_TAGS = "tags"; + private List tags; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_STATUS = "status"; + private StatusEnum status; + + public Pet() { + } + + public Pet id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Pet name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setName(String name) { + this.name = name; + } + + + public Pet category(Category category) { + + this.category = category; + return this; + } + + /** + * Get category + * @return category + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Category getCategory() { + return category; + } + + + @JsonProperty(JSON_PROPERTY_CATEGORY) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setCategory(Category category) { + this.category = category; + } + + + public Pet photoUrls(List photoUrls) { + + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + @javax.annotation.Nonnull + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + + public List getPhotoUrls() { + return photoUrls; + } + + + @JsonProperty(JSON_PROPERTY_PHOTO_URLS) + @JsonInclude(value = JsonInclude.Include.ALWAYS) + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + + public Pet tags(List tags) { + + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getTags() { + return tags; + } + + + @JsonProperty(JSON_PROPERTY_TAGS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setTags(List tags) { + this.tags = tags; + } + + + public Pet status(StatusEnum status) { + + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public StatusEnum getStatus() { + return status; + } + + + @JsonProperty(JSON_PROPERTY_STATUS) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, category, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Query.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Query.java new file mode 100644 index 000000000000..5e110710d726 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Query.java @@ -0,0 +1,183 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Query + */ +@JsonPropertyOrder({ + Query.JSON_PROPERTY_ID, + Query.JSON_PROPERTY_OUTCOMES +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Query { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + /** + * Gets or Sets outcomes + */ + public enum OutcomesEnum { + SUCCESS("SUCCESS"), + + FAILURE("FAILURE"), + + SKIPPED("SKIPPED"); + + private String value; + + OutcomesEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static OutcomesEnum fromValue(String value) { + for (OutcomesEnum b : OutcomesEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + public static final String JSON_PROPERTY_OUTCOMES = "outcomes"; + private List outcomes = new ArrayList<>(Arrays.asList(OutcomesEnum.SUCCESS, OutcomesEnum.FAILURE)); + + public Query() { + } + + public Query id(Long id) { + + this.id = id; + return this; + } + + /** + * Query + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Query outcomes(List outcomes) { + + this.outcomes = outcomes; + return this; + } + + public Query addOutcomesItem(OutcomesEnum outcomesItem) { + if (this.outcomes == null) { + this.outcomes = new ArrayList<>(Arrays.asList(OutcomesEnum.SUCCESS, OutcomesEnum.FAILURE)); + } + this.outcomes.add(outcomesItem); + return this; + } + + /** + * Get outcomes + * @return outcomes + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_OUTCOMES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getOutcomes() { + return outcomes; + } + + + @JsonProperty(JSON_PROPERTY_OUTCOMES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setOutcomes(List outcomes) { + this.outcomes = outcomes; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Query query = (Query) o; + return Objects.equals(this.id, query.id) && + Objects.equals(this.outcomes, query.outcomes); + } + + @Override + public int hashCode() { + return Objects.hash(id, outcomes); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Query {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" outcomes: ").append(toIndentedString(outcomes)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/StringEnumRef.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/StringEnumRef.java new file mode 100644 index 000000000000..6e706b20d44c --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/StringEnumRef.java @@ -0,0 +1,61 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; + +/** + * Gets or Sets StringEnumRef + */ +public enum StringEnumRef { + + SUCCESS("success"), + + FAILURE("failure"), + + UNCLASSIFIED("unclassified"); + + private String value; + + StringEnumRef(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StringEnumRef fromValue(String value) { + for (StringEnumRef b : StringEnumRef.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 000000000000..794d3457040b --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,135 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * Tag + */ +@JsonPropertyOrder({ + Tag.JSON_PROPERTY_ID, + Tag.JSON_PROPERTY_NAME +}) +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Tag { + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public Tag() { + } + + public Tag id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public Tag name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java new file mode 100644 index 000000000000..95ee4725f1a3 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.java @@ -0,0 +1,200 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ +@JsonPropertyOrder({ + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_SIZE, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_COLOR, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_ID, + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.JSON_PROPERTY_NAME +}) +@JsonTypeName("test_query_style_deepObject_explode_true_object_allOf_query_object_parameter") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter { + public static final String JSON_PROPERTY_SIZE = "size"; + private String size; + + public static final String JSON_PROPERTY_COLOR = "color"; + private String color; + + public static final String JSON_PROPERTY_ID = "id"; + private Long id; + + public static final String JSON_PROPERTY_NAME = "name"; + private String name; + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() { + } + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter size(String size) { + + this.size = size; + return this; + } + + /** + * Get size + * @return size + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getSize() { + return size; + } + + + @JsonProperty(JSON_PROPERTY_SIZE) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setSize(String size) { + this.size = size; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter color(String color) { + + this.color = color; + return this; + } + + /** + * Get color + * @return color + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getColor() { + return color; + } + + + @JsonProperty(JSON_PROPERTY_COLOR) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setColor(String color) { + this.color = color; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter id(Long id) { + + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public Long getId() { + return id; + } + + + @JsonProperty(JSON_PROPERTY_ID) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setId(Long id) { + this.id = id; + } + + + public TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter name(String name) { + + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public String getName() { + return name; + } + + + @JsonProperty(JSON_PROPERTY_NAME) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter = (TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter) o; + return Objects.equals(this.size, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.size) && + Objects.equals(this.color, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.color) && + Objects.equals(this.id, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.id) && + Objects.equals(this.name, testQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.name); + } + + @Override + public int hashCode() { + return Objects.hash(size, color, id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter {\n"); + sb.append(" size: ").append(toIndentedString(size)).append("\n"); + sb.append(" color: ").append(toIndentedString(color)).append("\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java new file mode 100644 index 000000000000..a28cc79320db --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/main/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.java @@ -0,0 +1,115 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import java.util.Arrays; +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonPropertyOrder; +import com.fasterxml.jackson.annotation.JsonTypeName; + +/** + * TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ +@JsonPropertyOrder({ + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.JSON_PROPERTY_VALUES +}) +@JsonTypeName("test_query_style_form_explode_true_array_string_query_object_parameter") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter { + public static final String JSON_PROPERTY_VALUES = "values"; + private List values; + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() { + } + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter values(List values) { + + this.values = values; + return this; + } + + public TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter addValuesItem(String valuesItem) { + if (this.values == null) { + this.values = new ArrayList<>(); + } + this.values.add(valuesItem); + return this; + } + + /** + * Get values + * @return values + **/ + @javax.annotation.Nullable + @JsonProperty(JSON_PROPERTY_VALUES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + + public List getValues() { + return values; + } + + + @JsonProperty(JSON_PROPERTY_VALUES) + @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) + public void setValues(List values) { + this.values = values; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter testQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = (TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter) o; + return Objects.equals(this.values, testQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.values); + } + + @Override + public int hashCode() { + return Objects.hash(values); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter {\n"); + sb.append(" values: ").append(toIndentedString(values)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + +} + diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/CustomTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/CustomTest.java new file mode 100644 index 000000000000..fc98c24a1286 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/CustomTest.java @@ -0,0 +1,61 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.oprg + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import org.junit.Assert; +import org.junit.Test; +import org.openapitools.client.api.BodyApi; +import org.openapitools.client.api.QueryApi; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Pet; + +import java.util.Arrays; + +import static org.junit.Assert.assertNotNull; + + +/** + * API tests + */ +public class CustomTest { + + private final QueryApi api = new QueryApi(); + private final BodyApi bodyApi = new BodyApi(); + + /** + * Test body parameter(s) + *

              + * Test body parameter(s) + * + */ + @Test + public void testEchoBodyPet() { + Pet pet = new Pet().id(12345L).name("Hello World"). + photoUrls(Arrays.asList(new String[]{"http://a.com", "http://b.com"})).category(new Category().id(987L).name("new category")); + + Pet p = bodyApi.testEchoBodyPet(pet); + assertNotNull(p); + Assert.assertEquals("Hello World", p.getName()); + Assert.assertEquals(Long.valueOf(12345L), p.getId()); + + // response is empty body + Pet p2 = bodyApi.testEchoBodyPet(null); + Assert.assertNull(p2); + } + + @Test + public void testQueryParamsExploded_whenQueryParamIsNull() { + assertNotNull(api.testQueryStyleFormExplodeTrueObject(null)); + } +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/AuthApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/AuthApiTest.java new file mode 100644 index 000000000000..385354f4b634 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/AuthApiTest.java @@ -0,0 +1,71 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.junit.Assert; +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for AuthApi + */ +public class AuthApiTest { + + private final AuthApi api = new AuthApi(); + + + /** + * To test HTTP basic authentication + * + * To test HTTP basic authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBasicTest() { + + String response = api.testAuthHttpBasic(); + + // TODO: test validations + } + + /** + * To test HTTP bearer authentication + * + * To test HTTP bearer authentication + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testAuthHttpBearerTest() { + String response; + api.getApiClient().setBearerToken("fixed token"); + response = api.testAuthHttpBearer(); + Assert.assertTrue(response.contains("Authorization: Bearer fixed token")); + + api.getApiClient().setBearerToken(() -> "dynamic token"); + response = api.testAuthHttpBearer(); + Assert.assertTrue(response.contains("Authorization: Bearer dynamic token")); + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/BodyApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/BodyApiTest.java new file mode 100644 index 000000000000..1a1842f6c553 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/BodyApiTest.java @@ -0,0 +1,173 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.io.File; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for BodyApi + */ +@Ignore +public class BodyApiTest { + + private final BodyApi api = new BodyApi(); + + + /** + * Test binary (gif) response body + * + * Test binary (gif) response body + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBinaryGifTest() { + + File response = api.testBinaryGif(); + + // TODO: test validations + } + + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyApplicationOctetstreamBinaryTest() { + File body = null; + + String response = api.testBodyApplicationOctetstreamBinary(body); + + // TODO: test validations + } + + /** + * Test array of binary in multipart mime + * + * Test array of binary in multipart mime + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testBodyMultipartFormdataArrayOfBinaryTest() { + List files = null; + + String response = api.testBodyMultipartFormdataArrayOfBinary(files); + + // TODO: test validations + } + + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyAllOfPetTest() { + Pet pet = null; + + Pet response = api.testEchoBodyAllOfPet(pet); + + // TODO: test validations + } + + /** + * Test free form object + * + * Test free form object + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyFreeFormObjectResponseStringTest() { + Object body = null; + + String response = api.testEchoBodyFreeFormObjectResponseString(body); + + // TODO: test validations + } + + /** + * Test body parameter(s) + * + * Test body parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyPetTest() { + Pet pet = null; + + Pet response = api.testEchoBodyPet(pet); + + // TODO: test validations + } + + /** + * Test empty response body + * + * Test empty response body + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyPetResponseStringTest() { + Pet pet = null; + + String response = api.testEchoBodyPetResponseString(pet); + + // TODO: test validations + } + + /** + * Test empty json (request body) + * + * Test empty json (request body) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEchoBodyTagResponseStringTest() { + Tag tag = null; + + String response = api.testEchoBodyTagResponseString(tag); + + // TODO: test validations + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/FormApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/FormApiTest.java new file mode 100644 index 000000000000..123f60544dcd --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/FormApiTest.java @@ -0,0 +1,76 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FormApi + */ +@Ignore +public class FormApiTest { + + private final FormApi api = new FormApi(); + + + /** + * Test form parameter(s) + * + * Test form parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testFormIntegerBooleanStringTest() { + Integer integerForm = null; + Boolean booleanForm = null; + String stringForm = null; + + String response = api.testFormIntegerBooleanString(integerForm, booleanForm, stringForm); + + // TODO: test validations + } + + /** + * Test form parameter(s) for oneOf schema + * + * Test form parameter(s) for oneOf schema + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testFormOneofTest() { + String form1 = null; + Integer form2 = null; + String form3 = null; + Boolean form4 = null; + Long id = null; + String name = null; + + String response = api.testFormOneof(form1, form2, form3, form4, id, name); + + // TODO: test validations + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/HeaderApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/HeaderApiTest.java new file mode 100644 index 000000000000..14f3c32bc5bd --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/HeaderApiTest.java @@ -0,0 +1,57 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.StringEnumRef; +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for HeaderApi + */ +@Ignore +public class HeaderApiTest { + + private final HeaderApi api = new HeaderApi(); + + + /** + * Test header parameter(s) + * + * Test header parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testHeaderIntegerBooleanStringEnumsTest() { + Integer integerHeader = null; + Boolean booleanHeader = null; + String stringHeader = null; + String enumNonrefStringHeader = null; + StringEnumRef enumRefStringHeader = null; + + String response = api.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader); + + // TODO: test validations + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/PathApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/PathApiTest.java new file mode 100644 index 000000000000..0b7e986b9815 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/PathApiTest.java @@ -0,0 +1,56 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.StringEnumRef; +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for PathApi + */ +@Ignore +public class PathApiTest { + + private final PathApi api = new PathApi(); + + + /** + * Test path parameter(s) + * + * Test path parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathTest() { + String pathString = null; + Integer pathInteger = null; + String enumNonrefStringPath = null; + StringEnumRef enumRefStringPath = null; + + String response = api.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath); + + // TODO: test validations + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/QueryApiTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/QueryApiTest.java new file mode 100644 index 000000000000..8f007ca9d156 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/api/QueryApiTest.java @@ -0,0 +1,183 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.DataQuery; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.client.model.TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter; +import org.openapitools.client.model.TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter; +import org.junit.Test; +import org.junit.Ignore; + +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for QueryApi + */ +@Ignore +public class QueryApiTest { + + private final QueryApi api = new QueryApi(); + + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testEnumRefStringTest() { + String enumNonrefStringQuery = null; + StringEnumRef enumRefStringQuery = null; + + String response = api.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryDatetimeDateStringTest() { + OffsetDateTime datetimeQuery = null; + LocalDate dateQuery = null; + String stringQuery = null; + + String response = api.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryIntegerBooleanStringTest() { + Integer integerQuery = null; + Boolean booleanQuery = null; + String stringQuery = null; + + String response = api.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleDeepObjectExplodeTrueObjectTest() { + Pet queryObject = null; + + String response = api.testQueryStyleDeepObjectExplodeTrueObject(queryObject); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleDeepObjectExplodeTrueObjectAllOfTest() { + TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter queryObject = null; + + String response = api.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueArrayStringTest() { + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter queryObject = null; + + String response = api.testQueryStyleFormExplodeTrueArrayString(queryObject); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueObjectTest() { + Pet queryObject = null; + + String response = api.testQueryStyleFormExplodeTrueObject(queryObject); + + // TODO: test validations + } + + /** + * Test query parameter(s) + * + * Test query parameter(s) + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void testQueryStyleFormExplodeTrueObjectAllOfTest() { + DataQuery queryObject = null; + + String response = api.testQueryStyleFormExplodeTrueObjectAllOf(queryObject); + + // TODO: test validations + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/BirdTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/BirdTest.java new file mode 100644 index 000000000000..3e82e9d75535 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/BirdTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Bird + */ +public class BirdTest { + private final Bird model = new Bird(); + + /** + * Model tests for Bird + */ + @Test + public void testBird() { + // TODO: test Bird + } + + /** + * Test the property 'size' + */ + @Test + public void sizeTest() { + // TODO: test size + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 000000000000..5b6a08fd6773 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DataQueryTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DataQueryTest.java new file mode 100644 index 000000000000..d08082e114ed --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DataQueryTest.java @@ -0,0 +1,84 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Query; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for DataQuery + */ +public class DataQueryTest { + private final DataQuery model = new DataQuery(); + + /** + * Model tests for DataQuery + */ + @Test + public void testDataQuery() { + // TODO: test DataQuery + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'outcomes' + */ + @Test + public void outcomesTest() { + // TODO: test outcomes + } + + /** + * Test the property 'suffix' + */ + @Test + public void suffixTest() { + // TODO: test suffix + } + + /** + * Test the property 'text' + */ + @Test + public void textTest() { + // TODO: test text + } + + /** + * Test the property 'date' + */ + @Test + public void dateTest() { + // TODO: test date + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DefaultValueTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DefaultValueTest.java new file mode 100644 index 000000000000..843a43b28d72 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/DefaultValueTest.java @@ -0,0 +1,111 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.StringEnumRef; +import org.openapitools.jackson.nullable.JsonNullable; +import com.fasterxml.jackson.annotation.JsonIgnore; +import org.openapitools.jackson.nullable.JsonNullable; +import java.util.NoSuchElementException; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for DefaultValue + */ +public class DefaultValueTest { + private final DefaultValue model = new DefaultValue(); + + /** + * Model tests for DefaultValue + */ + @Test + public void testDefaultValue() { + // TODO: test DefaultValue + } + + /** + * Test the property 'arrayStringEnumRefDefault' + */ + @Test + public void arrayStringEnumRefDefaultTest() { + // TODO: test arrayStringEnumRefDefault + } + + /** + * Test the property 'arrayStringEnumDefault' + */ + @Test + public void arrayStringEnumDefaultTest() { + // TODO: test arrayStringEnumDefault + } + + /** + * Test the property 'arrayStringDefault' + */ + @Test + public void arrayStringDefaultTest() { + // TODO: test arrayStringDefault + } + + /** + * Test the property 'arrayIntegerDefault' + */ + @Test + public void arrayIntegerDefaultTest() { + // TODO: test arrayIntegerDefault + } + + /** + * Test the property 'arrayString' + */ + @Test + public void arrayStringTest() { + // TODO: test arrayString + } + + /** + * Test the property 'arrayStringNullable' + */ + @Test + public void arrayStringNullableTest() { + // TODO: test arrayStringNullable + } + + /** + * Test the property 'arrayStringExtensionNullable' + */ + @Test + public void arrayStringExtensionNullableTest() { + // TODO: test arrayStringExtensionNullable + } + + /** + * Test the property 'stringNullable' + */ + @Test + public void stringNullableTest() { + // TODO: test stringNullable + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java new file mode 100644 index 000000000000..80e515fd707e --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/NumberPropertiesOnlyTest.java @@ -0,0 +1,64 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.math.BigDecimal; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for NumberPropertiesOnly + */ +public class NumberPropertiesOnlyTest { + private final NumberPropertiesOnly model = new NumberPropertiesOnly(); + + /** + * Model tests for NumberPropertiesOnly + */ + @Test + public void testNumberPropertiesOnly() { + // TODO: test NumberPropertiesOnly + } + + /** + * Test the property 'number' + */ + @Test + public void numberTest() { + // TODO: test number + } + + /** + * Test the property '_float' + */ + @Test + public void _floatTest() { + // TODO: test _float + } + + /** + * Test the property '_double' + */ + @Test + public void _doubleTest() { + // TODO: test _double + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..30e1991c7e32 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,92 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/QueryTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/QueryTest.java new file mode 100644 index 000000000000..3ae0ecb7b70d --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/QueryTest.java @@ -0,0 +1,58 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Query + */ +public class QueryTest { + private final Query model = new Query(); + + /** + * Model tests for Query + */ + @Test + public void testQuery() { + // TODO: test Query + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'outcomes' + */ + @Test + public void outcomesTest() { + // TODO: test outcomes + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/StringEnumRefTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/StringEnumRefTest.java new file mode 100644 index 000000000000..81bf17732bda --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/StringEnumRefTest.java @@ -0,0 +1,32 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for StringEnumRef + */ +public class StringEnumRefTest { + /** + * Model tests for StringEnumRef + */ + @Test + public void testStringEnumRef() { + // TODO: test StringEnumRef + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 000000000000..073b7aca33c1 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,55 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java new file mode 100644 index 000000000000..8ab39f47d766 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest.java @@ -0,0 +1,71 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ +public class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameterTest { + private final TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter model = new TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(); + + /** + * Model tests for TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + @Test + public void testTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter() { + // TODO: test TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + } + + /** + * Test the property 'size' + */ + @Test + public void sizeTest() { + // TODO: test size + } + + /** + * Test the property 'color' + */ + @Test + public void colorTest() { + // TODO: test color + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java new file mode 100644 index 000000000000..f3e020346fa0 --- /dev/null +++ b/samples/client/echo_api/java/resttemplate/src/test/java/org/openapitools/client/model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest.java @@ -0,0 +1,50 @@ +/* + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ +public class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameterTest { + private final TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter model = new TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(); + + /** + * Model tests for TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ + @Test + public void testTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter() { + // TODO: test TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + } + + /** + * Test the property 'values' + */ + @Test + public void valuesTest() { + // TODO: test values + } + +} diff --git a/samples/client/echo_api/php-nextgen/.openapi-generator/VERSION b/samples/client/echo_api/php-nextgen/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/php-nextgen/.openapi-generator/VERSION +++ b/samples/client/echo_api/php-nextgen/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/php-nextgen/README.md b/samples/client/echo_api/php-nextgen/README.md index 03fa13c33a9a..cf811c24b44c 100644 --- a/samples/client/echo_api/php-nextgen/README.md +++ b/samples/client/echo_api/php-nextgen/README.md @@ -77,9 +77,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**testAuthHttpBasic**](docs/Api/AuthApi.md#testauthhttpbasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**testAuthHttpBearer**](docs/Api/AuthApi.md#testauthhttpbearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**testBinaryGif**](docs/Api/BodyApi.md#testbinarygif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**testBodyApplicationOctetstreamBinary**](docs/Api/BodyApi.md#testbodyapplicationoctetstreambinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**testBodyMultipartFormdataArrayOfBinary**](docs/Api/BodyApi.md#testbodymultipartformdataarrayofbinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**testBodyMultipartFormdataSingleBinary**](docs/Api/BodyApi.md#testbodymultipartformdatasinglebinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**testEchoBodyAllOfPet**](docs/Api/BodyApi.md#testechobodyallofpet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyFreeFormObjectResponseString**](docs/Api/BodyApi.md#testechobodyfreeformobjectresponsestring) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**testEchoBodyPet**](docs/Api/BodyApi.md#testechobodypet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**testEchoBodyPetResponseString**](docs/Api/BodyApi.md#testechobodypetresponsestring) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -117,6 +120,11 @@ Class | Method | HTTP request | Description - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + ## Tests To run the tests, use: diff --git a/samples/client/echo_api/php-nextgen/docs/Api/AuthApi.md b/samples/client/echo_api/php-nextgen/docs/Api/AuthApi.md index 8fb88b69afef..874f3c61c69c 100644 --- a/samples/client/echo_api/php-nextgen/docs/Api/AuthApi.md +++ b/samples/client/echo_api/php-nextgen/docs/Api/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to http://localhost:3000, except if the operation defines | Method | HTTP request | Description | | ------------- | ------------- | ------------- | | [**testAuthHttpBasic()**](AuthApi.md#testAuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**testAuthHttpBearer()**](AuthApi.md#testAuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | ## `testAuthHttpBasic()` @@ -65,3 +66,60 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../../README.md#endpoints) [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) + +## `testAuthHttpBearer()` + +```php +testAuthHttpBearer(): string +``` + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +```php +setAccessToken('YOUR_ACCESS_TOKEN'); + + +$apiInstance = new OpenAPI\Client\Api\AuthApi( + // If you want use custom http client, pass your client which implements `GuzzleHttp\ClientInterface`. + // This is optional, `GuzzleHttp\Client` will be used as default. + new GuzzleHttp\Client(), + $config +); + +try { + $result = $apiInstance->testAuthHttpBearer(); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling AuthApi->testAuthHttpBearer: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**string** + +### Authorization + +[http_bearer_auth](../../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: `text/plain` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) diff --git a/samples/client/echo_api/php-nextgen/docs/Api/BodyApi.md b/samples/client/echo_api/php-nextgen/docs/Api/BodyApi.md index 84fb8a7aa783..cb2845fd730e 100644 --- a/samples/client/echo_api/php-nextgen/docs/Api/BodyApi.md +++ b/samples/client/echo_api/php-nextgen/docs/Api/BodyApi.md @@ -7,6 +7,8 @@ All URIs are relative to http://localhost:3000, except if the operation defines | [**testBinaryGif()**](BodyApi.md#testBinaryGif) | **POST** /binary/gif | Test binary (gif) response body | | [**testBodyApplicationOctetstreamBinary()**](BodyApi.md#testBodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**testBodyMultipartFormdataArrayOfBinary()**](BodyApi.md#testBodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**testBodyMultipartFormdataSingleBinary()**](BodyApi.md#testBodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**testEchoBodyAllOfPet()**](BodyApi.md#testEchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**testEchoBodyFreeFormObjectResponseString()**](BodyApi.md#testEchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**testEchoBodyPet()**](BodyApi.md#testEchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) | | [**testEchoBodyPetResponseString()**](BodyApi.md#testEchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body | @@ -178,6 +180,118 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testBodyMultipartFormdataSingleBinary()` + +```php +testBodyMultipartFormdataSingleBinary($my_file): string +``` + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```php +testBodyMultipartFormdataSingleBinary($my_file); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling BodyApi->testBodyMultipartFormdataSingleBinary: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **my_file** | **\SplFileObject****\SplFileObject**| | [optional] | + +### Return type + +**string** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `multipart/form-data` +- **Accept**: `text/plain` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + +## `testEchoBodyAllOfPet()` + +```php +testEchoBodyAllOfPet($pet): \OpenAPI\Client\Model\Pet +``` + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```php +testEchoBodyAllOfPet($pet); + print_r($result); +} catch (Exception $e) { + echo 'Exception when calling BodyApi->testEchoBodyAllOfPet: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **pet** | [**\OpenAPI\Client\Model\Pet**](../Model/Pet.md)| Pet object that needs to be added to the store | [optional] | + +### Return type + +[**\OpenAPI\Client\Model\Pet**](../Model/Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `application/json` +- **Accept**: `application/json` + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + ## `testEchoBodyFreeFormObjectResponseString()` ```php diff --git a/samples/client/echo_api/php-nextgen/src/Api/AuthApi.php b/samples/client/echo_api/php-nextgen/src/Api/AuthApi.php index 0a1888cca45e..b99314086901 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/AuthApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/AuthApi.php @@ -3,7 +3,6 @@ * AuthApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * AuthApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -77,6 +75,9 @@ class AuthApi 'testAuthHttpBasic' => [ 'application/json', ], + 'testAuthHttpBearer' => [ + 'application/json', + ], ]; /** @@ -132,7 +133,7 @@ public function getConfig(): Configuration * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBasic'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -151,7 +152,7 @@ public function testAuthHttpBasic( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBasic'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -203,7 +204,19 @@ public function testAuthHttpBasicWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -220,7 +233,19 @@ public function testAuthHttpBasicWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -402,6 +427,307 @@ public function testAuthHttpBasicRequest( ); } + /** + * Operation testAuthHttpBearer + * + * To test HTTP bearer authentication + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBearer'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return string + */ + public function testAuthHttpBearer( + string $contentType = self::contentTypes['testAuthHttpBearer'][0] + ): string + { + list($response) = $this->testAuthHttpBearerWithHttpInfo($contentType); + return $response; + } + + /** + * Operation testAuthHttpBearerWithHttpInfo + * + * To test HTTP bearer authentication + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBearer'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return array of string, HTTP status code, HTTP response headers (array of strings) + */ + public function testAuthHttpBearerWithHttpInfo( + string $contentType = self::contentTypes['testAuthHttpBearer'][0] + ): array + { + $request = $this->testAuthHttpBearerRequest($contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ('string' !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'string', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testAuthHttpBearerAsync + * + * To test HTTP bearer authentication + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBearer'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testAuthHttpBearerAsync( + string $contentType = self::contentTypes['testAuthHttpBearer'][0] + ): PromiseInterface + { + return $this->testAuthHttpBearerAsyncWithHttpInfo($contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testAuthHttpBearerAsyncWithHttpInfo + * + * To test HTTP bearer authentication + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBearer'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testAuthHttpBearerAsyncWithHttpInfo( + string $contentType = self::contentTypes['testAuthHttpBearer'][0] + ): PromiseInterface + { + $returnType = 'string'; + $request = $this->testAuthHttpBearerRequest($contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testAuthHttpBearer' + * + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAuthHttpBearer'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testAuthHttpBearerRequest( + string $contentType = self::contentTypes['testAuthHttpBearer'][0] + ): Request + { + + + $resourcePath = '/auth/http/bearer'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + ['text/plain', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + // this endpoint requires Bearer authentication (access token) + if (!empty($this->config->getAccessToken())) { + $headers['Authorization'] = 'Bearer ' . $this->config->getAccessToken(); + } + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'POST', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + /** * Create http client option * diff --git a/samples/client/echo_api/php-nextgen/src/Api/BodyApi.php b/samples/client/echo_api/php-nextgen/src/Api/BodyApi.php index dd5ceaf1b5e0..e7ec741d331a 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/BodyApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/BodyApi.php @@ -3,7 +3,6 @@ * BodyApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * BodyApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -83,6 +81,12 @@ class BodyApi 'testBodyMultipartFormdataArrayOfBinary' => [ 'multipart/form-data', ], + 'testBodyMultipartFormdataSingleBinary' => [ + 'multipart/form-data', + ], + 'testEchoBodyAllOfPet' => [ + 'application/json', + ], 'testEchoBodyFreeFormObjectResponseString' => [ 'application/json', ], @@ -150,7 +154,7 @@ public function getConfig(): Configuration * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBinaryGif'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \SplFileObject */ @@ -169,7 +173,7 @@ public function testBinaryGif( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBinaryGif'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \SplFileObject, HTTP status code, HTTP response headers (array of strings) */ @@ -221,7 +225,19 @@ public function testBinaryGifWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\SplFileObject' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -238,7 +254,19 @@ public function testBinaryGifWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -424,7 +452,7 @@ public function testBinaryGifRequest( * @param \SplFileObject|null $body body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyApplicationOctetstreamBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -445,7 +473,7 @@ public function testBodyApplicationOctetstreamBinary( * @param \SplFileObject|null $body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyApplicationOctetstreamBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -498,7 +526,19 @@ public function testBodyApplicationOctetstreamBinaryWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -515,7 +555,19 @@ public function testBodyApplicationOctetstreamBinaryWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -715,7 +767,7 @@ public function testBodyApplicationOctetstreamBinaryRequest( * @param \SplFileObject[] $files files (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataArrayOfBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -736,7 +788,7 @@ public function testBodyMultipartFormdataArrayOfBinary( * @param \SplFileObject[] $files (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataArrayOfBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -789,7 +841,19 @@ public function testBodyMultipartFormdataArrayOfBinaryWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -806,7 +870,19 @@ public function testBodyMultipartFormdataArrayOfBinaryWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1010,44 +1086,44 @@ public function testBodyMultipartFormdataArrayOfBinaryRequest( } /** - * Operation testEchoBodyFreeFormObjectResponseString + * Operation testBodyMultipartFormdataSingleBinary * - * Test free form object + * Test single binary in multipart mime * - * @param object|null $body Free form object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation + * @param \SplFileObject|null $my_file my_file (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataSingleBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ - public function testEchoBodyFreeFormObjectResponseString( - ?array $body = null, - string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] + public function testBodyMultipartFormdataSingleBinary( + ?\SplFileObject $my_file = null, + string $contentType = self::contentTypes['testBodyMultipartFormdataSingleBinary'][0] ): string { - list($response) = $this->testEchoBodyFreeFormObjectResponseStringWithHttpInfo($body, $contentType); + list($response) = $this->testBodyMultipartFormdataSingleBinaryWithHttpInfo($my_file, $contentType); return $response; } /** - * Operation testEchoBodyFreeFormObjectResponseStringWithHttpInfo + * Operation testBodyMultipartFormdataSingleBinaryWithHttpInfo * - * Test free form object + * Test single binary in multipart mime * - * @param object|null $body Free form object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation + * @param \SplFileObject|null $my_file (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataSingleBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ - public function testEchoBodyFreeFormObjectResponseStringWithHttpInfo( - ?array $body = null, - string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] + public function testBodyMultipartFormdataSingleBinaryWithHttpInfo( + ?\SplFileObject $my_file = null, + string $contentType = self::contentTypes['testBodyMultipartFormdataSingleBinary'][0] ): array { - $request = $this->testEchoBodyFreeFormObjectResponseStringRequest($body, $contentType); + $request = $this->testBodyMultipartFormdataSingleBinaryRequest($my_file, $contentType); try { $options = $this->createHttpClientOption(); @@ -1091,7 +1167,19 @@ public function testEchoBodyFreeFormObjectResponseStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1108,7 +1196,19 @@ public function testEchoBodyFreeFormObjectResponseStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1134,22 +1234,22 @@ public function testEchoBodyFreeFormObjectResponseStringWithHttpInfo( } /** - * Operation testEchoBodyFreeFormObjectResponseStringAsync + * Operation testBodyMultipartFormdataSingleBinaryAsync * - * Test free form object + * Test single binary in multipart mime * - * @param object|null $body Free form object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation + * @param \SplFileObject|null $my_file (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataSingleBinary'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyFreeFormObjectResponseStringAsync( - ?array $body = null, - string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] + public function testBodyMultipartFormdataSingleBinaryAsync( + ?\SplFileObject $my_file = null, + string $contentType = self::contentTypes['testBodyMultipartFormdataSingleBinary'][0] ): PromiseInterface { - return $this->testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo($body, $contentType) + return $this->testBodyMultipartFormdataSingleBinaryAsyncWithHttpInfo($my_file, $contentType) ->then( function ($response) { return $response[0]; @@ -1158,23 +1258,23 @@ function ($response) { } /** - * Operation testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo + * Operation testBodyMultipartFormdataSingleBinaryAsyncWithHttpInfo * - * Test free form object + * Test single binary in multipart mime * - * @param object|null $body Free form object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation + * @param \SplFileObject|null $my_file (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataSingleBinary'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo( - $body = null, - string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] + public function testBodyMultipartFormdataSingleBinaryAsyncWithHttpInfo( + $my_file = null, + string $contentType = self::contentTypes['testBodyMultipartFormdataSingleBinary'][0] ): PromiseInterface { $returnType = 'string'; - $request = $this->testEchoBodyFreeFormObjectResponseStringRequest($body, $contentType); + $request = $this->testBodyMultipartFormdataSingleBinaryRequest($my_file, $contentType); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -1213,23 +1313,23 @@ function ($exception) { } /** - * Create request for operation 'testEchoBodyFreeFormObjectResponseString' + * Create request for operation 'testBodyMultipartFormdataSingleBinary' * - * @param object|null $body Free form object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation + * @param \SplFileObject|null $my_file (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyMultipartFormdataSingleBinary'] to see the possible values for this operation * * @throws InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ - public function testEchoBodyFreeFormObjectResponseStringRequest( - $body = null, - string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] + public function testBodyMultipartFormdataSingleBinaryRequest( + $my_file = null, + string $contentType = self::contentTypes['testBodyMultipartFormdataSingleBinary'][0] ): Request { - $resourcePath = '/echo/body/FreeFormObject/response_string'; + $resourcePath = '/body/application/octetstream/single_binary'; $formParams = []; $queryParams = []; $headerParams = []; @@ -1239,6 +1339,18 @@ public function testEchoBodyFreeFormObjectResponseStringRequest( + // form params + if ($my_file !== null) { + $multipart = true; + $formParams['my-file'] = []; + $paramFiles = is_array($my_file) ? $my_file : [$my_file]; + foreach ($paramFiles as $paramFile) { + $formParams['my-file'][] = \GuzzleHttp\Psr7\Utils::tryFopen( + ObjectSerializer::toFormValue($paramFile), + 'rb' + ); + } + } $headers = $this->headerSelector->selectHeaders( ['text/plain', ], @@ -1247,14 +1359,7 @@ public function testEchoBodyFreeFormObjectResponseStringRequest( ); // for model (json/xml) - if (isset($body)) { - if (stripos($headers['Content-Type'], 'application/json') !== false) { - # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); - } else { - $httpBody = $body; - } - } elseif (count($formParams) > 0) { + if (count($formParams) > 0) { if ($multipart) { $multipartContents = []; foreach ($formParams as $formParamName => $formParamValue) { @@ -1301,44 +1406,44 @@ public function testEchoBodyFreeFormObjectResponseStringRequest( } /** - * Operation testEchoBodyPet + * Operation testEchoBodyAllOfPet * * Test body parameter(s) * * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyAllOfPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Pet */ - public function testEchoBodyPet( + public function testEchoBodyAllOfPet( ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPet'][0] + string $contentType = self::contentTypes['testEchoBodyAllOfPet'][0] ): \OpenAPI\Client\Model\Pet { - list($response) = $this->testEchoBodyPetWithHttpInfo($pet, $contentType); + list($response) = $this->testEchoBodyAllOfPetWithHttpInfo($pet, $contentType); return $response; } /** - * Operation testEchoBodyPetWithHttpInfo + * Operation testEchoBodyAllOfPetWithHttpInfo * * Test body parameter(s) * * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyAllOfPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ - public function testEchoBodyPetWithHttpInfo( + public function testEchoBodyAllOfPetWithHttpInfo( ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPet'][0] + string $contentType = self::contentTypes['testEchoBodyAllOfPet'][0] ): array { - $request = $this->testEchoBodyPetRequest($pet, $contentType); + $request = $this->testEchoBodyAllOfPetRequest($pet, $contentType); try { $options = $this->createHttpClientOption(); @@ -1382,7 +1487,19 @@ public function testEchoBodyPetWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1399,7 +1516,19 @@ public function testEchoBodyPetWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1425,22 +1554,22 @@ public function testEchoBodyPetWithHttpInfo( } /** - * Operation testEchoBodyPetAsync + * Operation testEchoBodyAllOfPetAsync * * Test body parameter(s) * * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyAllOfPet'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyPetAsync( + public function testEchoBodyAllOfPetAsync( ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPet'][0] + string $contentType = self::contentTypes['testEchoBodyAllOfPet'][0] ): PromiseInterface { - return $this->testEchoBodyPetAsyncWithHttpInfo($pet, $contentType) + return $this->testEchoBodyAllOfPetAsyncWithHttpInfo($pet, $contentType) ->then( function ($response) { return $response[0]; @@ -1449,23 +1578,23 @@ function ($response) { } /** - * Operation testEchoBodyPetAsyncWithHttpInfo + * Operation testEchoBodyAllOfPetAsyncWithHttpInfo * * Test body parameter(s) * * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyAllOfPet'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyPetAsyncWithHttpInfo( + public function testEchoBodyAllOfPetAsyncWithHttpInfo( $pet = null, - string $contentType = self::contentTypes['testEchoBodyPet'][0] + string $contentType = self::contentTypes['testEchoBodyAllOfPet'][0] ): PromiseInterface { $returnType = '\OpenAPI\Client\Model\Pet'; - $request = $this->testEchoBodyPetRequest($pet, $contentType); + $request = $this->testEchoBodyAllOfPetRequest($pet, $contentType); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -1504,23 +1633,23 @@ function ($exception) { } /** - * Create request for operation 'testEchoBodyPet' + * Create request for operation 'testEchoBodyAllOfPet' * * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyAllOfPet'] to see the possible values for this operation * * @throws InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ - public function testEchoBodyPetRequest( + public function testEchoBodyAllOfPetRequest( $pet = null, - string $contentType = self::contentTypes['testEchoBodyPet'][0] + string $contentType = self::contentTypes['testEchoBodyAllOfPet'][0] ): Request { - $resourcePath = '/echo/body/Pet'; + $resourcePath = '/echo/body/allOf/Pet'; $formParams = []; $queryParams = []; $headerParams = []; @@ -1592,44 +1721,44 @@ public function testEchoBodyPetRequest( } /** - * Operation testEchoBodyPetResponseString + * Operation testEchoBodyFreeFormObjectResponseString * - * Test empty response body + * Test free form object * - * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * @param object|null $body Free form object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ - public function testEchoBodyPetResponseString( - ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + public function testEchoBodyFreeFormObjectResponseString( + ?array $body = null, + string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] ): string { - list($response) = $this->testEchoBodyPetResponseStringWithHttpInfo($pet, $contentType); + list($response) = $this->testEchoBodyFreeFormObjectResponseStringWithHttpInfo($body, $contentType); return $response; } /** - * Operation testEchoBodyPetResponseStringWithHttpInfo + * Operation testEchoBodyFreeFormObjectResponseStringWithHttpInfo * - * Test empty response body + * Test free form object * - * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * @param object|null $body Free form object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ - public function testEchoBodyPetResponseStringWithHttpInfo( - ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + public function testEchoBodyFreeFormObjectResponseStringWithHttpInfo( + ?array $body = null, + string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] ): array { - $request = $this->testEchoBodyPetResponseStringRequest($pet, $contentType); + $request = $this->testEchoBodyFreeFormObjectResponseStringRequest($body, $contentType); try { $options = $this->createHttpClientOption(); @@ -1673,7 +1802,19 @@ public function testEchoBodyPetResponseStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1690,7 +1831,19 @@ public function testEchoBodyPetResponseStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1716,22 +1869,22 @@ public function testEchoBodyPetResponseStringWithHttpInfo( } /** - * Operation testEchoBodyPetResponseStringAsync + * Operation testEchoBodyFreeFormObjectResponseStringAsync * - * Test empty response body + * Test free form object * - * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * @param object|null $body Free form object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyPetResponseStringAsync( - ?\OpenAPI\Client\Model\Pet $pet = null, - string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + public function testEchoBodyFreeFormObjectResponseStringAsync( + ?array $body = null, + string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] ): PromiseInterface { - return $this->testEchoBodyPetResponseStringAsyncWithHttpInfo($pet, $contentType) + return $this->testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo($body, $contentType) ->then( function ($response) { return $response[0]; @@ -1740,23 +1893,23 @@ function ($response) { } /** - * Operation testEchoBodyPetResponseStringAsyncWithHttpInfo + * Operation testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo * - * Test empty response body + * Test free form object * - * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * @param object|null $body Free form object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation * * @throws InvalidArgumentException * @return PromiseInterface */ - public function testEchoBodyPetResponseStringAsyncWithHttpInfo( - $pet = null, - string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + public function testEchoBodyFreeFormObjectResponseStringAsyncWithHttpInfo( + $body = null, + string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] ): PromiseInterface { $returnType = 'string'; - $request = $this->testEchoBodyPetResponseStringRequest($pet, $contentType); + $request = $this->testEchoBodyFreeFormObjectResponseStringRequest($body, $contentType); return $this->client ->sendAsync($request, $this->createHttpClientOption()) @@ -1795,23 +1948,23 @@ function ($exception) { } /** - * Create request for operation 'testEchoBodyPetResponseString' + * Create request for operation 'testEchoBodyFreeFormObjectResponseString' * - * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * @param object|null $body Free form object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyFreeFormObjectResponseString'] to see the possible values for this operation * * @throws InvalidArgumentException * @return \GuzzleHttp\Psr7\Request */ - public function testEchoBodyPetResponseStringRequest( - $pet = null, - string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + public function testEchoBodyFreeFormObjectResponseStringRequest( + $body = null, + string $contentType = self::contentTypes['testEchoBodyFreeFormObjectResponseString'][0] ): Request { - $resourcePath = '/echo/body/Pet/response_string'; + $resourcePath = '/echo/body/FreeFormObject/response_string'; $formParams = []; $queryParams = []; $headerParams = []; @@ -1829,12 +1982,12 @@ public function testEchoBodyPetResponseStringRequest( ); // for model (json/xml) - if (isset($pet)) { + if (isset($body)) { if (stripos($headers['Content-Type'], 'application/json') !== false) { # if Content-Type contains "application/json", json_encode the body - $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($body)); } else { - $httpBody = $pet; + $httpBody = $body; } } elseif (count($formParams) > 0) { if ($multipart) { @@ -1883,44 +2036,44 @@ public function testEchoBodyPetResponseStringRequest( } /** - * Operation testEchoBodyTagResponseString + * Operation testEchoBodyPet * - * Test empty json (request body) + * Test body parameter(s) * - * @param \OpenAPI\Client\Model\Tag|null $tag Tag object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyTagResponseString'] to see the possible values for this operation + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException - * @return string + * @return \OpenAPI\Client\Model\Pet */ - public function testEchoBodyTagResponseString( - ?\OpenAPI\Client\Model\Tag $tag = null, - string $contentType = self::contentTypes['testEchoBodyTagResponseString'][0] - ): string + public function testEchoBodyPet( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPet'][0] + ): \OpenAPI\Client\Model\Pet { - list($response) = $this->testEchoBodyTagResponseStringWithHttpInfo($tag, $contentType); + list($response) = $this->testEchoBodyPetWithHttpInfo($pet, $contentType); return $response; } /** - * Operation testEchoBodyTagResponseStringWithHttpInfo + * Operation testEchoBodyPetWithHttpInfo * - * Test empty json (request body) + * Test body parameter(s) * - * @param \OpenAPI\Client\Model\Tag|null $tag Tag object (optional) - * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyTagResponseString'] to see the possible values for this operation + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException - * @return array of string, HTTP status code, HTTP response headers (array of strings) + * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ - public function testEchoBodyTagResponseStringWithHttpInfo( - ?\OpenAPI\Client\Model\Tag $tag = null, - string $contentType = self::contentTypes['testEchoBodyTagResponseString'][0] + public function testEchoBodyPetWithHttpInfo( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPet'][0] ): array { - $request = $this->testEchoBodyTagResponseStringRequest($tag, $contentType); + $request = $this->testEchoBodyPetRequest($pet, $contentType); try { $options = $this->createHttpClientOption(); @@ -1959,29 +2112,683 @@ public function testEchoBodyTagResponseStringWithHttpInfo( switch($statusCode) { case 200: - if ('string' === '\SplFileObject') { + if ('\OpenAPI\Client\Model\Pet' === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); - if ('string' !== 'string') { - $content = json_decode($content); + if ('\OpenAPI\Client\Model\Pet' !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } return [ - ObjectSerializer::deserialize($content, 'string', []), + ObjectSerializer::deserialize($content, '\OpenAPI\Client\Model\Pet', []), $response->getStatusCode(), $response->getHeaders() ]; } - $returnType = 'string'; + $returnType = '\OpenAPI\Client\Model\Pet'; if ($returnType === '\SplFileObject') { $content = $response->getBody(); //stream goes to serializer } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + '\OpenAPI\Client\Model\Pet', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testEchoBodyPetAsync + * + * Test body parameter(s) + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testEchoBodyPetAsync( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPet'][0] + ): PromiseInterface + { + return $this->testEchoBodyPetAsyncWithHttpInfo($pet, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testEchoBodyPetAsyncWithHttpInfo + * + * Test body parameter(s) + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testEchoBodyPetAsyncWithHttpInfo( + $pet = null, + string $contentType = self::contentTypes['testEchoBodyPet'][0] + ): PromiseInterface + { + $returnType = '\OpenAPI\Client\Model\Pet'; + $request = $this->testEchoBodyPetRequest($pet, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testEchoBodyPet' + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPet'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testEchoBodyPetRequest( + $pet = null, + string $contentType = self::contentTypes['testEchoBodyPet'][0] + ): Request + { + + + + $resourcePath = '/echo/body/Pet'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + ['application/json', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($pet)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); + } else { + $httpBody = $pet; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'POST', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testEchoBodyPetResponseString + * + * Test empty response body + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return string + */ + public function testEchoBodyPetResponseString( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + ): string + { + list($response) = $this->testEchoBodyPetResponseStringWithHttpInfo($pet, $contentType); + return $response; + } + + /** + * Operation testEchoBodyPetResponseStringWithHttpInfo + * + * Test empty response body + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return array of string, HTTP status code, HTTP response headers (array of strings) + */ + public function testEchoBodyPetResponseStringWithHttpInfo( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + ): array + { + $request = $this->testEchoBodyPetResponseStringRequest($pet, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ('string' !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + case 200: + $data = ObjectSerializer::deserialize( + $e->getResponseBody(), + 'string', + $e->getResponseHeaders() + ); + $e->setResponseObject($data); + break; + } + throw $e; + } + } + + /** + * Operation testEchoBodyPetResponseStringAsync + * + * Test empty response body + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testEchoBodyPetResponseStringAsync( + ?\OpenAPI\Client\Model\Pet $pet = null, + string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + ): PromiseInterface + { + return $this->testEchoBodyPetResponseStringAsyncWithHttpInfo($pet, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testEchoBodyPetResponseStringAsyncWithHttpInfo + * + * Test empty response body + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testEchoBodyPetResponseStringAsyncWithHttpInfo( + $pet = null, + string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + ): PromiseInterface + { + $returnType = 'string'; + $request = $this->testEchoBodyPetResponseStringRequest($pet, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + $content = json_decode($content); + } + } + + return [ + ObjectSerializer::deserialize($content, $returnType, []), + $response->getStatusCode(), + $response->getHeaders() + ]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testEchoBodyPetResponseString' + * + * @param \OpenAPI\Client\Model\Pet|null $pet Pet object that needs to be added to the store (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyPetResponseString'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testEchoBodyPetResponseStringRequest( + $pet = null, + string $contentType = self::contentTypes['testEchoBodyPetResponseString'][0] + ): Request + { + + + + $resourcePath = '/echo/body/Pet/response_string'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + ['text/plain', ], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($pet)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($pet)); + } else { + $httpBody = $pet; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'POST', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + + /** + * Operation testEchoBodyTagResponseString + * + * Test empty json (request body) + * + * @param \OpenAPI\Client\Model\Tag|null $tag Tag object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyTagResponseString'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return string + */ + public function testEchoBodyTagResponseString( + ?\OpenAPI\Client\Model\Tag $tag = null, + string $contentType = self::contentTypes['testEchoBodyTagResponseString'][0] + ): string + { + list($response) = $this->testEchoBodyTagResponseStringWithHttpInfo($tag, $contentType); + return $response; + } + + /** + * Operation testEchoBodyTagResponseStringWithHttpInfo + * + * Test empty json (request body) + * + * @param \OpenAPI\Client\Model\Tag|null $tag Tag object (optional) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEchoBodyTagResponseString'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return array of string, HTTP status code, HTTP response headers (array of strings) + */ + public function testEchoBodyTagResponseStringWithHttpInfo( + ?\OpenAPI\Client\Model\Tag $tag = null, + string $contentType = self::contentTypes['testEchoBodyTagResponseString'][0] + ): array + { + $request = $this->testEchoBodyTagResponseStringRequest($tag, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + switch($statusCode) { + case 200: + if ('string' === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ('string' !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } + } + } + + return [ + ObjectSerializer::deserialize($content, 'string', []), + $response->getStatusCode(), + $response->getHeaders() + ]; + } + + $returnType = 'string'; + if ($returnType === '\SplFileObject') { + $content = $response->getBody(); //stream goes to serializer + } else { + $content = (string) $response->getBody(); + if ($returnType !== 'string') { + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/echo_api/php-nextgen/src/Api/FormApi.php b/samples/client/echo_api/php-nextgen/src/Api/FormApi.php index 3a31716e44f4..cedfc7fe6a6a 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/FormApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/FormApi.php @@ -3,7 +3,6 @@ * FormApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * FormApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -138,7 +136,7 @@ public function getConfig(): Configuration * @param string|null $string_form string_form (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testFormIntegerBooleanString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -163,7 +161,7 @@ public function testFormIntegerBooleanString( * @param string|null $string_form (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testFormIntegerBooleanString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -218,7 +216,19 @@ public function testFormIntegerBooleanStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -235,7 +245,19 @@ public function testFormIntegerBooleanStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -459,7 +481,7 @@ public function testFormIntegerBooleanStringRequest( * @param string|null $name name (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testFormOneof'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -490,7 +512,7 @@ public function testFormOneof( * @param string|null $name (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testFormOneof'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -548,7 +570,19 @@ public function testFormOneofWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -565,7 +599,19 @@ public function testFormOneofWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/echo_api/php-nextgen/src/Api/HeaderApi.php b/samples/client/echo_api/php-nextgen/src/Api/HeaderApi.php index 433596362ff8..013c5602a8d6 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/HeaderApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/HeaderApi.php @@ -3,7 +3,6 @@ * HeaderApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * HeaderApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -137,7 +135,7 @@ public function getConfig(): Configuration * @param StringEnumRef|null $enum_ref_string_header enum_ref_string_header (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testHeaderIntegerBooleanStringEnums'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -166,7 +164,7 @@ public function testHeaderIntegerBooleanStringEnums( * @param StringEnumRef|null $enum_ref_string_header (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testHeaderIntegerBooleanStringEnums'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -223,7 +221,19 @@ public function testHeaderIntegerBooleanStringEnumsWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -240,7 +250,19 @@ public function testHeaderIntegerBooleanStringEnumsWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/echo_api/php-nextgen/src/Api/PathApi.php b/samples/client/echo_api/php-nextgen/src/Api/PathApi.php index 81b058c4e09d..3510238bbb76 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/PathApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/PathApi.php @@ -3,7 +3,6 @@ * PathApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * PathApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -136,7 +134,7 @@ public function getConfig(): Configuration * @param StringEnumRef $enum_ref_string_path enum_ref_string_path (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -163,7 +161,7 @@ public function testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathE * @param StringEnumRef $enum_ref_string_path (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -219,7 +217,19 @@ public function testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathE } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -236,7 +246,19 @@ public function testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathE } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/echo_api/php-nextgen/src/Api/QueryApi.php b/samples/client/echo_api/php-nextgen/src/Api/QueryApi.php index 75247d8e49d2..cecc621c4bb1 100644 --- a/samples/client/echo_api/php-nextgen/src/Api/QueryApi.php +++ b/samples/client/echo_api/php-nextgen/src/Api/QueryApi.php @@ -3,7 +3,6 @@ * QueryApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -45,7 +44,6 @@ /** * QueryApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -155,7 +153,7 @@ public function getConfig(): Configuration * @param StringEnumRef|null $enum_ref_string_query enum_ref_string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumRefString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -178,7 +176,7 @@ public function testEnumRefString( * @param StringEnumRef|null $enum_ref_string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumRefString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -232,7 +230,19 @@ public function testEnumRefStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -249,7 +259,19 @@ public function testEnumRefStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -469,7 +491,7 @@ public function testEnumRefStringRequest( * @param string|null $string_query string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryDatetimeDateString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -494,7 +516,7 @@ public function testQueryDatetimeDateString( * @param string|null $string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryDatetimeDateString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -549,7 +571,19 @@ public function testQueryDatetimeDateStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -566,7 +600,19 @@ public function testQueryDatetimeDateStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -802,7 +848,7 @@ public function testQueryDatetimeDateStringRequest( * @param string|null $string_query string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryIntegerBooleanString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -827,7 +873,7 @@ public function testQueryIntegerBooleanString( * @param string|null $string_query (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryIntegerBooleanString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -882,7 +928,19 @@ public function testQueryIntegerBooleanStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -899,7 +957,19 @@ public function testQueryIntegerBooleanStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1133,7 +1203,7 @@ public function testQueryIntegerBooleanStringRequest( * @param Pet|null $query_object query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleDeepObjectExplodeTrueObject'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -1154,7 +1224,7 @@ public function testQueryStyleDeepObjectExplodeTrueObject( * @param Pet|null $query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleDeepObjectExplodeTrueObject'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1207,7 +1277,19 @@ public function testQueryStyleDeepObjectExplodeTrueObjectWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1224,7 +1306,19 @@ public function testQueryStyleDeepObjectExplodeTrueObjectWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1426,7 +1520,7 @@ public function testQueryStyleDeepObjectExplodeTrueObjectRequest( * @param TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter|null $query_object query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleDeepObjectExplodeTrueObjectAllOf'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -1447,7 +1541,7 @@ public function testQueryStyleDeepObjectExplodeTrueObjectAllOf( * @param TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter|null $query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleDeepObjectExplodeTrueObjectAllOf'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1500,7 +1594,19 @@ public function testQueryStyleDeepObjectExplodeTrueObjectAllOfWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1517,7 +1623,19 @@ public function testQueryStyleDeepObjectExplodeTrueObjectAllOfWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1719,7 +1837,7 @@ public function testQueryStyleDeepObjectExplodeTrueObjectAllOfRequest( * @param TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter|null $query_object query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueArrayString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -1740,7 +1858,7 @@ public function testQueryStyleFormExplodeTrueArrayString( * @param TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter|null $query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueArrayString'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1793,7 +1911,19 @@ public function testQueryStyleFormExplodeTrueArrayStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1810,7 +1940,19 @@ public function testQueryStyleFormExplodeTrueArrayStringWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2012,7 +2154,7 @@ public function testQueryStyleFormExplodeTrueArrayStringRequest( * @param Pet|null $query_object query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueObject'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -2033,7 +2175,7 @@ public function testQueryStyleFormExplodeTrueObject( * @param Pet|null $query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueObject'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -2086,7 +2228,19 @@ public function testQueryStyleFormExplodeTrueObjectWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2103,7 +2257,19 @@ public function testQueryStyleFormExplodeTrueObjectWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2305,7 +2471,7 @@ public function testQueryStyleFormExplodeTrueObjectRequest( * @param DataQuery|null $query_object query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueObjectAllOf'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -2326,7 +2492,7 @@ public function testQueryStyleFormExplodeTrueObjectAllOf( * @param DataQuery|null $query_object (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryStyleFormExplodeTrueObjectAllOf'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -2379,7 +2545,19 @@ public function testQueryStyleFormExplodeTrueObjectAllOfWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2396,7 +2574,19 @@ public function testQueryStyleFormExplodeTrueObjectAllOfWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/echo_api/php-nextgen/src/ApiException.php b/samples/client/echo_api/php-nextgen/src/ApiException.php index 9749438fb080..a2d1e0df151f 100644 --- a/samples/client/echo_api/php-nextgen/src/ApiException.php +++ b/samples/client/echo_api/php-nextgen/src/ApiException.php @@ -3,7 +3,6 @@ * ApiException * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -34,7 +33,6 @@ /** * ApiException Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/echo_api/php-nextgen/src/Configuration.php b/samples/client/echo_api/php-nextgen/src/Configuration.php index 894155911830..32ced2100e89 100644 --- a/samples/client/echo_api/php-nextgen/src/Configuration.php +++ b/samples/client/echo_api/php-nextgen/src/Configuration.php @@ -3,7 +3,6 @@ * Configuration * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -33,7 +32,6 @@ /** * Configuration Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/echo_api/php-nextgen/src/HeaderSelector.php b/samples/client/echo_api/php-nextgen/src/HeaderSelector.php index 5641fc3b9b3c..2f559a207c03 100644 --- a/samples/client/echo_api/php-nextgen/src/HeaderSelector.php +++ b/samples/client/echo_api/php-nextgen/src/HeaderSelector.php @@ -3,7 +3,6 @@ * HeaderSelector * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * HeaderSelector Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/echo_api/php-nextgen/src/Model/Bird.php b/samples/client/echo_api/php-nextgen/src/Model/Bird.php index 77574df55cb6..3d2cb9754e30 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/Bird.php +++ b/samples/client/echo_api/php-nextgen/src/Model/Bird.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * Bird Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -82,7 +80,7 @@ class Bird implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'size' => false, - 'color' => false + 'color' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/Category.php b/samples/client/echo_api/php-nextgen/src/Model/Category.php index e703bbe32c1a..70a6368e5eae 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/Category.php +++ b/samples/client/echo_api/php-nextgen/src/Model/Category.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * Category Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -82,7 +80,7 @@ class Category implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/DataQuery.php b/samples/client/echo_api/php-nextgen/src/Model/DataQuery.php index 91531e57e382..1ef087566be7 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/DataQuery.php +++ b/samples/client/echo_api/php-nextgen/src/Model/DataQuery.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -32,7 +31,6 @@ /** * DataQuery Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -78,8 +76,8 @@ class DataQuery extends Query */ protected static array $openAPINullables = [ 'suffix' => false, - 'text' => false, - 'date' => false + 'text' => false, + 'date' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/DefaultValue.php b/samples/client/echo_api/php-nextgen/src/Model/DefaultValue.php index 6baca8675012..f36ec67fbcee 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/DefaultValue.php +++ b/samples/client/echo_api/php-nextgen/src/Model/DefaultValue.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * DefaultValue Class Doc Comment * - * @category Class * @description to test the default value of properties * @package OpenAPI\Client * @author OpenAPI Generator team @@ -95,13 +93,13 @@ class DefaultValue implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'array_string_enum_ref_default' => false, - 'array_string_enum_default' => false, - 'array_string_default' => false, - 'array_integer_default' => false, - 'array_string' => false, - 'array_string_nullable' => true, - 'array_string_extension_nullable' => true, - 'string_nullable' => true + 'array_string_enum_default' => false, + 'array_string_default' => false, + 'array_integer_default' => false, + 'array_string' => false, + 'array_string_nullable' => true, + 'array_string_extension_nullable' => true, + 'string_nullable' => true ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/ModelInterface.php b/samples/client/echo_api/php-nextgen/src/Model/ModelInterface.php index 81335252c9f5..e59caf476a44 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/ModelInterface.php +++ b/samples/client/echo_api/php-nextgen/src/Model/ModelInterface.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client\Model * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/NumberPropertiesOnly.php b/samples/client/echo_api/php-nextgen/src/Model/NumberPropertiesOnly.php index 7feabc87075a..7b146ae0d0b5 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/NumberPropertiesOnly.php +++ b/samples/client/echo_api/php-nextgen/src/Model/NumberPropertiesOnly.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * NumberPropertiesOnly Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -84,8 +82,8 @@ class NumberPropertiesOnly implements ModelInterface, ArrayAccess, JsonSerializa */ protected static array $openAPINullables = [ 'number' => false, - 'float' => false, - 'double' => false + 'float' => false, + 'double' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/Pet.php b/samples/client/echo_api/php-nextgen/src/Model/Pet.php index 7e4caa17594e..d706b062c6cb 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/Pet.php +++ b/samples/client/echo_api/php-nextgen/src/Model/Pet.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * Pet Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -90,11 +88,11 @@ class Pet implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false, - 'category' => false, - 'photo_urls' => false, - 'tags' => false, - 'status' => false + 'name' => false, + 'category' => false, + 'photo_urls' => false, + 'tags' => false, + 'status' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/Query.php b/samples/client/echo_api/php-nextgen/src/Model/Query.php index b6ccda99b3fa..f45710b6f80d 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/Query.php +++ b/samples/client/echo_api/php-nextgen/src/Model/Query.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * Query Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -82,7 +80,7 @@ class Query implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'outcomes' => false + 'outcomes' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php b/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php index 89c69d748036..bb02758f90d1 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php +++ b/samples/client/echo_api/php-nextgen/src/Model/StringEnumRef.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -32,7 +31,6 @@ /** * StringEnumRef Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/echo_api/php-nextgen/src/Model/Tag.php b/samples/client/echo_api/php-nextgen/src/Model/Tag.php index d3d5bebd6f10..ebf335ca9639 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/Tag.php +++ b/samples/client/echo_api/php-nextgen/src/Model/Tag.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * Tag Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -82,7 +80,7 @@ class Tag implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.php b/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.php index 7600cd21bb60..5bffd06e49bf 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.php +++ b/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -86,9 +84,9 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter impleme */ protected static array $openAPINullables = [ 'size' => false, - 'color' => false, - 'id' => false, - 'name' => false + 'color' => false, + 'id' => false, + 'name' => false ]; /** diff --git a/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.php b/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.php index 1f8bae6f6312..36eeb60cd434 100644 --- a/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.php +++ b/samples/client/echo_api/php-nextgen/src/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -38,7 +37,6 @@ /** * TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/echo_api/php-nextgen/src/ObjectSerializer.php b/samples/client/echo_api/php-nextgen/src/ObjectSerializer.php index 2b5ae4aefe85..bb6db4d4bbcf 100644 --- a/samples/client/echo_api/php-nextgen/src/ObjectSerializer.php +++ b/samples/client/echo_api/php-nextgen/src/ObjectSerializer.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -18,7 +17,7 @@ * The version of the OpenAPI document: 0.1.0 * Contact: team@openapitools.org * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ObjectSerializer Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -429,10 +427,7 @@ public static function deserialize(mixed $data, string $class, array $httpHeader return $deserialized; } - if ($class === 'object') { - settype($data, 'array'); - return $data; - } elseif ($class === 'mixed') { + if ($class === 'mixed') { settype($data, gettype($data)); return $data; } diff --git a/samples/client/echo_api/powershell/.openapi-generator-ignore b/samples/client/echo_api/powershell/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/echo_api/powershell/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/echo_api/powershell/.openapi-generator/FILES b/samples/client/echo_api/powershell/.openapi-generator/FILES new file mode 100644 index 000000000000..109ec0237363 --- /dev/null +++ b/samples/client/echo_api/powershell/.openapi-generator/FILES @@ -0,0 +1,45 @@ +Build.ps1 +README.md +appveyor.yml +docs/AuthApi.md +docs/Bird.md +docs/BodyApi.md +docs/Category.md +docs/DataQuery.md +docs/DefaultValue.md +docs/FormApi.md +docs/HeaderApi.md +docs/NumberPropertiesOnly.md +docs/PathApi.md +docs/Pet.md +docs/Query.md +docs/QueryApi.md +docs/StringEnumRef.md +docs/Tag.md +docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +src/PSOpenAPITools/Api/AuthApi.ps1 +src/PSOpenAPITools/Api/BodyApi.ps1 +src/PSOpenAPITools/Api/FormApi.ps1 +src/PSOpenAPITools/Api/HeaderApi.ps1 +src/PSOpenAPITools/Api/PathApi.ps1 +src/PSOpenAPITools/Api/QueryApi.ps1 +src/PSOpenAPITools/Client/Configuration.ps1 +src/PSOpenAPITools/Model/Bird.ps1 +src/PSOpenAPITools/Model/Category.ps1 +src/PSOpenAPITools/Model/DataQuery.ps1 +src/PSOpenAPITools/Model/DefaultValue.ps1 +src/PSOpenAPITools/Model/NumberPropertiesOnly.ps1 +src/PSOpenAPITools/Model/Pet.ps1 +src/PSOpenAPITools/Model/Query.ps1 +src/PSOpenAPITools/Model/StringEnumRef.ps1 +src/PSOpenAPITools/Model/Tag.ps1 +src/PSOpenAPITools/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.ps1 +src/PSOpenAPITools/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.ps1 +src/PSOpenAPITools/PSOpenAPITools.psm1 +src/PSOpenAPITools/Private/ApiClient.ps1 +src/PSOpenAPITools/Private/Get-CommonParameters.ps1 +src/PSOpenAPITools/Private/HttpSignatureAuth.ps1 +src/PSOpenAPITools/Private/Out-DebugParameter.ps1 +src/PSOpenAPITools/Private/RSAEncryptionProvider.cs +src/PSOpenAPITools/en-US/about_PSOpenAPITools.help.txt diff --git a/samples/client/echo_api/powershell/.openapi-generator/VERSION b/samples/client/echo_api/powershell/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/powershell/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/powershell/Build.ps1 b/samples/client/echo_api/powershell/Build.ps1 new file mode 100644 index 000000000000..f1d1898660c1 --- /dev/null +++ b/samples/client/echo_api/powershell/Build.ps1 @@ -0,0 +1,75 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +function Get-FunctionsToExport { + [CmdletBinding()] + Param ( + [Parameter(Mandatory = $true, ValueFromPipelineByPropertyName = $true)] + [ValidateNotNullOrEmpty()] + [Alias('FullName')] + $Path + ) + + Process { + $Token = $null + $ParserErr = $null + + $Ast = [System.Management.Automation.Language.Parser]::ParseFile( + $Path, + [ref]$Token, + [ref]$ParserErr + ) + + if ($ParserErr) { + throw $ParserErr + } else { + foreach ($name in 'Begin', 'Process', 'End') { + foreach ($Statement in $Ast."${name}Block".Statements) { + if ( + [String]::IsNullOrWhiteSpace($Statement.Name) -or + $Statement.Extent.ToString() -notmatch + ('function\W+{0}' -f $Statement.Name) + ) { + continue + } + + $Statement.Name + } + } + } + } +} + +$ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path +$FunctionPath = 'Api', 'Model', 'Client' | Where-Object { + Join-Path "$ScriptDir\src\PSOpenAPITools\" $_ | Test-Path +} | ForEach-Object { Join-Path "$ScriptDir\src\PSOpenAPITools\" $_ } + +$Manifest = @{ + Path = "$ScriptDir\src\PSOpenAPITools\PSOpenAPITools.psd1" + + Author = 'OpenAPI Generator Team' + CompanyName = 'openapitools.org' + Description = 'PSOpenAPITools - the PowerShell module for Echo Server API' + + ModuleVersion = '0.1.2' + + RootModule = 'PSOpenAPITools.psm1' + Guid = 'a27b908d-2a20-467f-bc32-af6f3a654ac5' # Has to be static, otherwise each new build will be considered different module + + PowerShellVersion = '6.2' + + FunctionsToExport = $FunctionPath | Get-ChildItem -Filter *.ps1 | Get-FunctionsToExport + + VariablesToExport = @() + AliasesToExport = @() + CmdletsToExport = @() + +} + +New-ModuleManifest @Manifest diff --git a/samples/client/echo_api/powershell/README.md b/samples/client/echo_api/powershell/README.md new file mode 100644 index 000000000000..163717284adf --- /dev/null +++ b/samples/client/echo_api/powershell/README.md @@ -0,0 +1,110 @@ +# PSOpenAPITools - the PowerShell module for the Echo Server API + +Echo Server API + +This PowerShell module is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.1.0 +- SDK version: 0.1.2 +- Build package: org.openapitools.codegen.languages.PowerShellClientCodegen + + +## Frameworks supported +- PowerShell 6.2 or later + + +## Dependencies + + +## Installation + + +To install from the source, run the following command to build and install the PowerShell module locally: +```powershell +Build.ps1 +Import-Module -Name '.\src\PSOpenAPITools' -Verbose +``` + +To avoid function name collision, one can use `-Prefix`, e.g. `Import-Module -Name '.\src\PSOpenAPITools' -Prefix prefix` + +To uninstall the module, simply run: +```powershell +Remove-Module -FullyQualifiedName @{ModuleName = "PSOpenAPITools"; ModuleVersion = "0.1.2"} +``` + + +## Tests + +To install and run `Pester`, please execute the following commands in the terminal: + +```powershell +Install-module -name Pester -force + +Invoke-Pester +``` + +For troubleshooting, please run `$DebugPreference = 'Continue'` to turn on debugging and disable it with `$DebugPreference = 'SilentlyContinue'` when done with the troubleshooting. + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:3000* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*AuthApi* | [**Test-AuthHttpBasic**](docs/AuthApi.md#Test-AuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**Test-AuthHttpBearer**](docs/AuthApi.md#Test-AuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*BodyApi* | [**Test-BinaryGif**](docs/BodyApi.md#Test-BinaryGif) | **POST** /binary/gif | Test binary (gif) response body +*BodyApi* | [**Test-BodyApplicationOctetstreamBinary**](docs/BodyApi.md#Test-BodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +*BodyApi* | [**Test-BodyMultipartFormdataArrayOfBinary**](docs/BodyApi.md#Test-BodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**Test-BodyMultipartFormdataSingleBinary**](docs/BodyApi.md#Test-BodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**Test-EchoBodyFreeFormObjectResponseString**](docs/BodyApi.md#Test-EchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +*BodyApi* | [**Test-EchoBodyPet**](docs/BodyApi.md#Test-EchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) +*BodyApi* | [**Test-EchoBodyPetResponseString**](docs/BodyApi.md#Test-EchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body +*BodyApi* | [**Test-EchoBodyTagResponseString**](docs/BodyApi.md#Test-EchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +*BodyApi* | [**Test-EchoBodyAllOfPet**](docs/BodyApi.md#Test-EchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*FormApi* | [**Test-FormIntegerBooleanString**](docs/FormApi.md#Test-FormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) +*FormApi* | [**Test-FormOneof**](docs/FormApi.md#Test-FormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema +*HeaderApi* | [**Test-HeaderIntegerBooleanStringEnums**](docs/HeaderApi.md#Test-HeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) +*PathApi* | [**Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](docs/PathApi.md#Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) +*QueryApi* | [**Test-EnumRefString**](docs/QueryApi.md#Test-EnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) +*QueryApi* | [**Test-QueryDatetimeDateString**](docs/QueryApi.md#Test-QueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) +*QueryApi* | [**Test-QueryIntegerBooleanString**](docs/QueryApi.md#Test-QueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) +*QueryApi* | [**Test-QueryStyleDeepObjectExplodeTrueObject**](docs/QueryApi.md#Test-QueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +*QueryApi* | [**Test-QueryStyleDeepObjectExplodeTrueObjectAllOf**](docs/QueryApi.md#Test-QueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +*QueryApi* | [**Test-QueryStyleFormExplodeTrueArrayString**](docs/QueryApi.md#Test-QueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +*QueryApi* | [**Test-QueryStyleFormExplodeTrueObject**](docs/QueryApi.md#Test-QueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +*QueryApi* | [**Test-QueryStyleFormExplodeTrueObjectAllOf**](docs/QueryApi.md#Test-QueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + +## Documentation for Models + + - [PSOpenAPITools\Model.Bird](docs/Bird.md) + - [PSOpenAPITools\Model.Category](docs/Category.md) + - [PSOpenAPITools\Model.DataQuery](docs/DataQuery.md) + - [PSOpenAPITools\Model.DefaultValue](docs/DefaultValue.md) + - [PSOpenAPITools\Model.NumberPropertiesOnly](docs/NumberPropertiesOnly.md) + - [PSOpenAPITools\Model.Pet](docs/Pet.md) + - [PSOpenAPITools\Model.Query](docs/Query.md) + - [PSOpenAPITools\Model.StringEnumRef](docs/StringEnumRef.md) + - [PSOpenAPITools\Model.Tag](docs/Tag.md) + - [PSOpenAPITools\Model.TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter](docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md) + - [PSOpenAPITools\Model.TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter](docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### http_auth + + +- **Type**: HTTP basic authentication + + +### http_bearer_auth + + +- **Type**: HTTP Bearer Token authentication + diff --git a/samples/client/echo_api/powershell/appveyor.yml b/samples/client/echo_api/powershell/appveyor.yml new file mode 100644 index 000000000000..0df91baedea4 --- /dev/null +++ b/samples/client/echo_api/powershell/appveyor.yml @@ -0,0 +1,41 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +version: 1.0.{build} +image: + - Visual Studio 2019 # PWSH 7.x + #- Visual Studio 2017 # PS 5.x, PWSH 6.x + #- Ubuntu # PWSH 6.x + # ref: https://www.appveyor.com/docs/windows-images-software/ +install: + - pwsh: $PSVersionTable.PSVersion + - pwsh: Install-Module Pester -Force -Scope CurrentUser +build: off +test_script: + - pwsh: | + .\Build.ps1 + Import-Module -Name '.\src\PSOpenAPITools' + $Result = Invoke-Pester -PassThru + if ($Result.FailedCount -gt 0) { + $host.SetShouldExit($Result.FailedCount) + exit $Result.FailedCount + } +deploy_script: + - pwsh: | + if ($env:APPVEYOR_REPO_TAG -eq $true -and $null -ne $env:NuGetApiKey) { + .\Build.ps1 + try { + Publish-Module -NuGetApiKey $env:NuGetApiKey -Path .\src\PSOpenAPITools\ -Confirm:$False -Verbose + Write-Host "Successfully published the PowerShell module." + } catch { + $host.SetShouldExit($LastExitCode) + Write-Host "Error when running Publish-Module:" + Write-Host $_ + exit + } + } diff --git a/samples/client/echo_api/powershell/docs/AuthApi.md b/samples/client/echo_api/powershell/docs/AuthApi.md new file mode 100644 index 000000000000..e9675ba8f0a2 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/AuthApi.md @@ -0,0 +1,95 @@ +# PSOpenAPITools.PSOpenAPITools\Api.AuthApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-AuthHttpBasic**](AuthApi.md#Test-AuthHttpBasic) | **POST** /auth/http/basic | To test HTTP basic authentication +[**Test-AuthHttpBearer**](AuthApi.md#Test-AuthHttpBearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication + + + +# **Test-AuthHttpBasic** +> String Test-AuthHttpBasic
              + +To test HTTP basic authentication + +To test HTTP basic authentication + +### Example +```powershell +# general setting of the PowerShell module, e.g. base URL, authentication, etc +$Configuration = Get-Configuration +# Configure HTTP basic authorization: http_auth +$Configuration.Username = "YOUR_USERNAME" +$Configuration.Password = "YOUR_PASSWORD" + + +# To test HTTP basic authentication +try { + $Result = Test-AuthHttpBasic +} catch { + Write-Host ("Exception occurred when calling Test-AuthHttpBasic: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-AuthHttpBearer** +> String Test-AuthHttpBearer
              + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example +```powershell +# general setting of the PowerShell module, e.g. base URL, authentication, etc +$Configuration = Get-Configuration + + +# To test HTTP bearer authentication +try { + $Result = Test-AuthHttpBearer +} catch { + Write-Host ("Exception occurred when calling Test-AuthHttpBearer: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/Bird.md b/samples/client/echo_api/powershell/docs/Bird.md new file mode 100644 index 000000000000..1f9a67dfe951 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/Bird.md @@ -0,0 +1,23 @@ +# Bird +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Size** | **String** | | [optional] +**Color** | **String** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$Bird = Initialize-PSOpenAPIToolsBird -Size null ` + -Color null +``` + +- Convert the resource to JSON +```powershell +$Bird | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/BodyApi.md b/samples/client/echo_api/powershell/docs/BodyApi.md new file mode 100644 index 000000000000..9302de3186fb --- /dev/null +++ b/samples/client/echo_api/powershell/docs/BodyApi.md @@ -0,0 +1,405 @@ +# PSOpenAPITools.PSOpenAPITools\Api.BodyApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-BinaryGif**](BodyApi.md#Test-BinaryGif) | **POST** /binary/gif | Test binary (gif) response body +[**Test-BodyApplicationOctetstreamBinary**](BodyApi.md#Test-BodyApplicationOctetstreamBinary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +[**Test-BodyMultipartFormdataArrayOfBinary**](BodyApi.md#Test-BodyMultipartFormdataArrayOfBinary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +[**Test-BodyMultipartFormdataSingleBinary**](BodyApi.md#Test-BodyMultipartFormdataSingleBinary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +[**Test-EchoBodyFreeFormObjectResponseString**](BodyApi.md#Test-EchoBodyFreeFormObjectResponseString) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +[**Test-EchoBodyPet**](BodyApi.md#Test-EchoBodyPet) | **POST** /echo/body/Pet | Test body parameter(s) +[**Test-EchoBodyPetResponseString**](BodyApi.md#Test-EchoBodyPetResponseString) | **POST** /echo/body/Pet/response_string | Test empty response body +[**Test-EchoBodyTagResponseString**](BodyApi.md#Test-EchoBodyTagResponseString) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +[**Test-EchoBodyAllOfPet**](BodyApi.md#Test-EchoBodyAllOfPet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) + + + +# **Test-BinaryGif** +> System.IO.FileInfo Test-BinaryGif
              + +Test binary (gif) response body + +Test binary (gif) response body + +### Example +```powershell + +# Test binary (gif) response body +try { + $Result = Test-BinaryGif +} catch { + Write-Host ("Exception occurred when calling Test-BinaryGif: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**System.IO.FileInfo** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: image/gif + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-BodyApplicationOctetstreamBinary** +> String Test-BodyApplicationOctetstreamBinary
              +>         [-Body]
              + +Test body parameter(s) + +Test body parameter(s) + +### Example +```powershell +$Body = # System.IO.FileInfo | (optional) + +# Test body parameter(s) +try { + $Result = Test-BodyApplicationOctetstreamBinary -Body $Body +} catch { + Write-Host ("Exception occurred when calling Test-BodyApplicationOctetstreamBinary: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Body** | **System.IO.FileInfo****System.IO.FileInfo**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/octet-stream + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-BodyMultipartFormdataArrayOfBinary** +> String Test-BodyMultipartFormdataArrayOfBinary
              +>         [-Files]
              + +Test array of binary in multipart mime + +Test array of binary in multipart mime + +### Example +```powershell +$Files = # System.IO.FileInfo[] | + +# Test array of binary in multipart mime +try { + $Result = Test-BodyMultipartFormdataArrayOfBinary -Files $Files +} catch { + Write-Host ("Exception occurred when calling Test-BodyMultipartFormdataArrayOfBinary: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Files** | **System.IO.FileInfo[]**| | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-BodyMultipartFormdataSingleBinary** +> String Test-BodyMultipartFormdataSingleBinary
              +>         [-MyFile]
              + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example +```powershell +$MyFile = # System.IO.FileInfo | (optional) + +# Test single binary in multipart mime +try { + $Result = Test-BodyMultipartFormdataSingleBinary -MyFile $MyFile +} catch { + Write-Host ("Exception occurred when calling Test-BodyMultipartFormdataSingleBinary: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **MyFile** | **System.IO.FileInfo****System.IO.FileInfo**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-EchoBodyFreeFormObjectResponseString** +> String Test-EchoBodyFreeFormObjectResponseString
              +>         [-Body]
              + +Test free form object + +Test free form object + +### Example +```powershell +$Body = @{ key_example = ... } # SystemCollectionsHashtable | Free form object (optional) + +# Test free form object +try { + $Result = Test-EchoBodyFreeFormObjectResponseString -Body $Body +} catch { + Write-Host ("Exception occurred when calling Test-EchoBodyFreeFormObjectResponseString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Body** | **SystemCollectionsHashtable**| Free form object | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-EchoBodyPet** +> Pet Test-EchoBodyPet
              +>         [-Pet]
              + +Test body parameter(s) + +Test body parameter(s) + +### Example +```powershell +$Category = Initialize-Category -Id 1 -Name "Dogs" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 10 -Name "doggie" -Category $Category -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | Pet object that needs to be added to the store (optional) + +# Test body parameter(s) +try { + $Result = Test-EchoBodyPet -Pet $Pet +} catch { + Write-Host ("Exception occurred when calling Test-EchoBodyPet: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) (PSCustomObject) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-EchoBodyPetResponseString** +> String Test-EchoBodyPetResponseString
              +>         [-Pet]
              + +Test empty response body + +Test empty response body + +### Example +```powershell +$Category = Initialize-Category -Id 1 -Name "Dogs" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 10 -Name "doggie" -Category $Category -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | Pet object that needs to be added to the store (optional) + +# Test empty response body +try { + $Result = Test-EchoBodyPetResponseString -Pet $Pet +} catch { + Write-Host ("Exception occurred when calling Test-EchoBodyPetResponseString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-EchoBodyTagResponseString** +> String Test-EchoBodyTagResponseString
              +>         [-Tag]
              + +Test empty json (request body) + +Test empty json (request body) + +### Example +```powershell +$Tag = Initialize-Tag -Id 0 -Name "MyName" # Tag | Tag object (optional) + +# Test empty json (request body) +try { + $Result = Test-EchoBodyTagResponseString -Tag $Tag +} catch { + Write-Host ("Exception occurred when calling Test-EchoBodyTagResponseString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Tag** | [**Tag**](Tag.md)| Tag object | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-EchoBodyAllOfPet** +> Pet Test-EchoBodyAllOfPet
              +>         [-Pet]
              + +Test body parameter(s) + +Test body parameter(s) + +### Example +```powershell +$Category = Initialize-Category -Id 1 -Name "Dogs" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 10 -Name "doggie" -Category $Category -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | Pet object that needs to be added to the store (optional) + +# Test body parameter(s) +try { + $Result = Test-EchoBodyAllOfPet -Pet $Pet +} catch { + Write-Host ("Exception occurred when calling Test-EchoBodyAllOfPet: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) (PSCustomObject) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/Category.md b/samples/client/echo_api/powershell/docs/Category.md new file mode 100644 index 000000000000..1d6bc8d56bef --- /dev/null +++ b/samples/client/echo_api/powershell/docs/Category.md @@ -0,0 +1,23 @@ +# Category +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **Int64** | | [optional] +**Name** | **String** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$Category = Initialize-PSOpenAPIToolsCategory -Id 1 ` + -Name Dogs +``` + +- Convert the resource to JSON +```powershell +$Category | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/DataQuery.md b/samples/client/echo_api/powershell/docs/DataQuery.md new file mode 100644 index 000000000000..68ac67b59906 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/DataQuery.md @@ -0,0 +1,29 @@ +# DataQuery +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **Int64** | Query | [optional] +**Outcomes** | **String[]** | | [optional] +**Suffix** | **String** | test suffix | [optional] +**Text** | **String** | Some text containing white spaces | [optional] +**Date** | **System.DateTime** | A date | [optional] + +## Examples + +- Prepare the resource +```powershell +$DataQuery = Initialize-PSOpenAPIToolsDataQuery -Id null ` + -Outcomes null ` + -Suffix null ` + -Text Some text ` + -Date null +``` + +- Convert the resource to JSON +```powershell +$DataQuery | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/DefaultValue.md b/samples/client/echo_api/powershell/docs/DefaultValue.md new file mode 100644 index 000000000000..6217b0b2e589 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/DefaultValue.md @@ -0,0 +1,35 @@ +# DefaultValue +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**ArrayStringEnumRefDefault** | [**StringEnumRef[]**](StringEnumRef.md) | | [optional] +**ArrayStringEnumDefault** | **String[]** | | [optional] +**ArrayStringDefault** | **String[]** | | [optional] +**ArrayIntegerDefault** | **Int32[]** | | [optional] +**ArrayString** | **String[]** | | [optional] +**ArrayStringNullable** | **String[]** | | [optional] +**ArrayStringExtensionNullable** | **String[]** | | [optional] +**StringNullable** | **String** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$DefaultValue = Initialize-PSOpenAPIToolsDefaultValue -ArrayStringEnumRefDefault null ` + -ArrayStringEnumDefault null ` + -ArrayStringDefault null ` + -ArrayIntegerDefault null ` + -ArrayString null ` + -ArrayStringNullable null ` + -ArrayStringExtensionNullable null ` + -StringNullable null +``` + +- Convert the resource to JSON +```powershell +$DefaultValue | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/FormApi.md b/samples/client/echo_api/powershell/docs/FormApi.md new file mode 100644 index 000000000000..96b1e233351c --- /dev/null +++ b/samples/client/echo_api/powershell/docs/FormApi.md @@ -0,0 +1,117 @@ +# PSOpenAPITools.PSOpenAPITools\Api.FormApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-FormIntegerBooleanString**](FormApi.md#Test-FormIntegerBooleanString) | **POST** /form/integer/boolean/string | Test form parameter(s) +[**Test-FormOneof**](FormApi.md#Test-FormOneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema + + + +# **Test-FormIntegerBooleanString** +> String Test-FormIntegerBooleanString
              +>         [-IntegerForm]
              +>         [-BooleanForm]
              +>         [-StringForm]
              + +Test form parameter(s) + +Test form parameter(s) + +### Example +```powershell +$IntegerForm = 56 # Int32 | (optional) +$BooleanForm = $true # Boolean | (optional) +$StringForm = "MyStringForm" # String | (optional) + +# Test form parameter(s) +try { + $Result = Test-FormIntegerBooleanString -IntegerForm $IntegerForm -BooleanForm $BooleanForm -StringForm $StringForm +} catch { + Write-Host ("Exception occurred when calling Test-FormIntegerBooleanString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **IntegerForm** | **Int32**| | [optional] + **BooleanForm** | **Boolean**| | [optional] + **StringForm** | **String**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-FormOneof** +> String Test-FormOneof
              +>         [-Form1]
              +>         [-Form2]
              +>         [-Form3]
              +>         [-Form4]
              +>         [-Id]
              +>         [-Name]
              + +Test form parameter(s) for oneOf schema + +Test form parameter(s) for oneOf schema + +### Example +```powershell +$Form1 = "MyForm1" # String | (optional) +$Form2 = 56 # Int32 | (optional) +$Form3 = "MyForm3" # String | (optional) +$Form4 = $true # Boolean | (optional) +$Id = 789 # Int64 | (optional) +$Name = "MyName" # String | (optional) + +# Test form parameter(s) for oneOf schema +try { + $Result = Test-FormOneof -Form1 $Form1 -Form2 $Form2 -Form3 $Form3 -Form4 $Form4 -Id $Id -Name $Name +} catch { + Write-Host ("Exception occurred when calling Test-FormOneof: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **Form1** | **String**| | [optional] + **Form2** | **Int32**| | [optional] + **Form3** | **String**| | [optional] + **Form4** | **Boolean**| | [optional] + **Id** | **Int64**| | [optional] + **Name** | **String**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/HeaderApi.md b/samples/client/echo_api/powershell/docs/HeaderApi.md new file mode 100644 index 000000000000..74b19de21298 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/HeaderApi.md @@ -0,0 +1,64 @@ +# PSOpenAPITools.PSOpenAPITools\Api.HeaderApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-HeaderIntegerBooleanStringEnums**](HeaderApi.md#Test-HeaderIntegerBooleanStringEnums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) + + + +# **Test-HeaderIntegerBooleanStringEnums** +> String Test-HeaderIntegerBooleanStringEnums
              +>         [-IntegerHeader]
              +>         [-BooleanHeader]
              +>         [-StringHeader]
              +>         [-EnumNonrefStringHeader]
              +>         [-EnumRefStringHeader]
              + +Test header parameter(s) + +Test header parameter(s) + +### Example +```powershell +$IntegerHeader = 56 # Int32 | (optional) +$BooleanHeader = $true # Boolean | (optional) +$StringHeader = "MyStringHeader" # String | (optional) +$EnumNonrefStringHeader = "success" # String | (optional) +$EnumRefStringHeader = "success" # StringEnumRef | (optional) + +# Test header parameter(s) +try { + $Result = Test-HeaderIntegerBooleanStringEnums -IntegerHeader $IntegerHeader -BooleanHeader $BooleanHeader -StringHeader $StringHeader -EnumNonrefStringHeader $EnumNonrefStringHeader -EnumRefStringHeader $EnumRefStringHeader +} catch { + Write-Host ("Exception occurred when calling Test-HeaderIntegerBooleanStringEnums: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **IntegerHeader** | **Int32**| | [optional] + **BooleanHeader** | **Boolean**| | [optional] + **StringHeader** | **String**| | [optional] + **EnumNonrefStringHeader** | **String**| | [optional] + **EnumRefStringHeader** | [**StringEnumRef**](StringEnumRef.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/NumberPropertiesOnly.md b/samples/client/echo_api/powershell/docs/NumberPropertiesOnly.md new file mode 100644 index 000000000000..155a209a85af --- /dev/null +++ b/samples/client/echo_api/powershell/docs/NumberPropertiesOnly.md @@ -0,0 +1,25 @@ +# NumberPropertiesOnly +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Number** | **Decimal** | | [optional] +**Float** | **Double** | | [optional] +**Double** | **Double** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$NumberPropertiesOnly = Initialize-PSOpenAPIToolsNumberPropertiesOnly -Number null ` + -Float null ` + -Double null +``` + +- Convert the resource to JSON +```powershell +$NumberPropertiesOnly | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/PathApi.md b/samples/client/echo_api/powershell/docs/PathApi.md new file mode 100644 index 000000000000..1ee5292fd84a --- /dev/null +++ b/samples/client/echo_api/powershell/docs/PathApi.md @@ -0,0 +1,61 @@ +# PSOpenAPITools.PSOpenAPITools\Api.PathApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath**](PathApi.md#Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) + + + +# **Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath** +> String Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath
              +>         [-PathString]
              +>         [-PathInteger]
              +>         [-EnumNonrefStringPath]
              +>         [-EnumRefStringPath]
              + +Test path parameter(s) + +Test path parameter(s) + +### Example +```powershell +$PathString = "MyPathString" # String | +$PathInteger = 56 # Int32 | +$EnumNonrefStringPath = "success" # String | +$EnumRefStringPath = "success" # StringEnumRef | + +# Test path parameter(s) +try { + $Result = Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath -PathString $PathString -PathInteger $PathInteger -EnumNonrefStringPath $EnumNonrefStringPath -EnumRefStringPath $EnumRefStringPath +} catch { + Write-Host ("Exception occurred when calling Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **PathString** | **String**| | + **PathInteger** | **Int32**| | + **EnumNonrefStringPath** | **String**| | + **EnumRefStringPath** | [**StringEnumRef**](StringEnumRef.md)| | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/Pet.md b/samples/client/echo_api/powershell/docs/Pet.md new file mode 100644 index 000000000000..5839d09c86dc --- /dev/null +++ b/samples/client/echo_api/powershell/docs/Pet.md @@ -0,0 +1,31 @@ +# Pet +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **Int64** | | [optional] +**Name** | **String** | | +**Category** | [**Category**](Category.md) | | [optional] +**PhotoUrls** | **String[]** | | +**Tags** | [**Tag[]**](Tag.md) | | [optional] +**Status** | **String** | pet status in the store | [optional] + +## Examples + +- Prepare the resource +```powershell +$Pet = Initialize-PSOpenAPIToolsPet -Id 10 ` + -Name doggie ` + -Category null ` + -PhotoUrls null ` + -Tags null ` + -Status null +``` + +- Convert the resource to JSON +```powershell +$Pet | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/Query.md b/samples/client/echo_api/powershell/docs/Query.md new file mode 100644 index 000000000000..b4b02112afb5 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/Query.md @@ -0,0 +1,23 @@ +# Query +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **Int64** | Query | [optional] +**Outcomes** | **String[]** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$Query = Initialize-PSOpenAPIToolsQuery -Id null ` + -Outcomes null +``` + +- Convert the resource to JSON +```powershell +$Query | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/QueryApi.md b/samples/client/echo_api/powershell/docs/QueryApi.md new file mode 100644 index 000000000000..0af0d6193910 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/QueryApi.md @@ -0,0 +1,379 @@ +# PSOpenAPITools.PSOpenAPITools\Api.QueryApi + +All URIs are relative to *http://localhost:3000* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**Test-EnumRefString**](QueryApi.md#Test-EnumRefString) | **GET** /query/enum_ref_string | Test query parameter(s) +[**Test-QueryDatetimeDateString**](QueryApi.md#Test-QueryDatetimeDateString) | **GET** /query/datetime/date/string | Test query parameter(s) +[**Test-QueryIntegerBooleanString**](QueryApi.md#Test-QueryIntegerBooleanString) | **GET** /query/integer/boolean/string | Test query parameter(s) +[**Test-QueryStyleDeepObjectExplodeTrueObject**](QueryApi.md#Test-QueryStyleDeepObjectExplodeTrueObject) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +[**Test-QueryStyleDeepObjectExplodeTrueObjectAllOf**](QueryApi.md#Test-QueryStyleDeepObjectExplodeTrueObjectAllOf) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +[**Test-QueryStyleFormExplodeTrueArrayString**](QueryApi.md#Test-QueryStyleFormExplodeTrueArrayString) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +[**Test-QueryStyleFormExplodeTrueObject**](QueryApi.md#Test-QueryStyleFormExplodeTrueObject) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +[**Test-QueryStyleFormExplodeTrueObjectAllOf**](QueryApi.md#Test-QueryStyleFormExplodeTrueObjectAllOf) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + + +# **Test-EnumRefString** +> String Test-EnumRefString
              +>         [-EnumNonrefStringQuery]
              +>         [-EnumRefStringQuery]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$EnumNonrefStringQuery = "success" # String | (optional) +$EnumRefStringQuery = "success" # StringEnumRef | (optional) + +# Test query parameter(s) +try { + $Result = Test-EnumRefString -EnumNonrefStringQuery $EnumNonrefStringQuery -EnumRefStringQuery $EnumRefStringQuery +} catch { + Write-Host ("Exception occurred when calling Test-EnumRefString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **EnumNonrefStringQuery** | **String**| | [optional] + **EnumRefStringQuery** | [**StringEnumRef**](StringEnumRef.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryDatetimeDateString** +> String Test-QueryDatetimeDateString
              +>         [-DatetimeQuery]
              +>         [-DateQuery]
              +>         [-StringQuery]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$DatetimeQuery = (Get-Date) # System.DateTime | (optional) +$DateQuery = (Get-Date) # System.DateTime | (optional) +$StringQuery = "MyStringQuery" # String | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryDatetimeDateString -DatetimeQuery $DatetimeQuery -DateQuery $DateQuery -StringQuery $StringQuery +} catch { + Write-Host ("Exception occurred when calling Test-QueryDatetimeDateString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **DatetimeQuery** | **System.DateTime**| | [optional] + **DateQuery** | **System.DateTime**| | [optional] + **StringQuery** | **String**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryIntegerBooleanString** +> String Test-QueryIntegerBooleanString
              +>         [-IntegerQuery]
              +>         [-BooleanQuery]
              +>         [-StringQuery]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$IntegerQuery = 56 # Int32 | (optional) +$BooleanQuery = $true # Boolean | (optional) +$StringQuery = "MyStringQuery" # String | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryIntegerBooleanString -IntegerQuery $IntegerQuery -BooleanQuery $BooleanQuery -StringQuery $StringQuery +} catch { + Write-Host ("Exception occurred when calling Test-QueryIntegerBooleanString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **IntegerQuery** | **Int32**| | [optional] + **BooleanQuery** | **Boolean**| | [optional] + **StringQuery** | **String**| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryStyleDeepObjectExplodeTrueObject** +> String Test-QueryStyleDeepObjectExplodeTrueObject
              +>         [-QueryObject]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$Category = Initialize-Category -Id 1 -Name "Dogs" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 10 -Name "doggie" -Category $Category -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryStyleDeepObjectExplodeTrueObject -QueryObject $QueryObject +} catch { + Write-Host ("Exception occurred when calling Test-QueryStyleDeepObjectExplodeTrueObject: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **QueryObject** | [**Pet**](Pet.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryStyleDeepObjectExplodeTrueObjectAllOf** +> String Test-QueryStyleDeepObjectExplodeTrueObjectAllOf
              +>         [-QueryObject]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter = Initialize-TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter -Size "MySize" -Color "MyColor" -Id 1 -Name "Dogs" # TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryStyleDeepObjectExplodeTrueObjectAllOf -QueryObject $QueryObject +} catch { + Write-Host ("Exception occurred when calling Test-QueryStyleDeepObjectExplodeTrueObjectAllOf: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **QueryObject** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryStyleFormExplodeTrueArrayString** +> String Test-QueryStyleFormExplodeTrueArrayString
              +>         [-QueryObject]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = Initialize-TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter -Values "MyValues" # TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryStyleFormExplodeTrueArrayString -QueryObject $QueryObject +} catch { + Write-Host ("Exception occurred when calling Test-QueryStyleFormExplodeTrueArrayString: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **QueryObject** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryStyleFormExplodeTrueObject** +> String Test-QueryStyleFormExplodeTrueObject
              +>         [-QueryObject]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +$Category = Initialize-Category -Id 1 -Name "Dogs" +$Tag = Initialize-Tag -Id 0 -Name "MyName" +$Pet = Initialize-Pet -Id 10 -Name "doggie" -Category $Category -PhotoUrls "MyPhotoUrls" -Tags $Tag -Status "available" # Pet | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryStyleFormExplodeTrueObject -QueryObject $QueryObject +} catch { + Write-Host ("Exception occurred when calling Test-QueryStyleFormExplodeTrueObject: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **QueryObject** | [**Pet**](Pet.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + + +# **Test-QueryStyleFormExplodeTrueObjectAllOf** +> String Test-QueryStyleFormExplodeTrueObjectAllOf
              +>         [-QueryObject]
              + +Test query parameter(s) + +Test query parameter(s) + +### Example +```powershell +"SUCCESS"$DataQuery = Initialize-DataQuery -Id 0 -Outcomes "SUCCESS" -Suffix "MySuffix" -Text "Some text" -Date (Get-Date) # DataQuery | (optional) + +# Test query parameter(s) +try { + $Result = Test-QueryStyleFormExplodeTrueObjectAllOf -QueryObject $QueryObject +} catch { + Write-Host ("Exception occurred when calling Test-QueryStyleFormExplodeTrueObjectAllOf: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **QueryObject** | [**DataQuery**](DataQuery.md)| | [optional] + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/StringEnumRef.md b/samples/client/echo_api/powershell/docs/StringEnumRef.md new file mode 100644 index 000000000000..0366f951001c --- /dev/null +++ b/samples/client/echo_api/powershell/docs/StringEnumRef.md @@ -0,0 +1,20 @@ +# StringEnumRef +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- + +## Examples + +- Prepare the resource +```powershell +$StringEnumRef = Initialize-PSOpenAPIToolsStringEnumRef +``` + +- Convert the resource to JSON +```powershell +$StringEnumRef | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/Tag.md b/samples/client/echo_api/powershell/docs/Tag.md new file mode 100644 index 000000000000..7f7ef9fbb883 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/Tag.md @@ -0,0 +1,23 @@ +# Tag +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | **Int64** | | [optional] +**Name** | **String** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$Tag = Initialize-PSOpenAPIToolsTag -Id null ` + -Name null +``` + +- Convert the resource to JSON +```powershell +$Tag | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/powershell/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md new file mode 100644 index 000000000000..b854fd2b9e65 --- /dev/null +++ b/samples/client/echo_api/powershell/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -0,0 +1,27 @@ +# TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Size** | **String** | | [optional] +**Color** | **String** | | [optional] +**Id** | **Int64** | | [optional] +**Name** | **String** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter = Initialize-PSOpenAPIToolsTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter -Size null ` + -Color null ` + -Id 1 ` + -Name Dogs +``` + +- Convert the resource to JSON +```powershell +$TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/powershell/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md new file mode 100644 index 000000000000..96c091c3b0fe --- /dev/null +++ b/samples/client/echo_api/powershell/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -0,0 +1,21 @@ +# TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Values** | **String[]** | | [optional] + +## Examples + +- Prepare the resource +```powershell +$TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = Initialize-PSOpenAPIToolsTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter -Values null +``` + +- Convert the resource to JSON +```powershell +$TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | ConvertTo-JSON +``` + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/AuthApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/AuthApi.ps1 new file mode 100644 index 000000000000..c04c137d6f67 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/AuthApi.ps1 @@ -0,0 +1,146 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +To test HTTP basic authentication + +.DESCRIPTION + +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-AuthHttpBasic { + [CmdletBinding()] + Param ( + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-AuthHttpBasic' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/auth/http/basic' + + if ($Configuration["Username"] -and $Configuration["Password"]) { + $LocalVarBytes = [System.Text.Encoding]::UTF8.GetBytes($Configuration["Username"] + ":" + $Configuration["Password"]) + $LocalVarBase64Text =[Convert]::ToBase64String($LocalVarBytes) + $LocalVarHeaderParameters['Authorization'] = "Basic " + $LocalVarBase64Text + Write-Verbose ("Using HTTP basic authentication in {0}" -f $MyInvocation.MyCommand) + } + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +To test HTTP bearer authentication + +.DESCRIPTION + +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-AuthHttpBearer { + [CmdletBinding()] + Param ( + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-AuthHttpBearer' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/auth/http/bearer' + + if ($Configuration["AccessToken"]) { + $LocalVarHeaderParameters['Authorization'] = "Bearer " + $Configuration["AccessToken"] + Write-Verbose ("Using Bearer authentication in {0}" -f $MyInvocation.MyCommand) + } + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/BodyApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/BodyApi.ps1 new file mode 100644 index 000000000000..dbd9ab879924 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/BodyApi.ps1 @@ -0,0 +1,668 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Test binary (gif) response body + +.DESCRIPTION + +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +System.IO.FileInfo +#> +function Test-BinaryGif { + [CmdletBinding()] + Param ( + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-BinaryGif' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('image/gif') + + $LocalVarUri = '/binary/gif' + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "System.IO.FileInfo" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test body parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER Body +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-BodyApplicationOctetstreamBinary { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.IO.FileInfo] + ${Body}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-BodyApplicationOctetstreamBinary' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/octet-stream') + + $LocalVarUri = '/body/application/octetstream/binary' + + $LocalVarBodyParameter = $Body | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test array of binary in multipart mime + +.DESCRIPTION + +No description available. + +.PARAMETER Files +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-BodyMultipartFormdataArrayOfBinary { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.IO.FileInfo[]] + ${Files}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-BodyMultipartFormdataArrayOfBinary' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('multipart/form-data') + + $LocalVarUri = '/body/application/octetstream/array_of_binary' + + if (!$Files) { + throw "Error! The required parameter `Files` missing when calling test_body_multipart_formdata_arrayOfBinary." + } + $LocalVarFormParameters['files'] = $Files + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test single binary in multipart mime + +.DESCRIPTION + +No description available. + +.PARAMETER MyFile +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-BodyMultipartFormdataSingleBinary { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.IO.FileInfo] + ${MyFile}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-BodyMultipartFormdataSingleBinary' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('multipart/form-data') + + $LocalVarUri = '/body/application/octetstream/single_binary' + + if ($MyFile) { + $LocalVarFormParameters['my-file'] = $MyFile + } + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test free form object + +.DESCRIPTION + +No description available. + +.PARAMETER Body +Free form object + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-EchoBodyFreeFormObjectResponseString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[SystemCollectionsHashtable]] + ${Body}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EchoBodyFreeFormObjectResponseString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/echo/body/FreeFormObject/response_string' + + $LocalVarBodyParameter = $Body | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test body parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER Pet +Pet object that needs to be added to the store + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +Pet +#> +function Test-EchoBodyPet { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${Pet}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EchoBodyPet' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('application/json') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/echo/body/Pet' + + $LocalVarBodyParameter = $Pet | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "Pet" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test empty response body + +.DESCRIPTION + +No description available. + +.PARAMETER Pet +Pet object that needs to be added to the store + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-EchoBodyPetResponseString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${Pet}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EchoBodyPetResponseString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/echo/body/Pet/response_string' + + $LocalVarBodyParameter = $Pet | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test empty json (request body) + +.DESCRIPTION + +No description available. + +.PARAMETER Tag +Tag object + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-EchoBodyTagResponseString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${Tag}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EchoBodyTagResponseString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/echo/body/Tag/response_string' + + $LocalVarBodyParameter = $Tag | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test body parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER Pet +Pet object that needs to be added to the store + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +Pet +#> +function Test-EchoBodyAllOfPet { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${Pet}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EchoBodyAllOfPet' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('application/json') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/echo/body/allOf/Pet' + + $LocalVarBodyParameter = $Pet | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "Pet" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/FormApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/FormApi.ps1 new file mode 100644 index 000000000000..677221d160f7 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/FormApi.ps1 @@ -0,0 +1,230 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Test form parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER IntegerForm +No description available. + +.PARAMETER BooleanForm +No description available. + +.PARAMETER StringForm +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-FormIntegerBooleanString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Int32]] + ${IntegerForm}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Boolean]] + ${BooleanForm}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${StringForm}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-FormIntegerBooleanString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/x-www-form-urlencoded') + + $LocalVarUri = '/form/integer/boolean/string' + + if ($IntegerForm) { + $LocalVarFormParameters['integer_form'] = $IntegerForm + } + + if ($BooleanForm) { + $LocalVarFormParameters['boolean_form'] = $BooleanForm + } + + if ($StringForm) { + $LocalVarFormParameters['string_form'] = $StringForm + } + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test form parameter(s) for oneOf schema + +.DESCRIPTION + +No description available. + +.PARAMETER Form1 +No description available. + +.PARAMETER Form2 +No description available. + +.PARAMETER Form3 +No description available. + +.PARAMETER Form4 +No description available. + +.PARAMETER Id +No description available. + +.PARAMETER Name +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-FormOneof { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${Form1}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Int32]] + ${Form2}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${Form3}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Boolean]] + ${Form4}, + [Parameter(Position = 4, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 5, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${Name}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-FormOneof' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/x-www-form-urlencoded') + + $LocalVarUri = '/form/oneof' + + if ($Form1) { + $LocalVarFormParameters['form1'] = $Form1 + } + + if ($Form2) { + $LocalVarFormParameters['form2'] = $Form2 + } + + if ($Form3) { + $LocalVarFormParameters['form3'] = $Form3 + } + + if ($Form4) { + $LocalVarFormParameters['form4'] = $Form4 + } + + if ($Id) { + $LocalVarFormParameters['id'] = $Id + } + + if ($Name) { + $LocalVarFormParameters['name'] = $Name + } + + $LocalVarResult = Invoke-ApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/HeaderApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/HeaderApi.ps1 new file mode 100644 index 000000000000..73e5c3da98e3 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/HeaderApi.ps1 @@ -0,0 +1,122 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Test header parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER IntegerHeader +No description available. + +.PARAMETER BooleanHeader +No description available. + +.PARAMETER StringHeader +No description available. + +.PARAMETER EnumNonrefStringHeader +No description available. + +.PARAMETER EnumRefStringHeader +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-HeaderIntegerBooleanStringEnums { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Int32]] + ${IntegerHeader}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Boolean]] + ${BooleanHeader}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${StringHeader}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [ValidateSet("success", "failure", "unclassified")] + [String] + ${EnumNonrefStringHeader}, + [Parameter(Position = 4, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${EnumRefStringHeader}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-HeaderIntegerBooleanStringEnums' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/header/integer/boolean/string/enums' + + if ($IntegerHeader) { + $LocalVarHeaderParameters['integer_header'] = $IntegerHeader + } + + if ($BooleanHeader) { + $LocalVarHeaderParameters['boolean_header'] = $BooleanHeader + } + + if ($StringHeader) { + $LocalVarHeaderParameters['string_header'] = $StringHeader + } + + if ($EnumNonrefStringHeader) { + $LocalVarHeaderParameters['enum_nonref_string_header'] = $EnumNonrefStringHeader + } + + if ($EnumRefStringHeader) { + $LocalVarHeaderParameters['enum_ref_string_header'] = $EnumRefStringHeader + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/PathApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/PathApi.ps1 new file mode 100644 index 000000000000..1eb5d3453b65 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/PathApi.ps1 @@ -0,0 +1,112 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Test path parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER PathString +No description available. + +.PARAMETER PathInteger +No description available. + +.PARAMETER EnumNonrefStringPath +No description available. + +.PARAMETER EnumRefStringPath +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${PathString}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [Int32] + ${PathInteger}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [ValidateSet("success", "failure", "unclassified")] + [String] + ${EnumNonrefStringPath}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${EnumRefStringPath}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}' + if (!$PathString) { + throw "Error! The required parameter `PathString` missing when calling tests_path_string_pathString_integer_pathInteger_enumNonrefStringPath_enumRefStringPath." + } + $LocalVarUri = $LocalVarUri.replace('{path_string}', [System.Web.HTTPUtility]::UrlEncode($PathString)) + if (!$PathInteger) { + throw "Error! The required parameter `PathInteger` missing when calling tests_path_string_pathString_integer_pathInteger_enumNonrefStringPath_enumRefStringPath." + } + $LocalVarUri = $LocalVarUri.replace('{path_integer}', [System.Web.HTTPUtility]::UrlEncode($PathInteger)) + if (!$EnumNonrefStringPath) { + throw "Error! The required parameter `EnumNonrefStringPath` missing when calling tests_path_string_pathString_integer_pathInteger_enumNonrefStringPath_enumRefStringPath." + } + $LocalVarUri = $LocalVarUri.replace('{enum_nonref_string_path}', [System.Web.HTTPUtility]::UrlEncode($EnumNonrefStringPath)) + if (!$EnumRefStringPath) { + throw "Error! The required parameter `EnumRefStringPath` missing when calling tests_path_string_pathString_integer_pathInteger_enumNonrefStringPath_enumRefStringPath." + } + $LocalVarUri = $LocalVarUri.replace('{enum_ref_string_path}', [System.Web.HTTPUtility]::UrlEncode($EnumRefStringPath)) + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/QueryApi.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/QueryApi.ps1 new file mode 100644 index 000000000000..13bc99c15f46 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Api/QueryApi.ps1 @@ -0,0 +1,643 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER EnumNonrefStringQuery +No description available. + +.PARAMETER EnumRefStringQuery +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-EnumRefString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [ValidateSet("success", "failure", "unclassified")] + [String] + ${EnumNonrefStringQuery}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${EnumRefStringQuery}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-EnumRefString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/enum_ref_string' + + if ($EnumNonrefStringQuery) { + $LocalVarQueryParameters['enum_nonref_string_query'] = $EnumNonrefStringQuery + } + + if ($EnumRefStringQuery) { + $LocalVarQueryParameters['enum_ref_string_query'] = $EnumRefStringQuery + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER DatetimeQuery +No description available. + +.PARAMETER DateQuery +No description available. + +.PARAMETER StringQuery +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryDatetimeDateString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[System.DateTime]] + ${DatetimeQuery}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[System.DateTime]] + ${DateQuery}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${StringQuery}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryDatetimeDateString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/datetime/date/string' + + if ($DatetimeQuery) { + $LocalVarQueryParameters['datetime_query'] = $DatetimeQuery + } + + if ($DateQuery) { + $LocalVarQueryParameters['date_query'] = $DateQuery + } + + if ($StringQuery) { + $LocalVarQueryParameters['string_query'] = $StringQuery + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER IntegerQuery +No description available. + +.PARAMETER BooleanQuery +No description available. + +.PARAMETER StringQuery +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryIntegerBooleanString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Int32]] + ${IntegerQuery}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Nullable[Boolean]] + ${BooleanQuery}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [String] + ${StringQuery}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryIntegerBooleanString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/integer/boolean/string' + + if ($IntegerQuery) { + $LocalVarQueryParameters['integer_query'] = $IntegerQuery + } + + if ($BooleanQuery) { + $LocalVarQueryParameters['boolean_query'] = $BooleanQuery + } + + if ($StringQuery) { + $LocalVarQueryParameters['string_query'] = $StringQuery + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER QueryObject +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryStyleDeepObjectExplodeTrueObject { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${QueryObject}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryStyleDeepObjectExplodeTrueObject' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/style_deepObject/explode_true/object' + + if ($QueryObject) { + $LocalVarQueryParameters['query_object'] = $QueryObject + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER QueryObject +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryStyleDeepObjectExplodeTrueObjectAllOf { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${QueryObject}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryStyleDeepObjectExplodeTrueObjectAllOf' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/style_deepObject/explode_true/object/allOf' + + if ($QueryObject) { + $LocalVarQueryParameters['query_object'] = $QueryObject + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER QueryObject +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryStyleFormExplodeTrueArrayString { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${QueryObject}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryStyleFormExplodeTrueArrayString' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/style_form/explode_true/array_string' + + if ($QueryObject) { + $LocalVarQueryParameters['query_object'] = $QueryObject + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER QueryObject +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryStyleFormExplodeTrueObject { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${QueryObject}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryStyleFormExplodeTrueObject' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/style_form/explode_true/object' + + if ($QueryObject) { + $LocalVarQueryParameters['query_object'] = $QueryObject + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + +Test query parameter(s) + +.DESCRIPTION + +No description available. + +.PARAMETER QueryObject +No description available. + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +String +#> +function Test-QueryStyleFormExplodeTrueObjectAllOf { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [PSCustomObject] + ${QueryObject}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-QueryStyleFormExplodeTrueObjectAllOf' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-Configuration + # HTTP header 'Accept' (if needed) + $LocalVarAccepts = @('text/plain') + + $LocalVarUri = '/query/style_form/explode_true/object/allOf' + + if ($QueryObject) { + $LocalVarQueryParameters['query_object'] = $QueryObject + } + + $LocalVarResult = Invoke-ApiClient -Method 'GET' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "String" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Client/Configuration.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Client/Configuration.ps1 new file mode 100644 index 000000000000..9e1aa107bbc1 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Client/Configuration.ps1 @@ -0,0 +1,515 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Get the configuration object 'Configuration'. + +.DESCRIPTION + +Get the configuration object 'Configuration'. + +.OUTPUTS + +System.Collections.Hashtable +#> +function Get-Configuration { + + $Configuration = $Script:Configuration + + if ([string]::IsNullOrEmpty($Configuration["BaseUrl"])) { + $Configuration["BaseUrl"] = "http://localhost:3000"; + } + + if (!$Configuration.containsKey("Username")) { + $Configuration["Username"] = $null + } + if (!$Configuration.containsKey("Password")) { + $Configuration["Password"] = $null + } + if (!$Configuration.containsKey("AccessToken")) { + $Configuration["AccessToken"] = $null + } + if (!$Configuration.containsKey("Cookie")) { + $Configuration["Cookie"] = $null + } + + if (!$Configuration["DefaultHeaders"]) { + $Configuration["DefaultHeaders"] = @{} + } + + if (!$Configuration["ApiKey"]) { + $Configuration["ApiKey"] = @{} + } + + if (!$Configuration["ApiKeyPrefix"]) { + $Configuration["ApiKeyPrefix"] = @{} + } + + if (!$Configuration.containsKey("SkipCertificateCheck")) { + $Configuration["SkipCertificateCheck"] = $false + } + + if (!$Configuration.containsKey("Proxy")) { + $Configuration["Proxy"] = $null + } + + Return $Configuration + +} + +<# +.SYNOPSIS + +Set the configuration. + +.DESCRIPTION + +Set the configuration. + +.PARAMETER BaseUrl +Base URL of the HTTP endpoints + +.PARAMETER Username +Username in HTTP basic authentication + +.PARAMETER Password +Password in HTTP basic authentication + +.PARAMETER ApiKey +API Keys for authentication/authorization + +.PARAMETER ApiKeyPrefix +Prefix in the API Keys + +.PARAMETER Cookie +Cookie for authentication/authorization + +.PARAMETER AccessToken +Access token for authentication/authorization + +.PARAMETER SkipCertificateCheck +Skip certificate verification + +.PARAMETER DefaultHeaders +Default HTTP headers to be included in the HTTP request + +.PARAMETER Proxy +Proxy setting in the HTTP request, e.g. + +$proxy = [System.Net.WebRequest]::GetSystemWebProxy() +$proxy.Credentials = [System.Net.CredentialCache]::DefaultCredentials + +.PARAMETER PassThru +Return an object of the Configuration + +.OUTPUTS + +System.Collections.Hashtable +#> +function Set-Configuration { + + [CmdletBinding()] + Param( + [string]$BaseUrl, + [AllowEmptyString()] + [string]$Username, + [AllowEmptyString()] + [string]$Password, + [hashtable]$ApiKey, + [hashtable]$ApiKeyPrefix, + [AllowEmptyString()] + [string]$Cookie, + [AllowEmptyString()] + [string]$AccessToken, + [switch]$SkipCertificateCheck, + [hashtable]$DefaultHeaders, + [System.Object]$Proxy, + [switch]$PassThru + ) + + Process { + + If ($BaseUrl) { + # validate URL + $URL = $BaseUrl -as [System.URI] + if (!($null -ne $URL.AbsoluteURI -and $URL.Scheme -match '[http|https]')) { + throw "Invalid URL '$($BaseUrl)' cannot be used in the base URL." + } + $Script:Configuration["BaseUrl"] = $BaseUrl + } + + If ($Username) { + $Script:Configuration['Username'] = $Username + } + + If ($Password) { + $Script:Configuration['Password'] = $Password + } + + If ($ApiKey) { + $Script:Configuration['ApiKey'] = $ApiKey + } + + If ($ApiKeyPrefix) { + $Script:Configuration['ApiKeyPrefix'] = $ApiKeyPrefix + } + + If ($Cookie) { + $Script:Configuration['Cookie'] = $Cookie + } + + If ($AccessToken) { + $Script:Configuration['AccessToken'] = $AccessToken + } + + If ($SkipCertificateCheck.IsPresent) { + $Script:Configuration['SkipCertificateCheck'] = $true + } else { + $Script:Configuration['SkipCertificateCheck'] = $false + } + + If ($DefaultHeaders) { + $Script:Configuration['DefaultHeaders'] = $DefaultHeaders + } + + If ($null -ne $Proxy) { + If ($Proxy.GetType().FullName -ne "System.Net.SystemWebProxy" -and $Proxy.GetType().FullName -ne "System.Net.WebRequest+WebProxyWrapperOpaque") { + throw "Incorrect Proxy type '$($Proxy.GetType().FullName)'. Must be System.Net.SystemWebProxy or System.Net.WebRequest+WebProxyWrapperOpaque." + } + $Script:Configuration['Proxy'] = $Proxy + } else { + $Script:Configuration['Proxy'] = $null + } + + If ($PassThru.IsPresent) { + $Script:Configuration + } + } +} + +<# +.SYNOPSIS + +Set the API Key. + +.DESCRIPTION + +Set the API Key. + +.PARAMETER Id +ID of the security schema + +.PARAMETER ApiKey +API Key + +.OUTPUTS + +None +#> +function Set-ConfigurationApiKey { + [CmdletBinding()] + Param( + [string]$Id, + [AllowEmptyString()] + [string]$ApiKey + ) + Process { + if (!$Script:Configuration["ApiKey"]) { + $Script:Configuration["ApiKey"] = @{} + } + $Script:Configuration["ApiKey"][$Id] = $ApiKey + } +} + +<# +.SYNOPSIS + +Set the API Key prefix. + +.DESCRIPTION + +Set the API Key prefix. + +.PARAMETER Id +ID of the security schema + +.PARAMETER ApiKey +API Key prefix + +.OUTPUTS + +None +#> +function Set-ConfigurationApiKeyPrefix { + [CmdletBinding()] + Param( + [string]$Id, + [AllowEmptyString()] + [string]$ApiKeyPrefix + ) + Process { + if (!$Script:Configuration["ApiKeyPrefix"]) { + $Script:Configuration["ApiKeyPrefix"] = @{} + } + $Script:Configuration["ApiKeyPrefix"][$Id] = $ApiKeyPrefix + } +} + +<# +.SYNOPSIS + +Set the default header. + +.DESCRIPTION + +Set the default header. + +.PARAMETER Key +Key of the HTTP header + +.PARAMETER Value +Value of the HTTP header + +.OUTPUTS + +None +#> +function Set-ConfigurationDefaultHeader { + [CmdletBinding()] + Param( + [string]$Key, + [AllowEmptyString()] + [string]$Value + ) + Process { + if (!$Script:Configuration["DefaultHeaders"]) { + $Script:Configuration["DefaultHeaders"] = @{} + } + $Script:Configuration["DefaultHeaders"][$Key] = $Value + } +} + + +<# +.SYNOPSIS + +Get the host setting. + +.DESCRIPTION + +Get the host setting in the form of array of hashtables. + +.OUTPUTS + +System.Collections.Hashtable[] +#> +function Get-HostSetting { + return ,@( + @{ + "Url" = "http://localhost:3000"; + "Description" = "No description provided"; + } + ) + +} + +<# +.SYNOPSIS + +Get the URL from the host settings. + +.PARAMETER Index +Index of the host settings (array) + +.PARAMETER Variables +Names and values of the variables (hashtable) + +.DESCRIPTION + +Get the URL from the host settings. + +.OUTPUTS + +String +#> +function Get-UrlFromHostSetting { + + [CmdletBinding()] + Param( + [Parameter(ValueFromPipeline = $true)] + [Int]$Index, + [Hashtable]$Variables = @{} + ) + + Process { + $Hosts = Get-HostSetting + + # check array index out of bound + if ($Index -lt 0 -or $Index -ge $Hosts.Length) { + throw "Invalid index $index when selecting the host. Must be less than $($Hosts.Length)" + } + + $MyHost = $Hosts[$Index]; + $Url = $MyHost["Url"]; + + # go through variable and assign a value + foreach ($h in $MyHost["Variables"].GetEnumerator()) { + if ($Variables.containsKey($h.Name)) { # check to see if it's in the variables provided by the user + if ($h.Value["EnumValues"] -Contains $Variables[$h.Name]) { + $Url = $Url.replace("{$($h.Name)}", $Variables[$h.Name]) + } else { + throw "The variable '$($h.Name)' in the host URL has invalid value $($Variables[$h.Name]). Must be $($h.Value["EnumValues"] -join ",")" + } + } else { + $Url = $Url.replace("{$($h.Name)}", $h.Value["DefaultValue"]) + } + } + + return $Url; + + } +} + +<# +.SYNOPSIS +Sets the configuration for http signing. +.DESCRIPTION + +Sets the configuration for the HTTP signature security scheme. +The HTTP signature security scheme is used to sign HTTP requests with a key +which is in possession of the API client. +An 'Authorization' header is calculated by creating a hash of select headers, +and optionally the body of the HTTP request, then signing the hash value using +a key. The 'Authorization' header is added to outbound HTTP requests. + +Ref: https://openapi-generator.tech + +.PARAMETER KeyId +KeyId for HTTP signing + +.PARAMETER KeyFilePath +KeyFilePath for HTTP signing + +.PARAMETER KeyPassPhrase +KeyPassPhrase, if the HTTP signing key is protected + +.PARAMETER HttpSigningHeader +HttpSigningHeader list of HTTP headers used to calculate the signature. The two special signature headers '(request-target)' and '(created)' +SHOULD be included. + The '(created)' header expresses when the signature was created. + The '(request-target)' header is a concatenation of the lowercased :method, an + ASCII space, and the :path pseudo-headers. +If no headers are specified then '(created)' sets as default. + +.PARAMETER HashAlgorithm +HashAlgorithm to calculate the hash, Supported values are "sha256" and "sha512" + +.PARAMETER SigningAlgorithm +SigningAlgorithm specifies the signature algorithm, supported values are "RSASSA-PKCS1-v1_5" and "RSASSA-PSS" +RSA key : Supported values "RSASSA-PKCS1-v1_5" and "RSASSA-PSS", for ECDSA key this parameter is not applicable + +.PARAMETER SignatureValidityPeriod +SignatureValidityPeriod specifies the signature maximum validity time in seconds. It accepts integer value + +.OUTPUTS + +System.Collections.Hashtable +#> +function Set-ConfigurationHttpSigning { + [CmdletBinding()] + param( + [Parameter(Mandatory = $true)] + [ValidateNotNullOrEmpty()] + [string]$KeyId, + [Parameter(Mandatory = $true)] + [string]$KeyFilePath, + [Parameter(Mandatory = $false)] + [securestring]$KeyPassPhrase, + [Parameter(Mandatory = $false)] + [ValidateNotNullOrEmpty()] + [string[]] $HttpSigningHeader = @("(created)"), + [Parameter(Mandatory = $false)] + [ValidateSet("sha256", "sha512")] + [string] $HashAlgorithm = "sha256", + [Parameter(Mandatory = $false)] + [ValidateSet("RSASSA-PKCS1-v1_5", "RSASSA-PSS")] + [string]$SigningAlgorithm , + [Parameter(Mandatory = $false)] + [int]$SignatureValidityPeriod + ) + + Process { + $httpSignatureConfiguration = @{ } + + if (Test-Path -Path $KeyFilePath) { + $httpSignatureConfiguration["KeyId"] = $KeyId + $httpSignatureConfiguration["KeyFilePath"] = $KeyFilePath + } + else { + throw "Private key file path does not exist" + } + + $keyType = Get-KeyTypeFromFile -KeyFilePath $KeyFilePath + if ([String]::IsNullOrEmpty($SigningAlgorithm)) { + if ($keyType -eq "RSA") { + $SigningAlgorithm = "RSASSA-PKCS1-v1_5" + } + } + + if ($keyType -eq "RSA" -and + ($SigningAlgorithm -ne "RSASSA-PKCS1-v1_5" -and $SigningAlgorithm -ne "RSASSA-PSS" )) { + throw "Provided Key and SigningAlgorithm : $SigningAlgorithm is not compatible." + } + + if ($HttpSigningHeader -contains "(expires)" -and $SignatureValidityPeriod -le 0) { + throw "SignatureValidityPeriod must be greater than 0 seconds." + } + + if ($HttpSigningHeader -contains "(expires)") { + $httpSignatureConfiguration["SignatureValidityPeriod"] = $SignatureValidityPeriod + } + if ($null -ne $HttpSigningHeader -and $HttpSigningHeader.Length -gt 0) { + $httpSignatureConfiguration["HttpSigningHeader"] = $HttpSigningHeader + } + + if ($null -ne $HashAlgorithm ) { + $httpSignatureConfiguration["HashAlgorithm"] = $HashAlgorithm + } + + if ($null -ne $SigningAlgorithm) { + $httpSignatureConfiguration["SigningAlgorithm"] = $SigningAlgorithm + } + + if ($null -ne $KeyPassPhrase) { + $httpSignatureConfiguration["KeyPassPhrase"] = $KeyPassPhrase + } + + $Script:Configuration["HttpSigning"] = New-Object -TypeName PSCustomObject -Property $httpSignatureConfiguration + } +} + +<# +.SYNOPSIS + +Get the configuration object 'ConfigurationHttpSigning'. + +.DESCRIPTION + +Get the configuration object 'ConfigurationHttpSigning'. + +.OUTPUTS + +[PSCustomObject] +#> +function Get-ConfigurationHttpSigning{ + + $httpSignatureConfiguration = $Script:Configuration["HttpSigning"] + return $httpSignatureConfiguration +} diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Bird.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Bird.ps1 new file mode 100644 index 000000000000..e699ce79035f --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Bird.ps1 @@ -0,0 +1,111 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Size +No description available. +.PARAMETER Color +No description available. +.OUTPUTS + +Bird +#> + +function Initialize-Bird { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [String] + ${Size}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [String] + ${Color} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => Bird' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "size" = ${Size} + "color" = ${Color} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to Bird + +.DESCRIPTION + +Convert from JSON to Bird + +.PARAMETER Json + +Json object + +.OUTPUTS + +Bird +#> +function ConvertFrom-JsonToBird { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => Bird' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in Bird + $AllProperties = ("size", "color") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "size"))) { #optional property not found + $Size = $null + } else { + $Size = $JsonParameters.PSobject.Properties["size"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "color"))) { #optional property not found + $Color = $null + } else { + $Color = $JsonParameters.PSobject.Properties["color"].value + } + + $PSO = [PSCustomObject]@{ + "size" = ${Size} + "color" = ${Color} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Category.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Category.ps1 new file mode 100644 index 000000000000..4e561693da9a --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Category.ps1 @@ -0,0 +1,111 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Id +No description available. +.PARAMETER Name +No description available. +.OUTPUTS + +Category +#> + +function Initialize-Category { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [String] + ${Name} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => Category' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to Category + +.DESCRIPTION + +Convert from JSON to Category + +.PARAMETER Json + +Json object + +.OUTPUTS + +Category +#> +function ConvertFrom-JsonToCategory { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => Category' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in Category + $AllProperties = ("id", "name") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found + $Name = $null + } else { + $Name = $JsonParameters.PSobject.Properties["name"].value + } + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DataQuery.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DataQuery.ps1 new file mode 100644 index 000000000000..9fadb40d2278 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DataQuery.ps1 @@ -0,0 +1,151 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Id +Query +.PARAMETER Outcomes +No description available. +.PARAMETER Suffix +test suffix +.PARAMETER Text +Some text containing white spaces +.PARAMETER Date +A date +.OUTPUTS + +DataQuery +#> + +function Initialize-DataQuery { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [ValidateSet("SUCCESS", "FAILURE", "SKIPPED")] + [String[]] + ${Outcomes}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] + [String] + ${Suffix}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true)] + [String] + ${Text}, + [Parameter(Position = 4, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[System.DateTime]] + ${Date} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => DataQuery' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "outcomes" = ${Outcomes} + "suffix" = ${Suffix} + "text" = ${Text} + "date" = ${Date} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to DataQuery + +.DESCRIPTION + +Convert from JSON to DataQuery + +.PARAMETER Json + +Json object + +.OUTPUTS + +DataQuery +#> +function ConvertFrom-JsonToDataQuery { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => DataQuery' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in DataQuery + $AllProperties = ("id", "outcomes", "suffix", "text", "date") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "outcomes"))) { #optional property not found + $Outcomes = $null + } else { + $Outcomes = $JsonParameters.PSobject.Properties["outcomes"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "suffix"))) { #optional property not found + $Suffix = $null + } else { + $Suffix = $JsonParameters.PSobject.Properties["suffix"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "text"))) { #optional property not found + $Text = $null + } else { + $Text = $JsonParameters.PSobject.Properties["text"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "date"))) { #optional property not found + $Date = $null + } else { + $Date = $JsonParameters.PSobject.Properties["date"].value + } + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "outcomes" = ${Outcomes} + "suffix" = ${Suffix} + "text" = ${Text} + "date" = ${Date} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DefaultValue.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DefaultValue.ps1 new file mode 100644 index 000000000000..0b01f22b39b4 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/DefaultValue.ps1 @@ -0,0 +1,190 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +to test the default value of properties + +.PARAMETER ArrayStringEnumRefDefault +No description available. +.PARAMETER ArrayStringEnumDefault +No description available. +.PARAMETER ArrayStringDefault +No description available. +.PARAMETER ArrayIntegerDefault +No description available. +.PARAMETER ArrayString +No description available. +.PARAMETER ArrayStringNullable +No description available. +.PARAMETER ArrayStringExtensionNullable +No description available. +.PARAMETER StringNullable +No description available. +.OUTPUTS + +DefaultValue +#> + +function Initialize-DefaultValue { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [PSCustomObject[]] + ${ArrayStringEnumRefDefault}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [ValidateSet("success", "failure", "unclassified")] + [String[]] + ${ArrayStringEnumDefault}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${ArrayStringDefault}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true)] + [Int32[]] + ${ArrayIntegerDefault}, + [Parameter(Position = 4, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${ArrayString}, + [Parameter(Position = 5, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${ArrayStringNullable}, + [Parameter(Position = 6, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${ArrayStringExtensionNullable}, + [Parameter(Position = 7, ValueFromPipelineByPropertyName = $true)] + [String] + ${StringNullable} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => DefaultValue' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "array_string_enum_ref_default" = ${ArrayStringEnumRefDefault} + "array_string_enum_default" = ${ArrayStringEnumDefault} + "array_string_default" = ${ArrayStringDefault} + "array_integer_default" = ${ArrayIntegerDefault} + "array_string" = ${ArrayString} + "array_string_nullable" = ${ArrayStringNullable} + "array_string_extension_nullable" = ${ArrayStringExtensionNullable} + "string_nullable" = ${StringNullable} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to DefaultValue + +.DESCRIPTION + +Convert from JSON to DefaultValue + +.PARAMETER Json + +Json object + +.OUTPUTS + +DefaultValue +#> +function ConvertFrom-JsonToDefaultValue { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => DefaultValue' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in DefaultValue + $AllProperties = ("array_string_enum_ref_default", "array_string_enum_default", "array_string_default", "array_integer_default", "array_string", "array_string_nullable", "array_string_extension_nullable", "string_nullable") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string_enum_ref_default"))) { #optional property not found + $ArrayStringEnumRefDefault = $null + } else { + $ArrayStringEnumRefDefault = $JsonParameters.PSobject.Properties["array_string_enum_ref_default"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string_enum_default"))) { #optional property not found + $ArrayStringEnumDefault = $null + } else { + $ArrayStringEnumDefault = $JsonParameters.PSobject.Properties["array_string_enum_default"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string_default"))) { #optional property not found + $ArrayStringDefault = $null + } else { + $ArrayStringDefault = $JsonParameters.PSobject.Properties["array_string_default"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_integer_default"))) { #optional property not found + $ArrayIntegerDefault = $null + } else { + $ArrayIntegerDefault = $JsonParameters.PSobject.Properties["array_integer_default"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string"))) { #optional property not found + $ArrayString = $null + } else { + $ArrayString = $JsonParameters.PSobject.Properties["array_string"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string_nullable"))) { #optional property not found + $ArrayStringNullable = $null + } else { + $ArrayStringNullable = $JsonParameters.PSobject.Properties["array_string_nullable"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "array_string_extension_nullable"))) { #optional property not found + $ArrayStringExtensionNullable = $null + } else { + $ArrayStringExtensionNullable = $JsonParameters.PSobject.Properties["array_string_extension_nullable"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "string_nullable"))) { #optional property not found + $StringNullable = $null + } else { + $StringNullable = $JsonParameters.PSobject.Properties["string_nullable"].value + } + + $PSO = [PSCustomObject]@{ + "array_string_enum_ref_default" = ${ArrayStringEnumRefDefault} + "array_string_enum_default" = ${ArrayStringEnumDefault} + "array_string_default" = ${ArrayStringDefault} + "array_integer_default" = ${ArrayIntegerDefault} + "array_string" = ${ArrayString} + "array_string_nullable" = ${ArrayStringNullable} + "array_string_extension_nullable" = ${ArrayStringExtensionNullable} + "string_nullable" = ${StringNullable} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/NumberPropertiesOnly.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/NumberPropertiesOnly.ps1 new file mode 100644 index 000000000000..131819de86a5 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/NumberPropertiesOnly.ps1 @@ -0,0 +1,132 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Number +No description available. +.PARAMETER Float +No description available. +.PARAMETER Double +No description available. +.OUTPUTS + +NumberPropertiesOnly +#> + +function Initialize-NumberPropertiesOnly { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Decimal]] + ${Number}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Double]] + ${Float}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Double]] + ${Double} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => NumberPropertiesOnly' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + if ($Double -and $Double -gt 50.2) { + throw "invalid value for 'Double', must be smaller than or equal to 50.2." + } + + if ($Double -and $Double -lt 0.8) { + throw "invalid value for 'Double', must be greater than or equal to 0.8." + } + + + $PSO = [PSCustomObject]@{ + "number" = ${Number} + "float" = ${Float} + "double" = ${Double} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to NumberPropertiesOnly + +.DESCRIPTION + +Convert from JSON to NumberPropertiesOnly + +.PARAMETER Json + +Json object + +.OUTPUTS + +NumberPropertiesOnly +#> +function ConvertFrom-JsonToNumberPropertiesOnly { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => NumberPropertiesOnly' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in NumberPropertiesOnly + $AllProperties = ("number", "float", "double") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "number"))) { #optional property not found + $Number = $null + } else { + $Number = $JsonParameters.PSobject.Properties["number"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "float"))) { #optional property not found + $Float = $null + } else { + $Float = $JsonParameters.PSobject.Properties["float"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "double"))) { #optional property not found + $Double = $null + } else { + $Double = $JsonParameters.PSobject.Properties["double"].value + } + + $PSO = [PSCustomObject]@{ + "number" = ${Number} + "float" = ${Float} + "double" = ${Double} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Pet.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Pet.ps1 new file mode 100644 index 000000000000..e89786caafd9 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Pet.ps1 @@ -0,0 +1,176 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Id +No description available. +.PARAMETER Name +No description available. +.PARAMETER Category +No description available. +.PARAMETER PhotoUrls +No description available. +.PARAMETER Tags +No description available. +.PARAMETER Status +pet status in the store +.OUTPUTS + +Pet +#> + +function Initialize-Pet { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [String] + ${Name}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] + [PSCustomObject] + ${Category}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${PhotoUrls}, + [Parameter(Position = 4, ValueFromPipelineByPropertyName = $true)] + [PSCustomObject[]] + ${Tags}, + [Parameter(Position = 5, ValueFromPipelineByPropertyName = $true)] + [ValidateSet("available", "pending", "sold")] + [String] + ${Status} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => Pet' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + if ($null -eq $Name) { + throw "invalid value for 'Name', 'Name' cannot be null." + } + + if ($null -eq $PhotoUrls) { + throw "invalid value for 'PhotoUrls', 'PhotoUrls' cannot be null." + } + + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + "category" = ${Category} + "photoUrls" = ${PhotoUrls} + "tags" = ${Tags} + "status" = ${Status} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to Pet + +.DESCRIPTION + +Convert from JSON to Pet + +.PARAMETER Json + +Json object + +.OUTPUTS + +Pet +#> +function ConvertFrom-JsonToPet { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => Pet' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in Pet + $AllProperties = ("id", "name", "category", "photoUrls", "tags", "status") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + If ([string]::IsNullOrEmpty($Json) -or $Json -eq "{}") { # empty json + throw "Error! Empty JSON cannot be serialized due to the required property 'name' missing." + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { + throw "Error! JSON cannot be serialized due to the required property 'name' missing." + } else { + $Name = $JsonParameters.PSobject.Properties["name"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "photoUrls"))) { + throw "Error! JSON cannot be serialized due to the required property 'photoUrls' missing." + } else { + $PhotoUrls = $JsonParameters.PSobject.Properties["photoUrls"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "category"))) { #optional property not found + $Category = $null + } else { + $Category = $JsonParameters.PSobject.Properties["category"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "tags"))) { #optional property not found + $Tags = $null + } else { + $Tags = $JsonParameters.PSobject.Properties["tags"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "status"))) { #optional property not found + $Status = $null + } else { + $Status = $JsonParameters.PSobject.Properties["status"].value + } + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + "category" = ${Category} + "photoUrls" = ${PhotoUrls} + "tags" = ${Tags} + "status" = ${Status} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Query.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Query.ps1 new file mode 100644 index 000000000000..def037062dc7 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Query.ps1 @@ -0,0 +1,112 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Id +Query +.PARAMETER Outcomes +No description available. +.OUTPUTS + +Query +#> + +function Initialize-Query { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [ValidateSet("SUCCESS", "FAILURE", "SKIPPED")] + [String[]] + ${Outcomes} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => Query' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "outcomes" = ${Outcomes} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to Query + +.DESCRIPTION + +Convert from JSON to Query + +.PARAMETER Json + +Json object + +.OUTPUTS + +Query +#> +function ConvertFrom-JsonToQuery { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => Query' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in Query + $AllProperties = ("id", "outcomes") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "outcomes"))) { #optional property not found + $Outcomes = $null + } else { + $Outcomes = $JsonParameters.PSobject.Properties["outcomes"].value + } + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "outcomes" = ${Outcomes} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/StringEnumRef.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/StringEnumRef.ps1 new file mode 100644 index 000000000000..3ea65a59c5ac --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/StringEnumRef.ps1 @@ -0,0 +1,27 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +Enum StringEnumRef. + +.DESCRIPTION + +No description available. +#> + +enum StringEnumRef { + # enum value: "success" + success + # enum value: "failure" + failure + # enum value: "unclassified" + unclassified +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Tag.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Tag.ps1 new file mode 100644 index 000000000000..ab572c56d99f --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/Tag.ps1 @@ -0,0 +1,111 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Id +No description available. +.PARAMETER Name +No description available. +.OUTPUTS + +Tag +#> + +function Initialize-Tag { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [String] + ${Name} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => Tag' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to Tag + +.DESCRIPTION + +Convert from JSON to Tag + +.PARAMETER Json + +Json object + +.OUTPUTS + +Tag +#> +function ConvertFrom-JsonToTag { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => Tag' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in Tag + $AllProperties = ("id", "name") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found + $Name = $null + } else { + $Name = $JsonParameters.PSobject.Properties["name"].value + } + + $PSO = [PSCustomObject]@{ + "id" = ${Id} + "name" = ${Name} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.ps1 new file mode 100644 index 000000000000..e38d86a22b86 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.ps1 @@ -0,0 +1,137 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Size +No description available. +.PARAMETER Color +No description available. +.PARAMETER Id +No description available. +.PARAMETER Name +No description available. +.OUTPUTS + +TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter +#> + +function Initialize-TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [String] + ${Size}, + [Parameter(Position = 1, ValueFromPipelineByPropertyName = $true)] + [String] + ${Color}, + [Parameter(Position = 2, ValueFromPipelineByPropertyName = $true)] + [System.Nullable[Int64]] + ${Id}, + [Parameter(Position = 3, ValueFromPipelineByPropertyName = $true)] + [String] + ${Name} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "size" = ${Size} + "color" = ${Color} + "id" = ${Id} + "name" = ${Name} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + +.DESCRIPTION + +Convert from JSON to TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + +.PARAMETER Json + +Json object + +.OUTPUTS + +TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter +#> +function ConvertFrom-JsonToTestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + $AllProperties = ("size", "color", "id", "name") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "size"))) { #optional property not found + $Size = $null + } else { + $Size = $JsonParameters.PSobject.Properties["size"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "color"))) { #optional property not found + $Color = $null + } else { + $Color = $JsonParameters.PSobject.Properties["color"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "id"))) { #optional property not found + $Id = $null + } else { + $Id = $JsonParameters.PSobject.Properties["id"].value + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "name"))) { #optional property not found + $Name = $null + } else { + $Name = $JsonParameters.PSobject.Properties["name"].value + } + + $PSO = [PSCustomObject]@{ + "size" = ${Size} + "color" = ${Color} + "id" = ${Id} + "name" = ${Name} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.ps1 new file mode 100644 index 000000000000..61b7084242be --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.ps1 @@ -0,0 +1,98 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + +No summary available. + +.DESCRIPTION + +No description available. + +.PARAMETER Values +No description available. +.OUTPUTS + +TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +#> + +function Initialize-TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipelineByPropertyName = $true)] + [String[]] + ${Values} + ) + + Process { + 'Creating PSCustomObject: PSOpenAPITools => TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + + $PSO = [PSCustomObject]@{ + "values" = ${Values} + } + + + return $PSO + } +} + +<# +.SYNOPSIS + +Convert from JSON to TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + +.DESCRIPTION + +Convert from JSON to TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + +.PARAMETER Json + +Json object + +.OUTPUTS + +TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +#> +function ConvertFrom-JsonToTestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter { + Param( + [AllowEmptyString()] + [string]$Json + ) + + Process { + 'Converting JSON to PSCustomObject: PSOpenAPITools => TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $JsonParameters = ConvertFrom-Json -InputObject $Json + + # check if Json contains properties not defined in TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + $AllProperties = ("values") + foreach ($name in $JsonParameters.PsObject.Properties.Name) { + if (!($AllProperties.Contains($name))) { + throw "Error! JSON key '$name' not found in the properties: $($AllProperties)" + } + } + + if (!([bool]($JsonParameters.PSobject.Properties.name -match "values"))) { #optional property not found + $Values = $null + } else { + $Values = $JsonParameters.PSobject.Properties["values"].value + } + + $PSO = [PSCustomObject]@{ + "values" = ${Values} + } + + return $PSO + } + +} + diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/PSOpenAPITools.psm1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/PSOpenAPITools.psm1 new file mode 100644 index 000000000000..5b32c2c0133e --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/PSOpenAPITools.psm1 @@ -0,0 +1,40 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +#region Import functions + +# define the following classes in PowerShell +try { + Add-Type -AssemblyName System.Web -ErrorAction Ignore | Out-Null + Add-Type -AssemblyName System.Net -ErrorAction Ignore | Out-Null +} catch { + Write-Verbose $_ +} + +# set $ErrorActionPreference to 'Stop' globally +$ErrorActionPreference = 'Stop' + +# store the API client's configuration +$Script:Configuration = [System.Collections.HashTable]@{} + +$Script:CmdletBindingParameters = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') + +'Api', 'Model', 'Client', 'Private' | Where-Object { + Join-Path $PSScriptRoot $_ | Test-Path +} | Get-ChildItem -Path { + Join-Path $PSScriptRoot $_ +} -Filter '*.ps1' | ForEach-Object { + Write-Debug "Importing file: $($_.BaseName)" + try { + . $_.FullName + } catch { + Write-Error -Message "Failed to import function $($_.Fullname): $_" + } +} + +#endregion diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/ApiClient.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/ApiClient.ps1 new file mode 100644 index 000000000000..832786cdae77 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/ApiClient.ps1 @@ -0,0 +1,260 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +function Invoke-ApiClient { + [OutputType('System.Collections.Hashtable')] + [CmdletBinding()] + Param( + [Parameter(Mandatory)] + [string]$Uri, + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]]$Accepts, + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]]$ContentTypes, + [Parameter(Mandatory)] + [hashtable]$HeaderParameters, + [Parameter(Mandatory)] + [hashtable]$FormParameters, + [Parameter(Mandatory)] + [hashtable]$QueryParameters, + [Parameter(Mandatory)] + [hashtable]$CookieParameters, + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$Body, + [Parameter(Mandatory)] + [string]$Method, + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$ReturnType, + [Parameter(Mandatory)] + [bool]$IsBodyNullable + ) + + 'Calling method: Invoke-ApiClient' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $Configuration = Get-Configuration + $RequestUri = $Configuration["BaseUrl"] + $Uri + $SkipCertificateCheck = $Configuration["SkipCertificateCheck"] + + # cookie parameters + foreach ($Parameter in $CookieParameters.GetEnumerator()) { + if ($Parameter.Name -eq "cookieAuth") { + $HeaderParameters["Cookie"] = $Parameter.Value + } else { + $HeaderParameters[$Parameter.Name] = $Parameter.Value + } + } + if ($CookieParameters -and $CookieParameters.Count -gt 1) { + Write-Warning "Multiple cookie parameters found. Currently only the first one is supported/used" + } + + # accept, content-type headers + $Accept = SelectHeaders -Headers $Accepts + if ($Accept) { + $HeaderParameters['Accept'] = $Accept + } + + [string]$MultiPartBoundary = $null + $ContentType= SelectHeaders -Headers $ContentTypes + if ($ContentType) { + $HeaderParameters['Content-Type'] = $ContentType + if ($ContentType -eq 'multipart/form-data') { + [string]$MultiPartBoundary = [System.Guid]::NewGuid() + $MultiPartBoundary = "---------------------------$MultiPartBoundary" + $HeaderParameters['Content-Type'] = "$ContentType; boundary=$MultiPartBoundary" + } + } + + # add default headers if any + foreach ($header in $Configuration["DefaultHeaders"].GetEnumerator()) { + $HeaderParameters[$header.Name] = $header.Value + } + + # construct URL query string + $HttpValues = [System.Web.HttpUtility]::ParseQueryString([String]::Empty) + foreach ($Parameter in $QueryParameters.GetEnumerator()) { + if ($Parameter.Value.Count -gt 1) { // array + foreach ($Value in $Parameter.Value) { + $HttpValues.Add($Parameter.Key + '[]', $Value) + } + } else { + $HttpValues.Add($Parameter.Key,$Parameter.Value) + } + } + # Build the request and load it with the query string. + $UriBuilder = [System.UriBuilder]($RequestUri) + $UriBuilder.Query = $HttpValues.ToString() + + # include form parameters in the request body + if ($FormParameters -and $FormParameters.Count -gt 0) { + if (![string]::IsNullOrEmpty($MultiPartBoundary)) { + $RequestBody = "" + $LF = "`r`n" + $FormParameters.Keys | ForEach-Object { + $value = $FormParameters[$_] + $isFile = $value.GetType().FullName -eq "System.IO.FileInfo" + + $RequestBody += "--$MultiPartBoundary$LF" + $RequestBody += "Content-Disposition: form-data; name=`"$_`"" + if ($isFile) { + $fileName = $value.Name + $RequestBody += "; filename=`"$fileName`"$LF" + $RequestBody += "Content-Type: application/octet-stream$LF$LF" + $RequestBody += Get-Content -Path $value.FullName + } else { + $RequestBody += "$LF$LF" + $RequestBody += ([string]$value) + } + $RequestBody += "$LF--$MultiPartBoundary" + } + $RequestBody += "--" + } else { + $RequestBody = $FormParameters + } + } + + + + if ($Body -or $IsBodyNullable) { + $RequestBody = $Body + if ([string]::IsNullOrEmpty($RequestBody) -and $IsBodyNullable -eq $true) { + $RequestBody = "null" + } + } + + if ($SkipCertificateCheck -eq $true) { + if ($null -eq $Configuration["Proxy"]) { + # skip certification check, no proxy + $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` + -Method $Method ` + -Headers $HeaderParameters ` + -Body $RequestBody ` + -ErrorAction Stop ` + -UseBasicParsing ` + -SkipCertificateCheck + } else { + # skip certification check, use proxy + $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` + -Method $Method ` + -Headers $HeaderParameters ` + -Body $RequestBody ` + -ErrorAction Stop ` + -UseBasicParsing ` + -SkipCertificateCheck ` + -Proxy $Configuration["Proxy"].GetProxy($UriBuilder.Uri) ` + -ProxyUseDefaultCredentials + } + } else { + if ($null -eq $Configuration["Proxy"]) { + # perform certification check, no proxy + $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` + -Method $Method ` + -Headers $HeaderParameters ` + -Body $RequestBody ` + -ErrorAction Stop ` + -UseBasicParsing + } else { + # perform certification check, use proxy + $Response = Invoke-WebRequest -Uri $UriBuilder.Uri ` + -Method $Method ` + -Headers $HeaderParameters ` + -Body $RequestBody ` + -ErrorAction Stop ` + -UseBasicParsing ` + -Proxy $Configuration["Proxy"].GetProxy($UriBuilder.Uri) ` + -ProxyUseDefaultCredentials + } + } + + return @{ + Response = DeserializeResponse -Response $Response.Content -ReturnType $ReturnType -ContentTypes $Response.Headers["Content-Type"] + StatusCode = $Response.StatusCode + Headers = $Response.Headers + } +} + +# Select JSON MIME if present, otherwise choose the first one if available +function SelectHeaders { + Param( + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [String[]]$Headers + ) + + foreach ($Header in $Headers) { + if (IsJsonMIME -MIME $Header) { + return $Header + } + } + + if (!($Headers) -or $Headers.Count -eq 0) { + return $null + } else { + return $Headers[0] # return the first one + } +} + +function IsJsonMIME { + Param( + [Parameter(Mandatory)] + [string]$MIME + ) + + if ($MIME -match "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$") { + return $true + } else { + return $false + } +} + +function DeserializeResponse { + Param( + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$ReturnType, + [Parameter(Mandatory)] + [AllowEmptyString()] + [string]$Response, + [Parameter(Mandatory)] + [AllowEmptyCollection()] + [string[]]$ContentTypes + ) + + If ($null -eq $ContentTypes) { + $ContentTypes = [string[]]@() + } + + If ([string]::IsNullOrEmpty($ReturnType) -and $ContentTypes.Count -eq 0) { # void response + return $Response + } Elseif ($ReturnType -match '\[\]$') { # array + return ConvertFrom-Json $Response + } Elseif (@("String", "Boolean", "System.DateTime") -contains $ReturnType) { # string, boolean ,datetime + return $Response + } Else { # others (e.g. model, file) + if ($ContentTypes) { + $ContentType = $null + if ($ContentTypes.Count -gt 1) { + $ContentType = SelectHeaders -Headers $ContentTypes + } else { + $ContentType = $ContentTypes[0] + } + + if (IsJsonMIME -MIME $ContentType) { # JSON + return ConvertFrom-Json $Response + } else { # XML, file, etc + return $Response + } + } else { # no content type in response header, returning raw response + return $Response + } + } +} diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Get-CommonParameters.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Get-CommonParameters.ps1 new file mode 100644 index 000000000000..4fb1d8172ecd --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Get-CommonParameters.ps1 @@ -0,0 +1,22 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.Synopsis + Helper function to get common parameters (Verbose, Debug, etc.) +.Example + Get-CommonParameters +#> +function Get-CommonParameters { + function tmp { + [CmdletBinding()] + Param () + } + + (Get-Command -Name tmp -CommandType Function).Parameters.Keys +} diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/HttpSignatureAuth.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/HttpSignatureAuth.ps1 new file mode 100644 index 000000000000..c0d7175768c0 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/HttpSignatureAuth.ps1 @@ -0,0 +1,437 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.SYNOPSIS + Gets the headers for HTTP signature. +.DESCRIPTION + Gets the headers for the http signature. +.PARAMETER Method + HTTP method +.PARAMETER UriBuilder + UriBuilder for url and query parameter +.PARAMETER Body + Request body +.OUTPUTS + Hashtable +#> +function Get-HttpSignedHeader { + param( + [string]$Method, + [System.UriBuilder]$UriBuilder, + [string]$Body, + [hashtable]$RequestHeader + ) + + $HEADER_REQUEST_TARGET = '(request-target)' + # The time when the HTTP signature was generated. + $HEADER_CREATED = '(created)' + # The time when the HTTP signature expires. The API server should reject HTTP requests + # that have expired. + $HEADER_EXPIRES = '(expires)' + # The 'Host' header. + $HEADER_HOST = 'Host' + # The 'Date' header. + $HEADER_DATE = 'Date' + # When the 'Digest' header is included in the HTTP signature, the client automatically + # computes the digest of the HTTP request body, per RFC 3230. + $HEADER_DIGEST = 'Digest' + # The 'Authorization' header is automatically generated by the client. It includes + # the list of signed headers and a base64-encoded signature. + $HEADER_AUTHORIZATION = 'Authorization' + + #Hash table to store singed headers + $HttpSignedRequestHeader = @{ } + $HttpSignatureHeader = @{ } + $TargetHost = $UriBuilder.Host + $httpSigningConfiguration = Get-ConfigurationHttpSigning + $Digest = $null + + #get the body digest + $bodyHash = Get-StringHash -String $Body -HashName $httpSigningConfiguration.HashAlgorithm + if ($httpSigningConfiguration.HashAlgorithm -eq "SHA256") { + $Digest = [String]::Format("SHA-256={0}", [Convert]::ToBase64String($bodyHash)) + } elseif ($httpSigningConfiguration.HashAlgorithm -eq "SHA512") { + $Digest = [String]::Format("SHA-512={0}", [Convert]::ToBase64String($bodyHash)) + } + + $dateTime = Get-Date + #get the date in UTC + $currentDate = $dateTime.ToUniversalTime().ToString("r") + + foreach ($headerItem in $httpSigningConfiguration.HttpSigningHeader) { + + if ($headerItem -eq $HEADER_REQUEST_TARGET) { + $requestTargetPath = [string]::Format("{0} {1}{2}", $Method.ToLower(), $UriBuilder.Path, $UriBuilder.Query) + $HttpSignatureHeader.Add($HEADER_REQUEST_TARGET, $requestTargetPath) + } elseif ($headerItem -eq $HEADER_CREATED) { + $created = Get-UnixTime -Date $dateTime -TotalTime TotalSeconds + $HttpSignatureHeader.Add($HEADER_CREATED, $created) + } elseif ($headerItem -eq $HEADER_EXPIRES) { + $expire = $dateTime.AddSeconds($httpSigningConfiguration.SignatureValidityPeriod) + $expireEpocTime = Get-UnixTime -Date $expire -TotalTime TotalSeconds + $HttpSignatureHeader.Add($HEADER_EXPIRES, $expireEpocTime) + } elseif ($headerItem -eq $HEADER_HOST) { + $HttpSignedRequestHeader[$HEADER_HOST] = $TargetHost + $HttpSignatureHeader.Add($HEADER_HOST.ToLower(), $TargetHost) + } elseif ($headerItem -eq $HEADER_DATE) { + $HttpSignedRequestHeader[$HEADER_DATE] = $currentDate + $HttpSignatureHeader.Add($HEADER_DATE.ToLower(), $currentDate) + } elseif ($headerItem -eq $HEADER_DIGEST) { + $HttpSignedRequestHeader[$HEADER_DIGEST] = $Digest + $HttpSignatureHeader.Add($HEADER_DIGEST.ToLower(), $Digest) + } elseif($RequestHeader.ContainsKey($headerItem)) { + $HttpSignatureHeader.Add($headerItem.ToLower(), $RequestHeader[$headerItem]) + } else { + throw "Cannot sign HTTP request. Request does not contain the $headerItem header." + } + } + + # header's name separated by space + $headersKeysString = $HttpSignatureHeader.Keys -join " " + $headerValuesList = @() + foreach ($item in $HttpSignatureHeader.GetEnumerator()) { + $headerValuesList += [string]::Format("{0}: {1}", $item.Name, $item.Value) + } + #Concatenate headers value separated by new line + $headerValuesString = $headerValuesList -join "`n" + + #Gets the hash of the headers value + $signatureHashString = Get-StringHash -String $headerValuesString -HashName $httpSigningConfiguration.HashAlgorithm + + #Gets the Key type to select the correct signing algorithm + $KeyType = Get-KeyTypeFromFile -KeyFilePath $httpSigningConfiguration.KeyFilePath + + if ($keyType -eq "RSA") { + $headerSignatureStr = Get-RSASignature -PrivateKeyFilePath $httpSigningConfiguration.KeyFilePath ` + -DataToSign $signatureHashString ` + -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` + -KeyPassPhrase $httpSigningConfiguration.KeyPassPhrase ` + -SigningAlgorithm $httpSigningConfiguration.SigningAlgorithm + } elseif ($KeyType -eq "EC") { + $headerSignatureStr = Get-ECDSASignature -ECKeyFilePath $httpSigningConfiguration.KeyFilePath ` + -DataToSign $signatureHashString ` + -HashAlgorithmName $httpSigningConfiguration.HashAlgorithm ` + -KeyPassPhrase $httpSigningConfiguration.KeyPassPhrase + } + #Deprecated + <#$cryptographicScheme = Get-CryptographicScheme -SigningAlgorithm $httpSigningConfiguration.SigningAlgorithm ` + -HashAlgorithm $httpSigningConfiguration.HashAlgorithm + #> + $cryptographicScheme = "hs2019" + $authorizationHeaderValue = [string]::Format("Signature keyId=""{0}"",algorithm=""{1}""", + $httpSigningConfiguration.KeyId, $cryptographicScheme) + + if ($HttpSignatureHeader.ContainsKey($HEADER_CREATED)) { + $authorizationHeaderValue += [string]::Format(",created={0}", $HttpSignatureHeader[$HEADER_CREATED]) + } + + if ($HttpSignatureHeader.ContainsKey($HEADER_EXPIRES)) { + $authorizationHeaderValue += [string]::Format(",expires={0}", $HttpSignatureHeader[$HEADER_EXPIRES]) + } + + $authorizationHeaderValue += [string]::Format(",headers=""{0}"",signature=""{1}""", + $headersKeysString , $headerSignatureStr) + + $HttpSignedRequestHeader[$HEADER_AUTHORIZATION] = $authorizationHeaderValue + return $HttpSignedRequestHeader +} + +<# +.SYNOPSIS + Gets the RSA signature + +.DESCRIPTION + Gets the RSA signature for the http signing +.PARAMETER PrivateKeyFilePath + Specify the API key file path +.PARAMETER DataToSign + Specify the data to sign +.PARAMETER HashAlgorithmName + HashAlgorithm to calculate the hash +.PARAMETER KeyPassPhrase + KeyPassPhrase for the encrypted key +.OUTPUTS + Base64String +#> +function Get-RSASignature { + Param( + [string]$PrivateKeyFilePath, + [byte[]]$DataToSign, + [string]$HashAlgorithmName, + [string]$SigningAlgorithm, + [securestring]$KeyPassPhrase + ) + try { + + if ($hashAlgorithmName -eq "sha256") { + $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA256 + } elseif ($hashAlgorithmName -eq "sha512") { + $hashAlgo = [System.Security.Cryptography.HashAlgorithmName]::SHA512 + } + + if ($PSVersionTable.PSVersion.Major -ge 7) { + $ecKeyHeader = "-----BEGIN RSA PRIVATE KEY-----" + $ecKeyFooter = "-----END RSA PRIVATE KEY-----" + $keyStr = Get-Content -Path $PrivateKeyFilePath -Raw + $ecKeyBase64String = $keyStr.Replace($ecKeyHeader, "").Replace($ecKeyFooter, "").Trim() + $keyBytes = [System.Convert]::FromBase64String($ecKeyBase64String) + $rsa = [System.Security.Cryptography.RSA]::Create() + [int]$bytCount = 0 + $rsa.ImportRSAPrivateKey($keyBytes, [ref] $bytCount) + + if ($SigningAlgorithm -eq "RSASSA-PSS") { + $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pss) + } else { + $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) + } + } else { + $rsa_provider_path = Join-Path -Path $PSScriptRoot -ChildPath "RSAEncryptionProvider.cs" + $rsa_provider_sourceCode = Get-Content -Path $rsa_provider_path -Raw + Add-Type -TypeDefinition $rsa_provider_sourceCode + + [System.Security.Cryptography.RSA]$rsa = [RSAEncryption.RSAEncryptionProvider]::GetRSAProviderFromPemFile($PrivateKeyFilePath, $KeyPassPhrase) + + if ($SigningAlgorithm -eq "RSASSA-PSS") { + throw "$SigningAlgorithm is not supported on $($PSVersionTable.PSVersion)" + } else { + $signedBytes = $rsa.SignHash($DataToSign, $hashAlgo, [System.Security.Cryptography.RSASignaturePadding]::Pkcs1) + } + } + + $signedString = [Convert]::ToBase64String($signedBytes) + return $signedString + } catch { + throw $_ + } +} + +<# +.SYNOPSIS + Gets the ECDSA signature + +.DESCRIPTION + Gets the ECDSA signature for the http signing +.PARAMETER PrivateKeyFilePath + Specify the API key file path +.PARAMETER DataToSign + Specify the data to sign +.PARAMETER HashAlgorithmName + HashAlgorithm to calculate the hash +.PARAMETER KeyPassPhrase + KeyPassPhrase for the encrypted key +.OUTPUTS + Base64String +#> +function Get-ECDSASignature { + param( + [Parameter(Mandatory = $true)] + [string]$ECKeyFilePath, + [Parameter(Mandatory = $true)] + [byte[]]$DataToSign, + [Parameter(Mandatory = $false)] + [String]$HashAlgorithmName, + [Parameter(Mandatory = $false)] + [securestring]$KeyPassPhrase + ) + if (!(Test-Path -Path $ECKeyFilePath)) { + throw "key file path does not exist." + } + + if ($PSVersionTable.PSVersion.Major -lt 7) { + throw "ECDSA key is not supported on PowerShell version $($PSVersionTable.PSVersion), Use PowerShell v7.0 and above" + } + + $ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----" + $ecKeyFooter = "-----END EC PRIVATE KEY-----" + $keyStr = Get-Content -Path $ECKeyFilePath -Raw + $ecKeyBase64String = $keyStr.Replace($ecKeyHeader, "").Replace($ecKeyFooter, "").Trim() + $keyBytes = [System.Convert]::FromBase64String($ecKeyBase64String) + $ecdsa = [System.Security.Cryptography.ECDsa]::Create() + + [int]$bytCount =0 + if (![string]::IsNullOrEmpty($KeyPassPhrase)) { + $ecdsa.ImportEncryptedPkcs8PrivateKey($KeyPassPhrase,$keyBytes,[ref]$bytCount) + } else { + $ecdsa.ImportPkcs8PrivateKey($keyBytes,[ref]$bytCount) + } + + $signedBytes = $ecdsa.SignHash($DataToSign) + $derBytes = ConvertTo-ECDSAANS1Format -RawBytes $signedBytes + $signedString = [System.Convert]::ToBase64String($derBytes) + return $signedString +} + +<# +.Synopsis + Gets the hash of string. +.Description + Gets the hash of string +.Parameter String + Specifies the string to calculate the hash +.Parameter HashName + Specifies the hash name to calculate the hash, Accepted values are "SHA1", "SHA256" and "SHA512" + It is recommended not to use "SHA1" to calculate the Hash +.Outputs + String +#> +Function Get-StringHash { + param( + [Parameter(Mandatory = $true)] + [AllowEmptyString()] + [string]$String, + [Parameter(Mandatory = $true)] + [ValidateSet("SHA1", "SHA256", "SHA512")] + $HashName + ) + $hashAlgorithm = [System.Security.Cryptography.HashAlgorithm]::Create($HashName) + $hashAlgorithm.ComputeHash([System.Text.Encoding]::UTF8.GetBytes($String)) +} + +<# +.Synopsis + Gets the Unix time. +.Description + Gets the Unix time +.Parameter Date + Specifies the date to calculate the unix time +.Parameter ToTalTime + Specifies the total time , Accepted values are "TotalDays", "TotalHours", "TotalMinutes", "TotalSeconds" and "TotalMilliseconds" +.Outputs +Integer +#> +function Get-UnixTime { + param( + [Parameter(Mandatory = $true)] + [DateTime]$Date, + [Parameter(Mandatory = $false)] + [ValidateSet("TotalDays", "TotalHours", "TotalMinutes", "TotalSeconds", "TotalMilliseconds")] + [string]$TotalTime = "TotalSeconds" + ) + $date1 = Get-Date -Date "01/01/1970" + $timespan = New-TimeSpan -Start $date1 -End $Date + switch ($TotalTime) { + "TotalDays" { [int]$timespan.TotalDays } + "TotalHours" { [int]$timespan.TotalHours } + "TotalMinutes" { [int]$timespan.TotalMinutes } + "TotalSeconds" { [int]$timespan.TotalSeconds } + "TotalMilliseconds" { [int]$timespan.TotalMilliseconds } + } +} + +function Get-CryptographicScheme { + param( + [Parameter(Mandatory = $true)] + [string]$SigningAlgorithm, + [Parameter(Mandatory = $true)] + [string]$HashAlgorithm + ) + $rsaSignatureType = @("RSASSA-PKCS1-v1_5", "RSASSA-PSS") + $SigningAlgorithm = $null + if ($rsaSignatureType -contains $SigningAlgorithm) { + switch ($HashAlgorithm) { + "sha256" { $SigningAlgorithm = "rsa-sha256" } + "sha512" { $SigningAlgorithm = "rsa-sha512" } + } + } + return $SigningAlgorithm +} + +<# +.Synopsis + Gets the key type from the pem file. +.Description + Gets the key type from the pem file. +.Parameter KeyFilePath + Specifies the key file path (pem file) +.Outputs +String +#> +function Get-KeyTypeFromFile { + param( + [Parameter(Mandatory = $true)] + [string]$KeyFilePath + ) + + if (-not(Test-Path -Path $KeyFilePath)) { + throw "Key file path does not exist." + } + $ecPrivateKeyHeader = "BEGIN EC PRIVATE KEY" + $ecPrivateKeyFooter = "END EC PRIVATE KEY" + $rsaPrivateKeyHeader = "BEGIN RSA PRIVATE KEY" + $rsaPrivateFooter = "END RSA PRIVATE KEY" + $pkcs8Header = "BEGIN PRIVATE KEY" + $pkcs8Footer = "END PRIVATE KEY" + $keyType = $null + $key = Get-Content -Path $KeyFilePath + + if ($key[0] -match $rsaPrivateKeyHeader -and $key[$key.Length - 1] -match $rsaPrivateFooter) { + $KeyType = "RSA" + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + $keyType = "EC" + } elseif ($key[0] -match $ecPrivateKeyHeader -and $key[$key.Length - 1] -match $ecPrivateKeyFooter) { + <#this type of key can hold many type different types of private key, but here due lack of pem header + Considering this as EC key + #> + #TODO :- update the key based on oid + $keyType = "EC" + } else { + throw "Either the key is invalid or key is not supported" + } + return $keyType +} + + +<# +.Synopsis + Converts sequence of R and S bytes to ANS1 format for ECDSASignature. +.Description + Converts sequence of R and S bytes to ANS1 format for ECDSASignature. +.Parameter RawBytes[] + Specifies the R and S bytes of ECDSA signature. +.Outputs + Byte[] +#> +function ConvertTo-ECDSAANS1Format{ + Param( + [Parameter(Mandatory = $true)] + [byte[]]$RawBytes + ) + + $derLength = 68 #default length for ECDSA code signing bit 0x44 + $rbytesLength = 32 #R length 0x20 + $sbytesLength = 32 #S length 0x20 + [byte[]]$rBytes = $signedBytes[0..31] + [byte[]]$sBytes = $signedBytes[32..63] + + if($rBytes[0] -gt 0x7F){ + $derLength++ + $rbytesLength++ + $rBytes = [byte[]]@(0x00) + $rBytes + } + + if($sBytes[0] -gt 0x7F){ + $derLength++ + $sbytesLength++ + $sBytes = [byte[]]@(0x00) + $sBytes + } + + [byte[]]$derBytes = @() + + $derBytes += 48 # start of the sequence 0x30 + $derBytes += $derLength # total length r length, type and r bytes + + $derBytes += 2 # tag for integer + $derBytes += $rbytesLength # length of r + $derBytes += $rBytes + + $derBytes += 2 #tag for integer + $derBytes += $sbytesLength #length of s + $derBytes += $sBytes + return $derBytes +} \ No newline at end of file diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Out-DebugParameter.ps1 b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Out-DebugParameter.ps1 new file mode 100644 index 000000000000..68c37a04ceed --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/Out-DebugParameter.ps1 @@ -0,0 +1,45 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +<# +.Synopsis + Helper function to format debug parameter output. +.Example + $PSBoundParameters | Out-DebugParameter | Write-Debug +#> +function Out-DebugParameter { + [CmdletBinding()] + Param ( + [Parameter(ValueFromPipeline = $true, Mandatory = $true)] + [AllowEmptyCollection()] + $InputObject + ) + + Begin { + $CommonParameters = Get-CommonParameters + } + + Process { + $InputObject.GetEnumerator() | Where-Object { + $CommonParameters -notcontains $_.Key + } | Format-Table -AutoSize -Property ( + @{ + Name = 'Parameter' + Expression = {$_.Key} + }, + @{ + Name = 'Value' + Expression = {$_.Value} + } + ) | Out-String -Stream | ForEach-Object { + if ($_.Trim()) { + $_ + } + } + } +} diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/RSAEncryptionProvider.cs b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/RSAEncryptionProvider.cs new file mode 100644 index 000000000000..e4783e6b17dd --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/Private/RSAEncryptionProvider.cs @@ -0,0 +1,354 @@ +/* + * Echo Server API + * + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * Generated by: https://github.com/openapitools/openapi-generator.git + */ +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Runtime.InteropServices; +using System.Security; +using System.Security.Cryptography; +using System.Text; + +namespace RSAEncryption +{ + ///

              + /// A RSA enccryption provider. + /// + public class RSAEncryptionProvider + { + /// + /// Get the RSA provider from the PEM file. + /// + /// PEM file. + /// Key pass phrase. + /// Get an instance of RSACryptoServiceProvider. + public static RSACryptoServiceProvider GetRSAProviderFromPemFile(String pemfile,SecureString keyPassPhrase = null) + { + const String pempubheader = "-----BEGIN PUBLIC KEY-----"; + const String pempubfooter = "-----END PUBLIC KEY-----"; + bool isPrivateKeyFile = true; + byte[] pemkey = null; + + if (!File.Exists(pemfile)) + { + throw new Exception("private key file does not exist."); + } + string pemstr = File.ReadAllText(pemfile).Trim(); + + if (pemstr.StartsWith(pempubheader) && pemstr.EndsWith(pempubfooter)) + { + isPrivateKeyFile = false; + } + + if (isPrivateKeyFile) + { + pemkey = ConvertPrivateKeyToBytes(pemstr,keyPassPhrase); + if (pemkey == null) + { + return null; + } + return DecodeRSAPrivateKey(pemkey); + } + return null ; + } + + /// + /// Convert the private key to bytes. + /// + /// Private key. + /// Key pass phrase. + /// The private key in the form of bytes. + static byte[] ConvertPrivateKeyToBytes(String instr, SecureString keyPassPhrase = null) + { + const String pemprivheader = "-----BEGIN RSA PRIVATE KEY-----"; + const String pemprivfooter = "-----END RSA PRIVATE KEY-----"; + String pemstr = instr.Trim(); + byte[] binkey; + + if (!pemstr.StartsWith(pemprivheader) || !pemstr.EndsWith(pemprivfooter)) + { + return null; + } + + StringBuilder sb = new StringBuilder(pemstr); + sb.Replace(pemprivheader, ""); + sb.Replace(pemprivfooter, ""); + String pvkstr = sb.ToString().Trim(); + + try + { // if there are no PEM encryption info lines, this is an UNencrypted PEM private key + binkey = Convert.FromBase64String(pvkstr); + return binkey; + } + catch (System.FormatException) + { + StringReader str = new StringReader(pvkstr); + + //-------- read PEM encryption info. lines and extract salt ----- + if (!str.ReadLine().StartsWith("Proc-Type: 4,ENCRYPTED")) + { + return null; + } + String saltline = str.ReadLine(); + if (!saltline.StartsWith("DEK-Info: DES-EDE3-CBC,")) + { + return null; + } + String saltstr = saltline.Substring(saltline.IndexOf(",") + 1).Trim(); + byte[] salt = new byte[saltstr.Length / 2]; + for (int i = 0; i < salt.Length; i++) + { + salt[i] = Convert.ToByte(saltstr.Substring(i * 2, 2), 16); + } + if (str.ReadLine() != "") + { + return null; + } + + //------ remaining b64 data is encrypted RSA key ---- + String encryptedstr = str.ReadToEnd(); + + try + { //should have b64 encrypted RSA key now + binkey = Convert.FromBase64String(encryptedstr); + } + catch (System.FormatException) + { //data is not in base64 format + return null; + } + + byte[] deskey = GetEncryptedKey(salt, keyPassPhrase, 1, 2); // count=1 (for OpenSSL implementation); 2 iterations to get at least 24 bytes + if (deskey == null) + { + return null; + } + + //------ Decrypt the encrypted 3des-encrypted RSA private key ------ + byte[] rsakey = DecryptKey(binkey, deskey, salt); //OpenSSL uses salt value in PEM header also as 3DES IV + return rsakey; + } + } + + /// + /// Decode the RSA private key. + /// + /// Private key. + /// An instance of RSACryptoServiceProvider. + public static RSACryptoServiceProvider DecodeRSAPrivateKey(byte[] privkey) + { + byte[] bytesModules, bytesE, bytesD, bytesP, bytesQ, bytesDp, bytesDq, bytesIq; + + // --------- Set up stream to decode the asn.1 encoded RSA private key ------ + MemoryStream mem = new MemoryStream(privkey); + BinaryReader binr = new BinaryReader(mem); //wrap Memory Stream with BinaryReader for easy reading + byte bt = 0; + ushort twobytes = 0; + int elems = 0; + try + { + twobytes = binr.ReadUInt16(); + if (twobytes == 0x8130) //data read as little endian order (actual data order for Sequence is 30 81) + { + binr.ReadByte(); //advance 1 byte + } + else if (twobytes == 0x8230) + { + binr.ReadInt16(); //advance 2 bytes + } + else + { + return null; + } + + twobytes = binr.ReadUInt16(); + if (twobytes != 0x0102) //version number + { + return null; + } + bt = binr.ReadByte(); + if (bt != 0x00) + { + return null; + } + + //------ all private key components are Integer sequences ---- + elems = GetIntegerSize(binr); + bytesModules = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesE = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesD = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesP = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesQ = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDp = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesDq = binr.ReadBytes(elems); + + elems = GetIntegerSize(binr); + bytesIq = binr.ReadBytes(elems); + + // ------- create RSACryptoServiceProvider instance and initialize with public key ----- + RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(); + RSAParameters RSAparams = new RSAParameters(); + RSAparams.Modulus = bytesModules; + RSAparams.Exponent = bytesE; + RSAparams.D = bytesD; + RSAparams.P = bytesP; + RSAparams.Q = bytesQ; + RSAparams.DP = bytesDp; + RSAparams.DQ = bytesDq; + RSAparams.InverseQ = bytesIq; + rsa.ImportParameters(RSAparams); + return rsa; + } + catch (Exception) + { + return null; + } + finally + { + binr.Close(); + } + } + + private static int GetIntegerSize(BinaryReader binr) + { + byte bt = 0; + byte lowbyte = 0x00; + byte highbyte = 0x00; + int count = 0; + bt = binr.ReadByte(); + if (bt != 0x02) //expect integer + { + return 0; + } + bt = binr.ReadByte(); + + if (bt == 0x81) + { + count = binr.ReadByte(); // data size in next byte + } + else if (bt == 0x82) + { + highbyte = binr.ReadByte(); // data size in next 2 bytes + lowbyte = binr.ReadByte(); + byte[] modint = { lowbyte, highbyte, 0x00, 0x00 }; + count = BitConverter.ToInt32(modint, 0); + } + else + { + count = bt; // we already have the data size + } + while (binr.ReadByte() == 0x00) + { //remove high order zeros in data + count -= 1; + } + binr.BaseStream.Seek(-1, SeekOrigin.Current); + //last ReadByte wasn't a removed zero, so back up a byte + return count; + } + + /// + /// Get the encrypted key. + /// + /// Random bytes to be added. + /// Password. + /// Count. + /// Miter. + /// Decrypted key. + static byte[] GetEncryptedKey(byte[] salt, SecureString secpswd, int count, int miter) + { + IntPtr unmanagedPswd = IntPtr.Zero; + const int HASHLENGTH = 16; //MD5 bytes + byte[] keymaterial = new byte[HASHLENGTH * miter]; //to store concatenated Mi hashed results + + byte[] psbytes = new byte[secpswd.Length]; + unmanagedPswd = Marshal.SecureStringToGlobalAllocAnsi(secpswd); + Marshal.Copy(unmanagedPswd, psbytes, 0, psbytes.Length); + Marshal.ZeroFreeGlobalAllocAnsi(unmanagedPswd); + + // --- concatenate salt and pswd bytes into fixed data array --- + byte[] data00 = new byte[psbytes.Length + salt.Length]; + Array.Copy(psbytes, data00, psbytes.Length); //copy the pswd bytes + Array.Copy(salt, 0, data00, psbytes.Length, salt.Length); //concatenate the salt bytes + + // ---- do multi-hashing and concatenate results D1, D2 ... into keymaterial bytes ---- + MD5 md5 = new MD5CryptoServiceProvider(); + byte[] result = null; + byte[] hashtarget = new byte[HASHLENGTH + data00.Length]; //fixed length initial hashtarget + + for (int j = 0; j < miter; j++) + { + // ---- Now hash consecutively for count times ------ + if (j == 0) + { + result = data00; //initialize + } + else + { + Array.Copy(result, hashtarget, result.Length); + Array.Copy(data00, 0, hashtarget, result.Length, data00.Length); + result = hashtarget; + } + + for (int i = 0; i < count; i++) + { + result = md5.ComputeHash(result); + } + Array.Copy(result, 0, keymaterial, j * HASHLENGTH, result.Length); //concatenate to keymaterial + } + byte[] deskey = new byte[24]; + Array.Copy(keymaterial, deskey, deskey.Length); + + Array.Clear(psbytes, 0, psbytes.Length); + Array.Clear(data00, 0, data00.Length); + Array.Clear(result, 0, result.Length); + Array.Clear(hashtarget, 0, hashtarget.Length); + Array.Clear(keymaterial, 0, keymaterial.Length); + return deskey; + } + + /// + /// Decrypt the key. + /// + /// Cipher data. + /// Key to decrypt. + /// Initialization vector. + /// Decrypted key. + static byte[] DecryptKey(byte[] cipherData, byte[] desKey, byte[] IV) + { + MemoryStream memst = new MemoryStream(); + TripleDES alg = TripleDES.Create(); + alg.Key = desKey; + alg.IV = IV; + try + { + CryptoStream cs = new CryptoStream(memst, alg.CreateDecryptor(), CryptoStreamMode.Write); + cs.Write(cipherData, 0, cipherData.Length); + cs.Close(); + } + catch (Exception) + { + return null; + } + byte[] decryptedData = memst.ToArray(); + return decryptedData; + } + } +} diff --git a/samples/client/echo_api/powershell/src/PSOpenAPITools/en-US/about_PSOpenAPITools.help.txt b/samples/client/echo_api/powershell/src/PSOpenAPITools/en-US/about_PSOpenAPITools.help.txt new file mode 100644 index 000000000000..91395c726269 --- /dev/null +++ b/samples/client/echo_api/powershell/src/PSOpenAPITools/en-US/about_PSOpenAPITools.help.txt @@ -0,0 +1,19 @@ +PSTOPIC + about_PSOpenAPITools + +SHORT DESCRIPTION + PSOpenAPITools - the PowerShell module for the Echo Server API + +LONG DESCRIPTION + Echo Server API + + This PowerShell module is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + + - API version: 0.1.0 + - SDK version: 0.1.2 + - Build package: org.openapitools.codegen.languages.PowerShellClientCodegen + + Frameworks supported: + + * PowerShell 6.2 or later + * .NET 4.0 or later diff --git a/samples/client/echo_api/powershell/tests/Api/AuthApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/AuthApi.Tests.ps1 new file mode 100644 index 000000000000..fb4b6a144d8a --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/AuthApi.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'AuthApi' { + Context 'Test-AuthHttpBasic' { + It 'Test Test-AuthHttpBasic' { + #$TestResult = Test-AuthHttpBasic + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Api/BodyApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/BodyApi.Tests.ps1 new file mode 100644 index 000000000000..4829c660719c --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/BodyApi.Tests.ps1 @@ -0,0 +1,74 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'BodyApi' { + Context 'Test-BinaryGif' { + It 'Test Test-BinaryGif' { + #$TestResult = Test-BinaryGif + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-BodyApplicationOctetstreamBinary' { + It 'Test Test-BodyApplicationOctetstreamBinary' { + #$TestResult = Test-BodyApplicationOctetstreamBinary -Body "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-BodyMultipartFormdataArrayOfBinary' { + It 'Test Test-BodyMultipartFormdataArrayOfBinary' { + #$TestResult = Test-BodyMultipartFormdataArrayOfBinary -Files "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-EchoBodyFreeFormObjectResponseString' { + It 'Test Test-EchoBodyFreeFormObjectResponseString' { + #$TestResult = Test-EchoBodyFreeFormObjectResponseString -Body "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-EchoBodyPet' { + It 'Test Test-EchoBodyPet' { + #$TestResult = Test-EchoBodyPet -Pet "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-EchoBodyPetResponseString' { + It 'Test Test-EchoBodyPetResponseString' { + #$TestResult = Test-EchoBodyPetResponseString -Pet "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-EchoBodyTagResponseString' { + It 'Test Test-EchoBodyTagResponseString' { + #$TestResult = Test-EchoBodyTagResponseString -Tag "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-EchoBodyAllOfPet' { + It 'Test Test-EchoBodyAllOfPet' { + #$TestResult = Test-EchoBodyAllOfPet -Pet "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Api/FormApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/FormApi.Tests.ps1 new file mode 100644 index 000000000000..db830207c63e --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/FormApi.Tests.ps1 @@ -0,0 +1,26 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'FormApi' { + Context 'Test-FormIntegerBooleanString' { + It 'Test Test-FormIntegerBooleanString' { + #$TestResult = Test-FormIntegerBooleanString -IntegerForm "TEST_VALUE" -BooleanForm "TEST_VALUE" -StringForm "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-FormOneof' { + It 'Test Test-FormOneof' { + #$TestResult = Test-FormOneof -Form1 "TEST_VALUE" -Form2 "TEST_VALUE" -Form3 "TEST_VALUE" -Form4 "TEST_VALUE" -Id "TEST_VALUE" -Name "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Api/HeaderApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/HeaderApi.Tests.ps1 new file mode 100644 index 000000000000..abb9ffbc5b01 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/HeaderApi.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'HeaderApi' { + Context 'Test-HeaderIntegerBooleanStringEnums' { + It 'Test Test-HeaderIntegerBooleanStringEnums' { + #$TestResult = Test-HeaderIntegerBooleanStringEnums -IntegerHeader "TEST_VALUE" -BooleanHeader "TEST_VALUE" -StringHeader "TEST_VALUE" -EnumNonrefStringHeader "TEST_VALUE" -EnumRefStringHeader "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Api/PathApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/PathApi.Tests.ps1 new file mode 100644 index 000000000000..33ea3411b713 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/PathApi.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'PathApi' { + Context 'Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath' { + It 'Test Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath' { + #$TestResult = Test-sPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath -PathString "TEST_VALUE" -PathInteger "TEST_VALUE" -EnumNonrefStringPath "TEST_VALUE" -EnumRefStringPath "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Api/QueryApi.Tests.ps1 b/samples/client/echo_api/powershell/tests/Api/QueryApi.Tests.ps1 new file mode 100644 index 000000000000..ebbdd643d0be --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Api/QueryApi.Tests.ps1 @@ -0,0 +1,74 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'QueryApi' { + Context 'Test-EnumRefString' { + It 'Test Test-EnumRefString' { + #$TestResult = Test-EnumRefString -EnumNonrefStringQuery "TEST_VALUE" -EnumRefStringQuery "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryDatetimeDateString' { + It 'Test Test-QueryDatetimeDateString' { + #$TestResult = Test-QueryDatetimeDateString -DatetimeQuery "TEST_VALUE" -DateQuery "TEST_VALUE" -StringQuery "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryIntegerBooleanString' { + It 'Test Test-QueryIntegerBooleanString' { + #$TestResult = Test-QueryIntegerBooleanString -IntegerQuery "TEST_VALUE" -BooleanQuery "TEST_VALUE" -StringQuery "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryStyleDeepObjectExplodeTrueObject' { + It 'Test Test-QueryStyleDeepObjectExplodeTrueObject' { + #$TestResult = Test-QueryStyleDeepObjectExplodeTrueObject -QueryObject "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryStyleDeepObjectExplodeTrueObjectAllOf' { + It 'Test Test-QueryStyleDeepObjectExplodeTrueObjectAllOf' { + #$TestResult = Test-QueryStyleDeepObjectExplodeTrueObjectAllOf -QueryObject "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryStyleFormExplodeTrueArrayString' { + It 'Test Test-QueryStyleFormExplodeTrueArrayString' { + #$TestResult = Test-QueryStyleFormExplodeTrueArrayString -QueryObject "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryStyleFormExplodeTrueObject' { + It 'Test Test-QueryStyleFormExplodeTrueObject' { + #$TestResult = Test-QueryStyleFormExplodeTrueObject -QueryObject "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + + Context 'Test-QueryStyleFormExplodeTrueObjectAllOf' { + It 'Test Test-QueryStyleFormExplodeTrueObjectAllOf' { + #$TestResult = Test-QueryStyleFormExplodeTrueObjectAllOf -QueryObject "TEST_VALUE" + #$TestResult | Should -BeOfType TODO + #$TestResult.property | Should -Be 0 + } + } + +} diff --git a/samples/client/echo_api/powershell/tests/Model/Bird.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/Bird.Tests.ps1 new file mode 100644 index 000000000000..d9e7a87e3406 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/Bird.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'Bird' { + Context 'Bird' { + It 'Initialize-Bird' { + # a simple test to create an object + #$NewObject = Initialize-Bird -Size "TEST_VALUE" -Color "TEST_VALUE" + #$NewObject | Should -BeOfType Bird + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/Category.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/Category.Tests.ps1 new file mode 100644 index 000000000000..578a4feaee64 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/Category.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'Category' { + Context 'Category' { + It 'Initialize-Category' { + # a simple test to create an object + #$NewObject = Initialize-Category -Id "TEST_VALUE" -Name "TEST_VALUE" + #$NewObject | Should -BeOfType Category + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/DataQuery.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/DataQuery.Tests.ps1 new file mode 100644 index 000000000000..909513d04a3f --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/DataQuery.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'DataQuery' { + Context 'DataQuery' { + It 'Initialize-DataQuery' { + # a simple test to create an object + #$NewObject = Initialize-DataQuery -Id "TEST_VALUE" -Outcomes "TEST_VALUE" -Suffix "TEST_VALUE" -Text "TEST_VALUE" -Date "TEST_VALUE" + #$NewObject | Should -BeOfType DataQuery + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/DefaultValue.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/DefaultValue.Tests.ps1 new file mode 100644 index 000000000000..e8c7191f70e7 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/DefaultValue.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'DefaultValue' { + Context 'DefaultValue' { + It 'Initialize-DefaultValue' { + # a simple test to create an object + #$NewObject = Initialize-DefaultValue -ArrayStringEnumRefDefault "TEST_VALUE" -ArrayStringEnumDefault "TEST_VALUE" -ArrayStringDefault "TEST_VALUE" -ArrayIntegerDefault "TEST_VALUE" -ArrayString "TEST_VALUE" -ArrayStringNullable "TEST_VALUE" -ArrayStringExtensionNullable "TEST_VALUE" -StringNullable "TEST_VALUE" + #$NewObject | Should -BeOfType DefaultValue + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/NumberPropertiesOnly.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/NumberPropertiesOnly.Tests.ps1 new file mode 100644 index 000000000000..c73cecf35759 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/NumberPropertiesOnly.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'NumberPropertiesOnly' { + Context 'NumberPropertiesOnly' { + It 'Initialize-NumberPropertiesOnly' { + # a simple test to create an object + #$NewObject = Initialize-NumberPropertiesOnly -Number "TEST_VALUE" -Float "TEST_VALUE" -Double "TEST_VALUE" + #$NewObject | Should -BeOfType NumberPropertiesOnly + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/Pet.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/Pet.Tests.ps1 new file mode 100644 index 000000000000..53a5c902141c --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/Pet.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'Pet' { + Context 'Pet' { + It 'Initialize-Pet' { + # a simple test to create an object + #$NewObject = Initialize-Pet -Id "TEST_VALUE" -Name "TEST_VALUE" -Category "TEST_VALUE" -PhotoUrls "TEST_VALUE" -Tags "TEST_VALUE" -Status "TEST_VALUE" + #$NewObject | Should -BeOfType Pet + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/Query.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/Query.Tests.ps1 new file mode 100644 index 000000000000..9b67d81c7681 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/Query.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'Query' { + Context 'Query' { + It 'Initialize-Query' { + # a simple test to create an object + #$NewObject = Initialize-Query -Id "TEST_VALUE" -Outcomes "TEST_VALUE" + #$NewObject | Should -BeOfType Query + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/StringEnumRef.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/StringEnumRef.Tests.ps1 new file mode 100644 index 000000000000..e13f82b9c5ab --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/StringEnumRef.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'StringEnumRef' { + Context 'StringEnumRef' { + It 'Initialize-StringEnumRef' { + # a simple test to create an object + #$NewObject = Initialize-StringEnumRef + #$NewObject | Should -BeOfType StringEnumRef + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/Tag.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/Tag.Tests.ps1 new file mode 100644 index 000000000000..c0100be827ac --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/Tag.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'Tag' { + Context 'Tag' { + It 'Initialize-Tag' { + # a simple test to create an object + #$NewObject = Initialize-Tag -Id "TEST_VALUE" -Name "TEST_VALUE" + #$NewObject | Should -BeOfType Tag + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.Tests.ps1 new file mode 100644 index 000000000000..04997034c0a6 --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' { + Context 'TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' { + It 'Initialize-TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' { + # a simple test to create an object + #$NewObject = Initialize-TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter -Size "TEST_VALUE" -Color "TEST_VALUE" -Id "TEST_VALUE" -Name "TEST_VALUE" + #$NewObject | Should -BeOfType TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/powershell/tests/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.Tests.ps1 b/samples/client/echo_api/powershell/tests/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.Tests.ps1 new file mode 100644 index 000000000000..6bfaed484b8e --- /dev/null +++ b/samples/client/echo_api/powershell/tests/Model/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.Tests.ps1 @@ -0,0 +1,18 @@ +# +# Echo Server API +# Echo Server API +# Version: 0.1.0 +# Contact: team@openapitools.org +# Generated by OpenAPI Generator: https://openapi-generator.tech +# + +Describe -tag 'PSOpenAPITools' -name 'TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' { + Context 'TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' { + It 'Initialize-TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' { + # a simple test to create an object + #$NewObject = Initialize-TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter -Values "TEST_VALUE" + #$NewObject | Should -BeOfType TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + #$NewObject.property | Should -Be 0 + } + } +} diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/.openapi-generator/VERSION b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/.openapi-generator/VERSION +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/README.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/README.md index 9096a78c85de..f44bd12c67c4 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/README.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/README.md @@ -50,7 +50,6 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python -import time import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -95,9 +94,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -141,6 +143,11 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + ## Author diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/AuthApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/AuthApi.md index 98ce834c3176..507592b4811e 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/AuthApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* Method | HTTP request | Description ------------- | ------------- | ------------- [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +[**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication # **test_auth_http_basic** @@ -17,9 +18,8 @@ To test HTTP basic authentication ### Example * Basic Authentication (http_auth): + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -58,6 +58,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -74,6 +75,80 @@ This endpoint does not need any parameter. - **Accept**: text/plain ### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_auth_http_bearer** +> str test_auth_http_bearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +* Bearer Authentication (http_bearer_auth): + +```python +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: http_bearer_auth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.AuthApi(api_client) + + try: + # To test HTTP bearer authentication + api_response = api_instance.test_auth_http_bearer() + print("The response of AuthApi->test_auth_http_bearer:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AuthApi->test_auth_http_bearer: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**str** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Bird.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Bird.md index f1ad71c2150f..d2434b50032f 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Bird.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Bird.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **str** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/BodyApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/BodyApi.md index 553100ffc922..acfbe28268d6 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/BodyApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/BodyApi.md @@ -7,6 +7,8 @@ Method | HTTP request | Description [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +[**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +[**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -22,9 +24,8 @@ Test binary (gif) response body ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -53,6 +54,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -69,6 +71,7 @@ No authorization required - **Accept**: image/gif ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -84,9 +87,8 @@ Test body parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -117,6 +119,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bytearray**| | [optional] @@ -135,6 +138,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -150,9 +154,8 @@ Test array of binary in multipart mime ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -183,6 +186,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **files** | **List[bytearray]**| | @@ -201,6 +205,142 @@ No authorization required - **Accept**: text/plain ### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_multipart_formdata_single_binary** +> str test_body_multipart_formdata_single_binary(my_file=my_file) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + + +```python +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + my_file = None # bytearray | (optional) + + try: + # Test single binary in multipart mime + api_response = api_instance.test_body_multipart_formdata_single_binary(my_file=my_file) + print("The response of BodyApi->test_body_multipart_formdata_single_binary:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_body_multipart_formdata_single_binary: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **my_file** | **bytearray**| | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_echo_body_all_of_pet** +> Pet test_echo_body_all_of_pet(pet=pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + + +```python +import openapi_client +from openapi_client.models.pet import Pet +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + pet = openapi_client.Pet() # Pet | Pet object that needs to be added to the store (optional) + + try: + # Test body parameter(s) + api_response = api_instance.test_echo_body_all_of_pet(pet=pet) + print("The response of BodyApi->test_echo_body_all_of_pet:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_echo_body_all_of_pet: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -216,9 +356,8 @@ Test free form object ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -249,6 +388,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **object**| Free form object | [optional] @@ -267,6 +407,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -282,9 +423,8 @@ Test body parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -316,6 +456,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] @@ -334,6 +475,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -349,9 +491,8 @@ Test empty response body ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -383,6 +524,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] @@ -401,6 +543,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -416,9 +559,8 @@ Test empty json (request body) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.tag import Tag from openapi_client.rest import ApiException @@ -450,6 +592,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **tag** | [**Tag**](Tag.md)| Tag object | [optional] @@ -468,6 +611,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Category.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Category.md index bf23e3b044dd..633bbe90398a 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Category.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Category.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DataQuery.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DataQuery.md index bac43a6cc706..dcc235611296 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DataQuery.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DataQuery.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **suffix** | **str** | test suffix | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DefaultValue.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DefaultValue.md index fcdbebf0e0ad..efdfff470b62 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DefaultValue.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/DefaultValue.md @@ -3,6 +3,7 @@ to test the default value of properties ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_string_enum_ref_default** | [**List[StringEnumRef]**](StringEnumRef.md) | | [optional] [default to ["success","failure"]] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/FormApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/FormApi.md index c823e4b82ae4..94205cd60e4a 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/FormApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/FormApi.md @@ -17,9 +17,8 @@ Test form parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -52,6 +51,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_form** | **int**| | [optional] @@ -72,6 +72,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -87,9 +88,8 @@ Test form parameter(s) for oneOf schema ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -125,6 +125,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **form1** | **str**| | [optional] @@ -148,6 +149,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/HeaderApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/HeaderApi.md index 7bf15b0037c0..137b5c00d105 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/HeaderApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/HeaderApi.md @@ -16,9 +16,8 @@ Test header parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -54,6 +53,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_header** | **int**| | [optional] @@ -76,6 +76,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/NumberPropertiesOnly.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/NumberPropertiesOnly.md index 709b3996be9a..f1bf5009836b 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/NumberPropertiesOnly.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/NumberPropertiesOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **number** | **float** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/PathApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/PathApi.md index 14e23b66b969..dd9362bb746e 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/PathApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/PathApi.md @@ -16,9 +16,8 @@ Test path parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -53,6 +52,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **path_string** | **str**| | @@ -74,6 +74,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Pet.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Pet.md index bd578ba9a501..1e97d80b3c19 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Pet.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Pet.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Query.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Query.md index 8a3462120895..98ed8b6eedfc 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Query.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Query.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | Query | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/QueryApi.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/QueryApi.md index d449cc3ea189..e84a872066f8 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/QueryApi.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/QueryApi.md @@ -23,9 +23,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -58,6 +57,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **enum_nonref_string_query** | **str**| | [optional] @@ -77,6 +77,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -92,9 +93,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -127,6 +127,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **datetime_query** | **datetime**| | [optional] @@ -147,6 +148,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -162,9 +164,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -197,6 +198,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_query** | **int**| | [optional] @@ -217,6 +219,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -232,9 +235,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -266,6 +268,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**Pet**](.md)| | [optional] @@ -284,6 +287,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -299,9 +303,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -332,6 +335,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md)| | [optional] @@ -350,6 +354,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -365,9 +370,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.test_query_style_form_explode_true_array_string_query_object_parameter import TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from openapi_client.rest import ApiException @@ -399,6 +403,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md)| | [optional] @@ -417,6 +422,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -432,9 +438,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -466,6 +471,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**Pet**](.md)| | [optional] @@ -484,6 +490,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -499,9 +506,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -532,6 +538,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**DataQuery**](.md)| | [optional] @@ -550,6 +557,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/StringEnumRef.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/StringEnumRef.md index f59594fb861f..8ff54010193c 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/StringEnumRef.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/StringEnumRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Tag.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Tag.md index febb268b1443..9b61fe147a9d 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Tag.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/Tag.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md index 3b0a87b71c53..723d8e9de9b3 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **str** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md index c741b723f003..c9d0c06a3532 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **values** | **List[str]** | | [optional] diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/auth_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/auth_api.py index 7589b21d02d5..9a00225bb97e 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/auth_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/auth_api.py @@ -12,21 +12,15 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class AuthApi: @@ -41,143 +35,488 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_auth_http_basic( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """To test HTTP basic authentication # noqa: E501 - - To test HTTP basic authentication # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """To test HTTP basic authentication - >>> thread = api.test_auth_http_basic(async_req=True) - >>> result = thread.get() + To test HTTP basic authentication - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_auth_http_basic_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return self.test_auth_http_basic_with_http_info.raw_function( - **kwargs, + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_auth_http_basic_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """To test HTTP basic authentication # noqa: E501 - - To test HTTP basic authentication # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_auth_http_basic_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """To test HTTP basic authentication + + To test HTTP basic authentication + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_auth_http_basic_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test HTTP basic authentication + + To test HTTP basic authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_auth_http_basic" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_auth_http_basic_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) + # authentication setting - _auth_settings: List[str] = ['http_auth'] # noqa: E501 + _auth_settings: List[str] = [ + 'http_auth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/auth/http/basic', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_auth_http_bearer( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> str: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_auth_http_bearer_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_auth_http_bearer_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) _response_types_map: Dict[str, Optional[str]] = { '200': "str", } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_auth_http_bearer_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None - return self.api_client.call_api( - '/auth/http/basic', 'POST', - _path_params, - _query_params, - _header_params, + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'text/plain' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'http_bearer_auth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/auth/http/bearer', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/body_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/body_api.py index fd4ef91e51a8..d9c2d64bea27 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/body_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/body_api.py @@ -12,29 +12,20 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictBytes, StrictStr +from pydantic import Field, StrictBytes, StrictStr from typing import Any, Dict, List, Optional, Union - +from typing_extensions import Annotated from openapi_client.models.pet import Pet from openapi_client.models.tag import Tag -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class BodyApi: @@ -49,1103 +40,2410 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_binary_gif( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> bytearray: - """Test binary (gif) response body # noqa: E501 - - Test binary (gif) response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test binary (gif) response body - >>> thread = api.test_binary_gif(async_req=True) - >>> result = thread.get() + Test binary (gif) response body - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: bytearray - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_binary_gif_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_binary_gif_with_http_info.raw_function( - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_binary_gif_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Test binary (gif) response body # noqa: E501 - - Test binary (gif) response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_binary_gif_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[bytearray]: + """Test binary (gif) response body + + Test binary (gif) response body + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_binary_gif_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test binary (gif) response body + + Test binary (gif) response body + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_binary_gif" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_binary_gif_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['image/gif']) # noqa: E501 + [ + 'image/gif' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "bytearray", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/binary/gif', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/binary/gif', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_body_application_octetstream_binary( self, body: Optional[Union[StrictBytes, StrictStr]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test body parameter(s) - >>> thread = api.test_body_application_octetstream_binary(body, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param body: :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_application_octetstream_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_application_octetstream_binary_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_body_application_octetstream_binary_with_http_info( self, body: Optional[Union[StrictBytes, StrictStr]] = None, - **kwargs, - ) -> ApiResponse: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test body parameter(s) - >>> thread = api.test_body_application_octetstream_binary_with_http_info(body, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param body: :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_body_application_octetstream_binary_without_preload_content( + self, + body: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param body: + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_application_octetstream_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_body_application_octetstream_binary_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file + if isinstance(body, str): + with open(body, "rb") as _fp: + _body_params = _fp.read() + else: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/octet-stream'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/octet-stream' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/body/application/octetstream/binary', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_body_multipart_formdata_array_of_binary( self, files: List[Union[StrictBytes, StrictStr]], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test array of binary in multipart mime # noqa: E501 + """Test array of binary in multipart mime - Test array of binary in multipart mime # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_body_multipart_formdata_array_of_binary(files, async_req=True) - >>> result = thread.get() + Test array of binary in multipart mime :param files: (required) :type files: List[bytearray] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_multipart_formdata_array_of_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_multipart_formdata_array_of_binary_with_http_info.raw_function( - files, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_body_multipart_formdata_array_of_binary_with_http_info( self, files: List[Union[StrictBytes, StrictStr]], - **kwargs, - ) -> ApiResponse: - """Test array of binary in multipart mime # noqa: E501 - - Test array of binary in multipart mime # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test array of binary in multipart mime - >>> thread = api.test_body_multipart_formdata_array_of_binary_with_http_info(files, async_req=True) - >>> result = thread.get() + Test array of binary in multipart mime :param files: (required) :type files: List[bytearray] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'files' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_body_multipart_formdata_array_of_binary_without_preload_content( + self, + files: List[Union[StrictBytes, StrictStr]], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test array of binary in multipart mime + + Test array of binary in multipart mime + + :param files: (required) + :type files: List[bytearray] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_multipart_formdata_array_of_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_body_multipart_formdata_array_of_binary_serialize( + self, + files, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'files': 'csv', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters + if files is not None: + _files['files'] = files + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'text/plain' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/array_of_binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_body_multipart_formdata_single_binary( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> str: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_body_multipart_formdata_single_binary_with_http_info( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_body_multipart_formdata_single_binary_without_preload_content( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_multipart_formdata_single_binary_serialize( + self, + my_file, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} - if _params['files'] is not None: - _files['files'] = _params['files'] - _collection_formats['files'] = 'csv' + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if my_file is not None: + _files['my-file'] = my_file # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/single_binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_echo_body_all_of_pet( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Pet: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) _response_types_map: Dict[str, Optional[str]] = { - '200': "str", + '200': "Pet", } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_echo_body_all_of_pet_with_http_info( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Test body parameter(s) - return self.api_client.call_api( - '/body/application/octetstream/array_of_binary', 'POST', - _path_params, - _query_params, - _header_params, + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_echo_body_all_of_pet_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_echo_body_all_of_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if pet is not None: + _body_params = pet + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/allOf/Pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_free_form_object_response_string( self, body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test free form object # noqa: E501 - - Test free form object # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test free form object - >>> thread = api.test_echo_body_free_form_object_response_string(body, async_req=True) - >>> result = thread.get() + Test free form object :param body: Free form object :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_free_form_object_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_free_form_object_response_string_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_free_form_object_response_string_with_http_info( self, body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, - **kwargs, - ) -> ApiResponse: - """Test free form object # noqa: E501 - - Test free form object # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test free form object + + Test free form object + + :param body: Free form object + :type body: object + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_echo_body_free_form_object_response_string_without_preload_content( + self, + body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test free form object - >>> thread = api.test_echo_body_free_form_object_response_string_with_http_info(body, async_req=True) - >>> result = thread.get() + Test free form object :param body: Free form object :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_free_form_object_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _test_echo_body_free_form_object_response_string_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/FreeFormObject/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/FreeFormObject/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_pet( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Pet: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test body parameter(s) - >>> thread = api.test_echo_body_pet(pet, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Pet - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_pet_with_http_info( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, - ) -> ApiResponse: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Test body parameter(s) - >>> thread = api.test_echo_body_pet_with_http_info(pet, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Pet, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_echo_body_pet_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Pet", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Pet', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_pet_response_string( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test empty response body # noqa: E501 + """Test empty response body - Test empty response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_echo_body_pet_response_string(pet, async_req=True) - >>> result = thread.get() + Test empty response body :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_pet_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_pet_response_string_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_pet_response_string_with_http_info( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, - ) -> ApiResponse: - """Test empty response body # noqa: E501 - - Test empty response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test empty response body - >>> thread = api.test_echo_body_pet_response_string_with_http_info(pet, async_req=True) - >>> result = thread.get() + Test empty response body :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_echo_body_pet_response_string_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test empty response body + + Test empty response body + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_pet_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_pet_response_string_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Pet/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Pet/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_tag_response_string( self, tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test empty json (request body) # noqa: E501 - - Test empty json (request body) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test empty json (request body) - >>> thread = api.test_echo_body_tag_response_string(tag, async_req=True) - >>> result = thread.get() + Test empty json (request body) :param tag: Tag object :type tag: Tag - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_tag_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_tag_response_string_with_http_info.raw_function( - tag, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_tag_response_string_with_http_info( self, tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, - **kwargs, - ) -> ApiResponse: - """Test empty json (request body) # noqa: E501 - - Test empty json (request body) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test empty json (request body) - >>> thread = api.test_echo_body_tag_response_string_with_http_info(tag, async_req=True) - >>> result = thread.get() + Test empty json (request body) :param tag: Tag object :type tag: Tag - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'tag' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_echo_body_tag_response_string_without_preload_content( + self, + tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test empty json (request body) + + Test empty json (request body) + + :param tag: Tag object + :type tag: Tag + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_tag_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_tag_response_string_serialize( + self, + tag, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['tag'] is not None: - _body_params = _params['tag'] + if tag is not None: + _body_params = tag + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Tag/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Tag/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/form_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/form_api.py index 322256935d64..da387bc2fd32 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/form_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/form_api.py @@ -12,25 +12,17 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictBool, StrictInt, StrictStr - from typing import Optional - -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class FormApi: @@ -45,22 +37,29 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_form_integer_boolean_string( self, integer_form: Optional[StrictInt] = None, boolean_form: Optional[StrictBool] = None, string_form: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test form parameter(s) # noqa: E501 + """Test form parameter(s) - Test form parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_form_integer_boolean_string(integer_form, boolean_form, string_form, async_req=True) - >>> result = thread.get() + Test form parameter(s) :param integer_form: :type integer_form: int @@ -68,45 +67,74 @@ def test_form_integer_boolean_string( :type boolean_form: bool :param string_form: :type string_form: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_form_integer_boolean_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_form_integer_boolean_string_with_http_info.raw_function( - integer_form, - boolean_form, - string_form, - **kwargs, + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_form_integer_boolean_string_with_http_info( self, integer_form: Optional[StrictInt] = None, boolean_form: Optional[StrictBool] = None, string_form: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test form parameter(s) # noqa: E501 - - Test form parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test form parameter(s) - >>> thread = api.test_form_integer_boolean_string_with_http_info(integer_form, boolean_form, string_form, async_req=True) - >>> result = thread.get() + Test form parameter(s) :param integer_form: :type integer_form: int @@ -114,117 +142,201 @@ def test_form_integer_boolean_string_with_http_info( :type boolean_form: bool :param string_form: :type string_form: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'integer_form', - 'boolean_form', - 'string_form' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_form_integer_boolean_string_without_preload_content( + self, + integer_form: Optional[StrictInt] = None, + boolean_form: Optional[StrictBool] = None, + string_form: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test form parameter(s) + + Test form parameter(s) + + :param integer_form: + :type integer_form: int + :param boolean_form: + :type boolean_form: bool + :param string_form: + :type string_form: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_form_integer_boolean_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_form_integer_boolean_string_serialize( + self, + integer_form, + boolean_form, + string_form, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the query parameters + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} - if _params['integer_form'] is not None: - _form_params.append(('integer_form', _params['integer_form'])) + _body_params: Optional[bytes] = None - if _params['boolean_form'] is not None: - _form_params.append(('boolean_form', _params['boolean_form'])) + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if integer_form is not None: + _form_params.append(('integer_form', integer_form)) + if boolean_form is not None: + _form_params.append(('boolean_form', boolean_form)) + if string_form is not None: + _form_params.append(('string_form', string_form)) + # process the body parameter - if _params['string_form'] is not None: - _form_params.append(('string_form', _params['string_form'])) - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/form/integer/boolean/string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/form/integer/boolean/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_form_oneof( @@ -235,16 +347,22 @@ def test_form_oneof( form4: Optional[StrictBool] = None, id: Optional[StrictInt] = None, name: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test form parameter(s) for oneOf schema # noqa: E501 - - Test form parameter(s) for oneOf schema # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test form parameter(s) for oneOf schema - >>> thread = api.test_form_oneof(form1, form2, form3, form4, id, name, async_req=True) - >>> result = thread.get() + Test form parameter(s) for oneOf schema :param form1: :type form1: str @@ -258,31 +376,54 @@ def test_form_oneof( :type id: int :param name: :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_form_oneof_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_form_oneof_with_http_info.raw_function( - form1, - form2, - form3, - form4, - id, - name, - **kwargs, + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_form_oneof_with_http_info( @@ -293,16 +434,22 @@ def test_form_oneof_with_http_info( form4: Optional[StrictBool] = None, id: Optional[StrictInt] = None, name: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test form parameter(s) for oneOf schema # noqa: E501 - - Test form parameter(s) for oneOf schema # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test form parameter(s) for oneOf schema - >>> thread = api.test_form_oneof_with_http_info(form1, form2, form3, form4, id, name, async_req=True) - >>> result = thread.get() + Test form parameter(s) for oneOf schema :param form1: :type form1: str @@ -316,126 +463,221 @@ def test_form_oneof_with_http_info( :type id: int :param name: :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'form1', - 'form2', - 'form3', - 'form4', - 'id', - 'name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_form_oneof" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def test_form_oneof_without_preload_content( + self, + form1: Optional[StrictStr] = None, + form2: Optional[StrictInt] = None, + form3: Optional[StrictStr] = None, + form4: Optional[StrictBool] = None, + id: Optional[StrictInt] = None, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test form parameter(s) for oneOf schema - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['form1'] is not None: - _form_params.append(('form1', _params['form1'])) + Test form parameter(s) for oneOf schema - if _params['form2'] is not None: - _form_params.append(('form2', _params['form2'])) + :param form1: + :type form1: str + :param form2: + :type form2: int + :param form3: + :type form3: str + :param form4: + :type form4: bool + :param id: + :type id: int + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['form3'] is not None: - _form_params.append(('form3', _params['form3'])) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['form4'] is not None: - _form_params.append(('form4', _params['form4'])) - if _params['id'] is not None: - _form_params.append(('id', _params['id'])) + def _test_form_oneof_serialize( + self, + form1, + form2, + form3, + form4, + id, + name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - if _params['name'] is not None: - _form_params.append(('name', _params['name'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if form1 is not None: + _form_params.append(('form1', form1)) + if form2 is not None: + _form_params.append(('form2', form2)) + if form3 is not None: + _form_params.append(('form3', form3)) + if form4 is not None: + _form_params.append(('form4', form4)) + if id is not None: + _form_params.append(('id', id)) + if name is not None: + _form_params.append(('name', name)) # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/form/oneof', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/form/oneof', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/header_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/header_api.py index f660475162f4..1ed0ff1f8227 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/header_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/header_api.py @@ -12,26 +12,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictBool, StrictInt, StrictStr, field_validator - from typing import Optional - from openapi_client.models.string_enum_ref import StringEnumRef -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class HeaderApi: @@ -46,6 +38,7 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_header_integer_boolean_string_enums( self, @@ -54,16 +47,22 @@ def test_header_integer_boolean_string_enums( string_header: Optional[StrictStr] = None, enum_nonref_string_header: Optional[StrictStr] = None, enum_ref_string_header: Optional[StringEnumRef] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test header parameter(s) # noqa: E501 + """Test header parameter(s) - Test header parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_header_integer_boolean_string_enums(integer_header, boolean_header, string_header, enum_nonref_string_header, enum_ref_string_header, async_req=True) - >>> result = thread.get() + Test header parameter(s) :param integer_header: :type integer_header: int @@ -75,31 +74,54 @@ def test_header_integer_boolean_string_enums( :type enum_nonref_string_header: str :param enum_ref_string_header: :type enum_ref_string_header: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_header_integer_boolean_string_enums_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_header_integer_boolean_string_enums_with_http_info.raw_function( - integer_header, - boolean_header, - string_header, - enum_nonref_string_header, - enum_ref_string_header, - **kwargs, + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_header_integer_boolean_string_enums_with_http_info( self, @@ -108,16 +130,22 @@ def test_header_integer_boolean_string_enums_with_http_info( string_header: Optional[StrictStr] = None, enum_nonref_string_header: Optional[StrictStr] = None, enum_ref_string_header: Optional[StringEnumRef] = None, - **kwargs, - ) -> ApiResponse: - """Test header parameter(s) # noqa: E501 - - Test header parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test header parameter(s) - >>> thread = api.test_header_integer_boolean_string_enums_with_http_info(integer_header, boolean_header, string_header, enum_nonref_string_header, enum_ref_string_header, async_req=True) - >>> result = thread.get() + Test header parameter(s) :param integer_header: :type integer_header: int @@ -129,115 +157,200 @@ def test_header_integer_boolean_string_enums_with_http_info( :type enum_nonref_string_header: str :param enum_ref_string_header: :type enum_ref_string_header: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'integer_header', - 'boolean_header', - 'string_header', - 'enum_nonref_string_header', - 'enum_ref_string_header' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_header_integer_boolean_string_enums" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def test_header_integer_boolean_string_enums_without_preload_content( + self, + integer_header: Optional[StrictInt] = None, + boolean_header: Optional[StrictBool] = None, + string_header: Optional[StrictStr] = None, + enum_nonref_string_header: Optional[StrictStr] = None, + enum_ref_string_header: Optional[StringEnumRef] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test header parameter(s) - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['integer_header'] is not None: - _header_params['integer_header'] = _params['integer_header'] + Test header parameter(s) - if _params['boolean_header'] is not None: - _header_params['boolean_header'] = _params['boolean_header'] + :param integer_header: + :type integer_header: int + :param boolean_header: + :type boolean_header: bool + :param string_header: + :type string_header: str + :param enum_nonref_string_header: + :type enum_nonref_string_header: str + :param enum_ref_string_header: + :type enum_ref_string_header: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['string_header'] is not None: - _header_params['string_header'] = _params['string_header'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['enum_nonref_string_header'] is not None: - _header_params['enum_nonref_string_header'] = _params['enum_nonref_string_header'] - if _params['enum_ref_string_header'] is not None: - _header_params['enum_ref_string_header'] = _params['enum_ref_string_header'] + def _test_header_integer_boolean_string_enums_serialize( + self, + integer_header, + boolean_header, + string_header, + enum_nonref_string_header, + enum_ref_string_header, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if integer_header is not None: + _header_params['integer_header'] = integer_header + if boolean_header is not None: + _header_params['boolean_header'] = boolean_header + if string_header is not None: + _header_params['string_header'] = string_header + if enum_nonref_string_header is not None: + _header_params['enum_nonref_string_header'] = enum_nonref_string_header + if enum_ref_string_header is not None: + _header_params['enum_ref_string_header'] = enum_ref_string_header + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/header/integer/boolean/string/enums', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/header/integer/boolean/string/enums', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/path_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/path_api.py index 9dd1eabe9f93..8939cbe596cd 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/path_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/path_api.py @@ -12,24 +12,17 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictInt, StrictStr, field_validator - from openapi_client.models.string_enum_ref import StringEnumRef -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class PathApi: @@ -44,6 +37,7 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path( self, @@ -51,16 +45,22 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e path_integer: StrictInt, enum_nonref_string_path: StrictStr, enum_ref_string_path: StringEnumRef, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test path parameter(s) # noqa: E501 - - Test path parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test path parameter(s) - >>> thread = api.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, async_req=True) - >>> result = thread.get() + Test path parameter(s) :param path_string: (required) :type path_string: str @@ -70,30 +70,53 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e :type enum_nonref_string_path: str :param enum_ref_string_path: (required) :type enum_ref_string_path: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info.raw_function( - path_string, - path_integer, - enum_nonref_string_path, - enum_ref_string_path, - **kwargs, + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info( self, @@ -101,16 +124,22 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e path_integer: StrictInt, enum_nonref_string_path: StrictStr, enum_ref_string_path: StringEnumRef, - **kwargs, - ) -> ApiResponse: - """Test path parameter(s) # noqa: E501 - - Test path parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test path parameter(s) - >>> thread = api.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, async_req=True) - >>> result = thread.get() + Test path parameter(s) :param path_string: (required) :type path_string: str @@ -120,111 +149,192 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e :type enum_nonref_string_path: str :param enum_ref_string_path: (required) :type enum_ref_string_path: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'path_string', - 'path_integer', - 'enum_nonref_string_path', - 'enum_ref_string_path' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['path_string'] is not None: - _path_params['path_string'] = _params['path_string'] + @validate_call + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_without_preload_content( + self, + path_string: StrictStr, + path_integer: StrictInt, + enum_nonref_string_path: StrictStr, + enum_ref_string_path: StringEnumRef, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test path parameter(s) + + Test path parameter(s) + + :param path_string: (required) + :type path_string: str + :param path_integer: (required) + :type path_integer: int + :param enum_nonref_string_path: (required) + :type enum_nonref_string_path: str + :param enum_ref_string_path: (required) + :type enum_ref_string_path: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['path_integer'] is not None: - _path_params['path_integer'] = _params['path_integer'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['enum_nonref_string_path'] is not None: - _path_params['enum_nonref_string_path'] = _params['enum_nonref_string_path'] - if _params['enum_ref_string_path'] is not None: - _path_params['enum_ref_string_path'] = _params['enum_ref_string_path'].value + def _tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + self, + path_string, + path_integer, + enum_nonref_string_path, + enum_ref_string_path, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if path_string is not None: + _path_params['path_string'] = path_string + if path_integer is not None: + _path_params['path_integer'] = path_integer + if enum_nonref_string_path is not None: + _path_params['enum_nonref_string_path'] = enum_nonref_string_path + if enum_ref_string_path is not None: + _path_params['enum_ref_string_path'] = enum_ref_string_path.value # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/query_api.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/query_api.py index d2287221eeb0..e27b8f5ce617 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/query_api.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api/query_api.py @@ -12,30 +12,21 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from datetime import date, datetime - from pydantic import StrictBool, StrictInt, StrictStr, field_validator - from typing import Any, Optional - from openapi_client.models.pet import Pet from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.models.test_query_style_form_explode_true_array_string_query_object_parameter import TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class QueryApi: @@ -50,168 +41,282 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_enum_ref_string( self, enum_nonref_string_query: Optional[StrictStr] = None, enum_ref_string_query: Optional[StringEnumRef] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_enum_ref_string(enum_nonref_string_query, enum_ref_string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param enum_nonref_string_query: :type enum_nonref_string_query: str :param enum_ref_string_query: :type enum_ref_string_query: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_enum_ref_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_enum_ref_string_with_http_info.raw_function( - enum_nonref_string_query, - enum_ref_string_query, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_enum_ref_string_with_http_info( self, enum_nonref_string_query: Optional[StrictStr] = None, enum_ref_string_query: Optional[StringEnumRef] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_enum_ref_string_with_http_info(enum_nonref_string_query, enum_ref_string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param enum_nonref_string_query: :type enum_nonref_string_query: str :param enum_ref_string_query: :type enum_ref_string_query: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'enum_nonref_string_query', - 'enum_ref_string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_enum_ref_string_without_preload_content( + self, + enum_nonref_string_query: Optional[StrictStr] = None, + enum_ref_string_query: Optional[StringEnumRef] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param enum_nonref_string_query: + :type enum_nonref_string_query: str + :param enum_ref_string_query: + :type enum_ref_string_query: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_enum_ref_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_enum_ref_string_serialize( + self, + enum_nonref_string_query, + enum_ref_string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('enum_nonref_string_query') is not None: # noqa: E501 - _query_params.append(('enum_nonref_string_query', _params['enum_nonref_string_query'])) + _host = None - if _params.get('enum_ref_string_query') is not None: # noqa: E501 - _query_params.append(('enum_ref_string_query', _params['enum_ref_string_query'].value)) + _collection_formats: Dict[str, str] = { + } - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if enum_nonref_string_query is not None: + + _query_params.append(('enum_nonref_string_query', enum_nonref_string_query)) + + if enum_ref_string_query is not None: + + _query_params.append(('enum_ref_string_query', enum_ref_string_query.value)) + + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/enum_ref_string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/enum_ref_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_datetime_date_string( @@ -219,16 +324,22 @@ def test_query_datetime_date_string( datetime_query: Optional[datetime] = None, date_query: Optional[date] = None, string_query: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_datetime_date_string(datetime_query, date_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param datetime_query: :type datetime_query: datetime @@ -236,28 +347,51 @@ def test_query_datetime_date_string( :type date_query: date :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_datetime_date_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_datetime_date_string_with_http_info.raw_function( - datetime_query, - date_query, - string_query, - **kwargs, + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_datetime_date_string_with_http_info( @@ -265,16 +399,22 @@ def test_query_datetime_date_string_with_http_info( datetime_query: Optional[datetime] = None, date_query: Optional[date] = None, string_query: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_datetime_date_string_with_http_info(datetime_query, date_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param datetime_query: :type datetime_query: datetime @@ -282,116 +422,212 @@ def test_query_datetime_date_string_with_http_info( :type date_query: date :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'datetime_query', - 'date_query', - 'string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_datetime_date_string_without_preload_content( + self, + datetime_query: Optional[datetime] = None, + date_query: Optional[date] = None, + string_query: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param datetime_query: + :type datetime_query: datetime + :param date_query: + :type date_query: date + :param string_query: + :type string_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_datetime_date_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_query_datetime_date_string_serialize( + self, + datetime_query, + date_query, + string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('datetime_query') is not None: # noqa: E501 - if isinstance(_params['datetime_query'], datetime): - _query_params.append(('datetime_query', _params['datetime_query'].strftime(self.api_client.configuration.datetime_format))) + if datetime_query is not None: + if isinstance(datetime_query, datetime): + _query_params.append( + ( + 'datetime_query', + datetime_query.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) else: - _query_params.append(('datetime_query', _params['datetime_query'])) - - if _params.get('date_query') is not None: # noqa: E501 - if isinstance(_params['date_query'], date): - _query_params.append(('date_query', _params['date_query'].strftime(self.api_client.configuration.date_format))) + _query_params.append(('datetime_query', datetime_query)) + + if date_query is not None: + if isinstance(date_query, date): + _query_params.append( + ( + 'date_query', + date_query.strftime( + self.api_client.configuration.date_format + ) + ) + ) else: - _query_params.append(('date_query', _params['date_query'])) - - if _params.get('string_query') is not None: # noqa: E501 - _query_params.append(('string_query', _params['string_query'])) - + _query_params.append(('date_query', date_query)) + + if string_query is not None: + + _query_params.append(('string_query', string_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/datetime/date/string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/datetime/date/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_integer_boolean_string( @@ -399,16 +635,22 @@ def test_query_integer_boolean_string( integer_query: Optional[StrictInt] = None, boolean_query: Optional[StrictBool] = None, string_query: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_integer_boolean_string(integer_query, boolean_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param integer_query: :type integer_query: int @@ -416,28 +658,51 @@ def test_query_integer_boolean_string( :type boolean_query: bool :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_integer_boolean_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_integer_boolean_string_with_http_info.raw_function( - integer_query, - boolean_query, - string_query, - **kwargs, + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_integer_boolean_string_with_http_info( @@ -445,16 +710,22 @@ def test_query_integer_boolean_string_with_http_info( integer_query: Optional[StrictInt] = None, boolean_query: Optional[StrictBool] = None, string_query: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_integer_boolean_string_with_http_info(integer_query, boolean_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param integer_query: :type integer_query: int @@ -462,867 +733,1485 @@ def test_query_integer_boolean_string_with_http_info( :type boolean_query: bool :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'integer_query', - 'boolean_query', - 'string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_integer_boolean_string_without_preload_content( + self, + integer_query: Optional[StrictInt] = None, + boolean_query: Optional[StrictBool] = None, + string_query: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] - ) + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_integer_boolean_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + Test query parameter(s) - _collection_formats: Dict[str, str] = {} + :param integer_query: + :type integer_query: int + :param boolean_query: + :type boolean_query: bool + :param string_query: + :type string_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # process the path parameters - _path_params: Dict[str, str] = {} + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('integer_query') is not None: # noqa: E501 - _query_params.append(('integer_query', _params['integer_query'])) - if _params.get('boolean_query') is not None: # noqa: E501 - _query_params.append(('boolean_query', _params['boolean_query'])) + def _test_query_integer_boolean_string_serialize( + self, + integer_query, + boolean_query, + string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - if _params.get('string_query') is not None: # noqa: E501 - _query_params.append(('string_query', _params['string_query'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if integer_query is not None: + + _query_params.append(('integer_query', integer_query)) + + if boolean_query is not None: + + _query_params.append(('boolean_query', boolean_query)) + + if string_query is not None: + + _query_params.append(('string_query', string_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/integer/boolean/string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/integer/boolean/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_deep_object_explode_true_object( self, query_object: Optional[Pet] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_deep_object_explode_true_object(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_deep_object_explode_true_object_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_style_deep_object_explode_true_object_with_http_info.raw_function( - query_object, - **kwargs, - ) + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_deep_object_explode_true_object_with_http_info( self, query_object: Optional[Pet] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_deep_object_explode_true_object_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_query_style_deep_object_explode_true_object_without_preload_content( + self, + query_object: Optional[Pet] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_deep_object_explode_true_object" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_deep_object_explode_true_object_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_deepObject/explode_true/object', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_deepObject/explode_true/object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_deep_object_explode_true_object_all_of( self, query_object: Optional[Any] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_deep_object_explode_true_object_all_of(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_deep_object_explode_true_object_all_of_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_deep_object_explode_true_object_all_of_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_deep_object_explode_true_object_all_of_with_http_info( self, query_object: Optional[Any] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_deep_object_explode_true_object_all_of_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_deep_object_explode_true_object_all_of_without_preload_content( + self, + query_object: Optional[Any] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_deep_object_explode_true_object_all_of" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_deep_object_explode_true_object_all_of_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_deepObject/explode_true/object/allOf', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_deepObject/explode_true/object/allOf', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_array_string( self, query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_array_string(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_array_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_array_string_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_array_string_with_http_info( self, query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_array_string_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_form_explode_true_array_string_without_preload_content( + self, + query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_array_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_array_string_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/array_string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/array_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_object( self, query_object: Optional[Pet] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_form_explode_true_object(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_object_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_object_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_object_with_http_info( self, query_object: Optional[Pet] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_form_explode_true_object_without_preload_content( + self, + query_object: Optional[Pet] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_object" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_object_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/object', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_object_all_of( self, query_object: Optional[Any] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_all_of(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: DataQuery - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_object_all_of_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_object_all_of_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_object_all_of_with_http_info( self, query_object: Optional[Any] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_all_of_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: DataQuery - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_query_style_form_explode_true_object_all_of_without_preload_content( + self, + query_object: Optional[Any] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: DataQuery + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_object_all_of" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_object_all_of_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/object/allOf', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/object/allOf', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_client.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_client.py index 962fad87d685..ce93eaca6dea 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_client.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_client.py @@ -13,24 +13,32 @@ """ # noqa: E501 -import atexit import datetime from dateutil.parser import parse import json import mimetypes -from multiprocessing.pool import ThreadPool import os import re import tempfile from urllib.parse import quote +from typing import Tuple, Optional, List, Dict from openapi_client.configuration import Configuration -from openapi_client.api_response import ApiResponse +from openapi_client.api_response import ApiResponse, T as ApiResponseT import openapi_client.models from openapi_client import rest -from openapi_client.exceptions import ApiValueError, ApiException - +from openapi_client.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -46,8 +54,6 @@ class ApiClient: the API. :param cookie: a cookie to include in the header when making calls to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. """ PRIMITIVE_TYPES = (float, bool, bytes, str, int) @@ -63,13 +69,17 @@ class ApiClient: } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1) -> None: + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration - self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} @@ -84,25 +94,7 @@ def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool + pass @property def user_agent(self): @@ -143,13 +135,42 @@ def set_default(cls, default): """ cls._default = default - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -160,14 +181,17 @@ def __call_api( header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -179,15 +203,22 @@ def __call_api( if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: @@ -203,59 +234,99 @@ def __call_api( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + try: # perform request and return response - response_data = self.request( + response_data = self.rest_client.request( method, url, - query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') raise e - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -276,15 +347,17 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except @@ -294,10 +367,12 @@ def sanitize_for_serialization(self, obj): # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -306,16 +381,12 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -332,12 +403,16 @@ def __deserialize(self, data, klass): if isinstance(klass, str): if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -358,136 +433,6 @@ def __deserialize(self, data, klass): else: return self.__deserialize_model(data, klass) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - if not async_req: - return self.__call_api(*args) - - return self.pool.apply_async(self.__call_api, args) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -495,10 +440,10 @@ def parameters_to_tuples(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -525,14 +470,14 @@ def parameters_to_url_query(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) + for k, v in params.items() if isinstance(params, dict) else params: if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) @@ -550,7 +495,8 @@ def parameters_to_url_query(self, params, collection_formats): else: # csv is the default delimiter = ',' new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -573,21 +519,24 @@ def files_parameters(self, files=None): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None for accept in accepts: if re.search('json', accept, re.IGNORECASE): @@ -610,9 +559,16 @@ def select_header_content_type(self, content_types): return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -629,21 +585,36 @@ def update_params_for_auth(self, headers, queries, auth_settings, return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -672,6 +643,9 @@ def __deserialize_file(self, response): Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -681,8 +655,12 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_response.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_response.py index a0b62b95246c..9bc7c11f6b9f 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_response.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/api_response.py @@ -1,25 +1,21 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel -class ApiResponse: +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): """ API response object """ - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data + model_config = { + "arbitrary_types_allowed": True + } diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/configuration.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/configuration.py index 8ff03cff3b9e..43604555bd8b 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/configuration.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/configuration.py @@ -15,8 +15,10 @@ import copy import logging +from logging import FileHandler import multiprocessing import sys +from typing import Optional import urllib3 import http.client as httplib @@ -133,7 +135,7 @@ def __init__(self, host=None, self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -173,7 +175,7 @@ def __init__(self, host=None, cpu_count * 5 is used as default value to increase performance. """ - self.proxy = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None @@ -382,6 +384,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() } + if self.access_token is not None: + auth['http_bearer_auth'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } return auth def to_debug_report(self): diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/exceptions.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/exceptions.py index ae3e985d2fee..bd5561d241ed 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/exceptions.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/exceptions.py @@ -12,6 +12,8 @@ Do not edit the class manually. """ # noqa: E501 +from typing import Any, Optional +from typing_extensions import Self class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" @@ -102,17 +104,56 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) def __str__(self): """Custom error messages for exception""" @@ -122,38 +163,30 @@ def __str__(self): error_message += "HTTP response headers: {0}\n".format( self.headers) - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message + class BadRequestException(ApiException): + pass - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + pass class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + pass class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + pass class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + pass def render_path(path_to_item): diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/bird.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/bird.py index 33c7b26e8484..5481dd4f015f 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/bird.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/bird.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Bird(BaseModel): """ Bird - """ + """ # noqa: E501 size: Optional[StrictStr] = None color: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["size", "color"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Bird from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Bird from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/category.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/category.py index 1bedf6f65d28..e46f6989cb44 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/category.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/category.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Category(BaseModel): """ Category - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Category from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Category from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/data_query.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/data_query.py index c91e48bd59fd..6bac8e154f55 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/data_query.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/data_query.py @@ -19,20 +19,16 @@ import json from datetime import datetime -from typing import Optional -from pydantic import StrictStr -from pydantic import Field +from pydantic import Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.query import Query -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class DataQuery(Query): """ DataQuery - """ + """ # noqa: E501 suffix: Optional[StrictStr] = Field(default=None, description="test suffix") text: Optional[StrictStr] = Field(default=None, description="Some text containing white spaces") var_date: Optional[datetime] = Field(default=None, description="A date", alias="date") @@ -40,7 +36,8 @@ class DataQuery(Query): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DataQuery from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,16 +65,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DataQuery from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/default_value.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/default_value.py index 4de9557f2ef7..aaaeb2682c12 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/default_value.py @@ -18,20 +18,16 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.string_enum_ref import StringEnumRef -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class DefaultValue(BaseModel): """ - to test the default value of properties # noqa: E501 - """ + to test the default value of properties + """ # noqa: E501 array_string_enum_ref_default: Optional[List[StringEnumRef]] = None array_string_enum_default: Optional[List[StrictStr]] = None array_string_default: Optional[List[StrictStr]] = None @@ -55,7 +51,8 @@ def array_string_enum_default_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -69,7 +66,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DefaultValue from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -83,10 +80,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if array_string_nullable (nullable) is None @@ -107,7 +106,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DefaultValue from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/number_properties_only.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/number_properties_only.py index 495bfaea144f..051e721ba13b 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/number_properties_only.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/number_properties_only.py @@ -18,21 +18,16 @@ import re # noqa: F401 import json - -from typing import Optional, Union -from pydantic import BaseModel, StrictFloat, StrictInt -from pydantic import Field +from pydantic import BaseModel, Field, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class NumberPropertiesOnly(BaseModel): """ NumberPropertiesOnly - """ + """ # noqa: E501 number: Optional[Union[StrictFloat, StrictInt]] = None var_float: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="float") double: Optional[Union[Annotated[float, Field(le=50.2, strict=True, ge=0.8)], Annotated[int, Field(le=50, strict=True, ge=1)]]] = None @@ -40,7 +35,8 @@ class NumberPropertiesOnly(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NumberPropertiesOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,16 +64,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NumberPropertiesOnly from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/pet.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/pet.py index 102f657a20b2..54caa7b78b9e 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/pet.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/pet.py @@ -18,22 +18,17 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.category import Category from openapi_client.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Pet(BaseModel): """ Pet - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: StrictStr category: Optional[Category] = None @@ -54,7 +49,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -68,7 +64,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Pet from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -82,10 +78,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of category @@ -101,7 +99,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Pet from a dict""" if obj is None: return None @@ -117,9 +115,9 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "id": obj.get("id"), "name": obj.get("name"), - "category": Category.from_dict(obj.get("category")) if obj.get("category") is not None else None, + "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj.get("tags")] if obj.get("tags") is not None else None, + "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, "status": obj.get("status") }) return _obj diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/query.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/query.py index e6277c3fa3d1..2f7343030130 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/query.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/query.py @@ -18,20 +18,15 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Query(BaseModel): """ Query - """ + """ # noqa: E501 id: Optional[StrictInt] = Field(default=None, description="Query") outcomes: Optional[List[StrictStr]] = None __properties: ClassVar[List[str]] = ["id", "outcomes"] @@ -49,7 +44,8 @@ def outcomes_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -63,7 +59,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Query from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -77,16 +73,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Optional[Self]: """Create an instance of Query from a dict""" diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/string_enum_ref.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/string_enum_ref.py index cedd6194f983..90328aea76dd 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/string_enum_ref.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/string_enum_ref.py @@ -15,16 +15,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class StringEnumRef(str, Enum): diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/tag.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/tag.py index d691e053b851..bd160fbe153b 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/tag.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/tag.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tag(BaseModel): """ Tag - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tag from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tag from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py index 572f5c4862e7..34bac06087ce 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py @@ -18,19 +18,15 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseModel): """ TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - """ + """ # noqa: E501 size: Optional[StrictStr] = None color: Optional[StrictStr] = None id: Optional[StrictInt] = None @@ -39,7 +35,8 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseMod model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,16 +64,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py index ccc499508dfb..7e3bd92a2737 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py @@ -18,25 +18,22 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): """ TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - """ + """ # noqa: E501 values: Optional[List[StrictStr]] = None __properties: ClassVar[List[str]] = ["values"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/rest.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/rest.py index d05e077260de..52aeb1cfa887 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/rest.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/openapi_client/rest.py @@ -15,43 +15,55 @@ import io import json -import logging import re import ssl -from urllib.parse import urlencode, quote_plus import urllib3 -from openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException +from openapi_client.exceptions import ApiException, ApiValueError +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse -logger = logging.getLogger(__name__) + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES class RESTResponse(io.IOBase): def __init__(self, resp) -> None: - self.urllib3_response = resp + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs @@ -60,74 +72,79 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: else: cert_reqs = ssl.CERT_NONE - addition_pool_args = {} + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries + pool_args['retries'] = configuration.retries if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name + pool_args['server_hostname'] = configuration.tls_server_name if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options + pool_args['socket_options'] = configuration.socket_options - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize # https pool manager + self.pool_manager: urllib3.PoolManager + if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -136,63 +153,84 @@ def request(self, method, url, query_params=None, headers=None, post_params = post_params or {} headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form + # other content types than JSON when `body` argument is + # provided in serialized form. elif isinstance(body, str) or isinstance(body, bytes): - request_body = body r = self.pool_manager.request( - method, url, + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, body=request_body, - preload_content=_preload_content, + preload_content=False, timeout=timeout, headers=headers) else: @@ -203,102 +241,16 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) + msg = "\n".join([type(e).__name__, str(e)]) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return RESTResponse(r) diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/pyproject.toml b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/pyproject.toml index af471ab63148..0d00a14b8ebd 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/pyproject.toml +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/pyproject.toml @@ -21,6 +21,9 @@ typing-extensions = ">=4.7.1" pytest = ">=7.2.1" tox = ">=3.9.0" flake8 = ">=4.0.0" +types-python-dateutil = ">=2.8.19.14" +mypy = "1.4.1" + [build-system] requires = ["setuptools"] @@ -28,3 +31,41 @@ build-backend = "setuptools.build_meta" [tool.pylint.'MESSAGES CONTROL'] extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "openapi_client", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +strict_concatenate = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test-requirements.txt b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test-requirements.txt index 3a0d0b939a1e..8e6d8cb13749 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test-requirements.txt +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test-requirements.txt @@ -1,3 +1,5 @@ pytest~=7.1.3 pytest-cov>=2.8.1 pytest-randomly>=3.12.0 +mypy>=1.4.1 +types-python-dateutil>=2.8.19 diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/__init__.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/tests/__init__.py similarity index 100% rename from samples/openapi3/server/petstore/python-flask/openapi_server/__init__.py rename to samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/tests/__init__.py diff --git a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test/test_manual.py b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/tests/test_manual.py similarity index 96% rename from samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test/test_manual.py rename to samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/tests/test_manual.py index ab1684f333ae..93e3c1c27a20 100644 --- a/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/test/test_manual.py +++ b/samples/client/echo_api/python-disallowAdditionalPropertiesIfNotPresent-true/tests/test_manual.py @@ -52,7 +52,7 @@ def testDateTimeQueryWithDateTimeFormat(self): datetime_format_backup = api_instance.api_client.configuration.datetime_format # backup dateime_format api_instance.api_client.configuration.datetime_format = "%Y-%m-%d %a %H:%M:%S%Z" datetime_query = datetime.datetime.fromisoformat('2013-10-20T19:20:30-05:00') # datetime | (optional) - date_query = '2013-10-20' # date | (optional) + date_query = datetime.date(2013, 10, 20) # date | (optional) string_query = 'string_query_example' # str | (optional) # Test query parameter(s) @@ -66,7 +66,7 @@ def testDateTimeQueryWithDateTimeFormat(self): def testDateTimeQueryWithDateTime(self): api_instance = openapi_client.QueryApi() datetime_query = datetime.datetime.fromisoformat('2013-10-20T19:20:30-05:00') # datetime | (optional) - date_query = '2013-10-20' # date | (optional) + date_query = datetime.date(2013, 10, 20) # date | (optional) string_query = 'string_query_example' # str | (optional) # Test query parameter(s) @@ -147,11 +147,14 @@ def test_from_to_methods(self): " \"status\": \"available\",\n" " \"tags\": [{\"id\": 1, \"name\": \"None\"}]}") pet = openapi_client.Pet.from_json(json_str) + assert pet is not None self.assertEqual(pet.id, 1) self.assertEqual(pet.status, "available") self.assertEqual(pet.photo_urls, ["string"]) + assert pet.tags is not None self.assertEqual(pet.tags[0].id, 1) self.assertEqual(pet.tags[0].name, "None") + assert pet.category is not None self.assertEqual(pet.category.id, 1) # test to_json self.assertEqual(pet.to_json(), @@ -165,11 +168,14 @@ def test_from_to_methods(self): # test from_dict pet2 = openapi_client.Pet.from_dict(pet.to_dict()) + assert pet2 is not None self.assertEqual(pet2.id, 1) self.assertEqual(pet2.status, "available") self.assertEqual(pet2.photo_urls, ["string"]) + assert pet2.tags is not None self.assertEqual(pet2.tags[0].id, 1) self.assertEqual(pet2.tags[0].name, "None") + assert pet2.category is not None self.assertEqual(pet2.category.id, 1) def echoServerResponseParaserTest(self): diff --git a/samples/client/echo_api/python-pydantic-v1/.openapi-generator/VERSION b/samples/client/echo_api/python-pydantic-v1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/python-pydantic-v1/.openapi-generator/VERSION +++ b/samples/client/echo_api/python-pydantic-v1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/python-pydantic-v1/README.md b/samples/client/echo_api/python-pydantic-v1/README.md index 65c5ff5e5437..fd797996cf68 100644 --- a/samples/client/echo_api/python-pydantic-v1/README.md +++ b/samples/client/echo_api/python-pydantic-v1/README.md @@ -95,9 +95,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -141,6 +144,11 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + ## Author diff --git a/samples/client/echo_api/python-pydantic-v1/docs/AuthApi.md b/samples/client/echo_api/python-pydantic-v1/docs/AuthApi.md index 98ce834c3176..e4db5503ece0 100644 --- a/samples/client/echo_api/python-pydantic-v1/docs/AuthApi.md +++ b/samples/client/echo_api/python-pydantic-v1/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* Method | HTTP request | Description ------------- | ------------- | ------------- [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +[**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication # **test_auth_http_basic** @@ -80,3 +81,75 @@ This endpoint does not need any parameter. [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_auth_http_bearer** +> str test_auth_http_bearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +* Bearer Authentication (http_bearer_auth): +```python +import time +import os +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: http_bearer_auth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.AuthApi(api_client) + + try: + # To test HTTP bearer authentication + api_response = api_instance.test_auth_http_bearer() + print("The response of AuthApi->test_auth_http_bearer:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AuthApi->test_auth_http_bearer: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**str** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/echo_api/python-pydantic-v1/docs/BodyApi.md b/samples/client/echo_api/python-pydantic-v1/docs/BodyApi.md index 553100ffc922..228fcafd1d24 100644 --- a/samples/client/echo_api/python-pydantic-v1/docs/BodyApi.md +++ b/samples/client/echo_api/python-pydantic-v1/docs/BodyApi.md @@ -7,6 +7,8 @@ Method | HTTP request | Description [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +[**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +[**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -207,6 +209,139 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_body_multipart_formdata_single_binary** +> str test_body_multipart_formdata_single_binary(my_file=my_file) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + +```python +import time +import os +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + my_file = None # bytearray | (optional) + + try: + # Test single binary in multipart mime + api_response = api_instance.test_body_multipart_formdata_single_binary(my_file=my_file) + print("The response of BodyApi->test_body_multipart_formdata_single_binary:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_body_multipart_formdata_single_binary: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **my_file** | **bytearray**| | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_echo_body_all_of_pet** +> Pet test_echo_body_all_of_pet(pet=pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + +```python +import time +import os +import openapi_client +from openapi_client.models.pet import Pet +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + pet = openapi_client.Pet() # Pet | Pet object that needs to be added to the store (optional) + + try: + # Test body parameter(s) + api_response = api_instance.test_echo_body_all_of_pet(pet=pet) + print("The response of BodyApi->test_echo_body_all_of_pet:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_echo_body_all_of_pet: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_echo_body_free_form_object_response_string** > str test_echo_body_free_form_object_response_string(body=body) diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/api/auth_api.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/api/auth_api.py index 16ee7463aad7..dcb3ff423f8e 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/api/auth_api.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/api/auth_api.py @@ -171,3 +171,135 @@ def test_auth_http_basic_with_http_info(self, **kwargs) -> ApiResponse: # noqa: _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + + @validate_arguments + def test_auth_http_bearer(self, **kwargs) -> str: # noqa: E501 + """To test HTTP bearer authentication # noqa: E501 + + To test HTTP bearer authentication # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_auth_http_bearer(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_auth_http_bearer_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_auth_http_bearer_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def test_auth_http_bearer_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """To test HTTP bearer authentication # noqa: E501 + + To test HTTP bearer authentication # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_auth_http_bearer_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_auth_http_bearer" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['text/plain']) # noqa: E501 + + # authentication setting + _auth_settings = ['http_bearer_auth'] # noqa: E501 + + _response_types_map = { + '200': "str", + } + + return self.api_client.call_api( + '/auth/http/bearer', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/api/body_api.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/api/body_api.py index ebb8111b7725..62db87074772 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/api/body_api.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/api/body_api.py @@ -479,6 +479,300 @@ def test_body_multipart_formdata_array_of_binary_with_http_info(self, files : co collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def test_body_multipart_formdata_single_binary(self, my_file : Optional[Union[StrictBytes, StrictStr]] = None, **kwargs) -> str: # noqa: E501 + """Test single binary in multipart mime # noqa: E501 + + Test single binary in multipart mime # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_multipart_formdata_single_binary(my_file, async_req=True) + >>> result = thread.get() + + :param my_file: + :type my_file: bytearray + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: str + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_body_multipart_formdata_single_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_body_multipart_formdata_single_binary_with_http_info(my_file, **kwargs) # noqa: E501 + + @validate_arguments + def test_body_multipart_formdata_single_binary_with_http_info(self, my_file : Optional[Union[StrictBytes, StrictStr]] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Test single binary in multipart mime # noqa: E501 + + Test single binary in multipart mime # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_body_multipart_formdata_single_binary_with_http_info(my_file, async_req=True) + >>> result = thread.get() + + :param my_file: + :type my_file: bytearray + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'my_file' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_body_multipart_formdata_single_binary" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + if _params['my_file'] is not None: + _files['my-file'] = _params['my_file'] + + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['text/plain']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['multipart/form-data'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "str", + } + + return self.api_client.call_api( + '/body/application/octetstream/single_binary', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + + @validate_arguments + def test_echo_body_all_of_pet(self, pet : Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, **kwargs) -> Pet: # noqa: E501 + """Test body parameter(s) # noqa: E501 + + Test body parameter(s) # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_echo_body_all_of_pet(pet, async_req=True) + >>> result = thread.get() + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: Pet + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_echo_body_all_of_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_echo_body_all_of_pet_with_http_info(pet, **kwargs) # noqa: E501 + + @validate_arguments + def test_echo_body_all_of_pet_with_http_info(self, pet : Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, **kwargs) -> ApiResponse: # noqa: E501 + """Test body parameter(s) # noqa: E501 + + Test body parameter(s) # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_echo_body_all_of_pet_with_http_info(pet, async_req=True) + >>> result = thread.get() + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(Pet, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + 'pet' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_echo_body_all_of_pet" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['pet'] is not None: + _body_params = _params['pet'] + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "Pet", + } + + return self.api_client.call_api( + '/echo/body/allOf/Pet', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def test_echo_body_free_form_object_response_string(self, body : Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, **kwargs) -> str: # noqa: E501 """Test free form object # noqa: E501 diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/api_client.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/api_client.py index 962fad87d685..459e3850849e 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/api_client.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/api_client.py @@ -529,10 +529,10 @@ def parameters_to_url_query(self, params, collection_formats): if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/configuration.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/configuration.py index 8ff03cff3b9e..7c6f3e11f99f 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/configuration.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/configuration.py @@ -382,6 +382,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() } + if self.access_token is not None: + auth['http_bearer_auth'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } return auth def to_debug_report(self): diff --git a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py index d05e077260de..f4a710085985 100644 --- a/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py +++ b/samples/client/echo_api/python-pydantic-v1/openapi_client/rest.py @@ -27,6 +27,18 @@ logger = logging.getLogger(__name__) +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + class RESTResponse(io.IOBase): @@ -82,17 +94,29 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: # https pool manager if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + self.pool_manager = SOCKSProxyManager( + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, diff --git a/samples/client/echo_api/python-pydantic-v1/test/test_manual.py b/samples/client/echo_api/python-pydantic-v1/test/test_manual.py index 48cd3cf7724a..fedf4cfad6bf 100644 --- a/samples/client/echo_api/python-pydantic-v1/test/test_manual.py +++ b/samples/client/echo_api/python-pydantic-v1/test/test_manual.py @@ -145,6 +145,11 @@ def testAuthHttpBasic(self): self.assertTrue("Authorization" in e.headers) self.assertEqual(e.headers["Authorization"], "Basic dGVzdF91c2VybmFtZTp0ZXN0X3Bhc3N3b3Jk") + def test_parameters_to_url_query_boolean_value(self): + client = openapi_client.ApiClient() + params = client.parameters_to_url_query([("boolean", True),], {}) + self.assertEqual(params, "boolean=true") + def echoServerResponseParaserTest(self): s = """POST /echo/body/Pet/response_string HTTP/1.1 Host: localhost:3000 diff --git a/samples/client/echo_api/python/.openapi-generator/VERSION b/samples/client/echo_api/python/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/python/.openapi-generator/VERSION +++ b/samples/client/echo_api/python/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/python/README.md b/samples/client/echo_api/python/README.md index 9096a78c85de..f44bd12c67c4 100644 --- a/samples/client/echo_api/python/README.md +++ b/samples/client/echo_api/python/README.md @@ -50,7 +50,6 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python -import time import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -95,9 +94,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body *BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) *BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -141,6 +143,11 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + ## Author diff --git a/samples/client/echo_api/python/docs/AuthApi.md b/samples/client/echo_api/python/docs/AuthApi.md index 98ce834c3176..507592b4811e 100644 --- a/samples/client/echo_api/python/docs/AuthApi.md +++ b/samples/client/echo_api/python/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* Method | HTTP request | Description ------------- | ------------- | ------------- [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +[**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication # **test_auth_http_basic** @@ -17,9 +18,8 @@ To test HTTP basic authentication ### Example * Basic Authentication (http_auth): + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -58,6 +58,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -74,6 +75,80 @@ This endpoint does not need any parameter. - **Accept**: text/plain ### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_auth_http_bearer** +> str test_auth_http_bearer() + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Example + +* Bearer Authentication (http_bearer_auth): + +```python +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + +# The client must configure the authentication and authorization parameters +# in accordance with the API server security policy. +# Examples for each auth method are provided below, use the example that +# satisfies your auth use case. + +# Configure Bearer authorization: http_bearer_auth +configuration = openapi_client.Configuration( + access_token = os.environ["BEARER_TOKEN"] +) + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.AuthApi(api_client) + + try: + # To test HTTP bearer authentication + api_response = api_instance.test_auth_http_bearer() + print("The response of AuthApi->test_auth_http_bearer:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling AuthApi->test_auth_http_bearer: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**str** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/Bird.md b/samples/client/echo_api/python/docs/Bird.md index f1ad71c2150f..d2434b50032f 100644 --- a/samples/client/echo_api/python/docs/Bird.md +++ b/samples/client/echo_api/python/docs/Bird.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **str** | | [optional] diff --git a/samples/client/echo_api/python/docs/BodyApi.md b/samples/client/echo_api/python/docs/BodyApi.md index 553100ffc922..acfbe28268d6 100644 --- a/samples/client/echo_api/python/docs/BodyApi.md +++ b/samples/client/echo_api/python/docs/BodyApi.md @@ -7,6 +7,8 @@ Method | HTTP request | Description [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +[**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +[**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -22,9 +24,8 @@ Test binary (gif) response body ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -53,6 +54,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -69,6 +71,7 @@ No authorization required - **Accept**: image/gif ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -84,9 +87,8 @@ Test body parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -117,6 +119,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bytearray**| | [optional] @@ -135,6 +138,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -150,9 +154,8 @@ Test array of binary in multipart mime ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -183,6 +186,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **files** | **List[bytearray]**| | @@ -201,6 +205,142 @@ No authorization required - **Accept**: text/plain ### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_body_multipart_formdata_single_binary** +> str test_body_multipart_formdata_single_binary(my_file=my_file) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Example + + +```python +import openapi_client +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + my_file = None # bytearray | (optional) + + try: + # Test single binary in multipart mime + api_response = api_instance.test_body_multipart_formdata_single_binary(my_file=my_file) + print("The response of BodyApi->test_body_multipart_formdata_single_binary:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_body_multipart_formdata_single_binary: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **my_file** | **bytearray**| | [optional] + +### Return type + +**str** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: text/plain + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | Successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **test_echo_body_all_of_pet** +> Pet test_echo_body_all_of_pet(pet=pet) + +Test body parameter(s) + +Test body parameter(s) + +### Example + + +```python +import openapi_client +from openapi_client.models.pet import Pet +from openapi_client.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://localhost:3000 +# See configuration.py for a list of all supported configuration parameters. +configuration = openapi_client.Configuration( + host = "http://localhost:3000" +) + + +# Enter a context with an instance of the API client +with openapi_client.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = openapi_client.BodyApi(api_client) + pet = openapi_client.Pet() # Pet | Pet object that needs to be added to the store (optional) + + try: + # Test body parameter(s) + api_response = api_instance.test_echo_body_all_of_pet(pet=pet) + print("The response of BodyApi->test_echo_body_all_of_pet:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling BodyApi->test_echo_body_all_of_pet: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/json + +### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -216,9 +356,8 @@ Test free form object ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -249,6 +388,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **object**| Free form object | [optional] @@ -267,6 +407,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -282,9 +423,8 @@ Test body parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -316,6 +456,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] @@ -334,6 +475,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -349,9 +491,8 @@ Test empty response body ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -383,6 +524,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | [optional] @@ -401,6 +543,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -416,9 +559,8 @@ Test empty json (request body) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.tag import Tag from openapi_client.rest import ApiException @@ -450,6 +592,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **tag** | [**Tag**](Tag.md)| Tag object | [optional] @@ -468,6 +611,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/Category.md b/samples/client/echo_api/python/docs/Category.md index bf23e3b044dd..633bbe90398a 100644 --- a/samples/client/echo_api/python/docs/Category.md +++ b/samples/client/echo_api/python/docs/Category.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python/docs/DataQuery.md b/samples/client/echo_api/python/docs/DataQuery.md index bac43a6cc706..dcc235611296 100644 --- a/samples/client/echo_api/python/docs/DataQuery.md +++ b/samples/client/echo_api/python/docs/DataQuery.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **suffix** | **str** | test suffix | [optional] diff --git a/samples/client/echo_api/python/docs/DefaultValue.md b/samples/client/echo_api/python/docs/DefaultValue.md index fcdbebf0e0ad..efdfff470b62 100644 --- a/samples/client/echo_api/python/docs/DefaultValue.md +++ b/samples/client/echo_api/python/docs/DefaultValue.md @@ -3,6 +3,7 @@ to test the default value of properties ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_string_enum_ref_default** | [**List[StringEnumRef]**](StringEnumRef.md) | | [optional] [default to ["success","failure"]] diff --git a/samples/client/echo_api/python/docs/FormApi.md b/samples/client/echo_api/python/docs/FormApi.md index c823e4b82ae4..94205cd60e4a 100644 --- a/samples/client/echo_api/python/docs/FormApi.md +++ b/samples/client/echo_api/python/docs/FormApi.md @@ -17,9 +17,8 @@ Test form parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -52,6 +51,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_form** | **int**| | [optional] @@ -72,6 +72,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -87,9 +88,8 @@ Test form parameter(s) for oneOf schema ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -125,6 +125,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **form1** | **str**| | [optional] @@ -148,6 +149,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/HeaderApi.md b/samples/client/echo_api/python/docs/HeaderApi.md index 7bf15b0037c0..137b5c00d105 100644 --- a/samples/client/echo_api/python/docs/HeaderApi.md +++ b/samples/client/echo_api/python/docs/HeaderApi.md @@ -16,9 +16,8 @@ Test header parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -54,6 +53,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_header** | **int**| | [optional] @@ -76,6 +76,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/NumberPropertiesOnly.md b/samples/client/echo_api/python/docs/NumberPropertiesOnly.md index 709b3996be9a..f1bf5009836b 100644 --- a/samples/client/echo_api/python/docs/NumberPropertiesOnly.md +++ b/samples/client/echo_api/python/docs/NumberPropertiesOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **number** | **float** | | [optional] diff --git a/samples/client/echo_api/python/docs/PathApi.md b/samples/client/echo_api/python/docs/PathApi.md index 14e23b66b969..dd9362bb746e 100644 --- a/samples/client/echo_api/python/docs/PathApi.md +++ b/samples/client/echo_api/python/docs/PathApi.md @@ -16,9 +16,8 @@ Test path parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -53,6 +52,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **path_string** | **str**| | @@ -74,6 +74,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/Pet.md b/samples/client/echo_api/python/docs/Pet.md index bd578ba9a501..1e97d80b3c19 100644 --- a/samples/client/echo_api/python/docs/Pet.md +++ b/samples/client/echo_api/python/docs/Pet.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python/docs/Query.md b/samples/client/echo_api/python/docs/Query.md index 8a3462120895..98ed8b6eedfc 100644 --- a/samples/client/echo_api/python/docs/Query.md +++ b/samples/client/echo_api/python/docs/Query.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | Query | [optional] diff --git a/samples/client/echo_api/python/docs/QueryApi.md b/samples/client/echo_api/python/docs/QueryApi.md index d449cc3ea189..e84a872066f8 100644 --- a/samples/client/echo_api/python/docs/QueryApi.md +++ b/samples/client/echo_api/python/docs/QueryApi.md @@ -23,9 +23,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.rest import ApiException @@ -58,6 +57,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **enum_nonref_string_query** | **str**| | [optional] @@ -77,6 +77,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -92,9 +93,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -127,6 +127,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **datetime_query** | **datetime**| | [optional] @@ -147,6 +148,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -162,9 +164,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -197,6 +198,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **integer_query** | **int**| | [optional] @@ -217,6 +219,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -232,9 +235,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -266,6 +268,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**Pet**](.md)| | [optional] @@ -284,6 +287,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -299,9 +303,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -332,6 +335,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md)| | [optional] @@ -350,6 +354,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -365,9 +370,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.test_query_style_form_explode_true_array_string_query_object_parameter import TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from openapi_client.rest import ApiException @@ -399,6 +403,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md)| | [optional] @@ -417,6 +422,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -432,9 +438,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.models.pet import Pet from openapi_client.rest import ApiException @@ -466,6 +471,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**Pet**](.md)| | [optional] @@ -484,6 +490,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -499,9 +506,8 @@ Test query parameter(s) ### Example + ```python -import time -import os import openapi_client from openapi_client.rest import ApiException from pprint import pprint @@ -532,6 +538,7 @@ with openapi_client.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query_object** | [**DataQuery**](.md)| | [optional] @@ -550,6 +557,7 @@ No authorization required - **Accept**: text/plain ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | diff --git a/samples/client/echo_api/python/docs/StringEnumRef.md b/samples/client/echo_api/python/docs/StringEnumRef.md index f59594fb861f..8ff54010193c 100644 --- a/samples/client/echo_api/python/docs/StringEnumRef.md +++ b/samples/client/echo_api/python/docs/StringEnumRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/client/echo_api/python/docs/Tag.md b/samples/client/echo_api/python/docs/Tag.md index febb268b1443..9b61fe147a9d 100644 --- a/samples/client/echo_api/python/docs/Tag.md +++ b/samples/client/echo_api/python/docs/Tag.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md index 3b0a87b71c53..723d8e9de9b3 100644 --- a/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +++ b/samples/client/echo_api/python/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **str** | | [optional] diff --git a/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md index c741b723f003..c9d0c06a3532 100644 --- a/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +++ b/samples/client/echo_api/python/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **values** | **List[str]** | | [optional] diff --git a/samples/client/echo_api/python/openapi_client/api/auth_api.py b/samples/client/echo_api/python/openapi_client/api/auth_api.py index 7589b21d02d5..9a00225bb97e 100644 --- a/samples/client/echo_api/python/openapi_client/api/auth_api.py +++ b/samples/client/echo_api/python/openapi_client/api/auth_api.py @@ -12,21 +12,15 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class AuthApi: @@ -41,143 +35,488 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_auth_http_basic( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """To test HTTP basic authentication # noqa: E501 - - To test HTTP basic authentication # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """To test HTTP basic authentication - >>> thread = api.test_auth_http_basic(async_req=True) - >>> result = thread.get() + To test HTTP basic authentication - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_auth_http_basic_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return self.test_auth_http_basic_with_http_info.raw_function( - **kwargs, + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_auth_http_basic_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """To test HTTP basic authentication # noqa: E501 - - To test HTTP basic authentication # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_auth_http_basic_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """To test HTTP basic authentication + + To test HTTP basic authentication + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_auth_http_basic_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test HTTP basic authentication + + To test HTTP basic authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_basic_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_auth_http_basic" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_auth_http_basic_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) + # authentication setting - _auth_settings: List[str] = ['http_auth'] # noqa: E501 + _auth_settings: List[str] = [ + 'http_auth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/auth/http/basic', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_auth_http_bearer( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> str: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_auth_http_bearer_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_auth_http_bearer_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test HTTP bearer authentication + + To test HTTP bearer authentication + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_auth_http_bearer_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) _response_types_map: Dict[str, Optional[str]] = { '200': "str", } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_auth_http_bearer_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None - return self.api_client.call_api( - '/auth/http/basic', 'POST', - _path_params, - _query_params, - _header_params, + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'text/plain' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + 'http_bearer_auth' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/auth/http/bearer', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api/body_api.py b/samples/client/echo_api/python/openapi_client/api/body_api.py index fd4ef91e51a8..d9c2d64bea27 100644 --- a/samples/client/echo_api/python/openapi_client/api/body_api.py +++ b/samples/client/echo_api/python/openapi_client/api/body_api.py @@ -12,29 +12,20 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictBytes, StrictStr +from pydantic import Field, StrictBytes, StrictStr from typing import Any, Dict, List, Optional, Union - +from typing_extensions import Annotated from openapi_client.models.pet import Pet from openapi_client.models.tag import Tag -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class BodyApi: @@ -49,1103 +40,2410 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_binary_gif( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> bytearray: - """Test binary (gif) response body # noqa: E501 - - Test binary (gif) response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test binary (gif) response body - >>> thread = api.test_binary_gif(async_req=True) - >>> result = thread.get() + Test binary (gif) response body - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: bytearray - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_binary_gif_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_binary_gif_with_http_info.raw_function( - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_binary_gif_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Test binary (gif) response body # noqa: E501 - - Test binary (gif) response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_binary_gif_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[bytearray]: + """Test binary (gif) response body + + Test binary (gif) response body + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(bytearray, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_binary_gif_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test binary (gif) response body + + Test binary (gif) response body + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_binary_gif_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_binary_gif" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "bytearray", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_binary_gif_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['image/gif']) # noqa: E501 + [ + 'image/gif' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "bytearray", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/binary/gif', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/binary/gif', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_body_application_octetstream_binary( self, body: Optional[Union[StrictBytes, StrictStr]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test body parameter(s) - >>> thread = api.test_body_application_octetstream_binary(body, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param body: :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_application_octetstream_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_application_octetstream_binary_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_body_application_octetstream_binary_with_http_info( self, body: Optional[Union[StrictBytes, StrictStr]] = None, - **kwargs, - ) -> ApiResponse: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test body parameter(s) - >>> thread = api.test_body_application_octetstream_binary_with_http_info(body, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param body: :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_body_application_octetstream_binary_without_preload_content( + self, + body: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param body: + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_application_octetstream_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_application_octetstream_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_body_application_octetstream_binary_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file + if isinstance(body, str): + with open(body, "rb") as _fp: + _body_params = _fp.read() + else: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/octet-stream'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/octet-stream' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/body/application/octetstream/binary', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_body_multipart_formdata_array_of_binary( self, files: List[Union[StrictBytes, StrictStr]], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test array of binary in multipart mime # noqa: E501 + """Test array of binary in multipart mime - Test array of binary in multipart mime # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_body_multipart_formdata_array_of_binary(files, async_req=True) - >>> result = thread.get() + Test array of binary in multipart mime :param files: (required) :type files: List[bytearray] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_multipart_formdata_array_of_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_multipart_formdata_array_of_binary_with_http_info.raw_function( - files, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_body_multipart_formdata_array_of_binary_with_http_info( self, files: List[Union[StrictBytes, StrictStr]], - **kwargs, - ) -> ApiResponse: - """Test array of binary in multipart mime # noqa: E501 - - Test array of binary in multipart mime # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test array of binary in multipart mime - >>> thread = api.test_body_multipart_formdata_array_of_binary_with_http_info(files, async_req=True) - >>> result = thread.get() + Test array of binary in multipart mime :param files: (required) :type files: List[bytearray] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'files' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_body_multipart_formdata_array_of_binary_without_preload_content( + self, + files: List[Union[StrictBytes, StrictStr]], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test array of binary in multipart mime + + Test array of binary in multipart mime + + :param files: (required) + :type files: List[bytearray] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_array_of_binary_serialize( + files=files, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_multipart_formdata_array_of_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_body_multipart_formdata_array_of_binary_serialize( + self, + files, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'files': 'csv', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters + if files is not None: + _files['files'] = files + # process the body parameter + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'text/plain' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/array_of_binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_body_multipart_formdata_single_binary( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> str: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_body_multipart_formdata_single_binary_with_http_info( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_body_multipart_formdata_single_binary_without_preload_content( + self, + my_file: Optional[Union[StrictBytes, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test single binary in multipart mime + + Test single binary in multipart mime + + :param my_file: + :type my_file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_multipart_formdata_single_binary_serialize( + my_file=my_file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_multipart_formdata_single_binary_serialize( + self, + my_file, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} - if _params['files'] is not None: - _files['files'] = _params['files'] - _collection_formats['files'] = 'csv' + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if my_file is not None: + _files['my-file'] = my_file # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/body/application/octetstream/single_binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_echo_body_all_of_pet( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Pet: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) _response_types_map: Dict[str, Optional[str]] = { - '200': "str", + '200': "Pet", } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_echo_body_all_of_pet_with_http_info( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Test body parameter(s) - return self.api_client.call_api( - '/body/application/octetstream/array_of_binary', 'POST', - _path_params, - _query_params, - _header_params, + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_echo_body_all_of_pet_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_all_of_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_echo_body_all_of_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if pet is not None: + _body_params = pet + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/allOf/Pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_free_form_object_response_string( self, body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test free form object # noqa: E501 - - Test free form object # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test free form object - >>> thread = api.test_echo_body_free_form_object_response_string(body, async_req=True) - >>> result = thread.get() + Test free form object :param body: Free form object :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_free_form_object_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_free_form_object_response_string_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_free_form_object_response_string_with_http_info( self, body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, - **kwargs, - ) -> ApiResponse: - """Test free form object # noqa: E501 - - Test free form object # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test free form object + + Test free form object + + :param body: Free form object + :type body: object + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_echo_body_free_form_object_response_string_without_preload_content( + self, + body: Annotated[Optional[Dict[str, Any]], Field(description="Free form object")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test free form object - >>> thread = api.test_echo_body_free_form_object_response_string_with_http_info(body, async_req=True) - >>> result = thread.get() + Test free form object :param body: Free form object :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() + """ # noqa: E501 + + _param = self._test_echo_body_free_form_object_response_string_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_free_form_object_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _test_echo_body_free_form_object_response_string_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/FreeFormObject/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/FreeFormObject/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_pet( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Pet: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test body parameter(s) - >>> thread = api.test_echo_body_pet(pet, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Pet - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_pet_with_http_info( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, - ) -> ApiResponse: - """Test body parameter(s) # noqa: E501 - - Test body parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Test body parameter(s) - >>> thread = api.test_echo_body_pet_with_http_info(pet, async_req=True) - >>> result = thread.get() + Test body parameter(s) :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Pet, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_echo_body_pet_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test body parameter(s) + + Test body parameter(s) + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Pet", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Pet', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_pet_response_string( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test empty response body # noqa: E501 + """Test empty response body - Test empty response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_echo_body_pet_response_string(pet, async_req=True) - >>> result = thread.get() + Test empty response body :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_pet_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_pet_response_string_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_pet_response_string_with_http_info( self, pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, - **kwargs, - ) -> ApiResponse: - """Test empty response body # noqa: E501 - - Test empty response body # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test empty response body - >>> thread = api.test_echo_body_pet_response_string_with_http_info(pet, async_req=True) - >>> result = thread.get() + Test empty response body :param pet: Pet object that needs to be added to the store :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_echo_body_pet_response_string_without_preload_content( + self, + pet: Annotated[Optional[Pet], Field(description="Pet object that needs to be added to the store")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test empty response body + + Test empty response body + + :param pet: Pet object that needs to be added to the store + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_pet_response_string_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_pet_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_pet_response_string_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Pet/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Pet/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_echo_body_tag_response_string( self, tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test empty json (request body) # noqa: E501 - - Test empty json (request body) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test empty json (request body) - >>> thread = api.test_echo_body_tag_response_string(tag, async_req=True) - >>> result = thread.get() + Test empty json (request body) :param tag: Tag object :type tag: Tag - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_echo_body_tag_response_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_echo_body_tag_response_string_with_http_info.raw_function( - tag, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_echo_body_tag_response_string_with_http_info( self, tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, - **kwargs, - ) -> ApiResponse: - """Test empty json (request body) # noqa: E501 - - Test empty json (request body) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test empty json (request body) - >>> thread = api.test_echo_body_tag_response_string_with_http_info(tag, async_req=True) - >>> result = thread.get() + Test empty json (request body) :param tag: Tag object :type tag: Tag - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'tag' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_echo_body_tag_response_string_without_preload_content( + self, + tag: Annotated[Optional[Tag], Field(description="Tag object")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test empty json (request body) + + Test empty json (request body) + + :param tag: Tag object + :type tag: Tag + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_echo_body_tag_response_string_serialize( + tag=tag, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_echo_body_tag_response_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_echo_body_tag_response_string_serialize( + self, + tag, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['tag'] is not None: - _body_params = _params['tag'] + if tag is not None: + _body_params = tag + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/echo/body/Tag/response_string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/echo/body/Tag/response_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api/form_api.py b/samples/client/echo_api/python/openapi_client/api/form_api.py index 322256935d64..da387bc2fd32 100644 --- a/samples/client/echo_api/python/openapi_client/api/form_api.py +++ b/samples/client/echo_api/python/openapi_client/api/form_api.py @@ -12,25 +12,17 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictBool, StrictInt, StrictStr - from typing import Optional - -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class FormApi: @@ -45,22 +37,29 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_form_integer_boolean_string( self, integer_form: Optional[StrictInt] = None, boolean_form: Optional[StrictBool] = None, string_form: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test form parameter(s) # noqa: E501 + """Test form parameter(s) - Test form parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_form_integer_boolean_string(integer_form, boolean_form, string_form, async_req=True) - >>> result = thread.get() + Test form parameter(s) :param integer_form: :type integer_form: int @@ -68,45 +67,74 @@ def test_form_integer_boolean_string( :type boolean_form: bool :param string_form: :type string_form: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_form_integer_boolean_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_form_integer_boolean_string_with_http_info.raw_function( - integer_form, - boolean_form, - string_form, - **kwargs, + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_form_integer_boolean_string_with_http_info( self, integer_form: Optional[StrictInt] = None, boolean_form: Optional[StrictBool] = None, string_form: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test form parameter(s) # noqa: E501 - - Test form parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test form parameter(s) - >>> thread = api.test_form_integer_boolean_string_with_http_info(integer_form, boolean_form, string_form, async_req=True) - >>> result = thread.get() + Test form parameter(s) :param integer_form: :type integer_form: int @@ -114,117 +142,201 @@ def test_form_integer_boolean_string_with_http_info( :type boolean_form: bool :param string_form: :type string_form: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'integer_form', - 'boolean_form', - 'string_form' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_form_integer_boolean_string_without_preload_content( + self, + integer_form: Optional[StrictInt] = None, + boolean_form: Optional[StrictBool] = None, + string_form: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test form parameter(s) + + Test form parameter(s) + + :param integer_form: + :type integer_form: int + :param boolean_form: + :type boolean_form: bool + :param string_form: + :type string_form: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_form_integer_boolean_string_serialize( + integer_form=integer_form, + boolean_form=boolean_form, + string_form=string_form, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_form_integer_boolean_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_form_integer_boolean_string_serialize( + self, + integer_form, + boolean_form, + string_form, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the query parameters + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} - if _params['integer_form'] is not None: - _form_params.append(('integer_form', _params['integer_form'])) + _body_params: Optional[bytes] = None - if _params['boolean_form'] is not None: - _form_params.append(('boolean_form', _params['boolean_form'])) + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if integer_form is not None: + _form_params.append(('integer_form', integer_form)) + if boolean_form is not None: + _form_params.append(('boolean_form', boolean_form)) + if string_form is not None: + _form_params.append(('string_form', string_form)) + # process the body parameter - if _params['string_form'] is not None: - _form_params.append(('string_form', _params['string_form'])) - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/form/integer/boolean/string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/form/integer/boolean/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_form_oneof( @@ -235,16 +347,22 @@ def test_form_oneof( form4: Optional[StrictBool] = None, id: Optional[StrictInt] = None, name: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test form parameter(s) for oneOf schema # noqa: E501 - - Test form parameter(s) for oneOf schema # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test form parameter(s) for oneOf schema - >>> thread = api.test_form_oneof(form1, form2, form3, form4, id, name, async_req=True) - >>> result = thread.get() + Test form parameter(s) for oneOf schema :param form1: :type form1: str @@ -258,31 +376,54 @@ def test_form_oneof( :type id: int :param name: :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_form_oneof_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_form_oneof_with_http_info.raw_function( - form1, - form2, - form3, - form4, - id, - name, - **kwargs, + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_form_oneof_with_http_info( @@ -293,16 +434,22 @@ def test_form_oneof_with_http_info( form4: Optional[StrictBool] = None, id: Optional[StrictInt] = None, name: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test form parameter(s) for oneOf schema # noqa: E501 - - Test form parameter(s) for oneOf schema # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test form parameter(s) for oneOf schema - >>> thread = api.test_form_oneof_with_http_info(form1, form2, form3, form4, id, name, async_req=True) - >>> result = thread.get() + Test form parameter(s) for oneOf schema :param form1: :type form1: str @@ -316,126 +463,221 @@ def test_form_oneof_with_http_info( :type id: int :param name: :type name: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'form1', - 'form2', - 'form3', - 'form4', - 'id', - 'name' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_form_oneof" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def test_form_oneof_without_preload_content( + self, + form1: Optional[StrictStr] = None, + form2: Optional[StrictInt] = None, + form3: Optional[StrictStr] = None, + form4: Optional[StrictBool] = None, + id: Optional[StrictInt] = None, + name: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test form parameter(s) for oneOf schema - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['form1'] is not None: - _form_params.append(('form1', _params['form1'])) + Test form parameter(s) for oneOf schema - if _params['form2'] is not None: - _form_params.append(('form2', _params['form2'])) + :param form1: + :type form1: str + :param form2: + :type form2: int + :param form3: + :type form3: str + :param form4: + :type form4: bool + :param id: + :type id: int + :param name: + :type name: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_form_oneof_serialize( + form1=form1, + form2=form2, + form3=form3, + form4=form4, + id=id, + name=name, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['form3'] is not None: - _form_params.append(('form3', _params['form3'])) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['form4'] is not None: - _form_params.append(('form4', _params['form4'])) - if _params['id'] is not None: - _form_params.append(('id', _params['id'])) + def _test_form_oneof_serialize( + self, + form1, + form2, + form3, + form4, + id, + name, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - if _params['name'] is not None: - _form_params.append(('name', _params['name'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + if form1 is not None: + _form_params.append(('form1', form1)) + if form2 is not None: + _form_params.append(('form2', form2)) + if form3 is not None: + _form_params.append(('form3', form3)) + if form4 is not None: + _form_params.append(('form4', form4)) + if id is not None: + _form_params.append(('id', id)) + if name is not None: + _form_params.append(('name', name)) # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/form/oneof', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/form/oneof', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api/header_api.py b/samples/client/echo_api/python/openapi_client/api/header_api.py index f660475162f4..1ed0ff1f8227 100644 --- a/samples/client/echo_api/python/openapi_client/api/header_api.py +++ b/samples/client/echo_api/python/openapi_client/api/header_api.py @@ -12,26 +12,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictBool, StrictInt, StrictStr, field_validator - from typing import Optional - from openapi_client.models.string_enum_ref import StringEnumRef -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class HeaderApi: @@ -46,6 +38,7 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_header_integer_boolean_string_enums( self, @@ -54,16 +47,22 @@ def test_header_integer_boolean_string_enums( string_header: Optional[StrictStr] = None, enum_nonref_string_header: Optional[StrictStr] = None, enum_ref_string_header: Optional[StringEnumRef] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test header parameter(s) # noqa: E501 + """Test header parameter(s) - Test header parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_header_integer_boolean_string_enums(integer_header, boolean_header, string_header, enum_nonref_string_header, enum_ref_string_header, async_req=True) - >>> result = thread.get() + Test header parameter(s) :param integer_header: :type integer_header: int @@ -75,31 +74,54 @@ def test_header_integer_boolean_string_enums( :type enum_nonref_string_header: str :param enum_ref_string_header: :type enum_ref_string_header: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_header_integer_boolean_string_enums_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_header_integer_boolean_string_enums_with_http_info.raw_function( - integer_header, - boolean_header, - string_header, - enum_nonref_string_header, - enum_ref_string_header, - **kwargs, + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_header_integer_boolean_string_enums_with_http_info( self, @@ -108,16 +130,22 @@ def test_header_integer_boolean_string_enums_with_http_info( string_header: Optional[StrictStr] = None, enum_nonref_string_header: Optional[StrictStr] = None, enum_ref_string_header: Optional[StringEnumRef] = None, - **kwargs, - ) -> ApiResponse: - """Test header parameter(s) # noqa: E501 - - Test header parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test header parameter(s) - >>> thread = api.test_header_integer_boolean_string_enums_with_http_info(integer_header, boolean_header, string_header, enum_nonref_string_header, enum_ref_string_header, async_req=True) - >>> result = thread.get() + Test header parameter(s) :param integer_header: :type integer_header: int @@ -129,115 +157,200 @@ def test_header_integer_boolean_string_enums_with_http_info( :type enum_nonref_string_header: str :param enum_ref_string_header: :type enum_ref_string_header: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'integer_header', - 'boolean_header', - 'string_header', - 'enum_nonref_string_header', - 'enum_ref_string_header' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_header_integer_boolean_string_enums" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def test_header_integer_boolean_string_enums_without_preload_content( + self, + integer_header: Optional[StrictInt] = None, + boolean_header: Optional[StrictBool] = None, + string_header: Optional[StrictStr] = None, + enum_nonref_string_header: Optional[StrictStr] = None, + enum_ref_string_header: Optional[StringEnumRef] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test header parameter(s) - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['integer_header'] is not None: - _header_params['integer_header'] = _params['integer_header'] + Test header parameter(s) - if _params['boolean_header'] is not None: - _header_params['boolean_header'] = _params['boolean_header'] + :param integer_header: + :type integer_header: int + :param boolean_header: + :type boolean_header: bool + :param string_header: + :type string_header: str + :param enum_nonref_string_header: + :type enum_nonref_string_header: str + :param enum_ref_string_header: + :type enum_ref_string_header: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_header_integer_boolean_string_enums_serialize( + integer_header=integer_header, + boolean_header=boolean_header, + string_header=string_header, + enum_nonref_string_header=enum_nonref_string_header, + enum_ref_string_header=enum_ref_string_header, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['string_header'] is not None: - _header_params['string_header'] = _params['string_header'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['enum_nonref_string_header'] is not None: - _header_params['enum_nonref_string_header'] = _params['enum_nonref_string_header'] - if _params['enum_ref_string_header'] is not None: - _header_params['enum_ref_string_header'] = _params['enum_ref_string_header'] + def _test_header_integer_boolean_string_enums_serialize( + self, + integer_header, + boolean_header, + string_header, + enum_nonref_string_header, + enum_ref_string_header, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + if integer_header is not None: + _header_params['integer_header'] = integer_header + if boolean_header is not None: + _header_params['boolean_header'] = boolean_header + if string_header is not None: + _header_params['string_header'] = string_header + if enum_nonref_string_header is not None: + _header_params['enum_nonref_string_header'] = enum_nonref_string_header + if enum_ref_string_header is not None: + _header_params['enum_ref_string_header'] = enum_ref_string_header + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/header/integer/boolean/string/enums', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/header/integer/boolean/string/enums', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api/path_api.py b/samples/client/echo_api/python/openapi_client/api/path_api.py index 9dd1eabe9f93..8939cbe596cd 100644 --- a/samples/client/echo_api/python/openapi_client/api/path_api.py +++ b/samples/client/echo_api/python/openapi_client/api/path_api.py @@ -12,24 +12,17 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import StrictInt, StrictStr, field_validator - from openapi_client.models.string_enum_ref import StringEnumRef -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class PathApi: @@ -44,6 +37,7 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path( self, @@ -51,16 +45,22 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e path_integer: StrictInt, enum_nonref_string_path: StrictStr, enum_ref_string_path: StringEnumRef, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test path parameter(s) # noqa: E501 - - Test path parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test path parameter(s) - >>> thread = api.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, async_req=True) - >>> result = thread.get() + Test path parameter(s) :param path_string: (required) :type path_string: str @@ -70,30 +70,53 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e :type enum_nonref_string_path: str :param enum_ref_string_path: (required) :type enum_ref_string_path: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info.raw_function( - path_string, - path_integer, - enum_nonref_string_path, - enum_ref_string_path, - **kwargs, + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info( self, @@ -101,16 +124,22 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e path_integer: StrictInt, enum_nonref_string_path: StrictStr, enum_ref_string_path: StringEnumRef, - **kwargs, - ) -> ApiResponse: - """Test path parameter(s) # noqa: E501 - - Test path parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test path parameter(s) - >>> thread = api.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, async_req=True) - >>> result = thread.get() + Test path parameter(s) :param path_string: (required) :type path_string: str @@ -120,111 +149,192 @@ def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_e :type enum_nonref_string_path: str :param enum_ref_string_path: (required) :type enum_ref_string_path: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() - - _all_params = [ - 'path_string', - 'path_integer', - 'enum_nonref_string_path', - 'enum_ref_string_path' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['path_string'] is not None: - _path_params['path_string'] = _params['path_string'] + @validate_call + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_without_preload_content( + self, + path_string: StrictStr, + path_integer: StrictInt, + enum_nonref_string_path: StrictStr, + enum_ref_string_path: StringEnumRef, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test path parameter(s) + + Test path parameter(s) + + :param path_string: (required) + :type path_string: str + :param path_integer: (required) + :type path_integer: int + :param enum_nonref_string_path: (required) + :type enum_nonref_string_path: str + :param enum_ref_string_path: (required) + :type enum_ref_string_path: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + path_string=path_string, + path_integer=path_integer, + enum_nonref_string_path=enum_nonref_string_path, + enum_ref_string_path=enum_ref_string_path, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['path_integer'] is not None: - _path_params['path_integer'] = _params['path_integer'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['enum_nonref_string_path'] is not None: - _path_params['enum_nonref_string_path'] = _params['enum_nonref_string_path'] - if _params['enum_ref_string_path'] is not None: - _path_params['enum_ref_string_path'] = _params['enum_ref_string_path'].value + def _tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_serialize( + self, + path_string, + path_integer, + enum_nonref_string_path, + enum_ref_string_path, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if path_string is not None: + _path_params['path_string'] = path_string + if path_integer is not None: + _path_params['path_integer'] = path_integer + if enum_nonref_string_path is not None: + _path_params['enum_nonref_string_path'] = enum_nonref_string_path + if enum_ref_string_path is not None: + _path_params['enum_ref_string_path'] = enum_ref_string_path.value # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api/query_api.py b/samples/client/echo_api/python/openapi_client/api/query_api.py index d2287221eeb0..e27b8f5ce617 100644 --- a/samples/client/echo_api/python/openapi_client/api/query_api.py +++ b/samples/client/echo_api/python/openapi_client/api/query_api.py @@ -12,30 +12,21 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from datetime import date, datetime - from pydantic import StrictBool, StrictInt, StrictStr, field_validator - from typing import Any, Optional - from openapi_client.models.pet import Pet from openapi_client.models.string_enum_ref import StringEnumRef from openapi_client.models.test_query_style_form_explode_true_array_string_query_object_parameter import TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter -from openapi_client.api_client import ApiClient +from openapi_client.api_client import ApiClient, RequestSerialized from openapi_client.api_response import ApiResponse -from openapi_client.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from openapi_client.rest import RESTResponseType class QueryApi: @@ -50,168 +41,282 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_enum_ref_string( self, enum_nonref_string_query: Optional[StrictStr] = None, enum_ref_string_query: Optional[StringEnumRef] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_enum_ref_string(enum_nonref_string_query, enum_ref_string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param enum_nonref_string_query: :type enum_nonref_string_query: str :param enum_ref_string_query: :type enum_ref_string_query: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_enum_ref_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_enum_ref_string_with_http_info.raw_function( - enum_nonref_string_query, - enum_ref_string_query, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_enum_ref_string_with_http_info( self, enum_nonref_string_query: Optional[StrictStr] = None, enum_ref_string_query: Optional[StringEnumRef] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_enum_ref_string_with_http_info(enum_nonref_string_query, enum_ref_string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param enum_nonref_string_query: :type enum_nonref_string_query: str :param enum_ref_string_query: :type enum_ref_string_query: StringEnumRef - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'enum_nonref_string_query', - 'enum_ref_string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_enum_ref_string_without_preload_content( + self, + enum_nonref_string_query: Optional[StrictStr] = None, + enum_ref_string_query: Optional[StringEnumRef] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param enum_nonref_string_query: + :type enum_nonref_string_query: str + :param enum_ref_string_query: + :type enum_ref_string_query: StringEnumRef + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_enum_ref_string_serialize( + enum_nonref_string_query=enum_nonref_string_query, + enum_ref_string_query=enum_ref_string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_enum_ref_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_enum_ref_string_serialize( + self, + enum_nonref_string_query, + enum_ref_string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('enum_nonref_string_query') is not None: # noqa: E501 - _query_params.append(('enum_nonref_string_query', _params['enum_nonref_string_query'])) + _host = None - if _params.get('enum_ref_string_query') is not None: # noqa: E501 - _query_params.append(('enum_ref_string_query', _params['enum_ref_string_query'].value)) + _collection_formats: Dict[str, str] = { + } - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if enum_nonref_string_query is not None: + + _query_params.append(('enum_nonref_string_query', enum_nonref_string_query)) + + if enum_ref_string_query is not None: + + _query_params.append(('enum_ref_string_query', enum_ref_string_query.value)) + + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/enum_ref_string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/enum_ref_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_datetime_date_string( @@ -219,16 +324,22 @@ def test_query_datetime_date_string( datetime_query: Optional[datetime] = None, date_query: Optional[date] = None, string_query: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_datetime_date_string(datetime_query, date_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param datetime_query: :type datetime_query: datetime @@ -236,28 +347,51 @@ def test_query_datetime_date_string( :type date_query: date :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_datetime_date_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_datetime_date_string_with_http_info.raw_function( - datetime_query, - date_query, - string_query, - **kwargs, + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_datetime_date_string_with_http_info( @@ -265,16 +399,22 @@ def test_query_datetime_date_string_with_http_info( datetime_query: Optional[datetime] = None, date_query: Optional[date] = None, string_query: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_datetime_date_string_with_http_info(datetime_query, date_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param datetime_query: :type datetime_query: datetime @@ -282,116 +422,212 @@ def test_query_datetime_date_string_with_http_info( :type date_query: date :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'datetime_query', - 'date_query', - 'string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_datetime_date_string_without_preload_content( + self, + datetime_query: Optional[datetime] = None, + date_query: Optional[date] = None, + string_query: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param datetime_query: + :type datetime_query: datetime + :param date_query: + :type date_query: date + :param string_query: + :type string_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_datetime_date_string_serialize( + datetime_query=datetime_query, + date_query=date_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_datetime_date_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_query_datetime_date_string_serialize( + self, + datetime_query, + date_query, + string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('datetime_query') is not None: # noqa: E501 - if isinstance(_params['datetime_query'], datetime): - _query_params.append(('datetime_query', _params['datetime_query'].strftime(self.api_client.configuration.datetime_format))) + if datetime_query is not None: + if isinstance(datetime_query, datetime): + _query_params.append( + ( + 'datetime_query', + datetime_query.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) else: - _query_params.append(('datetime_query', _params['datetime_query'])) - - if _params.get('date_query') is not None: # noqa: E501 - if isinstance(_params['date_query'], date): - _query_params.append(('date_query', _params['date_query'].strftime(self.api_client.configuration.date_format))) + _query_params.append(('datetime_query', datetime_query)) + + if date_query is not None: + if isinstance(date_query, date): + _query_params.append( + ( + 'date_query', + date_query.strftime( + self.api_client.configuration.date_format + ) + ) + ) else: - _query_params.append(('date_query', _params['date_query'])) - - if _params.get('string_query') is not None: # noqa: E501 - _query_params.append(('string_query', _params['string_query'])) - + _query_params.append(('date_query', date_query)) + + if string_query is not None: + + _query_params.append(('string_query', string_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/datetime/date/string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/datetime/date/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_integer_boolean_string( @@ -399,16 +635,22 @@ def test_query_integer_boolean_string( integer_query: Optional[StrictInt] = None, boolean_query: Optional[StrictBool] = None, string_query: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_integer_boolean_string(integer_query, boolean_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param integer_query: :type integer_query: int @@ -416,28 +658,51 @@ def test_query_integer_boolean_string( :type boolean_query: bool :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_integer_boolean_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_integer_boolean_string_with_http_info.raw_function( - integer_query, - boolean_query, - string_query, - **kwargs, + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_integer_boolean_string_with_http_info( @@ -445,16 +710,22 @@ def test_query_integer_boolean_string_with_http_info( integer_query: Optional[StrictInt] = None, boolean_query: Optional[StrictBool] = None, string_query: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_integer_boolean_string_with_http_info(integer_query, boolean_query, string_query, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param integer_query: :type integer_query: int @@ -462,867 +733,1485 @@ def test_query_integer_boolean_string_with_http_info( :type boolean_query: bool :param string_query: :type string_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'integer_query', - 'boolean_query', - 'string_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_integer_boolean_string_without_preload_content( + self, + integer_query: Optional[StrictInt] = None, + boolean_query: Optional[StrictBool] = None, + string_query: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] - ) + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_integer_boolean_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + Test query parameter(s) - _collection_formats: Dict[str, str] = {} + :param integer_query: + :type integer_query: int + :param boolean_query: + :type boolean_query: bool + :param string_query: + :type string_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_integer_boolean_string_serialize( + integer_query=integer_query, + boolean_query=boolean_query, + string_query=string_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # process the path parameters - _path_params: Dict[str, str] = {} + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('integer_query') is not None: # noqa: E501 - _query_params.append(('integer_query', _params['integer_query'])) - if _params.get('boolean_query') is not None: # noqa: E501 - _query_params.append(('boolean_query', _params['boolean_query'])) + def _test_query_integer_boolean_string_serialize( + self, + integer_query, + boolean_query, + string_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - if _params.get('string_query') is not None: # noqa: E501 - _query_params.append(('string_query', _params['string_query'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if integer_query is not None: + + _query_params.append(('integer_query', integer_query)) + + if boolean_query is not None: + + _query_params.append(('boolean_query', boolean_query)) + + if string_query is not None: + + _query_params.append(('string_query', string_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/integer/boolean/string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/integer/boolean/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_deep_object_explode_true_object( self, query_object: Optional[Pet] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_deep_object_explode_true_object(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_deep_object_explode_true_object_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_style_deep_object_explode_true_object_with_http_info.raw_function( - query_object, - **kwargs, - ) + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_deep_object_explode_true_object_with_http_info( self, query_object: Optional[Pet] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_deep_object_explode_true_object_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_query_style_deep_object_explode_true_object_without_preload_content( + self, + query_object: Optional[Pet] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_deep_object_explode_true_object" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_deep_object_explode_true_object_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_deepObject/explode_true/object', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_deepObject/explode_true/object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_deep_object_explode_true_object_all_of( self, query_object: Optional[Any] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_deep_object_explode_true_object_all_of(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_deep_object_explode_true_object_all_of_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_deep_object_explode_true_object_all_of_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_deep_object_explode_true_object_all_of_with_http_info( self, query_object: Optional[Any] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_deep_object_explode_true_object_all_of_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_deep_object_explode_true_object_all_of_without_preload_content( + self, + query_object: Optional[Any] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_deep_object_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_deep_object_explode_true_object_all_of" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_deep_object_explode_true_object_all_of_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_deepObject/explode_true/object/allOf', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_deepObject/explode_true/object/allOf', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_array_string( self, query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_array_string(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_array_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_array_string_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_array_string_with_http_info( self, query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_array_string_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_form_explode_true_array_string_without_preload_content( + self, + query_object: Optional[TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_array_string_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_array_string" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_array_string_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/array_string', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/array_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_object( self, query_object: Optional[Pet] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 + """Test query parameter(s) - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_style_form_explode_true_object(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_object_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_object_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_object_with_http_info( self, query_object: Optional[Pet] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def test_query_style_form_explode_true_object_without_preload_content( + self, + query_object: Optional[Pet] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_object" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_object_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/object', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_style_form_explode_true_object_all_of( self, query_object: Optional[Any] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_all_of(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: DataQuery - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_style_form_explode_true_object_all_of_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_query_style_form_explode_true_object_all_of_with_http_info.raw_function( - query_object, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_style_form_explode_true_object_all_of_with_http_info( self, query_object: Optional[Any] = None, - **kwargs, - ) -> ApiResponse: - """Test query parameter(s) # noqa: E501 - - Test query parameter(s) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Test query parameter(s) - >>> thread = api.test_query_style_form_explode_true_object_all_of_with_http_info(query_object, async_req=True) - >>> result = thread.get() + Test query parameter(s) :param query_object: :type query_object: DataQuery - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'query_object' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_query_style_form_explode_true_object_all_of_without_preload_content( + self, + query_object: Optional[Any] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Test query parameter(s) + + Test query parameter(s) + + :param query_object: + :type query_object: DataQuery + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_style_form_explode_true_object_all_of_serialize( + query_object=query_object, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_style_form_explode_true_object_all_of" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_query_style_form_explode_true_object_all_of_serialize( + self, + query_object, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query_object') is not None: # noqa: E501 - _query_params.append(('query_object', _params['query_object'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if query_object is not None: + + _query_params.append(('query_object', query_object)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['text/plain']) # noqa: E501 + [ + 'text/plain' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/query/style_form/explode_true/object/allOf', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/query/style_form/explode_true/object/allOf', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/client/echo_api/python/openapi_client/api_client.py b/samples/client/echo_api/python/openapi_client/api_client.py index 962fad87d685..ce93eaca6dea 100644 --- a/samples/client/echo_api/python/openapi_client/api_client.py +++ b/samples/client/echo_api/python/openapi_client/api_client.py @@ -13,24 +13,32 @@ """ # noqa: E501 -import atexit import datetime from dateutil.parser import parse import json import mimetypes -from multiprocessing.pool import ThreadPool import os import re import tempfile from urllib.parse import quote +from typing import Tuple, Optional, List, Dict from openapi_client.configuration import Configuration -from openapi_client.api_response import ApiResponse +from openapi_client.api_response import ApiResponse, T as ApiResponseT import openapi_client.models from openapi_client import rest -from openapi_client.exceptions import ApiValueError, ApiException - +from openapi_client.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -46,8 +54,6 @@ class ApiClient: the API. :param cookie: a cookie to include in the header when making calls to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. """ PRIMITIVE_TYPES = (float, bool, bytes, str, int) @@ -63,13 +69,17 @@ class ApiClient: } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1) -> None: + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration - self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} @@ -84,25 +94,7 @@ def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool + pass @property def user_agent(self): @@ -143,13 +135,42 @@ def set_default(cls, default): """ cls._default = default - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -160,14 +181,17 @@ def __call_api( header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -179,15 +203,22 @@ def __call_api( if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: @@ -203,59 +234,99 @@ def __call_api( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + try: # perform request and return response - response_data = self.request( + response_data = self.rest_client.request( method, url, - query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') raise e - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -276,15 +347,17 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except @@ -294,10 +367,12 @@ def sanitize_for_serialization(self, obj): # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -306,16 +381,12 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -332,12 +403,16 @@ def __deserialize(self, data, klass): if isinstance(klass, str): if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -358,136 +433,6 @@ def __deserialize(self, data, klass): else: return self.__deserialize_model(data, klass) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - if not async_req: - return self.__call_api(*args) - - return self.pool.apply_async(self.__call_api, args) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -495,10 +440,10 @@ def parameters_to_tuples(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -525,14 +470,14 @@ def parameters_to_url_query(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) + for k, v in params.items() if isinstance(params, dict) else params: if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) @@ -550,7 +495,8 @@ def parameters_to_url_query(self, params, collection_formats): else: # csv is the default delimiter = ',' new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -573,21 +519,24 @@ def files_parameters(self, files=None): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None for accept in accepts: if re.search('json', accept, re.IGNORECASE): @@ -610,9 +559,16 @@ def select_header_content_type(self, content_types): return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -629,21 +585,36 @@ def update_params_for_auth(self, headers, queries, auth_settings, return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -672,6 +643,9 @@ def __deserialize_file(self, response): Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -681,8 +655,12 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/client/echo_api/python/openapi_client/api_response.py b/samples/client/echo_api/python/openapi_client/api_response.py index a0b62b95246c..9bc7c11f6b9f 100644 --- a/samples/client/echo_api/python/openapi_client/api_response.py +++ b/samples/client/echo_api/python/openapi_client/api_response.py @@ -1,25 +1,21 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel -class ApiResponse: +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): """ API response object """ - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data + model_config = { + "arbitrary_types_allowed": True + } diff --git a/samples/client/echo_api/python/openapi_client/configuration.py b/samples/client/echo_api/python/openapi_client/configuration.py index 8ff03cff3b9e..43604555bd8b 100644 --- a/samples/client/echo_api/python/openapi_client/configuration.py +++ b/samples/client/echo_api/python/openapi_client/configuration.py @@ -15,8 +15,10 @@ import copy import logging +from logging import FileHandler import multiprocessing import sys +from typing import Optional import urllib3 import http.client as httplib @@ -133,7 +135,7 @@ def __init__(self, host=None, self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -173,7 +175,7 @@ def __init__(self, host=None, cpu_count * 5 is used as default value to increase performance. """ - self.proxy = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None @@ -382,6 +384,13 @@ def auth_settings(self): 'key': 'Authorization', 'value': self.get_basic_auth_token() } + if self.access_token is not None: + auth['http_bearer_auth'] = { + 'type': 'bearer', + 'in': 'header', + 'key': 'Authorization', + 'value': 'Bearer ' + self.access_token + } return auth def to_debug_report(self): diff --git a/samples/client/echo_api/python/openapi_client/exceptions.py b/samples/client/echo_api/python/openapi_client/exceptions.py index ae3e985d2fee..bd5561d241ed 100644 --- a/samples/client/echo_api/python/openapi_client/exceptions.py +++ b/samples/client/echo_api/python/openapi_client/exceptions.py @@ -12,6 +12,8 @@ Do not edit the class manually. """ # noqa: E501 +from typing import Any, Optional +from typing_extensions import Self class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" @@ -102,17 +104,56 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) def __str__(self): """Custom error messages for exception""" @@ -122,38 +163,30 @@ def __str__(self): error_message += "HTTP response headers: {0}\n".format( self.headers) - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message + class BadRequestException(ApiException): + pass - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + pass class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + pass class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + pass class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + pass def render_path(path_to_item): diff --git a/samples/client/echo_api/python/openapi_client/models/bird.py b/samples/client/echo_api/python/openapi_client/models/bird.py index 54c0ee31a70b..f86a1aff96cb 100644 --- a/samples/client/echo_api/python/openapi_client/models/bird.py +++ b/samples/client/echo_api/python/openapi_client/models/bird.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Bird(BaseModel): """ Bird - """ + """ # noqa: E501 size: Optional[StrictStr] = None color: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["size", "color"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Bird from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Bird from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/category.py b/samples/client/echo_api/python/openapi_client/models/category.py index 9b17e13e9315..d9a6df479279 100644 --- a/samples/client/echo_api/python/openapi_client/models/category.py +++ b/samples/client/echo_api/python/openapi_client/models/category.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Category(BaseModel): """ Category - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Category from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Category from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/data_query.py b/samples/client/echo_api/python/openapi_client/models/data_query.py index e13342733d34..c55a1261d200 100644 --- a/samples/client/echo_api/python/openapi_client/models/data_query.py +++ b/samples/client/echo_api/python/openapi_client/models/data_query.py @@ -19,20 +19,16 @@ import json from datetime import datetime -from typing import Optional -from pydantic import StrictStr -from pydantic import Field +from pydantic import Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.query import Query -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class DataQuery(Query): """ DataQuery - """ + """ # noqa: E501 suffix: Optional[StrictStr] = Field(default=None, description="test suffix") text: Optional[StrictStr] = Field(default=None, description="Some text containing white spaces") var_date: Optional[datetime] = Field(default=None, description="A date", alias="date") @@ -40,7 +36,8 @@ class DataQuery(Query): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DataQuery from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,16 +65,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DataQuery from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/default_value.py b/samples/client/echo_api/python/openapi_client/models/default_value.py index 7c07bcfa89a2..80cdb03a45d1 100644 --- a/samples/client/echo_api/python/openapi_client/models/default_value.py +++ b/samples/client/echo_api/python/openapi_client/models/default_value.py @@ -18,20 +18,16 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.string_enum_ref import StringEnumRef -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class DefaultValue(BaseModel): """ - to test the default value of properties # noqa: E501 - """ + to test the default value of properties + """ # noqa: E501 array_string_enum_ref_default: Optional[List[StringEnumRef]] = None array_string_enum_default: Optional[List[StrictStr]] = None array_string_default: Optional[List[StrictStr]] = None @@ -55,7 +51,8 @@ def array_string_enum_default_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -69,7 +66,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DefaultValue from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -83,10 +80,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if array_string_nullable (nullable) is None @@ -107,7 +106,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DefaultValue from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/number_properties_only.py b/samples/client/echo_api/python/openapi_client/models/number_properties_only.py index cd532e0609f2..de1c47ad8454 100644 --- a/samples/client/echo_api/python/openapi_client/models/number_properties_only.py +++ b/samples/client/echo_api/python/openapi_client/models/number_properties_only.py @@ -18,21 +18,16 @@ import re # noqa: F401 import json - -from typing import Optional, Union -from pydantic import BaseModel, StrictFloat, StrictInt -from pydantic import Field +from pydantic import BaseModel, Field, StrictFloat, StrictInt +from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class NumberPropertiesOnly(BaseModel): """ NumberPropertiesOnly - """ + """ # noqa: E501 number: Optional[Union[StrictFloat, StrictInt]] = None var_float: Optional[Union[StrictFloat, StrictInt]] = Field(default=None, alias="float") double: Optional[Union[Annotated[float, Field(le=50.2, strict=True, ge=0.8)], Annotated[int, Field(le=50, strict=True, ge=1)]]] = None @@ -40,7 +35,8 @@ class NumberPropertiesOnly(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NumberPropertiesOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,16 +64,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NumberPropertiesOnly from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/pet.py b/samples/client/echo_api/python/openapi_client/models/pet.py index 61b642b5ad46..62c473647ba5 100644 --- a/samples/client/echo_api/python/openapi_client/models/pet.py +++ b/samples/client/echo_api/python/openapi_client/models/pet.py @@ -18,22 +18,17 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from openapi_client.models.category import Category from openapi_client.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Pet(BaseModel): """ Pet - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: StrictStr category: Optional[Category] = None @@ -54,7 +49,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -68,7 +64,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Pet from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -82,10 +78,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of category @@ -101,7 +99,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Pet from a dict""" if obj is None: return None @@ -112,9 +110,9 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "id": obj.get("id"), "name": obj.get("name"), - "category": Category.from_dict(obj.get("category")) if obj.get("category") is not None else None, + "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj.get("tags")] if obj.get("tags") is not None else None, + "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, "status": obj.get("status") }) return _obj diff --git a/samples/client/echo_api/python/openapi_client/models/query.py b/samples/client/echo_api/python/openapi_client/models/query.py index e6277c3fa3d1..2f7343030130 100644 --- a/samples/client/echo_api/python/openapi_client/models/query.py +++ b/samples/client/echo_api/python/openapi_client/models/query.py @@ -18,20 +18,15 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Query(BaseModel): """ Query - """ + """ # noqa: E501 id: Optional[StrictInt] = Field(default=None, description="Query") outcomes: Optional[List[StrictStr]] = None __properties: ClassVar[List[str]] = ["id", "outcomes"] @@ -49,7 +44,8 @@ def outcomes_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -63,7 +59,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Query from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -77,16 +73,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Optional[Self]: """Create an instance of Query from a dict""" diff --git a/samples/client/echo_api/python/openapi_client/models/string_enum_ref.py b/samples/client/echo_api/python/openapi_client/models/string_enum_ref.py index cedd6194f983..90328aea76dd 100644 --- a/samples/client/echo_api/python/openapi_client/models/string_enum_ref.py +++ b/samples/client/echo_api/python/openapi_client/models/string_enum_ref.py @@ -15,16 +15,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class StringEnumRef(str, Enum): diff --git a/samples/client/echo_api/python/openapi_client/models/tag.py b/samples/client/echo_api/python/openapi_client/models/tag.py index 9a0eda31e738..b26318f76074 100644 --- a/samples/client/echo_api/python/openapi_client/models/tag.py +++ b/samples/client/echo_api/python/openapi_client/models/tag.py @@ -18,26 +18,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tag(BaseModel): """ Tag - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tag from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tag from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py b/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py index 24b4279ea4d4..80184c582aca 100644 --- a/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py +++ b/samples/client/echo_api/python/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.py @@ -18,19 +18,15 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseModel): """ TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter - """ + """ # noqa: E501 size: Optional[StrictStr] = None color: Optional[StrictStr] = None id: Optional[StrictInt] = None @@ -39,7 +35,8 @@ class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter(BaseMod model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,16 +64,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py b/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py index d53ca53f8c09..1a84a025f48e 100644 --- a/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py +++ b/samples/client/echo_api/python/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.py @@ -18,25 +18,22 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter(BaseModel): """ TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter - """ + """ # noqa: E501 values: Optional[List[StrictStr]] = None __properties: ClassVar[List[str]] = ["values"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter from a dict""" if obj is None: return None diff --git a/samples/client/echo_api/python/openapi_client/rest.py b/samples/client/echo_api/python/openapi_client/rest.py index d05e077260de..52aeb1cfa887 100644 --- a/samples/client/echo_api/python/openapi_client/rest.py +++ b/samples/client/echo_api/python/openapi_client/rest.py @@ -15,43 +15,55 @@ import io import json -import logging import re import ssl -from urllib.parse import urlencode, quote_plus import urllib3 -from openapi_client.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException +from openapi_client.exceptions import ApiException, ApiValueError +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse -logger = logging.getLogger(__name__) + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES class RESTResponse(io.IOBase): def __init__(self, resp) -> None: - self.urllib3_response = resp + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs @@ -60,74 +72,79 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: else: cert_reqs = ssl.CERT_NONE - addition_pool_args = {} + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries + pool_args['retries'] = configuration.retries if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name + pool_args['server_hostname'] = configuration.tls_server_name if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options + pool_args['socket_options'] = configuration.socket_options - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize # https pool manager + self.pool_manager: urllib3.PoolManager + if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -136,63 +153,84 @@ def request(self, method, url, query_params=None, headers=None, post_params = post_params or {} headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form + # other content types than JSON when `body` argument is + # provided in serialized form. elif isinstance(body, str) or isinstance(body, bytes): - request_body = body r = self.pool_manager.request( - method, url, + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, body=request_body, - preload_content=_preload_content, + preload_content=False, timeout=timeout, headers=headers) else: @@ -203,102 +241,16 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) + msg = "\n".join([type(e).__name__, str(e)]) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return RESTResponse(r) diff --git a/samples/client/echo_api/python/poetry.lock b/samples/client/echo_api/python/poetry.lock new file mode 100644 index 000000000000..7dfd40d63a77 --- /dev/null +++ b/samples/client/echo_api/python/poetry.lock @@ -0,0 +1,614 @@ +# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand. + +[[package]] +name = "annotated-types" +version = "0.5.0" +description = "Reusable constraint types to use with typing.Annotated" +optional = false +python-versions = ">=3.7" +files = [ + {file = "annotated_types-0.5.0-py3-none-any.whl", hash = "sha256:58da39888f92c276ad970249761ebea80ba544b77acddaa1a4d6cf78287d45fd"}, + {file = "annotated_types-0.5.0.tar.gz", hash = "sha256:47cdc3490d9ac1506ce92c7aaa76c579dc3509ff11e098fc867e5130ab7be802"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""} + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "distlib" +version = "0.3.8" +description = "Distribution utilities" +optional = false +python-versions = "*" +files = [ + {file = "distlib-0.3.8-py2.py3-none-any.whl", hash = "sha256:034db59a0b96f8ca18035f36290806a9a6e6bd9d1ff91e45a7f172eb17e51784"}, + {file = "distlib-0.3.8.tar.gz", hash = "sha256:1530ea13e350031b6312d8580ddb6b27a104275a31106523b8f123787f494f64"}, +] + +[[package]] +name = "exceptiongroup" +version = "1.2.0" +description = "Backport of PEP 654 (exception groups)" +optional = false +python-versions = ">=3.7" +files = [ + {file = "exceptiongroup-1.2.0-py3-none-any.whl", hash = "sha256:4bfd3996ac73b41e9b9628b04e079f193850720ea5945fc96a08633c66912f14"}, + {file = "exceptiongroup-1.2.0.tar.gz", hash = "sha256:91f5c769735f051a4290d52edd0858999b57e5876e9f85937691bd4c9fa3ed68"}, +] + +[package.extras] +test = ["pytest (>=6)"] + +[[package]] +name = "filelock" +version = "3.12.2" +description = "A platform independent file lock." +optional = false +python-versions = ">=3.7" +files = [ + {file = "filelock-3.12.2-py3-none-any.whl", hash = "sha256:cbb791cdea2a72f23da6ac5b5269ab0a0d161e9ef0100e653b69049a7706d1ec"}, + {file = "filelock-3.12.2.tar.gz", hash = "sha256:002740518d8aa59a26b0c76e10fb8c6e15eae825d34b6fdf670333fd7b938d81"}, +] + +[package.extras] +docs = ["furo (>=2023.5.20)", "sphinx (>=7.0.1)", "sphinx-autodoc-typehints (>=1.23,!=1.23.4)"] +testing = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "diff-cover (>=7.5)", "pytest (>=7.3.1)", "pytest-cov (>=4.1)", "pytest-mock (>=3.10)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "flake8" +version = "5.0.4" +description = "the modular source code checker: pep8 pyflakes and co" +optional = false +python-versions = ">=3.6.1" +files = [ + {file = "flake8-5.0.4-py2.py3-none-any.whl", hash = "sha256:7a1cf6b73744f5806ab95e526f6f0d8c01c66d7bbe349562d22dfca20610b248"}, + {file = "flake8-5.0.4.tar.gz", hash = "sha256:6fbe320aad8d6b95cec8b8e47bc933004678dc63095be98528b7bdd2a9f510db"}, +] + +[package.dependencies] +importlib-metadata = {version = ">=1.1.0,<4.3", markers = "python_version < \"3.8\""} +mccabe = ">=0.7.0,<0.8.0" +pycodestyle = ">=2.9.0,<2.10.0" +pyflakes = ">=2.5.0,<2.6.0" + +[[package]] +name = "importlib-metadata" +version = "4.2.0" +description = "Read metadata from Python packages" +optional = false +python-versions = ">=3.6" +files = [ + {file = "importlib_metadata-4.2.0-py3-none-any.whl", hash = "sha256:057e92c15bc8d9e8109738a48db0ccb31b4d9d5cfbee5a8670879a30be66304b"}, + {file = "importlib_metadata-4.2.0.tar.gz", hash = "sha256:b7e52a1f8dec14a75ea73e0891f3060099ca1d8e6a462a4dff11c3e119ea1b31"}, +] + +[package.dependencies] +typing-extensions = {version = ">=3.6.4", markers = "python_version < \"3.8\""} +zipp = ">=0.5" + +[package.extras] +docs = ["jaraco.packaging (>=8.2)", "rst.linker (>=1.9)", "sphinx"] +testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pep517", "pyfakefs", "pytest (>=4.6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.0.1)", "pytest-flake8", "pytest-mypy"] + +[[package]] +name = "iniconfig" +version = "2.0.0" +description = "brain-dead simple config-ini parsing" +optional = false +python-versions = ">=3.7" +files = [ + {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, + {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, +] + +[[package]] +name = "mccabe" +version = "0.7.0" +description = "McCabe checker, plugin for flake8" +optional = false +python-versions = ">=3.6" +files = [ + {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"}, + {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, +] + +[[package]] +name = "mypy" +version = "1.4.1" +description = "Optional static typing for Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "mypy-1.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:566e72b0cd6598503e48ea610e0052d1b8168e60a46e0bfd34b3acf2d57f96a8"}, + {file = "mypy-1.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca637024ca67ab24a7fd6f65d280572c3794665eaf5edcc7e90a866544076878"}, + {file = "mypy-1.4.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0dde1d180cd84f0624c5dcaaa89c89775550a675aff96b5848de78fb11adabcd"}, + {file = "mypy-1.4.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8c4d8e89aa7de683e2056a581ce63c46a0c41e31bd2b6d34144e2c80f5ea53dc"}, + {file = "mypy-1.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:bfdca17c36ae01a21274a3c387a63aa1aafe72bff976522886869ef131b937f1"}, + {file = "mypy-1.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7549fbf655e5825d787bbc9ecf6028731973f78088fbca3a1f4145c39ef09462"}, + {file = "mypy-1.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:98324ec3ecf12296e6422939e54763faedbfcc502ea4a4c38502082711867258"}, + {file = "mypy-1.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:141dedfdbfe8a04142881ff30ce6e6653c9685b354876b12e4fe6c78598b45e2"}, + {file = "mypy-1.4.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8207b7105829eca6f3d774f64a904190bb2231de91b8b186d21ffd98005f14a7"}, + {file = "mypy-1.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:16f0db5b641ba159eff72cff08edc3875f2b62b2fa2bc24f68c1e7a4e8232d01"}, + {file = "mypy-1.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:470c969bb3f9a9efcedbadcd19a74ffb34a25f8e6b0e02dae7c0e71f8372f97b"}, + {file = "mypy-1.4.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5952d2d18b79f7dc25e62e014fe5a23eb1a3d2bc66318df8988a01b1a037c5b"}, + {file = "mypy-1.4.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:190b6bab0302cec4e9e6767d3eb66085aef2a1cc98fe04936d8a42ed2ba77bb7"}, + {file = "mypy-1.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:9d40652cc4fe33871ad3338581dca3297ff5f2213d0df345bcfbde5162abf0c9"}, + {file = "mypy-1.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:01fd2e9f85622d981fd9063bfaef1aed6e336eaacca00892cd2d82801ab7c042"}, + {file = "mypy-1.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:2460a58faeea905aeb1b9b36f5065f2dc9a9c6e4c992a6499a2360c6c74ceca3"}, + {file = "mypy-1.4.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2746d69a8196698146a3dbe29104f9eb6a2a4d8a27878d92169a6c0b74435b6"}, + {file = "mypy-1.4.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:ae704dcfaa180ff7c4cfbad23e74321a2b774f92ca77fd94ce1049175a21c97f"}, + {file = "mypy-1.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:43d24f6437925ce50139a310a64b2ab048cb2d3694c84c71c3f2a1626d8101dc"}, + {file = "mypy-1.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c482e1246726616088532b5e964e39765b6d1520791348e6c9dc3af25b233828"}, + {file = "mypy-1.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:43b592511672017f5b1a483527fd2684347fdffc041c9ef53428c8dc530f79a3"}, + {file = "mypy-1.4.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:34a9239d5b3502c17f07fd7c0b2ae6b7dd7d7f6af35fbb5072c6208e76295816"}, + {file = "mypy-1.4.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5703097c4936bbb9e9bce41478c8d08edd2865e177dc4c52be759f81ee4dd26c"}, + {file = "mypy-1.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:e02d700ec8d9b1859790c0475df4e4092c7bf3272a4fd2c9f33d87fac4427b8f"}, + {file = "mypy-1.4.1-py3-none-any.whl", hash = "sha256:45d32cec14e7b97af848bddd97d85ea4f0db4d5a149ed9676caa4eb2f7402bb4"}, + {file = "mypy-1.4.1.tar.gz", hash = "sha256:9bbcd9ab8ea1f2e1c8031c21445b511442cc45c89951e49bbf852cbb70755b1b"}, +] + +[package.dependencies] +mypy-extensions = ">=1.0.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typed-ast = {version = ">=1.4.0,<2", markers = "python_version < \"3.8\""} +typing-extensions = ">=4.1.0" + +[package.extras] +dmypy = ["psutil (>=4.0)"] +install-types = ["pip"] +python2 = ["typed-ast (>=1.4.0,<2)"] +reports = ["lxml"] + +[[package]] +name = "mypy-extensions" +version = "1.0.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.5" +files = [ + {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, + {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, +] + +[[package]] +name = "packaging" +version = "23.2" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.7" +files = [ + {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"}, + {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"}, +] + +[[package]] +name = "platformdirs" +version = "2.6.2" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +optional = false +python-versions = ">=3.7" +files = [ + {file = "platformdirs-2.6.2-py3-none-any.whl", hash = "sha256:83c8f6d04389165de7c9b6f0c682439697887bca0aa2f1c87ef1826be3584490"}, + {file = "platformdirs-2.6.2.tar.gz", hash = "sha256:e1fea1fe471b9ff8332e229df3cb7de4f53eeea4998d3b6bfff542115e998bd2"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.4", markers = "python_version < \"3.8\""} + +[package.extras] +docs = ["furo (>=2022.12.7)", "proselint (>=0.13)", "sphinx (>=5.3)", "sphinx-autodoc-typehints (>=1.19.5)"] +test = ["appdirs (==1.4.4)", "covdefaults (>=2.2.2)", "pytest (>=7.2)", "pytest-cov (>=4)", "pytest-mock (>=3.10)"] + +[[package]] +name = "pluggy" +version = "1.2.0" +description = "plugin and hook calling mechanisms for python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pluggy-1.2.0-py3-none-any.whl", hash = "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849"}, + {file = "pluggy-1.2.0.tar.gz", hash = "sha256:d12f0c4b579b15f5e054301bb226ee85eeeba08ffec228092f8defbaa3a4c4b3"}, +] + +[package.dependencies] +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +files = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] + +[[package]] +name = "pycodestyle" +version = "2.9.1" +description = "Python style guide checker" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pycodestyle-2.9.1-py2.py3-none-any.whl", hash = "sha256:d1735fc58b418fd7c5f658d28d943854f8a849b01a5d0a1e6f3f3fdd0166804b"}, + {file = "pycodestyle-2.9.1.tar.gz", hash = "sha256:2c9607871d58c76354b697b42f5d57e1ada7d261c261efac224b664affdc5785"}, +] + +[[package]] +name = "pydantic" +version = "2.5.3" +description = "Data validation using Python type hints" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic-2.5.3-py3-none-any.whl", hash = "sha256:d0caf5954bee831b6bfe7e338c32b9e30c85dfe080c843680783ac2b631673b4"}, + {file = "pydantic-2.5.3.tar.gz", hash = "sha256:b3ef57c62535b0941697cce638c08900d87fcb67e29cfa99e8a68f747f393f7a"}, +] + +[package.dependencies] +annotated-types = ">=0.4.0" +importlib-metadata = {version = "*", markers = "python_version == \"3.7\""} +pydantic-core = "2.14.6" +typing-extensions = ">=4.6.1" + +[package.extras] +email = ["email-validator (>=2.0.0)"] + +[[package]] +name = "pydantic-core" +version = "2.14.6" +description = "" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic_core-2.14.6-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:72f9a942d739f09cd42fffe5dc759928217649f070056f03c70df14f5770acf9"}, + {file = "pydantic_core-2.14.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:6a31d98c0d69776c2576dda4b77b8e0c69ad08e8b539c25c7d0ca0dc19a50d6c"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5aa90562bc079c6c290f0512b21768967f9968e4cfea84ea4ff5af5d917016e4"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:370ffecb5316ed23b667d99ce4debe53ea664b99cc37bfa2af47bc769056d534"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f85f3843bdb1fe80e8c206fe6eed7a1caeae897e496542cee499c374a85c6e08"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9862bf828112e19685b76ca499b379338fd4c5c269d897e218b2ae8fcb80139d"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:036137b5ad0cb0004c75b579445a1efccd072387a36c7f217bb8efd1afbe5245"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:92879bce89f91f4b2416eba4429c7b5ca22c45ef4a499c39f0c5c69257522c7c"}, + {file = "pydantic_core-2.14.6-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:0c08de15d50fa190d577e8591f0329a643eeaed696d7771760295998aca6bc66"}, + {file = "pydantic_core-2.14.6-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:36099c69f6b14fc2c49d7996cbf4f87ec4f0e66d1c74aa05228583225a07b590"}, + {file = "pydantic_core-2.14.6-cp310-none-win32.whl", hash = "sha256:7be719e4d2ae6c314f72844ba9d69e38dff342bc360379f7c8537c48e23034b7"}, + {file = "pydantic_core-2.14.6-cp310-none-win_amd64.whl", hash = "sha256:36fa402dcdc8ea7f1b0ddcf0df4254cc6b2e08f8cd80e7010d4c4ae6e86b2a87"}, + {file = "pydantic_core-2.14.6-cp311-cp311-macosx_10_7_x86_64.whl", hash = "sha256:dea7fcd62915fb150cdc373212141a30037e11b761fbced340e9db3379b892d4"}, + {file = "pydantic_core-2.14.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ffff855100bc066ff2cd3aa4a60bc9534661816b110f0243e59503ec2df38421"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b027c86c66b8627eb90e57aee1f526df77dc6d8b354ec498be9a757d513b92b"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:00b1087dabcee0b0ffd104f9f53d7d3eaddfaa314cdd6726143af6bc713aa27e"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:75ec284328b60a4e91010c1acade0c30584f28a1f345bc8f72fe8b9e46ec6a96"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7e1f4744eea1501404b20b0ac059ff7e3f96a97d3e3f48ce27a139e053bb370b"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b2602177668f89b38b9f84b7b3435d0a72511ddef45dc14446811759b82235a1"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6c8edaea3089bf908dd27da8f5d9e395c5b4dc092dbcce9b65e7156099b4b937"}, + {file = "pydantic_core-2.14.6-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:478e9e7b360dfec451daafe286998d4a1eeaecf6d69c427b834ae771cad4b622"}, + {file = "pydantic_core-2.14.6-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:b6ca36c12a5120bad343eef193cc0122928c5c7466121da7c20f41160ba00ba2"}, + {file = "pydantic_core-2.14.6-cp311-none-win32.whl", hash = "sha256:2b8719037e570639e6b665a4050add43134d80b687288ba3ade18b22bbb29dd2"}, + {file = "pydantic_core-2.14.6-cp311-none-win_amd64.whl", hash = "sha256:78ee52ecc088c61cce32b2d30a826f929e1708f7b9247dc3b921aec367dc1b23"}, + {file = "pydantic_core-2.14.6-cp311-none-win_arm64.whl", hash = "sha256:a19b794f8fe6569472ff77602437ec4430f9b2b9ec7a1105cfd2232f9ba355e6"}, + {file = "pydantic_core-2.14.6-cp312-cp312-macosx_10_7_x86_64.whl", hash = "sha256:667aa2eac9cd0700af1ddb38b7b1ef246d8cf94c85637cbb03d7757ca4c3fdec"}, + {file = "pydantic_core-2.14.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cdee837710ef6b56ebd20245b83799fce40b265b3b406e51e8ccc5b85b9099b7"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c5bcf3414367e29f83fd66f7de64509a8fd2368b1edf4351e862910727d3e51"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:26a92ae76f75d1915806b77cf459811e772d8f71fd1e4339c99750f0e7f6324f"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a983cca5ed1dd9a35e9e42ebf9f278d344603bfcb174ff99a5815f953925140a"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cb92f9061657287eded380d7dc455bbf115430b3aa4741bdc662d02977e7d0af"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e4ace1e220b078c8e48e82c081e35002038657e4b37d403ce940fa679e57113b"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ef633add81832f4b56d3b4c9408b43d530dfca29e68fb1b797dcb861a2c734cd"}, + {file = "pydantic_core-2.14.6-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:7e90d6cc4aad2cc1f5e16ed56e46cebf4877c62403a311af20459c15da76fd91"}, + {file = "pydantic_core-2.14.6-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e8a5ac97ea521d7bde7621d86c30e86b798cdecd985723c4ed737a2aa9e77d0c"}, + {file = "pydantic_core-2.14.6-cp312-none-win32.whl", hash = "sha256:f27207e8ca3e5e021e2402ba942e5b4c629718e665c81b8b306f3c8b1ddbb786"}, + {file = "pydantic_core-2.14.6-cp312-none-win_amd64.whl", hash = "sha256:b3e5fe4538001bb82e2295b8d2a39356a84694c97cb73a566dc36328b9f83b40"}, + {file = "pydantic_core-2.14.6-cp312-none-win_arm64.whl", hash = "sha256:64634ccf9d671c6be242a664a33c4acf12882670b09b3f163cd00a24cffbd74e"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:24368e31be2c88bd69340fbfe741b405302993242ccb476c5c3ff48aeee1afe0"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:e33b0834f1cf779aa839975f9d8755a7c2420510c0fa1e9fa0497de77cd35d2c"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6af4b3f52cc65f8a0bc8b1cd9676f8c21ef3e9132f21fed250f6958bd7223bed"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15687d7d7f40333bd8266f3814c591c2e2cd263fa2116e314f60d82086e353a"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:095b707bb287bfd534044166ab767bec70a9bba3175dcdc3371782175c14e43c"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:94fc0e6621e07d1e91c44e016cc0b189b48db053061cc22d6298a611de8071bb"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ce830e480f6774608dedfd4a90c42aac4a7af0a711f1b52f807130c2e434c06"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a306cdd2ad3a7d795d8e617a58c3a2ed0f76c8496fb7621b6cd514eb1532cae8"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:2f5fa187bde8524b1e37ba894db13aadd64faa884657473b03a019f625cee9a8"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:438027a975cc213a47c5d70672e0d29776082155cfae540c4e225716586be75e"}, + {file = "pydantic_core-2.14.6-cp37-none-win32.whl", hash = "sha256:f96ae96a060a8072ceff4cfde89d261837b4294a4f28b84a28765470d502ccc6"}, + {file = "pydantic_core-2.14.6-cp37-none-win_amd64.whl", hash = "sha256:e646c0e282e960345314f42f2cea5e0b5f56938c093541ea6dbf11aec2862391"}, + {file = "pydantic_core-2.14.6-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:db453f2da3f59a348f514cfbfeb042393b68720787bbef2b4c6068ea362c8149"}, + {file = "pydantic_core-2.14.6-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:3860c62057acd95cc84044e758e47b18dcd8871a328ebc8ccdefd18b0d26a21b"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:36026d8f99c58d7044413e1b819a67ca0e0b8ebe0f25e775e6c3d1fabb3c38fb"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8ed1af8692bd8d2a29d702f1a2e6065416d76897d726e45a1775b1444f5928a7"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:314ccc4264ce7d854941231cf71b592e30d8d368a71e50197c905874feacc8a8"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:982487f8931067a32e72d40ab6b47b1628a9c5d344be7f1a4e668fb462d2da42"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2dbe357bc4ddda078f79d2a36fc1dd0494a7f2fad83a0a684465b6f24b46fe80"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2f6ffc6701a0eb28648c845f4945a194dc7ab3c651f535b81793251e1185ac3d"}, + {file = "pydantic_core-2.14.6-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:7f5025db12fc6de7bc1104d826d5aee1d172f9ba6ca936bf6474c2148ac336c1"}, + {file = "pydantic_core-2.14.6-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:dab03ed811ed1c71d700ed08bde8431cf429bbe59e423394f0f4055f1ca0ea60"}, + {file = "pydantic_core-2.14.6-cp38-none-win32.whl", hash = "sha256:dfcbebdb3c4b6f739a91769aea5ed615023f3c88cb70df812849aef634c25fbe"}, + {file = "pydantic_core-2.14.6-cp38-none-win_amd64.whl", hash = "sha256:99b14dbea2fdb563d8b5a57c9badfcd72083f6006caf8e126b491519c7d64ca8"}, + {file = "pydantic_core-2.14.6-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:4ce8299b481bcb68e5c82002b96e411796b844d72b3e92a3fbedfe8e19813eab"}, + {file = "pydantic_core-2.14.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b9a9d92f10772d2a181b5ca339dee066ab7d1c9a34ae2421b2a52556e719756f"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fd9e98b408384989ea4ab60206b8e100d8687da18b5c813c11e92fd8212a98e0"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4f86f1f318e56f5cbb282fe61eb84767aee743ebe32c7c0834690ebea50c0a6b"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:86ce5fcfc3accf3a07a729779d0b86c5d0309a4764c897d86c11089be61da160"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dcf1978be02153c6a31692d4fbcc2a3f1db9da36039ead23173bc256ee3b91b"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eedf97be7bc3dbc8addcef4142f4b4164066df0c6f36397ae4aaed3eb187d8ab"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d5f916acf8afbcab6bacbb376ba7dc61f845367901ecd5e328fc4d4aef2fcab0"}, + {file = "pydantic_core-2.14.6-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:8a14c192c1d724c3acbfb3f10a958c55a2638391319ce8078cb36c02283959b9"}, + {file = "pydantic_core-2.14.6-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0348b1dc6b76041516e8a854ff95b21c55f5a411c3297d2ca52f5528e49d8411"}, + {file = "pydantic_core-2.14.6-cp39-none-win32.whl", hash = "sha256:de2a0645a923ba57c5527497daf8ec5df69c6eadf869e9cd46e86349146e5975"}, + {file = "pydantic_core-2.14.6-cp39-none-win_amd64.whl", hash = "sha256:aca48506a9c20f68ee61c87f2008f81f8ee99f8d7f0104bff3c47e2d148f89d9"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-macosx_10_7_x86_64.whl", hash = "sha256:d5c28525c19f5bb1e09511669bb57353d22b94cf8b65f3a8d141c389a55dec95"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:78d0768ee59baa3de0f4adac9e3748b4b1fffc52143caebddfd5ea2961595277"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b93785eadaef932e4fe9c6e12ba67beb1b3f1e5495631419c784ab87e975670"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a874f21f87c485310944b2b2734cd6d318765bcbb7515eead33af9641816506e"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b89f4477d915ea43b4ceea6756f63f0288941b6443a2b28c69004fe07fde0d0d"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:172de779e2a153d36ee690dbc49c6db568d7b33b18dc56b69a7514aecbcf380d"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:dfcebb950aa7e667ec226a442722134539e77c575f6cfaa423f24371bb8d2e94"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:55a23dcd98c858c0db44fc5c04fc7ed81c4b4d33c653a7c45ddaebf6563a2f66"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-macosx_10_7_x86_64.whl", hash = "sha256:4241204e4b36ab5ae466ecec5c4c16527a054c69f99bba20f6f75232a6a534e2"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e574de99d735b3fc8364cba9912c2bec2da78775eba95cbb225ef7dda6acea24"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1302a54f87b5cd8528e4d6d1bf2133b6aa7c6122ff8e9dc5220fbc1e07bffebd"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f8e81e4b55930e5ffab4a68db1af431629cf2e4066dbdbfef65348b8ab804ea8"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:c99462ffc538717b3e60151dfaf91125f637e801f5ab008f81c402f1dff0cd0f"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:e4cf2d5829f6963a5483ec01578ee76d329eb5caf330ecd05b3edd697e7d768a"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-macosx_10_7_x86_64.whl", hash = "sha256:cf10b7d58ae4a1f07fccbf4a0a956d705356fea05fb4c70608bb6fa81d103cda"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-macosx_11_0_arm64.whl", hash = "sha256:399ac0891c284fa8eb998bcfa323f2234858f5d2efca3950ae58c8f88830f145"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c6a5c79b28003543db3ba67d1df336f253a87d3112dac3a51b94f7d48e4c0e1"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:599c87d79cab2a6a2a9df4aefe0455e61e7d2aeede2f8577c1b7c0aec643ee8e"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:43e166ad47ba900f2542a80d83f9fc65fe99eb63ceec4debec160ae729824052"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:3a0b5db001b98e1c649dd55afa928e75aa4087e587b9524a4992316fa23c9fba"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:747265448cb57a9f37572a488a57d873fd96bf51e5bb7edb52cfb37124516da4"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:7ebe3416785f65c28f4f9441e916bfc8a54179c8dea73c23023f7086fa601c5d"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-macosx_10_7_x86_64.whl", hash = "sha256:86c963186ca5e50d5c8287b1d1c9d3f8f024cbe343d048c5bd282aec2d8641f2"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:e0641b506486f0b4cd1500a2a65740243e8670a2549bb02bc4556a83af84ae03"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71d72ca5eaaa8d38c8df16b7deb1a2da4f650c41b58bb142f3fb75d5ad4a611f"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27e524624eace5c59af499cd97dc18bb201dc6a7a2da24bfc66ef151c69a5f2a"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a3dde6cac75e0b0902778978d3b1646ca9f438654395a362cb21d9ad34b24acf"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:00646784f6cd993b1e1c0e7b0fdcbccc375d539db95555477771c27555e3c556"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:23598acb8ccaa3d1d875ef3b35cb6376535095e9405d91a3d57a8c7db5d29341"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:7f41533d7e3cf9520065f610b41ac1c76bc2161415955fbcead4981b22c7611e"}, + {file = "pydantic_core-2.14.6.tar.gz", hash = "sha256:1fd0c1d395372843fba13a51c28e3bb9d59bd7aebfeb17358ffaaa1e4dbbe948"}, +] + +[package.dependencies] +typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0" + +[[package]] +name = "pyflakes" +version = "2.5.0" +description = "passive checker of Python programs" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pyflakes-2.5.0-py2.py3-none-any.whl", hash = "sha256:4579f67d887f804e67edb544428f264b7b24f435b263c4614f384135cea553d2"}, + {file = "pyflakes-2.5.0.tar.gz", hash = "sha256:491feb020dca48ccc562a8c0cbe8df07ee13078df59813b83959cbdada312ea3"}, +] + +[[package]] +name = "pytest" +version = "7.4.4" +description = "pytest: simple powerful testing with Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pytest-7.4.4-py3-none-any.whl", hash = "sha256:b090cdf5ed60bf4c45261be03239c2c1c22df034fbffe691abe93cd80cea01d8"}, + {file = "pytest-7.4.4.tar.gz", hash = "sha256:2cf0005922c6ace4a3e2ec8b4080eb0d9753fdc93107415332f50ce9e7994280"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "sys_platform == \"win32\""} +exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} + +[package.extras] +testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] + +[[package]] +name = "python-dateutil" +version = "2.8.2" +description = "Extensions to the standard Python datetime module" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" +files = [ + {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"}, + {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"}, +] + +[package.dependencies] +six = ">=1.5" + +[[package]] +name = "six" +version = "1.16.0" +description = "Python 2 and 3 compatibility utilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +files = [ + {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, + {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, +] + +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +optional = false +python-versions = ">=3.7" +files = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] + +[[package]] +name = "tox" +version = "3.28.0" +description = "tox is a generic virtualenv management and test command line tool" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" +files = [ + {file = "tox-3.28.0-py2.py3-none-any.whl", hash = "sha256:57b5ab7e8bb3074edc3c0c0b4b192a4f3799d3723b2c5b76f1fa9f2d40316eea"}, + {file = "tox-3.28.0.tar.gz", hash = "sha256:d0d28f3fe6d6d7195c27f8b054c3e99d5451952b54abdae673b71609a581f640"}, +] + +[package.dependencies] +colorama = {version = ">=0.4.1", markers = "platform_system == \"Windows\""} +filelock = ">=3.0.0" +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +packaging = ">=14" +pluggy = ">=0.12.0" +py = ">=1.4.17" +six = ">=1.14.0" +tomli = {version = ">=2.0.1", markers = "python_version >= \"3.7\" and python_version < \"3.11\""} +virtualenv = ">=16.0.0,<20.0.0 || >20.0.0,<20.0.1 || >20.0.1,<20.0.2 || >20.0.2,<20.0.3 || >20.0.3,<20.0.4 || >20.0.4,<20.0.5 || >20.0.5,<20.0.6 || >20.0.6,<20.0.7 || >20.0.7" + +[package.extras] +docs = ["pygments-github-lexers (>=0.0.5)", "sphinx (>=2.0.0)", "sphinxcontrib-autoprogram (>=0.1.5)", "towncrier (>=18.5.0)"] +testing = ["flaky (>=3.4.0)", "freezegun (>=0.3.11)", "pathlib2 (>=2.3.3)", "psutil (>=5.6.1)", "pytest (>=4.0.0)", "pytest-cov (>=2.5.1)", "pytest-mock (>=1.10.0)", "pytest-randomly (>=1.0.0)"] + +[[package]] +name = "typed-ast" +version = "1.5.5" +description = "a fork of Python 2 and 3 ast modules with type comment support" +optional = false +python-versions = ">=3.6" +files = [ + {file = "typed_ast-1.5.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4bc1efe0ce3ffb74784e06460f01a223ac1f6ab31c6bc0376a21184bf5aabe3b"}, + {file = "typed_ast-1.5.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:5f7a8c46a8b333f71abd61d7ab9255440d4a588f34a21f126bbfc95f6049e686"}, + {file = "typed_ast-1.5.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:597fc66b4162f959ee6a96b978c0435bd63791e31e4f410622d19f1686d5e769"}, + {file = "typed_ast-1.5.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d41b7a686ce653e06c2609075d397ebd5b969d821b9797d029fccd71fdec8e04"}, + {file = "typed_ast-1.5.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:5fe83a9a44c4ce67c796a1b466c270c1272e176603d5e06f6afbc101a572859d"}, + {file = "typed_ast-1.5.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:d5c0c112a74c0e5db2c75882a0adf3133adedcdbfd8cf7c9d6ed77365ab90a1d"}, + {file = "typed_ast-1.5.5-cp310-cp310-win_amd64.whl", hash = "sha256:e1a976ed4cc2d71bb073e1b2a250892a6e968ff02aa14c1f40eba4f365ffec02"}, + {file = "typed_ast-1.5.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c631da9710271cb67b08bd3f3813b7af7f4c69c319b75475436fcab8c3d21bee"}, + {file = "typed_ast-1.5.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b445c2abfecab89a932b20bd8261488d574591173d07827c1eda32c457358b18"}, + {file = "typed_ast-1.5.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cc95ffaaab2be3b25eb938779e43f513e0e538a84dd14a5d844b8f2932593d88"}, + {file = "typed_ast-1.5.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:61443214d9b4c660dcf4b5307f15c12cb30bdfe9588ce6158f4a005baeb167b2"}, + {file = "typed_ast-1.5.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:6eb936d107e4d474940469e8ec5b380c9b329b5f08b78282d46baeebd3692dc9"}, + {file = "typed_ast-1.5.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e48bf27022897577d8479eaed64701ecaf0467182448bd95759883300ca818c8"}, + {file = "typed_ast-1.5.5-cp311-cp311-win_amd64.whl", hash = "sha256:83509f9324011c9a39faaef0922c6f720f9623afe3fe220b6d0b15638247206b"}, + {file = "typed_ast-1.5.5-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:44f214394fc1af23ca6d4e9e744804d890045d1643dd7e8229951e0ef39429b5"}, + {file = "typed_ast-1.5.5-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:118c1ce46ce58fda78503eae14b7664163aa735b620b64b5b725453696f2a35c"}, + {file = "typed_ast-1.5.5-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be4919b808efa61101456e87f2d4c75b228f4e52618621c77f1ddcaae15904fa"}, + {file = "typed_ast-1.5.5-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:fc2b8c4e1bc5cd96c1a823a885e6b158f8451cf6f5530e1829390b4d27d0807f"}, + {file = "typed_ast-1.5.5-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:16f7313e0a08c7de57f2998c85e2a69a642e97cb32f87eb65fbfe88381a5e44d"}, + {file = "typed_ast-1.5.5-cp36-cp36m-win_amd64.whl", hash = "sha256:2b946ef8c04f77230489f75b4b5a4a6f24c078be4aed241cfabe9cbf4156e7e5"}, + {file = "typed_ast-1.5.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:2188bc33d85951ea4ddad55d2b35598b2709d122c11c75cffd529fbc9965508e"}, + {file = "typed_ast-1.5.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0635900d16ae133cab3b26c607586131269f88266954eb04ec31535c9a12ef1e"}, + {file = "typed_ast-1.5.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:57bfc3cf35a0f2fdf0a88a3044aafaec1d2f24d8ae8cd87c4f58d615fb5b6311"}, + {file = "typed_ast-1.5.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:fe58ef6a764de7b4b36edfc8592641f56e69b7163bba9f9c8089838ee596bfb2"}, + {file = "typed_ast-1.5.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:d09d930c2d1d621f717bb217bf1fe2584616febb5138d9b3e8cdd26506c3f6d4"}, + {file = "typed_ast-1.5.5-cp37-cp37m-win_amd64.whl", hash = "sha256:d40c10326893ecab8a80a53039164a224984339b2c32a6baf55ecbd5b1df6431"}, + {file = "typed_ast-1.5.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fd946abf3c31fb50eee07451a6aedbfff912fcd13cf357363f5b4e834cc5e71a"}, + {file = "typed_ast-1.5.5-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ed4a1a42df8a3dfb6b40c3d2de109e935949f2f66b19703eafade03173f8f437"}, + {file = "typed_ast-1.5.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:045f9930a1550d9352464e5149710d56a2aed23a2ffe78946478f7b5416f1ede"}, + {file = "typed_ast-1.5.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:381eed9c95484ceef5ced626355fdc0765ab51d8553fec08661dce654a935db4"}, + {file = "typed_ast-1.5.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:bfd39a41c0ef6f31684daff53befddae608f9daf6957140228a08e51f312d7e6"}, + {file = "typed_ast-1.5.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:8c524eb3024edcc04e288db9541fe1f438f82d281e591c548903d5b77ad1ddd4"}, + {file = "typed_ast-1.5.5-cp38-cp38-win_amd64.whl", hash = "sha256:7f58fabdde8dcbe764cef5e1a7fcb440f2463c1bbbec1cf2a86ca7bc1f95184b"}, + {file = "typed_ast-1.5.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:042eb665ff6bf020dd2243307d11ed626306b82812aba21836096d229fdc6a10"}, + {file = "typed_ast-1.5.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:622e4a006472b05cf6ef7f9f2636edc51bda670b7bbffa18d26b255269d3d814"}, + {file = "typed_ast-1.5.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1efebbbf4604ad1283e963e8915daa240cb4bf5067053cf2f0baadc4d4fb51b8"}, + {file = "typed_ast-1.5.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0aefdd66f1784c58f65b502b6cf8b121544680456d1cebbd300c2c813899274"}, + {file = "typed_ast-1.5.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:48074261a842acf825af1968cd912f6f21357316080ebaca5f19abbb11690c8a"}, + {file = "typed_ast-1.5.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:429ae404f69dc94b9361bb62291885894b7c6fb4640d561179548c849f8492ba"}, + {file = "typed_ast-1.5.5-cp39-cp39-win_amd64.whl", hash = "sha256:335f22ccb244da2b5c296e6f96b06ee9bed46526db0de38d2f0e5a6597b81155"}, + {file = "typed_ast-1.5.5.tar.gz", hash = "sha256:94282f7a354f36ef5dbce0ef3467ebf6a258e370ab33d5b40c249fa996e590dd"}, +] + +[[package]] +name = "types-python-dateutil" +version = "2.8.19.14" +description = "Typing stubs for python-dateutil" +optional = false +python-versions = "*" +files = [ + {file = "types-python-dateutil-2.8.19.14.tar.gz", hash = "sha256:1f4f10ac98bb8b16ade9dbee3518d9ace017821d94b057a425b069f834737f4b"}, + {file = "types_python_dateutil-2.8.19.14-py3-none-any.whl", hash = "sha256:f977b8de27787639986b4e28963263fd0e5158942b3ecef91b9335c130cb1ce9"}, +] + +[[package]] +name = "typing-extensions" +version = "4.7.1" +description = "Backported and Experimental Type Hints for Python 3.7+" +optional = false +python-versions = ">=3.7" +files = [ + {file = "typing_extensions-4.7.1-py3-none-any.whl", hash = "sha256:440d5dd3af93b060174bf433bccd69b0babc3b15b1a8dca43789fd7f61514b36"}, + {file = "typing_extensions-4.7.1.tar.gz", hash = "sha256:b75ddc264f0ba5615db7ba217daeb99701ad295353c45f9e95963337ceeeffb2"}, +] + +[[package]] +name = "urllib3" +version = "2.0.7" +description = "HTTP library with thread-safe connection pooling, file post, and more." +optional = false +python-versions = ">=3.7" +files = [ + {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"}, + {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"}, +] + +[package.extras] +brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] +secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["zstandard (>=0.18.0)"] + +[[package]] +name = "virtualenv" +version = "20.16.2" +description = "Virtual Python Environment builder" +optional = false +python-versions = ">=3.6" +files = [ + {file = "virtualenv-20.16.2-py2.py3-none-any.whl", hash = "sha256:635b272a8e2f77cb051946f46c60a54ace3cb5e25568228bd6b57fc70eca9ff3"}, + {file = "virtualenv-20.16.2.tar.gz", hash = "sha256:0ef5be6d07181946891f5abc8047fda8bc2f0b4b9bf222c64e6e8963baee76db"}, +] + +[package.dependencies] +distlib = ">=0.3.1,<1" +filelock = ">=3.2,<4" +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +platformdirs = ">=2,<3" + +[package.extras] +docs = ["proselint (>=0.10.2)", "sphinx (>=3)", "sphinx-argparse (>=0.2.5)", "sphinx-rtd-theme (>=0.4.3)", "towncrier (>=21.3)"] +testing = ["coverage (>=4)", "coverage-enable-subprocess (>=1)", "flaky (>=3)", "packaging (>=20.0)", "pytest (>=4)", "pytest-env (>=0.6.2)", "pytest-freezegun (>=0.4.1)", "pytest-mock (>=2)", "pytest-randomly (>=1)", "pytest-timeout (>=1)"] + +[[package]] +name = "zipp" +version = "3.15.0" +description = "Backport of pathlib-compatible object wrapper for zip files" +optional = false +python-versions = ">=3.7" +files = [ + {file = "zipp-3.15.0-py3-none-any.whl", hash = "sha256:48904fc76a60e542af151aded95726c1a5c34ed43ab4134b597665c86d7ad556"}, + {file = "zipp-3.15.0.tar.gz", hash = "sha256:112929ad649da941c23de50f356a2b5570c954b65150642bccdd66bf194d224b"}, +] + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"] +testing = ["big-O", "flake8 (<5)", "jaraco.functools", "jaraco.itertools", "more-itertools", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[metadata] +lock-version = "2.0" +python-versions = "^3.7" +content-hash = "e3db4fda1f09507e7001e5eccf6e0827b049b9384dba0fe21c7e1ff0a118503d" diff --git a/samples/client/echo_api/python/pyproject.toml b/samples/client/echo_api/python/pyproject.toml index af471ab63148..0d00a14b8ebd 100644 --- a/samples/client/echo_api/python/pyproject.toml +++ b/samples/client/echo_api/python/pyproject.toml @@ -21,6 +21,9 @@ typing-extensions = ">=4.7.1" pytest = ">=7.2.1" tox = ">=3.9.0" flake8 = ">=4.0.0" +types-python-dateutil = ">=2.8.19.14" +mypy = "1.4.1" + [build-system] requires = ["setuptools"] @@ -28,3 +31,41 @@ build-backend = "setuptools.build_meta" [tool.pylint.'MESSAGES CONTROL'] extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "openapi_client", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +strict_concatenate = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true diff --git a/samples/client/echo_api/python/test-requirements.txt b/samples/client/echo_api/python/test-requirements.txt index 3a0d0b939a1e..8e6d8cb13749 100644 --- a/samples/client/echo_api/python/test-requirements.txt +++ b/samples/client/echo_api/python/test-requirements.txt @@ -1,3 +1,5 @@ pytest~=7.1.3 pytest-cov>=2.8.1 pytest-randomly>=3.12.0 +mypy>=1.4.1 +types-python-dateutil>=2.8.19 diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/__init__.py b/samples/client/echo_api/python/tests/__init__.py similarity index 100% rename from samples/openapi3/server/petstore/python-flask/openapi_server/controllers/__init__.py rename to samples/client/echo_api/python/tests/__init__.py diff --git a/samples/client/echo_api/python/test/test_manual.py b/samples/client/echo_api/python/tests/test_manual.py similarity index 94% rename from samples/client/echo_api/python/test/test_manual.py rename to samples/client/echo_api/python/tests/test_manual.py index 60199244ed2d..17e0e1014051 100644 --- a/samples/client/echo_api/python/test/test_manual.py +++ b/samples/client/echo_api/python/tests/test_manual.py @@ -85,7 +85,7 @@ def testDateTimeQueryWithDateTimeFormat(self): datetime_format_backup = api_instance.api_client.configuration.datetime_format # backup dateime_format api_instance.api_client.configuration.datetime_format = "%Y-%m-%d %a %H:%M:%S%Z" datetime_query = datetime.datetime.fromisoformat('2013-10-20T19:20:30-05:00') # datetime | (optional) - date_query = '2013-10-20' # date | (optional) + date_query = datetime.date(2013, 10, 20) # date | (optional) string_query = 'string_query_example' # str | (optional) # Test query parameter(s) @@ -99,7 +99,7 @@ def testDateTimeQueryWithDateTimeFormat(self): def testDateTimeQueryWithDateTime(self): api_instance = openapi_client.QueryApi() datetime_query = datetime.datetime.fromisoformat('2013-10-20T19:20:30-05:00') # datetime | (optional) - date_query = '2013-10-20' # date | (optional) + date_query = datetime.date(2013, 10, 20) # date | (optional) string_query = 'string_query_example' # str | (optional) # Test query parameter(s) @@ -116,12 +116,14 @@ def testBinaryGif(self): def testNumberPropertiesOnly(self): n = openapi_client.NumberPropertiesOnly.from_json('{"number": 123, "float": 456, "double": 34}') + assert n is not None self.assertEqual(n.number, 123) # TODO: pydantic v2: this field name override the default `float` type # self.assertEqual(n.float, 456) self.assertEqual(n.double, 34) n = openapi_client.NumberPropertiesOnly.from_json('{"number": 123.1, "float": 456.2, "double": 34.3}') + assert n is not None self.assertEqual(n.number, 123.1) # TODO: pydantic v2: this field name override the default `float` type # self.assertEqual(n.float, 456.2) @@ -187,11 +189,14 @@ def test_from_to_methods(self): " \"status\": \"available\",\n" " \"tags\": [{\"id\": 1, \"name\": \"None\"}]}") pet = openapi_client.Pet.from_json(json_str) + assert pet is not None self.assertEqual(pet.id, 1) self.assertEqual(pet.status, "available") self.assertEqual(pet.photo_urls, ["string"]) + assert pet.tags is not None self.assertEqual(pet.tags[0].id, 1) self.assertEqual(pet.tags[0].name, "None") + assert pet.category is not None self.assertEqual(pet.category.id, 1) # test to_json self.assertEqual(pet.to_json(), @@ -205,13 +210,21 @@ def test_from_to_methods(self): # test from_dict pet2 = openapi_client.Pet.from_dict(pet.to_dict()) + assert pet2 is not None self.assertEqual(pet2.id, 1) self.assertEqual(pet2.status, "available") self.assertEqual(pet2.photo_urls, ["string"]) + assert pet2.tags is not None self.assertEqual(pet2.tags[0].id, 1) self.assertEqual(pet2.tags[0].name, "None") + assert pet2.category is not None self.assertEqual(pet2.category.id, 1) + def test_parameters_to_url_query_boolean_value(self): + client = openapi_client.ApiClient() + params = client.parameters_to_url_query([("boolean", True),], {}) + self.assertEqual(params, "boolean=true") + def echoServerResponseParaserTest(self): s = """POST /echo/body/Pet/response_string HTTP/1.1 Host: localhost:3000 diff --git a/samples/client/echo_api/ruby-faraday/.gitignore b/samples/client/echo_api/ruby-faraday/.gitignore new file mode 100644 index 000000000000..05a17cb8f0a0 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/client/echo_api/ruby-faraday/.gitlab-ci.yml b/samples/client/echo_api/ruby-faraday/.gitlab-ci.yml new file mode 100644 index 000000000000..3a253c45c056 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.gitlab-ci.yml @@ -0,0 +1,26 @@ +.ruby: &ruby + variables: + LANG: "C.UTF-8" + before_script: + - ruby -v + - bundle config set --local deployment true + - bundle install -j $(nproc) + parallel: + matrix: + - RUBY_VERSION: ['2.7', '3.0', '3.1'] + image: "ruby:$RUBY_VERSION" + cache: + paths: + - vendor/ruby + key: 'ruby-$RUBY_VERSION' + +gem: + extends: .ruby + script: + - bundle exec rspec + - bundle exec rake build + - bundle exec rake install + artifacts: + paths: + - pkg/*.gem + diff --git a/samples/client/echo_api/ruby-faraday/.openapi-generator-ignore b/samples/client/echo_api/ruby-faraday/.openapi-generator-ignore new file mode 100644 index 000000000000..c6690c915802 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.openapi-generator-ignore @@ -0,0 +1,25 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md +spec/api_client_spec.rb +spec/configuration_spec.rb diff --git a/samples/client/echo_api/ruby-faraday/.openapi-generator/FILES b/samples/client/echo_api/ruby-faraday/.openapi-generator/FILES new file mode 100644 index 000000000000..a54b808c26ff --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.openapi-generator/FILES @@ -0,0 +1,50 @@ +.gitignore +.gitlab-ci.yml +.rspec +.rubocop.yml +.travis.yml +Gemfile +README.md +Rakefile +docs/AuthApi.md +docs/Bird.md +docs/BodyApi.md +docs/Category.md +docs/DataQuery.md +docs/DefaultValue.md +docs/FormApi.md +docs/HeaderApi.md +docs/NumberPropertiesOnly.md +docs/PathApi.md +docs/Pet.md +docs/Query.md +docs/QueryApi.md +docs/StringEnumRef.md +docs/Tag.md +docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +git_push.sh +lib/openapi_client.rb +lib/openapi_client/api/auth_api.rb +lib/openapi_client/api/body_api.rb +lib/openapi_client/api/form_api.rb +lib/openapi_client/api/header_api.rb +lib/openapi_client/api/path_api.rb +lib/openapi_client/api/query_api.rb +lib/openapi_client/api_client.rb +lib/openapi_client/api_error.rb +lib/openapi_client/configuration.rb +lib/openapi_client/models/bird.rb +lib/openapi_client/models/category.rb +lib/openapi_client/models/data_query.rb +lib/openapi_client/models/default_value.rb +lib/openapi_client/models/number_properties_only.rb +lib/openapi_client/models/pet.rb +lib/openapi_client/models/query.rb +lib/openapi_client/models/string_enum_ref.rb +lib/openapi_client/models/tag.rb +lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb +lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb +lib/openapi_client/version.rb +openapi_client.gemspec +spec/spec_helper.rb diff --git a/samples/client/echo_api/ruby-faraday/.openapi-generator/VERSION b/samples/client/echo_api/ruby-faraday/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/ruby-faraday/.rspec b/samples/client/echo_api/ruby-faraday/.rspec new file mode 100644 index 000000000000..83e16f804474 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/client/echo_api/ruby-faraday/.rubocop.yml b/samples/client/echo_api/ruby-faraday/.rubocop.yml new file mode 100644 index 000000000000..d32b2b1cdab5 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/samples/client/echo_api/ruby-faraday/.travis.yml b/samples/client/echo_api/ruby-faraday/.travis.yml new file mode 100644 index 000000000000..ef5d971f6be8 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/.travis.yml @@ -0,0 +1,11 @@ +language: ruby +cache: bundler +rvm: + - 2.7 + - 3.0 + - 3.1 +script: + - bundle install --path vendor/bundle + - bundle exec rspec + - gem build openapi_client.gemspec + - gem install ./openapi_client-1.0.0.gem diff --git a/samples/client/echo_api/ruby-faraday/Gemfile b/samples/client/echo_api/ruby-faraday/Gemfile new file mode 100644 index 000000000000..c2e3127cdcfe --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/samples/client/echo_api/ruby-faraday/README.md b/samples/client/echo_api/ruby-faraday/README.md new file mode 100644 index 000000000000..0c10000333e9 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/README.md @@ -0,0 +1,137 @@ +# openapi_client + +OpenapiClient - the Ruby gem for the Echo Server API + +Echo Server API + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.1.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RubyClientCodegen + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build openapi_client.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./openapi_client-1.0.0.gem +``` + +(for development, run `gem install --dev ./openapi_client-1.0.0.gem` to install the development dependencies) + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem 'openapi_client', '~> 1.0.0' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/GIT_USER_ID/GIT_REPO_ID, then add the following in the Gemfile: + + gem 'openapi_client', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: + +```ruby +# Load the gem +require 'openapi_client' + +# Setup authorization +OpenapiClient.configure do |config| + # Configure HTTP basic authorization: http_auth + config.username = 'YOUR_USERNAME' + config.password = 'YOUR_PASSWORD' + # Configure faraday connection + config.configure_faraday_connection { |connection| 'YOUR CONNECTION CONFIG PROC' } +end + +api_instance = OpenapiClient::AuthApi.new + +begin + #To test HTTP basic authentication + result = api_instance.test_auth_http_basic + p result +rescue OpenapiClient::ApiError => e + puts "Exception when calling AuthApi->test_auth_http_basic: #{e}" +end + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:3000* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*OpenapiClient::AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*OpenapiClient::AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*OpenapiClient::BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body +*OpenapiClient::BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*OpenapiClient::BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*OpenapiClient::BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +*OpenapiClient::BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body +*OpenapiClient::BodyApi* | [**test_echo_body_tag_response_string**](docs/BodyApi.md#test_echo_body_tag_response_string) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +*OpenapiClient::FormApi* | [**test_form_integer_boolean_string**](docs/FormApi.md#test_form_integer_boolean_string) | **POST** /form/integer/boolean/string | Test form parameter(s) +*OpenapiClient::FormApi* | [**test_form_oneof**](docs/FormApi.md#test_form_oneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema +*OpenapiClient::HeaderApi* | [**test_header_integer_boolean_string_enums**](docs/HeaderApi.md#test_header_integer_boolean_string_enums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) +*OpenapiClient::PathApi* | [**tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path**](docs/PathApi.md#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) +*OpenapiClient::QueryApi* | [**test_enum_ref_string**](docs/QueryApi.md#test_enum_ref_string) | **GET** /query/enum_ref_string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_datetime_date_string**](docs/QueryApi.md#test_query_datetime_date_string) | **GET** /query/datetime/date/string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_integer_boolean_string**](docs/QueryApi.md#test_query_integer_boolean_string) | **GET** /query/integer/boolean/string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_deep_object_explode_true_object**](docs/QueryApi.md#test_query_style_deep_object_explode_true_object) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_deep_object_explode_true_object_all_of**](docs/QueryApi.md#test_query_style_deep_object_explode_true_object_all_of) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_array_string**](docs/QueryApi.md#test_query_style_form_explode_true_array_string) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_object**](docs/QueryApi.md#test_query_style_form_explode_true_object) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_object_all_of**](docs/QueryApi.md#test_query_style_form_explode_true_object_all_of) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + +## Documentation for Models + + - [OpenapiClient::Bird](docs/Bird.md) + - [OpenapiClient::Category](docs/Category.md) + - [OpenapiClient::DataQuery](docs/DataQuery.md) + - [OpenapiClient::DefaultValue](docs/DefaultValue.md) + - [OpenapiClient::NumberPropertiesOnly](docs/NumberPropertiesOnly.md) + - [OpenapiClient::Pet](docs/Pet.md) + - [OpenapiClient::Query](docs/Query.md) + - [OpenapiClient::StringEnumRef](docs/StringEnumRef.md) + - [OpenapiClient::Tag](docs/Tag.md) + - [OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter](docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md) + - [OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter](docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md) + + +## Documentation for Authorization + + +Authentication schemes defined for the API: +### http_auth + +- **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + diff --git a/samples/client/echo_api/ruby-faraday/Rakefile b/samples/client/echo_api/ruby-faraday/Rakefile new file mode 100644 index 000000000000..c72ca30d454e --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/Rakefile @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/client/echo_api/ruby-faraday/docs/AuthApi.md b/samples/client/echo_api/ruby-faraday/docs/AuthApi.md new file mode 100644 index 000000000000..9d924e77375f --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/AuthApi.md @@ -0,0 +1,142 @@ +# OpenapiClient::AuthApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | + + +## test_auth_http_basic + +> String test_auth_http_basic + +To test HTTP basic authentication + +To test HTTP basic authentication + +### Examples + +```ruby +require 'time' +require 'openapi_client' +# setup authorization +OpenapiClient.configure do |config| + # Configure HTTP basic authorization: http_auth + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + # To test HTTP basic authentication + result = api_instance.test_auth_http_basic + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_basic: #{e}" +end +``` + +#### Using the test_auth_http_basic_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_auth_http_basic_with_http_info + +```ruby +begin + # To test HTTP basic authentication + data, status_code, headers = api_instance.test_auth_http_basic_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_basic_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_auth_http_bearer + +> String test_auth_http_bearer + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Examples + +```ruby +require 'time' +require 'openapi_client' +# setup authorization +OpenapiClient.configure do |config| + # Configure Bearer authorization: http_bearer_auth + config.access_token = 'YOUR_BEARER_TOKEN' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + # To test HTTP bearer authentication + result = api_instance.test_auth_http_bearer + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer: #{e}" +end +``` + +#### Using the test_auth_http_bearer_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_auth_http_bearer_with_http_info + +```ruby +begin + # To test HTTP bearer authentication + data, status_code, headers = api_instance.test_auth_http_bearer_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/Bird.md b/samples/client/echo_api/ruby-faraday/docs/Bird.md new file mode 100644 index 000000000000..53207a9a2f10 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/Bird.md @@ -0,0 +1,20 @@ +# OpenapiClient::Bird + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **size** | **String** | | [optional] | +| **color** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Bird.new( + size: null, + color: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/BodyApi.md b/samples/client/echo_api/ruby-faraday/docs/BodyApi.md new file mode 100644 index 000000000000..f5d6d57479e9 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/BodyApi.md @@ -0,0 +1,603 @@ +# OpenapiClient::BodyApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body | +| [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | +| [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | +| [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | +| [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) | +| [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body | +| [**test_echo_body_tag_response_string**](BodyApi.md#test_echo_body_tag_response_string) | **POST** /echo/body/Tag/response_string | Test empty json (request body) | + + +## test_binary_gif + +> File test_binary_gif + +Test binary (gif) response body + +Test binary (gif) response body + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new + +begin + # Test binary (gif) response body + result = api_instance.test_binary_gif + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_binary_gif: #{e}" +end +``` + +#### Using the test_binary_gif_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_binary_gif_with_http_info + +```ruby +begin + # Test binary (gif) response body + data, status_code, headers = api_instance.test_binary_gif_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => File +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_binary_gif_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**File** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/gif + + +## test_body_application_octetstream_binary + +> String test_body_application_octetstream_binary(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + body: File.new('/path/to/some/file') # File | +} + +begin + # Test body parameter(s) + result = api_instance.test_body_application_octetstream_binary(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_application_octetstream_binary: #{e}" +end +``` + +#### Using the test_body_application_octetstream_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_application_octetstream_binary_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_body_application_octetstream_binary_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_application_octetstream_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/octet-stream +- **Accept**: text/plain + + +## test_body_multipart_formdata_array_of_binary + +> String test_body_multipart_formdata_array_of_binary(files) + +Test array of binary in multipart mime + +Test array of binary in multipart mime + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +files = [File.new('/path/to/some/file')] # Array | + +begin + # Test array of binary in multipart mime + result = api_instance.test_body_multipart_formdata_array_of_binary(files) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_array_of_binary: #{e}" +end +``` + +#### Using the test_body_multipart_formdata_array_of_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_multipart_formdata_array_of_binary_with_http_info(files) + +```ruby +begin + # Test array of binary in multipart mime + data, status_code, headers = api_instance.test_body_multipart_formdata_array_of_binary_with_http_info(files) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_array_of_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **files** | **Array<File>** | | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +## test_body_multipart_formdata_single_binary + +> String test_body_multipart_formdata_single_binary(opts) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + my_file: File.new('/path/to/some/file') # File | +} + +begin + # Test single binary in multipart mime + result = api_instance.test_body_multipart_formdata_single_binary(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary: #{e}" +end +``` + +#### Using the test_body_multipart_formdata_single_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_multipart_formdata_single_binary_with_http_info(opts) + +```ruby +begin + # Test single binary in multipart mime + data, status_code, headers = api_instance.test_body_multipart_formdata_single_binary_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **my_file** | **File** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +## test_echo_body_all_of_pet + +> test_echo_body_all_of_pet(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test body parameter(s) + result = api_instance.test_echo_body_all_of_pet(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet: #{e}" +end +``` + +#### Using the test_echo_body_all_of_pet_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_echo_body_all_of_pet_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_echo_body_all_of_pet_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## test_echo_body_free_form_object_response_string + +> String test_echo_body_free_form_object_response_string(opts) + +Test free form object + +Test free form object + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + body: { ... } # Object | Free form object +} + +begin + # Test free form object + result = api_instance.test_echo_body_free_form_object_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_free_form_object_response_string: #{e}" +end +``` + +#### Using the test_echo_body_free_form_object_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_free_form_object_response_string_with_http_info(opts) + +```ruby +begin + # Test free form object + data, status_code, headers = api_instance.test_echo_body_free_form_object_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_free_form_object_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **Object** | Free form object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +## test_echo_body_pet + +> test_echo_body_pet(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test body parameter(s) + result = api_instance.test_echo_body_pet(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet: #{e}" +end +``` + +#### Using the test_echo_body_pet_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_echo_body_pet_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_echo_body_pet_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## test_echo_body_pet_response_string + +> String test_echo_body_pet_response_string(opts) + +Test empty response body + +Test empty response body + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test empty response body + result = api_instance.test_echo_body_pet_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_response_string: #{e}" +end +``` + +#### Using the test_echo_body_pet_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_pet_response_string_with_http_info(opts) + +```ruby +begin + # Test empty response body + data, status_code, headers = api_instance.test_echo_body_pet_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +## test_echo_body_tag_response_string + +> String test_echo_body_tag_response_string(opts) + +Test empty json (request body) + +Test empty json (request body) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + tag: OpenapiClient::Tag.new # Tag | Tag object +} + +begin + # Test empty json (request body) + result = api_instance.test_echo_body_tag_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_tag_response_string: #{e}" +end +``` + +#### Using the test_echo_body_tag_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_tag_response_string_with_http_info(opts) + +```ruby +begin + # Test empty json (request body) + data, status_code, headers = api_instance.test_echo_body_tag_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_tag_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **tag** | [**Tag**](Tag.md) | Tag object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/Category.md b/samples/client/echo_api/ruby-faraday/docs/Category.md new file mode 100644 index 000000000000..17adafbed759 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/Category.md @@ -0,0 +1,20 @@ +# OpenapiClient::Category + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Category.new( + id: 1, + name: Dogs +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/DataQuery.md b/samples/client/echo_api/ruby-faraday/docs/DataQuery.md new file mode 100644 index 000000000000..2ef4c6b1a0d6 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/DataQuery.md @@ -0,0 +1,22 @@ +# OpenapiClient::DataQuery + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **suffix** | **String** | test suffix | [optional] | +| **text** | **String** | Some text containing white spaces | [optional] | +| **date** | **Time** | A date | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::DataQuery.new( + suffix: null, + text: Some text, + date: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/DefaultValue.md b/samples/client/echo_api/ruby-faraday/docs/DefaultValue.md new file mode 100644 index 000000000000..72736b7608dc --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/DefaultValue.md @@ -0,0 +1,32 @@ +# OpenapiClient::DefaultValue + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **array_string_enum_ref_default** | [**Array<StringEnumRef>**](StringEnumRef.md) | | [optional] | +| **array_string_enum_default** | **Array<String>** | | [optional] | +| **array_string_default** | **Array<String>** | | [optional] | +| **array_integer_default** | **Array<Integer>** | | [optional] | +| **array_string** | **Array<String>** | | [optional] | +| **array_string_nullable** | **Array<String>** | | [optional] | +| **array_string_extension_nullable** | **Array<String>** | | [optional] | +| **string_nullable** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::DefaultValue.new( + array_string_enum_ref_default: null, + array_string_enum_default: null, + array_string_default: null, + array_integer_default: null, + array_string: null, + array_string_nullable: null, + array_string_extension_nullable: null, + string_nullable: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/FormApi.md b/samples/client/echo_api/ruby-faraday/docs/FormApi.md new file mode 100644 index 000000000000..632949e8b808 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/FormApi.md @@ -0,0 +1,155 @@ +# OpenapiClient::FormApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_form_integer_boolean_string**](FormApi.md#test_form_integer_boolean_string) | **POST** /form/integer/boolean/string | Test form parameter(s) | +| [**test_form_oneof**](FormApi.md#test_form_oneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema | + + +## test_form_integer_boolean_string + +> String test_form_integer_boolean_string(opts) + +Test form parameter(s) + +Test form parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::FormApi.new +opts = { + integer_form: 56, # Integer | + boolean_form: true, # Boolean | + string_form: 'string_form_example' # String | +} + +begin + # Test form parameter(s) + result = api_instance.test_form_integer_boolean_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_integer_boolean_string: #{e}" +end +``` + +#### Using the test_form_integer_boolean_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_form_integer_boolean_string_with_http_info(opts) + +```ruby +begin + # Test form parameter(s) + data, status_code, headers = api_instance.test_form_integer_boolean_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_integer_boolean_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_form** | **Integer** | | [optional] | +| **boolean_form** | **Boolean** | | [optional] | +| **string_form** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +## test_form_oneof + +> String test_form_oneof(opts) + +Test form parameter(s) for oneOf schema + +Test form parameter(s) for oneOf schema + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::FormApi.new +opts = { + form1: 'form1_example', # String | + form2: 56, # Integer | + form3: 'form3_example', # String | + form4: true, # Boolean | + id: 789, # Integer | + name: 'name_example' # String | +} + +begin + # Test form parameter(s) for oneOf schema + result = api_instance.test_form_oneof(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_oneof: #{e}" +end +``` + +#### Using the test_form_oneof_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_form_oneof_with_http_info(opts) + +```ruby +begin + # Test form parameter(s) for oneOf schema + data, status_code, headers = api_instance.test_form_oneof_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_oneof_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **form1** | **String** | | [optional] | +| **form2** | **Integer** | | [optional] | +| **form3** | **String** | | [optional] | +| **form4** | **Boolean** | | [optional] | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/HeaderApi.md b/samples/client/echo_api/ruby-faraday/docs/HeaderApi.md new file mode 100644 index 000000000000..cb350e92a9c8 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/HeaderApi.md @@ -0,0 +1,82 @@ +# OpenapiClient::HeaderApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_header_integer_boolean_string_enums**](HeaderApi.md#test_header_integer_boolean_string_enums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) | + + +## test_header_integer_boolean_string_enums + +> String test_header_integer_boolean_string_enums(opts) + +Test header parameter(s) + +Test header parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::HeaderApi.new +opts = { + integer_header: 56, # Integer | + boolean_header: true, # Boolean | + string_header: 'string_header_example', # String | + enum_nonref_string_header: 'success', # String | + enum_ref_string_header: OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | +} + +begin + # Test header parameter(s) + result = api_instance.test_header_integer_boolean_string_enums(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling HeaderApi->test_header_integer_boolean_string_enums: #{e}" +end +``` + +#### Using the test_header_integer_boolean_string_enums_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_header_integer_boolean_string_enums_with_http_info(opts) + +```ruby +begin + # Test header parameter(s) + data, status_code, headers = api_instance.test_header_integer_boolean_string_enums_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling HeaderApi->test_header_integer_boolean_string_enums_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_header** | **Integer** | | [optional] | +| **boolean_header** | **Boolean** | | [optional] | +| **string_header** | **String** | | [optional] | +| **enum_nonref_string_header** | **String** | | [optional] | +| **enum_ref_string_header** | [**StringEnumRef**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/NumberPropertiesOnly.md b/samples/client/echo_api/ruby-faraday/docs/NumberPropertiesOnly.md new file mode 100644 index 000000000000..5040bff00ddd --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/NumberPropertiesOnly.md @@ -0,0 +1,22 @@ +# OpenapiClient::NumberPropertiesOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **number** | **Float** | | [optional] | +| **float** | **Float** | | [optional] | +| **double** | **Float** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::NumberPropertiesOnly.new( + number: null, + float: null, + double: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/PathApi.md b/samples/client/echo_api/ruby-faraday/docs/PathApi.md new file mode 100644 index 000000000000..fdaf80f85704 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/PathApi.md @@ -0,0 +1,78 @@ +# OpenapiClient::PathApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path**](PathApi.md#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) | + + +## tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path + +> String tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + +Test path parameter(s) + +Test path parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::PathApi.new +path_string = 'path_string_example' # String | +path_integer = 56 # Integer | +enum_nonref_string_path = 'success' # String | +enum_ref_string_path = OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | + +begin + # Test path parameter(s) + result = api_instance.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling PathApi->tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path: #{e}" +end +``` + +#### Using the tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + +```ruby +begin + # Test path parameter(s) + data, status_code, headers = api_instance.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling PathApi->tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **path_string** | **String** | | | +| **path_integer** | **Integer** | | | +| **enum_nonref_string_path** | **String** | | | +| **enum_ref_string_path** | [**StringEnumRef**](.md) | | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/Pet.md b/samples/client/echo_api/ruby-faraday/docs/Pet.md new file mode 100644 index 000000000000..817b46ce714a --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/Pet.md @@ -0,0 +1,28 @@ +# OpenapiClient::Pet + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | | +| **category** | [**Category**](Category.md) | | [optional] | +| **photo_urls** | **Array<String>** | | | +| **tags** | [**Array<Tag>**](Tag.md) | | [optional] | +| **status** | **String** | pet status in the store | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Pet.new( + id: 10, + name: doggie, + category: null, + photo_urls: null, + tags: null, + status: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/Query.md b/samples/client/echo_api/ruby-faraday/docs/Query.md new file mode 100644 index 000000000000..e7b670a033da --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/Query.md @@ -0,0 +1,20 @@ +# OpenapiClient::Query + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | Query | [optional] | +| **outcomes** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Query.new( + id: null, + outcomes: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/QueryApi.md b/samples/client/echo_api/ruby-faraday/docs/QueryApi.md new file mode 100644 index 000000000000..2dd28c34060b --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/QueryApi.md @@ -0,0 +1,553 @@ +# OpenapiClient::QueryApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_enum_ref_string**](QueryApi.md#test_enum_ref_string) | **GET** /query/enum_ref_string | Test query parameter(s) | +| [**test_query_datetime_date_string**](QueryApi.md#test_query_datetime_date_string) | **GET** /query/datetime/date/string | Test query parameter(s) | +| [**test_query_integer_boolean_string**](QueryApi.md#test_query_integer_boolean_string) | **GET** /query/integer/boolean/string | Test query parameter(s) | +| [**test_query_style_deep_object_explode_true_object**](QueryApi.md#test_query_style_deep_object_explode_true_object) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) | +| [**test_query_style_deep_object_explode_true_object_all_of**](QueryApi.md#test_query_style_deep_object_explode_true_object_all_of) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) | +| [**test_query_style_form_explode_true_array_string**](QueryApi.md#test_query_style_form_explode_true_array_string) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) | +| [**test_query_style_form_explode_true_object**](QueryApi.md#test_query_style_form_explode_true_object) | **GET** /query/style_form/explode_true/object | Test query parameter(s) | +| [**test_query_style_form_explode_true_object_all_of**](QueryApi.md#test_query_style_form_explode_true_object_all_of) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) | + + +## test_enum_ref_string + +> String test_enum_ref_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + enum_nonref_string_query: 'success', # String | + enum_ref_string_query: OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | +} + +begin + # Test query parameter(s) + result = api_instance.test_enum_ref_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_enum_ref_string: #{e}" +end +``` + +#### Using the test_enum_ref_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_enum_ref_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_enum_ref_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_enum_ref_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **enum_nonref_string_query** | **String** | | [optional] | +| **enum_ref_string_query** | [**StringEnumRef**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_datetime_date_string + +> String test_query_datetime_date_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + datetime_query: Time.parse('2013-10-20T19:20:30+01:00'), # Time | + date_query: Date.parse('2013-10-20'), # Date | + string_query: 'string_query_example' # String | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_datetime_date_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_datetime_date_string: #{e}" +end +``` + +#### Using the test_query_datetime_date_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_datetime_date_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_datetime_date_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_datetime_date_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **datetime_query** | **Time** | | [optional] | +| **date_query** | **Date** | | [optional] | +| **string_query** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_integer_boolean_string + +> String test_query_integer_boolean_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + integer_query: 56, # Integer | + boolean_query: true, # Boolean | + string_query: 'string_query_example' # String | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_integer_boolean_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_integer_boolean_string: #{e}" +end +``` + +#### Using the test_query_integer_boolean_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_integer_boolean_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_integer_boolean_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_integer_boolean_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_query** | **Integer** | | [optional] | +| **boolean_query** | **Boolean** | | [optional] | +| **string_query** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_deep_object_explode_true_object + +> String test_query_style_deep_object_explode_true_object(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_deep_object_explode_true_object(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object: #{e}" +end +``` + +#### Using the test_query_style_deep_object_explode_true_object_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_deep_object_explode_true_object_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_deep_object_explode_true_object_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**Pet**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_deep_object_explode_true_object_all_of + +> String test_query_style_deep_object_explode_true_object_all_of(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new # TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_deep_object_explode_true_object_all_of(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_all_of: #{e}" +end +``` + +#### Using the test_query_style_deep_object_explode_true_object_all_of_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_all_of_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_array_string + +> String test_query_style_form_explode_true_array_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new # TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_array_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_array_string: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_array_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_array_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_array_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_array_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_object + +> String test_query_style_form_explode_true_object(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_object(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_object_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_object_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_object_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**Pet**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_object_all_of + +> String test_query_style_form_explode_true_object_all_of(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::DataQuery.new # DataQuery | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_object_all_of(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_all_of: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_object_all_of_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_object_all_of_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_object_all_of_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_all_of_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**DataQuery**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-faraday/docs/StringEnumRef.md b/samples/client/echo_api/ruby-faraday/docs/StringEnumRef.md new file mode 100644 index 000000000000..169bcb44d76f --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/StringEnumRef.md @@ -0,0 +1,15 @@ +# OpenapiClient::StringEnumRef + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::StringEnumRef.new() +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/Tag.md b/samples/client/echo_api/ruby-faraday/docs/Tag.md new file mode 100644 index 000000000000..d3bcb5933abd --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/Tag.md @@ -0,0 +1,20 @@ +# OpenapiClient::Tag + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Tag.new( + id: null, + name: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md new file mode 100644 index 000000000000..a0f7cd16fe86 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -0,0 +1,24 @@ +# OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **size** | **String** | | [optional] | +| **color** | **String** | | [optional] | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new( + size: null, + color: null, + id: 1, + name: Dogs +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md new file mode 100644 index 000000000000..b21365f8f3a8 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -0,0 +1,18 @@ +# OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **values** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new( + values: null +) +``` + diff --git a/samples/client/echo_api/ruby-faraday/git_push.sh b/samples/client/echo_api/ruby-faraday/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client.rb new file mode 100644 index 000000000000..b91b0953227a --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client.rb @@ -0,0 +1,56 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +# Common files +require 'openapi_client/api_client' +require 'openapi_client/api_error' +require 'openapi_client/version' +require 'openapi_client/configuration' + +# Models +require 'openapi_client/models/bird' +require 'openapi_client/models/category' +require 'openapi_client/models/default_value' +require 'openapi_client/models/number_properties_only' +require 'openapi_client/models/pet' +require 'openapi_client/models/query' +require 'openapi_client/models/string_enum_ref' +require 'openapi_client/models/tag' +require 'openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter' +require 'openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter' +require 'openapi_client/models/data_query' + +# APIs +require 'openapi_client/api/auth_api' +require 'openapi_client/api/body_api' +require 'openapi_client/api/form_api' +require 'openapi_client/api/header_api' +require 'openapi_client/api/path_api' +require 'openapi_client/api/query_api' + +module OpenapiClient + class << self + # Customize default settings for the SDK using block. + # OpenapiClient.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/auth_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/auth_api.rb new file mode 100644 index 000000000000..74395866bb1e --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/auth_api.rb @@ -0,0 +1,136 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class AuthApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [String] + def test_auth_http_basic(opts = {}) + data, _status_code, _headers = test_auth_http_basic_with_http_info(opts) + data + end + + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_auth_http_basic_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AuthApi.test_auth_http_basic ...' + end + # resource path + local_var_path = '/auth/http/basic' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_auth'] + + new_options = opts.merge( + :operation => :"AuthApi.test_auth_http_basic", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AuthApi#test_auth_http_basic\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [String] + def test_auth_http_bearer(opts = {}) + data, _status_code, _headers = test_auth_http_bearer_with_http_info(opts) + data + end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_auth_http_bearer_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AuthApi.test_auth_http_bearer ...' + end + # resource path + local_var_path = '/auth/http/bearer' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_bearer_auth'] + + new_options = opts.merge( + :operation => :"AuthApi.test_auth_http_bearer", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AuthApi#test_auth_http_bearer\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/body_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/body_api.rb new file mode 100644 index 000000000000..16dc16b730bd --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/body_api.rb @@ -0,0 +1,597 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class BodyApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [File] + def test_binary_gif(opts = {}) + data, _status_code, _headers = test_binary_gif_with_http_info(opts) + data + end + + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [Array<(File, Integer, Hash)>] File data, response status code and response headers + def test_binary_gif_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_binary_gif ...' + end + # resource path + local_var_path = '/binary/gif' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['image/gif']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'File' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_binary_gif", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_binary_gif\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [String] + def test_body_application_octetstream_binary(opts = {}) + data, _status_code, _headers = test_body_application_octetstream_binary_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_application_octetstream_binary_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_application_octetstream_binary ...' + end + # resource path + local_var_path = '/body/application/octetstream/binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/octet-stream']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_application_octetstream_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_application_octetstream_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files [Array] + # @param [Hash] opts the optional parameters + # @return [String] + def test_body_multipart_formdata_array_of_binary(files, opts = {}) + data, _status_code, _headers = test_body_multipart_formdata_array_of_binary_with_http_info(files, opts) + data + end + + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files [Array] + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_multipart_formdata_array_of_binary_with_http_info(files, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_multipart_formdata_array_of_binary ...' + end + # verify the required parameter 'files' is set + if @api_client.config.client_side_validation && files.nil? + fail ArgumentError, "Missing the required parameter 'files' when calling BodyApi.test_body_multipart_formdata_array_of_binary" + end + # resource path + local_var_path = '/body/application/octetstream/array_of_binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['files'] = @api_client.build_collection_param(files, :csv) + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_multipart_formdata_array_of_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_multipart_formdata_array_of_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [String] + def test_body_multipart_formdata_single_binary(opts = {}) + data, _status_code, _headers = test_body_multipart_formdata_single_binary_with_http_info(opts) + data + end + + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_multipart_formdata_single_binary_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_multipart_formdata_single_binary ...' + end + # resource path + local_var_path = '/body/application/octetstream/single_binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['my-file'] = opts[:'my_file'] if !opts[:'my_file'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_multipart_formdata_single_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_multipart_formdata_single_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + def test_echo_body_all_of_pet(opts = {}) + data, _status_code, _headers = test_echo_body_all_of_pet_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def test_echo_body_all_of_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_all_of_pet ...' + end + # resource path + local_var_path = '/echo/body/allOf/Pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_all_of_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_all_of_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [String] + def test_echo_body_free_form_object_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_free_form_object_response_string_with_http_info(opts) + data + end + + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_free_form_object_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_free_form_object_response_string ...' + end + # resource path + local_var_path = '/echo/body/FreeFormObject/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_free_form_object_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_free_form_object_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + def test_echo_body_pet(opts = {}) + data, _status_code, _headers = test_echo_body_pet_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def test_echo_body_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_pet ...' + end + # resource path + local_var_path = '/echo/body/Pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [String] + def test_echo_body_pet_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_pet_response_string_with_http_info(opts) + data + end + + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_pet_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_pet_response_string ...' + end + # resource path + local_var_path = '/echo/body/Pet/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_pet_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_pet_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [String] + def test_echo_body_tag_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_tag_response_string_with_http_info(opts) + data + end + + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_tag_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_tag_response_string ...' + end + # resource path + local_var_path = '/echo/body/Tag/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'tag']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_tag_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_tag_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/form_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/form_api.rb new file mode 100644 index 000000000000..04147499b1b0 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/form_api.rb @@ -0,0 +1,173 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class FormApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [String] + def test_form_integer_boolean_string(opts = {}) + data, _status_code, _headers = test_form_integer_boolean_string_with_http_info(opts) + data + end + + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_form_integer_boolean_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FormApi.test_form_integer_boolean_string ...' + end + # resource path + local_var_path = '/form/integer/boolean/string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['integer_form'] = opts[:'integer_form'] if !opts[:'integer_form'].nil? + form_params['boolean_form'] = opts[:'boolean_form'] if !opts[:'boolean_form'].nil? + form_params['string_form'] = opts[:'string_form'] if !opts[:'string_form'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FormApi.test_form_integer_boolean_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FormApi#test_form_integer_boolean_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [String] + def test_form_oneof(opts = {}) + data, _status_code, _headers = test_form_oneof_with_http_info(opts) + data + end + + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_form_oneof_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FormApi.test_form_oneof ...' + end + # resource path + local_var_path = '/form/oneof' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['form1'] = opts[:'form1'] if !opts[:'form1'].nil? + form_params['form2'] = opts[:'form2'] if !opts[:'form2'].nil? + form_params['form3'] = opts[:'form3'] if !opts[:'form3'].nil? + form_params['form4'] = opts[:'form4'] if !opts[:'form4'].nil? + form_params['id'] = opts[:'id'] if !opts[:'id'].nil? + form_params['name'] = opts[:'name'] if !opts[:'name'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FormApi.test_form_oneof", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FormApi#test_form_oneof\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/header_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/header_api.rb new file mode 100644 index 000000000000..239edb742474 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/header_api.rb @@ -0,0 +1,98 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class HeaderApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [String] + def test_header_integer_boolean_string_enums(opts = {}) + data, _status_code, _headers = test_header_integer_boolean_string_enums_with_http_info(opts) + data + end + + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_header_integer_boolean_string_enums_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: HeaderApi.test_header_integer_boolean_string_enums ...' + end + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && opts[:'enum_nonref_string_header'] && !allowable_values.include?(opts[:'enum_nonref_string_header']) + fail ArgumentError, "invalid value for \"enum_nonref_string_header\", must be one of #{allowable_values}" + end + # resource path + local_var_path = '/header/integer/boolean/string/enums' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + header_params['integer_header'] = opts[:'integer_header'] if !opts[:'integer_header'].nil? + header_params['boolean_header'] = opts[:'boolean_header'] if !opts[:'boolean_header'].nil? + header_params['string_header'] = opts[:'string_header'] if !opts[:'string_header'].nil? + header_params['enum_nonref_string_header'] = opts[:'enum_nonref_string_header'] if !opts[:'enum_nonref_string_header'].nil? + header_params['enum_ref_string_header'] = opts[:'enum_ref_string_header'] if !opts[:'enum_ref_string_header'].nil? + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"HeaderApi.test_header_integer_boolean_string_enums", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: HeaderApi#test_header_integer_boolean_string_enums\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/path_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/path_api.rb new file mode 100644 index 000000000000..4d4838371838 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/path_api.rb @@ -0,0 +1,108 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class PathApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test path parameter(s) + # Test path parameter(s) + # @param path_string [String] + # @param path_integer [Integer] + # @param enum_nonref_string_path [String] + # @param enum_ref_string_path [StringEnumRef] + # @param [Hash] opts the optional parameters + # @return [String] + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts = {}) + data, _status_code, _headers = tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts) + data + end + + # Test path parameter(s) + # Test path parameter(s) + # @param path_string [String] + # @param path_integer [Integer] + # @param enum_nonref_string_path [String] + # @param enum_ref_string_path [StringEnumRef] + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path ...' + end + # verify the required parameter 'path_string' is set + if @api_client.config.client_side_validation && path_string.nil? + fail ArgumentError, "Missing the required parameter 'path_string' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify the required parameter 'path_integer' is set + if @api_client.config.client_side_validation && path_integer.nil? + fail ArgumentError, "Missing the required parameter 'path_integer' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify the required parameter 'enum_nonref_string_path' is set + if @api_client.config.client_side_validation && enum_nonref_string_path.nil? + fail ArgumentError, "Missing the required parameter 'enum_nonref_string_path' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify enum value + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && !allowable_values.include?(enum_nonref_string_path) + fail ArgumentError, "invalid value for \"enum_nonref_string_path\", must be one of #{allowable_values}" + end + # verify the required parameter 'enum_ref_string_path' is set + if @api_client.config.client_side_validation && enum_ref_string_path.nil? + fail ArgumentError, "Missing the required parameter 'enum_ref_string_path' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # resource path + local_var_path = '/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}'.sub('{' + 'path_string' + '}', CGI.escape(path_string.to_s)).sub('{' + 'path_integer' + '}', CGI.escape(path_integer.to_s)).sub('{' + 'enum_nonref_string_path' + '}', CGI.escape(enum_nonref_string_path.to_s)).sub('{' + 'enum_ref_string_path' + '}', CGI.escape(enum_ref_string_path.to_s)) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PathApi#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/query_api.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/query_api.rb new file mode 100644 index 000000000000..5871d351e006 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api/query_api.rb @@ -0,0 +1,521 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class QueryApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [String] + def test_enum_ref_string(opts = {}) + data, _status_code, _headers = test_enum_ref_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_enum_ref_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_enum_ref_string ...' + end + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && opts[:'enum_nonref_string_query'] && !allowable_values.include?(opts[:'enum_nonref_string_query']) + fail ArgumentError, "invalid value for \"enum_nonref_string_query\", must be one of #{allowable_values}" + end + # resource path + local_var_path = '/query/enum_ref_string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'enum_nonref_string_query'] = opts[:'enum_nonref_string_query'] if !opts[:'enum_nonref_string_query'].nil? + query_params[:'enum_ref_string_query'] = opts[:'enum_ref_string_query'] if !opts[:'enum_ref_string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_enum_ref_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_enum_ref_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [String] + def test_query_datetime_date_string(opts = {}) + data, _status_code, _headers = test_query_datetime_date_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_datetime_date_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_datetime_date_string ...' + end + # resource path + local_var_path = '/query/datetime/date/string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'datetime_query'] = opts[:'datetime_query'] if !opts[:'datetime_query'].nil? + query_params[:'date_query'] = opts[:'date_query'] if !opts[:'date_query'].nil? + query_params[:'string_query'] = opts[:'string_query'] if !opts[:'string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_datetime_date_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_datetime_date_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [String] + def test_query_integer_boolean_string(opts = {}) + data, _status_code, _headers = test_query_integer_boolean_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_integer_boolean_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_integer_boolean_string ...' + end + # resource path + local_var_path = '/query/integer/boolean/string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'integer_query'] = opts[:'integer_query'] if !opts[:'integer_query'].nil? + query_params[:'boolean_query'] = opts[:'boolean_query'] if !opts[:'boolean_query'].nil? + query_params[:'string_query'] = opts[:'string_query'] if !opts[:'string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_integer_boolean_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_integer_boolean_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + def test_query_style_deep_object_explode_true_object(opts = {}) + data, _status_code, _headers = test_query_style_deep_object_explode_true_object_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_deep_object_explode_true_object_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_deep_object_explode_true_object ...' + end + # resource path + local_var_path = '/query/style_deepObject/explode_true/object' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_deep_object_explode_true_object", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_deep_object_explode_true_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [String] + def test_query_style_deep_object_explode_true_object_all_of(opts = {}) + data, _status_code, _headers = test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_deep_object_explode_true_object_all_of ...' + end + # resource path + local_var_path = '/query/style_deepObject/explode_true/object/allOf' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_deep_object_explode_true_object_all_of", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_deep_object_explode_true_object_all_of\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [String] + def test_query_style_form_explode_true_array_string(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_array_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_array_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_array_string ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/array_string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_array_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_array_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + def test_query_style_form_explode_true_object(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_object_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_object_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_object ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/object' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_object", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [String] + def test_query_style_form_explode_true_object_all_of(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_object_all_of_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_object_all_of_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_object_all_of ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/object/allOf' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_object_all_of", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_object_all_of\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_client.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_client.rb new file mode 100644 index 000000000000..82d425814d09 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_client.rb @@ -0,0 +1,431 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'json' +require 'logger' +require 'tempfile' +require 'time' +require 'faraday' +require 'faraday/multipart' if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0') + + +module OpenapiClient + class ApiClient + # The Configuration object holding settings to be used in the API client. + attr_accessor :config + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(config = Configuration.default) + @config = config + @user_agent = "OpenAPI-Generator/#{VERSION}/ruby" + @default_headers = { + 'Content-Type' => 'application/json', + 'User-Agent' => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (could be nil), response status code and response headers. + def call_api(http_method, path, opts = {}) + stream = nil + begin + response = connection(opts).public_send(http_method.to_sym.downcase) do |req| + request = build_request(http_method, path, req, opts) + stream = download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' + end + + if config.debugging + config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.status == 0 && response.respond_to?(:return_message) + # Errors from libcurl will be made visible here + fail ApiError.new(code: 0, + message: response.return_message) + else + fail ApiError.new(code: response.status, + response_headers: response.headers, + response_body: response.body), + response.reason_phrase + end + end + rescue Faraday::TimeoutError + fail ApiError.new('Connection timed out') + rescue Faraday::ConnectionFailed + fail ApiError.new('Connection failed') + end + + if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' + data = deserialize_file(response, stream) + elsif opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.status, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Faraday::Request] A Faraday Request + def build_request(http_method, path, request, opts = {}) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + if config.debugging + config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + request.headers = header_params + request.body = req_body + + # Overload default options only if provided + request.options.params_encoder = config.params_encoder if config.params_encoder + request.options.timeout = config.timeout if config.timeout + + request.url url + request.params = query_params + request + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' + data = URI.encode_www_form(form_params) + elsif header_params['Content-Type'] == 'multipart/form-data' + data = {} + form_params.each do |key, value| + case value + when ::File, ::Tempfile + # TODO hardcode to application/octet-stream, need better way to detect content type + data[key] = Faraday::FilePart.new(value.path, 'application/octet-stream', value.path) + when ::Array, nil + # let Faraday handle Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + def download_file(request) + stream = [] + + # handle streaming Responses + request.options.on_data = Proc.new do |chunk, overall_received_bytes| + stream << chunk + end + stream + end + + def deserialize_file(response, stream) + body = response.body + if @config.return_binary_data == true + # return byte stream + encoding = body.encoding + stream.join.force_encoding(encoding) + else + # return file instead of binary data + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + tempfile.write(stream.join.force_encoding(encoding)) + tempfile.close + config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + tempfile + end + end + + def connection(opts) + opts[:header_params]['Content-Type'] == 'multipart/form-data' ? connection_multipart : connection_regular + end + + def connection_multipart + @connection_multipart ||= build_connection do |conn| + conn.request :multipart + conn.request :url_encoded + end + end + + def connection_regular + @connection_regular ||= build_connection + end + + def build_connection + Faraday.new(url: config.base_url, ssl: ssl_options, proxy: config.proxy) do |conn| + basic_auth(conn) + config.configure_middleware(conn) + yield(conn) if block_given? + conn.adapter(Faraday.default_adapter) + config.configure_connection(conn) + end + end + + def ssl_options + { + ca_file: config.ssl_ca_file, + verify: config.ssl_verify, + verify_mode: config.ssl_verify_mode, + client_cert: config.ssl_client_cert, + client_key: config.ssl_client_key + } + end + + def basic_auth(conn) + if config.username && config.password + if Gem::Version.new(Faraday::VERSION) >= Gem::Version.new('2.0') + conn.request(:authorization, :basic, config.username, config.password) + else + conn.request(:basic_auth, config.username, config.password) + end + end + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body.to_s if return_type == 'String' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date Time).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'Boolean' + data == true + when 'Time' + # parse date time (expecting ISO 8601 format) + Time.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + filename.gsub(/.*[\/\\]/, '') + end + + def build_request_url(path, opts = {}) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + @config.base_url(opts[:operation]) + path + end + + # Update header and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array(auth_names).each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] + else fail ArgumentError, 'Authentication token must be in `query` or `header`' + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + json_accept || accepts.join(',') + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # return nil by default + return if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_error.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_error.rb new file mode 100644 index 000000000000..c9d0c194a36e --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/api_error.rb @@ -0,0 +1,58 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + + arg.each do |k, v| + instance_variable_set "@#{k}", v + end + else + super arg + @message = arg + end + end + + # Override to_s to display a friendly error message + def to_s + message + end + + def message + if @message.nil? + msg = "Error message: the server returns an error" + else + msg = @message + end + + msg += "\nHTTP status code: #{code}" if code + msg += "\nResponse headers: #{response_headers}" if response_headers + msg += "\nResponse body: #{response_body}" if response_body + + msg + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/configuration.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/configuration.rb new file mode 100644 index 000000000000..e598aab0be48 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/configuration.rb @@ -0,0 +1,389 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + class Configuration + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Define server configuration index + attr_accessor :server_index + + # Define server operation configuration index + attr_accessor :server_operation_index + + # Default server variables + attr_accessor :server_variables + + # Default server operation variables + attr_accessor :server_operation_variables + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + + # Defines a Proc used to fetch or refresh access tokens (Bearer) used with OAuth2. + # Overrides the access_token if set + # @return [Proc] + attr_accessor :access_token_getter + + # Set this to return data as binary instead of downloading a temp file. When enabled (set to true) + # HTTP responses with return type `File` will be returned as a stream of binary data. + # Default to false. + attr_accessor :return_binary_data + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + attr_accessor :timeout + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + attr_accessor :client_side_validation + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :ssl_verify + + ### TLS/SSL setting + # Any `OpenSSL::SSL::` constant (see https://ruby-doc.org/stdlib-2.5.1/libdoc/openssl/rdoc/OpenSSL/SSL.html) + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + attr_accessor :ssl_verify_mode + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + attr_accessor :ssl_ca_file + + ### TLS/SSL setting + # Client certificate file (for client certificate) + attr_accessor :ssl_client_cert + + ### TLS/SSL setting + # Client private key file (for client certificate) + attr_accessor :ssl_client_key + + ### Proxy setting + # HTTP Proxy settings + attr_accessor :proxy + + # Set this to customize parameters encoder of array parameter. + # Default to nil. Faraday uses NestedParamsEncoder when nil. + # + # @see The params_encoder option of Faraday. Related source code: + # https://github.com/lostisland/faraday/tree/main/lib/faraday/encoders + attr_accessor :params_encoder + + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + def initialize + @scheme = 'http' + @host = 'localhost:3000' + @base_path = '' + @server_index = nil + @server_operation_index = {} + @server_variables = {} + @server_operation_variables = {} + @api_key = {} + @api_key_prefix = {} + @client_side_validation = true + @ssl_verify = true + @ssl_verify_mode = nil + @ssl_ca_file = nil + @ssl_client_cert = nil + @ssl_client_key = nil + @middlewares = Hash.new { |h, k| h[k] = [] } + @configure_connection_blocks = [] + @timeout = 60 + # return data as binary instead of file + @return_binary_data = false + @params_encoder = nil + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = '' if @base_path == '/' + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = nil) + if operation_server_settings.key?(operation) then + index = server_operation_index.fetch(operation, server_index) + server_url(index.nil? ? 0 : index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + else + server_index.nil? ? "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') : server_url(server_index, server_variables, nil) + end + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{key}" + else + key + end + end + + # Gets access_token using access_token_getter or uses the static access_token + def access_token_with_refresh + return access_token if access_token_getter.nil? + access_token_getter.call + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'http_auth' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, + 'http_bearer_auth' => + { + type: 'bearer', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token_with_refresh}" + }, + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "http://localhost:3000", + description: "No description provided", + } + ] + end + + def operation_server_settings + { + } + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {}, servers = nil) + servers = server_settings if servers == nil + + # check array index out of bound + if (index.nil? || index < 0 || index >= servers.size) + fail ArgumentError, "Invalid index #{index} when selecting the server. Must not be nil and must be less than #{servers.size}" + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}." + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + + # Configure Faraday connection directly. + # + # ``` + # c.configure_faraday_connection do |conn| + # conn.use Faraday::HttpCache, shared_cache: false, logger: logger + # conn.response :logger, nil, headers: true, bodies: true, log_level: :debug do |logger| + # logger.filter(/(Authorization: )(.*)/, '\1[REDACTED]') + # end + # end + # + # c.configure_faraday_connection do |conn| + # conn.adapter :typhoeus + # end + # ``` + # + # @param block [Proc] `#call`able object that takes one arg, the connection + def configure_faraday_connection(&block) + @configure_connection_blocks << block + end + + def configure_connection(conn) + @configure_connection_blocks.each do |block| + block.call(conn) + end + end + + # Adds middleware to the stack + def use(*middleware) + set_faraday_middleware(:use, *middleware) + end + + # Adds request middleware to the stack + def request(*middleware) + set_faraday_middleware(:request, *middleware) + end + + # Adds response middleware to the stack + def response(*middleware) + set_faraday_middleware(:response, *middleware) + end + + # Adds Faraday middleware setting information to the stack + # + # @example Use the `set_faraday_middleware` method to set middleware information + # config.set_faraday_middleware(:request, :retry, max: 3, methods: [:get, :post], retry_statuses: [503]) + # config.set_faraday_middleware(:response, :logger, nil, { bodies: true, log_level: :debug }) + # config.set_faraday_middleware(:use, Faraday::HttpCache, store: Rails.cache, shared_cache: false) + # config.set_faraday_middleware(:insert, 0, FaradayMiddleware::FollowRedirects, { standards_compliant: true, limit: 1 }) + # config.set_faraday_middleware(:swap, 0, Faraday::Response::Logger) + # config.set_faraday_middleware(:delete, Faraday::Multipart::Middleware) + # + # @see https://github.com/lostisland/faraday/blob/v2.3.0/lib/faraday/rack_builder.rb#L92-L143 + def set_faraday_middleware(operation, key, *args, &block) + unless [:request, :response, :use, :insert, :insert_before, :insert_after, :swap, :delete].include?(operation) + fail ArgumentError, "Invalid faraday middleware operation #{operation}. Must be" \ + " :request, :response, :use, :insert, :insert_before, :insert_after, :swap or :delete." + end + + @middlewares[operation] << [key, args, block] + end + ruby2_keywords(:set_faraday_middleware) if respond_to?(:ruby2_keywords, true) + + # Set up middleware on the connection + def configure_middleware(connection) + return if @middlewares.empty? + + [:request, :response, :use, :insert, :insert_before, :insert_after, :swap].each do |operation| + next unless @middlewares.key?(operation) + + @middlewares[operation].each do |key, args, block| + connection.builder.send(operation, key, *args, &block) + end + end + + if @middlewares.key?(:delete) + @middlewares[:delete].each do |key, _args, _block| + connection.builder.delete(key) + end + end + end + + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/bird.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/bird.rb new file mode 100644 index 000000000000..a131cb068352 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/bird.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Bird + attr_accessor :size + + attr_accessor :color + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'size' => :'size', + :'color' => :'color' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'size' => :'String', + :'color' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Bird` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Bird`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'size') + self.size = attributes[:'size'] + end + + if attributes.key?(:'color') + self.color = attributes[:'color'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + size == o.size && + color == o.color + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [size, color].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/category.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/category.rb new file mode 100644 index 000000000000..0d1badac1693 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/category.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Category + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Category` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Category`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/data_query.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/data_query.rb new file mode 100644 index 000000000000..8a367642bd13 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/data_query.rb @@ -0,0 +1,268 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class DataQuery < Query + # test suffix + attr_accessor :suffix + + # Some text containing white spaces + attr_accessor :text + + # A date + attr_accessor :date + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'suffix' => :'suffix', + :'text' => :'text', + :'date' => :'date' + } + end + + # Returns all the JSON keys this model knows about, including the ones defined in its parent(s) + def self.acceptable_attributes + attribute_map.values.concat(superclass.acceptable_attributes) + end + + # Attribute type mapping. + def self.openapi_types + { + :'suffix' => :'String', + :'text' => :'String', + :'date' => :'Time' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Query' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::DataQuery` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::DataQuery`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + # call parent's initialize + super(attributes) + + if attributes.key?(:'suffix') + self.suffix = attributes[:'suffix'] + end + + if attributes.key?(:'text') + self.text = attributes[:'text'] + end + + if attributes.key?(:'date') + self.date = attributes[:'date'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = super + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true && super + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + suffix == o.suffix && + text == o.text && + date == o.date && super(o) + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [suffix, text, date].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + super(attributes) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = super + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/default_value.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/default_value.rb new file mode 100644 index 000000000000..20b339e41c48 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/default_value.rb @@ -0,0 +1,317 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + # to test the default value of properties + class DefaultValue + attr_accessor :array_string_enum_ref_default + + attr_accessor :array_string_enum_default + + attr_accessor :array_string_default + + attr_accessor :array_integer_default + + attr_accessor :array_string + + attr_accessor :array_string_nullable + + attr_accessor :array_string_extension_nullable + + attr_accessor :string_nullable + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'array_string_enum_ref_default' => :'array_string_enum_ref_default', + :'array_string_enum_default' => :'array_string_enum_default', + :'array_string_default' => :'array_string_default', + :'array_integer_default' => :'array_integer_default', + :'array_string' => :'array_string', + :'array_string_nullable' => :'array_string_nullable', + :'array_string_extension_nullable' => :'array_string_extension_nullable', + :'string_nullable' => :'string_nullable' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'array_string_enum_ref_default' => :'Array', + :'array_string_enum_default' => :'Array', + :'array_string_default' => :'Array', + :'array_integer_default' => :'Array', + :'array_string' => :'Array', + :'array_string_nullable' => :'Array', + :'array_string_extension_nullable' => :'Array', + :'string_nullable' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'array_string_nullable', + :'array_string_extension_nullable', + :'string_nullable' + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::DefaultValue` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::DefaultValue`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'array_string_enum_ref_default') + if (value = attributes[:'array_string_enum_ref_default']).is_a?(Array) + self.array_string_enum_ref_default = value + end + end + + if attributes.key?(:'array_string_enum_default') + if (value = attributes[:'array_string_enum_default']).is_a?(Array) + self.array_string_enum_default = value + end + end + + if attributes.key?(:'array_string_default') + if (value = attributes[:'array_string_default']).is_a?(Array) + self.array_string_default = value + end + end + + if attributes.key?(:'array_integer_default') + if (value = attributes[:'array_integer_default']).is_a?(Array) + self.array_integer_default = value + end + end + + if attributes.key?(:'array_string') + if (value = attributes[:'array_string']).is_a?(Array) + self.array_string = value + end + end + + if attributes.key?(:'array_string_nullable') + if (value = attributes[:'array_string_nullable']).is_a?(Array) + self.array_string_nullable = value + end + end + + if attributes.key?(:'array_string_extension_nullable') + if (value = attributes[:'array_string_extension_nullable']).is_a?(Array) + self.array_string_extension_nullable = value + end + end + + if attributes.key?(:'string_nullable') + self.string_nullable = attributes[:'string_nullable'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + array_string_enum_ref_default == o.array_string_enum_ref_default && + array_string_enum_default == o.array_string_enum_default && + array_string_default == o.array_string_default && + array_integer_default == o.array_integer_default && + array_string == o.array_string && + array_string_nullable == o.array_string_nullable && + array_string_extension_nullable == o.array_string_extension_nullable && + string_nullable == o.string_nullable + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [array_string_enum_ref_default, array_string_enum_default, array_string_default, array_integer_default, array_string, array_string_nullable, array_string_extension_nullable, string_nullable].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/number_properties_only.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/number_properties_only.rb new file mode 100644 index 000000000000..59c453fd378b --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/number_properties_only.rb @@ -0,0 +1,260 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class NumberPropertiesOnly + attr_accessor :number + + attr_accessor :float + + attr_accessor :double + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'number' => :'number', + :'float' => :'float', + :'double' => :'double' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'number' => :'Float', + :'float' => :'Float', + :'double' => :'Float' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::NumberPropertiesOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::NumberPropertiesOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'number') + self.number = attributes[:'number'] + end + + if attributes.key?(:'float') + self.float = attributes[:'float'] + end + + if attributes.key?(:'double') + self.double = attributes[:'double'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + if !@double.nil? && @double > 50.2 + invalid_properties.push('invalid value for "double", must be smaller than or equal to 50.2.') + end + + if !@double.nil? && @double < 0.8 + invalid_properties.push('invalid value for "double", must be greater than or equal to 0.8.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + return false if !@double.nil? && @double > 50.2 + return false if !@double.nil? && @double < 0.8 + true + end + + # Custom attribute writer method with validation + # @param [Object] double Value to be assigned + def double=(double) + if double.nil? + fail ArgumentError, 'double cannot be nil' + end + + if double > 50.2 + fail ArgumentError, 'invalid value for "double", must be smaller than or equal to 50.2.' + end + + if double < 0.8 + fail ArgumentError, 'invalid value for "double", must be greater than or equal to 0.8.' + end + + @double = double + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + number == o.number && + float == o.float && + double == o.double + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [number, float, double].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/pet.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/pet.rb new file mode 100644 index 000000000000..e2d3358a953d --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/pet.rb @@ -0,0 +1,312 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Pet + attr_accessor :id + + attr_accessor :name + + attr_accessor :category + + attr_accessor :photo_urls + + attr_accessor :tags + + # pet status in the store + attr_accessor :status + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name', + :'category' => :'category', + :'photo_urls' => :'photoUrls', + :'tags' => :'tags', + :'status' => :'status' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String', + :'category' => :'Category', + :'photo_urls' => :'Array', + :'tags' => :'Array', + :'status' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Pet` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Pet`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + else + self.name = nil + end + + if attributes.key?(:'category') + self.category = attributes[:'category'] + end + + if attributes.key?(:'photo_urls') + if (value = attributes[:'photo_urls']).is_a?(Array) + self.photo_urls = value + end + else + self.photo_urls = nil + end + + if attributes.key?(:'tags') + if (value = attributes[:'tags']).is_a?(Array) + self.tags = value + end + end + + if attributes.key?(:'status') + self.status = attributes[:'status'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + if @name.nil? + invalid_properties.push('invalid value for "name", name cannot be nil.') + end + + if @photo_urls.nil? + invalid_properties.push('invalid value for "photo_urls", photo_urls cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + return false if @name.nil? + return false if @photo_urls.nil? + status_validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for \"status\", must be one of #{validator.allowable_values}." + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name && + category == o.category && + photo_urls == o.photo_urls && + tags == o.tags && + status == o.status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name, category, photo_urls, tags, status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/query.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/query.rb new file mode 100644 index 000000000000..4bddb7bcc412 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/query.rb @@ -0,0 +1,248 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Query + # Query + attr_accessor :id + + attr_accessor :outcomes + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'outcomes' => :'outcomes' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'outcomes' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Query` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Query`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'outcomes') + if (value = attributes[:'outcomes']).is_a?(Array) + self.outcomes = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + outcomes == o.outcomes + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, outcomes].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/string_enum_ref.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/string_enum_ref.rb new file mode 100644 index 000000000000..5aa83ea64b6c --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/string_enum_ref.rb @@ -0,0 +1,41 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class StringEnumRef + SUCCESS = "success".freeze + FAILURE = "failure".freeze + UNCLASSIFIED = "unclassified".freeze + + def self.all_vars + @all_vars ||= [SUCCESS, FAILURE, UNCLASSIFIED].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if StringEnumRef.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #StringEnumRef" + end + end +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/tag.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/tag.rb new file mode 100644 index 000000000000..b8496889c787 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/tag.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Tag + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Tag` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Tag`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb new file mode 100644 index 000000000000..65d19fa1a98e --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb @@ -0,0 +1,249 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + attr_accessor :size + + attr_accessor :color + + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'size' => :'size', + :'color' => :'color', + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'size' => :'String', + :'color' => :'String', + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Bird', + :'Category' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'size') + self.size = attributes[:'size'] + end + + if attributes.key?(:'color') + self.color = attributes[:'color'] + end + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + size == o.size && + color == o.color && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [size, color, id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb new file mode 100644 index 000000000000..5f88a0c939b7 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb @@ -0,0 +1,216 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + attr_accessor :values + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'values' => :'values' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'values' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'values') + if (value = attributes[:'values']).is_a?(Array) + self.values = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + values == o.values + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [values].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-faraday/lib/openapi_client/version.rb b/samples/client/echo_api/ruby-faraday/lib/openapi_client/version.rb new file mode 100644 index 000000000000..e7a852ecb1e5 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/lib/openapi_client/version.rb @@ -0,0 +1,15 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + VERSION = '1.0.0' +end diff --git a/samples/client/echo_api/ruby-faraday/openapi_client.gemspec b/samples/client/echo_api/ruby-faraday/openapi_client.gemspec new file mode 100644 index 000000000000..13f669f78a51 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/openapi_client.gemspec @@ -0,0 +1,40 @@ +# -*- encoding: utf-8 -*- + +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +$:.push File.expand_path("../lib", __FILE__) +require "openapi_client/version" + +Gem::Specification.new do |s| + s.name = "openapi_client" + s.version = OpenapiClient::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["OpenAPI-Generator"] + s.email = ["team@openapitools.org"] + s.homepage = "https://openapi-generator.tech" + s.summary = "Echo Server API Ruby Gem" + s.description = "Echo Server API" + s.license = "Unlicense" + s.required_ruby_version = ">= 2.7" + s.metadata = {} + + s.add_runtime_dependency 'faraday', '>= 1.0.1', '< 3.0' + s.add_runtime_dependency 'faraday-multipart' + + s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0' + + s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/auth_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/auth_api_spec.rb new file mode 100644 index 000000000000..565fe5d2a239 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/auth_api_spec.rb @@ -0,0 +1,57 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::AuthApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'AuthApi' do + before do + # run before each test + @api_instance = OpenapiClient::AuthApi.new + end + + after do + # run after each test + end + + describe 'test an instance of AuthApi' do + it 'should create an instance of AuthApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::AuthApi) + end + end + + # unit tests for test_auth_http_basic + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_auth_http_basic test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_auth_http_bearer + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_auth_http_bearer test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/body_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/body_api_spec.rb new file mode 100644 index 000000000000..363e9f8b8b64 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/body_api_spec.rb @@ -0,0 +1,130 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::BodyApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'BodyApi' do + before do + # run before each test + @api_instance = OpenapiClient::BodyApi.new + end + + after do + # run after each test + end + + describe 'test an instance of BodyApi' do + it 'should create an instance of BodyApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::BodyApi) + end + end + + # unit tests for test_binary_gif + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [File] + describe 'test_binary_gif test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_body_application_octetstream_binary + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [String] + describe 'test_body_application_octetstream_binary test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_body_multipart_formdata_array_of_binary + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_body_multipart_formdata_array_of_binary test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_all_of_pet + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + describe 'test_echo_body_all_of_pet test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_free_form_object_response_string + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [String] + describe 'test_echo_body_free_form_object_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_pet + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + describe 'test_echo_body_pet test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_pet_response_string + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [String] + describe 'test_echo_body_pet_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_tag_response_string + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [String] + describe 'test_echo_body_tag_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/form_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/form_api_spec.rb new file mode 100644 index 000000000000..c404fc538470 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/form_api_spec.rb @@ -0,0 +1,66 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::FormApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'FormApi' do + before do + # run before each test + @api_instance = OpenapiClient::FormApi.new + end + + after do + # run after each test + end + + describe 'test an instance of FormApi' do + it 'should create an instance of FormApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::FormApi) + end + end + + # unit tests for test_form_integer_boolean_string + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [String] + describe 'test_form_integer_boolean_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_form_oneof + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [String] + describe 'test_form_oneof test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/header_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/header_api_spec.rb new file mode 100644 index 000000000000..e7772849df69 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/header_api_spec.rb @@ -0,0 +1,51 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::HeaderApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'HeaderApi' do + before do + # run before each test + @api_instance = OpenapiClient::HeaderApi.new + end + + after do + # run after each test + end + + describe 'test an instance of HeaderApi' do + it 'should create an instance of HeaderApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::HeaderApi) + end + end + + # unit tests for test_header_integer_boolean_string_enums + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [String] + describe 'test_header_integer_boolean_string_enums test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/path_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/path_api_spec.rb new file mode 100644 index 000000000000..6ac30f152f7b --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/path_api_spec.rb @@ -0,0 +1,50 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::PathApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'PathApi' do + before do + # run before each test + @api_instance = OpenapiClient::PathApi.new + end + + after do + # run after each test + end + + describe 'test an instance of PathApi' do + it 'should create an instance of PathApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::PathApi) + end + end + + # unit tests for tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path + # Test path parameter(s) + # Test path parameter(s) + # @param path_string + # @param path_integer + # @param enum_nonref_string_path + # @param enum_ref_string_path + # @param [Hash] opts the optional parameters + # @return [String] + describe 'tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/api/query_api_spec.rb b/samples/client/echo_api/ruby-faraday/spec/api/query_api_spec.rb new file mode 100644 index 000000000000..f9043d4f8b7b --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/api/query_api_spec.rb @@ -0,0 +1,136 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::QueryApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'QueryApi' do + before do + # run before each test + @api_instance = OpenapiClient::QueryApi.new + end + + after do + # run after each test + end + + describe 'test an instance of QueryApi' do + it 'should create an instance of QueryApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::QueryApi) + end + end + + # unit tests for test_enum_ref_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [String] + describe 'test_enum_ref_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_datetime_date_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [String] + describe 'test_query_datetime_date_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_integer_boolean_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [String] + describe 'test_query_integer_boolean_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_deep_object_explode_true_object + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + describe 'test_query_style_deep_object_explode_true_object test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_deep_object_explode_true_object_all_of + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [String] + describe 'test_query_style_deep_object_explode_true_object_all_of test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_array_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_array_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_object + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_object test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_object_all_of + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_object_all_of test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/manual_spec.rb b/samples/client/echo_api/ruby-faraday/spec/manual_spec.rb new file mode 100644 index 000000000000..023b2538c7bb --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/manual_spec.rb @@ -0,0 +1,26 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' + +describe "Body API tests" do + describe 'the test_binary_gif method' do + let(:body_api_instance) { OpenapiClient::BodyApi.new } + + it 'can return file response' do + gif_base64 = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\n" + response = body_api_instance.test_binary_gif() + expect(Base64.encode64(File.read(response.path))).to eq(gif_base64) + end + + end +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/bird_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/bird_spec.rb new file mode 100644 index 000000000000..764ab5329e01 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/bird_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Bird +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Bird do + let(:instance) { OpenapiClient::Bird.new } + + describe 'test an instance of Bird' do + it 'should create an instance of Bird' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Bird) + end + end + + describe 'test attribute "size"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "color"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/category_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/category_spec.rb new file mode 100644 index 000000000000..6bf16df513c7 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/category_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Category +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Category do + let(:instance) { OpenapiClient::Category.new } + + describe 'test an instance of Category' do + it 'should create an instance of Category' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Category) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/data_query_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/data_query_spec.rb new file mode 100644 index 000000000000..616516cd6f18 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/data_query_spec.rb @@ -0,0 +1,48 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::DataQuery +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::DataQuery do + let(:instance) { OpenapiClient::DataQuery.new } + + describe 'test an instance of DataQuery' do + it 'should create an instance of DataQuery' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::DataQuery) + end + end + + describe 'test attribute "suffix"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "text"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "date"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/default_value_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/default_value_spec.rb new file mode 100644 index 000000000000..1601e3bf0be2 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/default_value_spec.rb @@ -0,0 +1,82 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::DefaultValue +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::DefaultValue do + let(:instance) { OpenapiClient::DefaultValue.new } + + describe 'test an instance of DefaultValue' do + it 'should create an instance of DefaultValue' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::DefaultValue) + end + end + + describe 'test attribute "array_string_enum_ref_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_enum_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["success", "failure", "unclassified"]) + # validator.allowable_values.each do |value| + # expect { instance.array_string_enum_default = value }.not_to raise_error + # end + end + end + + describe 'test attribute "array_string_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_integer_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_extension_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "string_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/number_properties_only_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/number_properties_only_spec.rb new file mode 100644 index 000000000000..c528b0ff2628 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/number_properties_only_spec.rb @@ -0,0 +1,48 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::NumberPropertiesOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::NumberPropertiesOnly do + let(:instance) { OpenapiClient::NumberPropertiesOnly.new } + + describe 'test an instance of NumberPropertiesOnly' do + it 'should create an instance of NumberPropertiesOnly' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::NumberPropertiesOnly) + end + end + + describe 'test attribute "number"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "float"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "double"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/pet_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/pet_spec.rb new file mode 100644 index 000000000000..75d8b5f6079d --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/pet_spec.rb @@ -0,0 +1,70 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Pet +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Pet do + let(:instance) { OpenapiClient::Pet.new } + + describe 'test an instance of Pet' do + it 'should create an instance of Pet' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Pet) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "category"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "photo_urls"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "tags"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "status"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/query_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/query_spec.rb new file mode 100644 index 000000000000..893943f3a776 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/query_spec.rb @@ -0,0 +1,46 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Query +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Query do + let(:instance) { OpenapiClient::Query.new } + + describe 'test an instance of Query' do + it 'should create an instance of Query' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Query) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "outcomes"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["SUCCESS", "FAILURE", "SKIPPED"]) + # validator.allowable_values.each do |value| + # expect { instance.outcomes = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/string_enum_ref_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/string_enum_ref_spec.rb new file mode 100644 index 000000000000..6bd5883ca5a6 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/string_enum_ref_spec.rb @@ -0,0 +1,30 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::StringEnumRef +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::StringEnumRef do + let(:instance) { OpenapiClient::StringEnumRef.new } + + describe 'test an instance of StringEnumRef' do + it 'should create an instance of StringEnumRef' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::StringEnumRef) + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/tag_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/tag_spec.rb new file mode 100644 index 000000000000..9ee4d2c31c78 --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/tag_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Tag +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Tag do + let(:instance) { OpenapiClient::Tag.new } + + describe 'test an instance of Tag' do + it 'should create an instance of Tag' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Tag) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb new file mode 100644 index 000000000000..4fd29f1fc78e --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb @@ -0,0 +1,54 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter do + let(:instance) { OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new } + + describe 'test an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' do + it 'should create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter) + end + end + + describe 'test attribute "size"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "color"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb b/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb new file mode 100644 index 000000000000..092ead39ae9c --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb @@ -0,0 +1,36 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter do + let(:instance) { OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new } + + describe 'test an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' do + it 'should create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter) + end + end + + describe 'test attribute "values"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-faraday/spec/spec_helper.rb b/samples/client/echo_api/ruby-faraday/spec/spec_helper.rb new file mode 100644 index 000000000000..6cbca24b26da --- /dev/null +++ b/samples/client/echo_api/ruby-faraday/spec/spec_helper.rb @@ -0,0 +1,111 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +# load the gem +require 'openapi_client' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/samples/client/echo_api/ruby-httpx/.openapi-generator-ignore b/samples/client/echo_api/ruby-httpx/.openapi-generator-ignore index 7484ee590a38..c6690c915802 100644 --- a/samples/client/echo_api/ruby-httpx/.openapi-generator-ignore +++ b/samples/client/echo_api/ruby-httpx/.openapi-generator-ignore @@ -21,3 +21,5 @@ #docs/*.md # Then explicitly reverse the ignore rule for a single file: #!docs/README.md +spec/api_client_spec.rb +spec/configuration_spec.rb diff --git a/samples/client/echo_api/ruby-httpx/.openapi-generator/FILES b/samples/client/echo_api/ruby-httpx/.openapi-generator/FILES index ecf4fd0bbcd3..a54b808c26ff 100644 --- a/samples/client/echo_api/ruby-httpx/.openapi-generator/FILES +++ b/samples/client/echo_api/ruby-httpx/.openapi-generator/FILES @@ -47,6 +47,4 @@ lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_o lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb lib/openapi_client/version.rb openapi_client.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/client/echo_api/ruby-httpx/.openapi-generator/VERSION b/samples/client/echo_api/ruby-httpx/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/echo_api/ruby-httpx/.openapi-generator/VERSION +++ b/samples/client/echo_api/ruby-httpx/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/ruby-httpx/README.md b/samples/client/echo_api/ruby-httpx/README.md index b5f01671a665..d389064972b1 100644 --- a/samples/client/echo_api/ruby-httpx/README.md +++ b/samples/client/echo_api/ruby-httpx/README.md @@ -84,9 +84,12 @@ All URIs are relative to *http://localhost:3000* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- *OpenapiClient::AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*OpenapiClient::AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication *OpenapiClient::BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body *OpenapiClient::BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) *OpenapiClient::BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*OpenapiClient::BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*OpenapiClient::BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) *OpenapiClient::BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object *OpenapiClient::BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) *OpenapiClient::BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body @@ -128,3 +131,7 @@ Authentication schemes defined for the API: - **Type**: HTTP basic authentication +### http_bearer_auth + +- **Type**: Bearer authentication + diff --git a/samples/client/echo_api/ruby-httpx/docs/AuthApi.md b/samples/client/echo_api/ruby-httpx/docs/AuthApi.md index d82f08464e14..9d924e77375f 100644 --- a/samples/client/echo_api/ruby-httpx/docs/AuthApi.md +++ b/samples/client/echo_api/ruby-httpx/docs/AuthApi.md @@ -5,6 +5,7 @@ All URIs are relative to *http://localhost:3000* | Method | HTTP request | Description | | ------ | ------------ | ----------- | | [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | ## test_auth_http_basic @@ -73,3 +74,69 @@ This endpoint does not need any parameter. - **Content-Type**: Not defined - **Accept**: text/plain + +## test_auth_http_bearer + +> String test_auth_http_bearer + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Examples + +```ruby +require 'time' +require 'openapi_client' +# setup authorization +OpenapiClient.configure do |config| + # Configure Bearer authorization: http_bearer_auth + config.access_token = 'YOUR_BEARER_TOKEN' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + # To test HTTP bearer authentication + result = api_instance.test_auth_http_bearer + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer: #{e}" +end +``` + +#### Using the test_auth_http_bearer_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_auth_http_bearer_with_http_info + +```ruby +begin + # To test HTTP bearer authentication + data, status_code, headers = api_instance.test_auth_http_bearer_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-httpx/docs/BodyApi.md b/samples/client/echo_api/ruby-httpx/docs/BodyApi.md index 89a5d10159a0..f5d6d57479e9 100644 --- a/samples/client/echo_api/ruby-httpx/docs/BodyApi.md +++ b/samples/client/echo_api/ruby-httpx/docs/BodyApi.md @@ -7,6 +7,8 @@ All URIs are relative to *http://localhost:3000* | [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body | | [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | | [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | | [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | | [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) | | [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body | @@ -204,6 +206,138 @@ No authorization required - **Accept**: text/plain +## test_body_multipart_formdata_single_binary + +> String test_body_multipart_formdata_single_binary(opts) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + my_file: File.new('/path/to/some/file') # File | +} + +begin + # Test single binary in multipart mime + result = api_instance.test_body_multipart_formdata_single_binary(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary: #{e}" +end +``` + +#### Using the test_body_multipart_formdata_single_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_multipart_formdata_single_binary_with_http_info(opts) + +```ruby +begin + # Test single binary in multipart mime + data, status_code, headers = api_instance.test_body_multipart_formdata_single_binary_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **my_file** | **File** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +## test_echo_body_all_of_pet + +> test_echo_body_all_of_pet(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test body parameter(s) + result = api_instance.test_echo_body_all_of_pet(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet: #{e}" +end +``` + +#### Using the test_echo_body_all_of_pet_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_echo_body_all_of_pet_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_echo_body_all_of_pet_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + ## test_echo_body_free_form_object_response_string > String test_echo_body_free_form_object_response_string(opts) diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client.rb index ed71a17389e7..b91b0953227a 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/auth_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/auth_api.rb index a5922ca0ade0..74395866bb1e 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/auth_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/auth_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -75,5 +75,62 @@ def test_auth_http_basic_with_http_info(opts = {}) end return data, status_code, headers end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [String] + def test_auth_http_bearer(opts = {}) + data, _status_code, _headers = test_auth_http_bearer_with_http_info(opts) + data + end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_auth_http_bearer_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AuthApi.test_auth_http_bearer ...' + end + # resource path + local_var_path = '/auth/http/bearer' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_bearer_auth'] + + new_options = opts.merge( + :operation => :"AuthApi.test_auth_http_bearer", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AuthApi#test_auth_http_bearer\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/body_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/body_api.rb index 1a9970d95a3e..16dc16b730bd 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/body_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/body_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -209,6 +209,135 @@ def test_body_multipart_formdata_array_of_binary_with_http_info(files, opts = {} return data, status_code, headers end + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [String] + def test_body_multipart_formdata_single_binary(opts = {}) + data, _status_code, _headers = test_body_multipart_formdata_single_binary_with_http_info(opts) + data + end + + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_multipart_formdata_single_binary_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_multipart_formdata_single_binary ...' + end + # resource path + local_var_path = '/body/application/octetstream/single_binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['my-file'] = opts[:'my_file'] if !opts[:'my_file'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_multipart_formdata_single_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_multipart_formdata_single_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + def test_echo_body_all_of_pet(opts = {}) + data, _status_code, _headers = test_echo_body_all_of_pet_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def test_echo_body_all_of_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_all_of_pet ...' + end + # resource path + local_var_path = '/echo/body/allOf/Pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_all_of_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_all_of_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # Test free form object # Test free form object # @param [Hash] opts the optional parameters diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/form_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/form_api.rb index a387e7b5f539..04147499b1b0 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/form_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/form_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/header_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/header_api.rb index 3bf3cd501f7d..239edb742474 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/header_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/header_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/path_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/path_api.rb index 76ec07a10843..4d4838371838 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/path_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/path_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/query_api.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/query_api.rb index d40034e46e00..5871d351e006 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/query_api.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api/query_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_client.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_client.rb index e3e9c1e0f1d0..4fddfcc8309c 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_client.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -69,7 +69,9 @@ def call_api(http_method, path, opts = {}) fail ApiError.new('Connection failed') end - if opts[:return_type] + if opts[:return_type] == 'File' + data = deserialize_file(response) + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -126,6 +128,33 @@ def build_request_body(header_params, form_params, body) end end + def deserialize_file(response) + body = response.body + if @config.return_binary_data == true + # TODO: force response encoding + body.to_s + else + content_disposition = response.headers['content-disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + response.copy_to(tempfile) + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + + tempfile + end + end + def session return @session if defined?(@session) @@ -168,35 +197,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - if return_type == 'File' - if @config.return_binary_data == true - # TODO: force response encoding - return body.to_s - else - content_disposition = response.headers['content-disposition'] - if content_disposition && content_disposition =~ /filename=/i - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - prefix = sanitize_filename(filename) - else - prefix = 'download-' - end - prefix = prefix + '-' unless prefix.end_with?('-') - encoding = response.body.encoding - tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - response.copy_to(tempfile) - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - - return tempfile - end - end - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_error.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_error.rb index 8b2759ed2a40..c9d0c194a36e 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_error.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/configuration.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/configuration.rb index bd2fd9bf1034..0ed6063c739c 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/configuration.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -209,6 +209,13 @@ def auth_settings key: 'Authorization', value: basic_auth_token }, + 'http_bearer_auth' => + { + type: 'bearer', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token_with_refresh}" + }, } end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/bird.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/bird.rb index 36503338037b..a131cb068352 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/bird.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/bird.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/category.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/category.rb index d8433b0236d6..0d1badac1693 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/category.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/data_query.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/data_query.rb index 9fd58e63b275..8a367642bd13 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/data_query.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/data_query.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -213,7 +213,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/default_value.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/default_value.rb index 957a945a2fc5..20b339e41c48 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/default_value.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -262,7 +262,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/number_properties_only.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/number_properties_only.rb index d4b05f3c1aa6..59c453fd378b 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/number_properties_only.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/number_properties_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -205,7 +205,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/pet.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/pet.rb index a37a969818cc..e2d3358a953d 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/pet.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -257,7 +257,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/query.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/query.rb index 0bf87a363177..4bddb7bcc412 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/query.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/query.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -193,7 +193,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/string_enum_ref.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/string_enum_ref.rb index 6bcbcf63da9e..5aa83ea64b6c 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/string_enum_ref.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/string_enum_ref.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/tag.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/tag.rb index 58dfc611926b..b8496889c787 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/tag.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb index 47baf2203b0c..65d19fa1a98e 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -194,7 +194,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb index 50c87fbae0e8..5f88a0c939b7 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = OpenapiClient.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/echo_api/ruby-httpx/lib/openapi_client/version.rb b/samples/client/echo_api/ruby-httpx/lib/openapi_client/version.rb index 563f648be69d..e7a852ecb1e5 100644 --- a/samples/client/echo_api/ruby-httpx/lib/openapi_client/version.rb +++ b/samples/client/echo_api/ruby-httpx/lib/openapi_client/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-httpx/openapi_client.gemspec b/samples/client/echo_api/ruby-httpx/openapi_client.gemspec index d479c1892b02..9ee963cc376b 100644 --- a/samples/client/echo_api/ruby-httpx/openapi_client.gemspec +++ b/samples/client/echo_api/ruby-httpx/openapi_client.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "Echo Server API" s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'httpx', '~> 1.0', '>= 1.0.0' diff --git a/samples/client/echo_api/ruby-httpx/spec/api_client_spec.rb b/samples/client/echo_api/ruby-httpx/spec/api_client_spec.rb deleted file mode 100644 index 0fd815af5f22..000000000000 --- a/samples/client/echo_api/ruby-httpx/spec/api_client_spec.rb +++ /dev/null @@ -1,190 +0,0 @@ -=begin -#Echo Server API - -#Echo Server API - -The version of the OpenAPI document: 0.1.0 -Contact: team@openapitools.org -Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT - -=end - -require 'spec_helper' - -describe OpenapiClient::ApiClient do - context 'initialization' do - context 'URL stuff' do - context 'host' do - it 'removes http from host' do - OpenapiClient.configure { |c| c.host = 'http://example.com' } - expect(OpenapiClient::Configuration.default.host).to eq('example.com') - end - - it 'removes https from host' do - OpenapiClient.configure { |c| c.host = 'https://wookiee.com' } - expect(OpenapiClient::ApiClient.default.config.host).to eq('wookiee.com') - end - - it 'removes trailing path from host' do - OpenapiClient.configure { |c| c.host = 'hobo.com/v4' } - expect(OpenapiClient::Configuration.default.host).to eq('hobo.com') - end - end - - context 'base_path' do - it "prepends a slash to base_path" do - OpenapiClient.configure { |c| c.base_path = 'v4/dog' } - expect(OpenapiClient::Configuration.default.base_path).to eq('/v4/dog') - end - - it "doesn't prepend a slash if one is already there" do - OpenapiClient.configure { |c| c.base_path = '/v4/dog' } - expect(OpenapiClient::Configuration.default.base_path).to eq('/v4/dog') - end - - it "ends up as a blank string if nil" do - OpenapiClient.configure { |c| c.base_path = nil } - expect(OpenapiClient::Configuration.default.base_path).to eq('') - end - end - end - end - - - - describe '#deserialize' do - it "handles Array" do - api_client = OpenapiClient::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '[12, 34]') - data = api_client.deserialize(response, 'Array') - expect(data).to be_instance_of(Array) - expect(data).to eq([12, 34]) - end - - it 'handles Array>' do - api_client = OpenapiClient::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '[[12, 34], [56]]') - data = api_client.deserialize(response, 'Array>') - expect(data).to be_instance_of(Array) - expect(data).to eq([[12, 34], [56]]) - end - - it 'handles Hash' do - api_client = OpenapiClient::ApiClient.new - headers = { 'Content-Type' => 'application/json' } - response = double('response', headers: headers, body: '{"message": "Hello"}') - data = api_client.deserialize(response, 'Hash') - expect(data).to be_instance_of(Hash) - expect(data).to eq(:message => 'Hello') - end - end - - describe "#object_to_hash" do - it 'ignores nils and includes empty arrays' do - # uncomment below to test object_to_hash for model - # api_client = OpenapiClient::ApiClient.new - # _model = OpenapiClient::ModelName.new - # update the model attribute below - # _model.id = 1 - # update the expected value (hash) below - # expected = {id: 1, name: '', tags: []} - # expect(api_client.object_to_hash(_model)).to eq(expected) - end - end - - describe '#build_collection_param' do - let(:param) { ['aa', 'bb', 'cc'] } - let(:api_client) { OpenapiClient::ApiClient.new } - - it 'works for csv' do - expect(api_client.build_collection_param(param, :csv)).to eq('aa,bb,cc') - end - - it 'works for ssv' do - expect(api_client.build_collection_param(param, :ssv)).to eq('aa bb cc') - end - - it 'works for tsv' do - expect(api_client.build_collection_param(param, :tsv)).to eq("aa\tbb\tcc") - end - - it 'works for pipes' do - expect(api_client.build_collection_param(param, :pipes)).to eq('aa|bb|cc') - end - - it 'works for multi' do - expect(api_client.build_collection_param(param, :multi)).to eq(['aa', 'bb', 'cc']) - end - - it 'fails for invalid collection format' do - expect { api_client.build_collection_param(param, :INVALID) }.to raise_error(RuntimeError, 'unknown collection format: :INVALID') - end - end - - describe '#json_mime?' do - let(:api_client) { OpenapiClient::ApiClient.new } - - it 'works' do - expect(api_client.json_mime?(nil)).to eq false - expect(api_client.json_mime?('')).to eq false - - expect(api_client.json_mime?('application/json')).to eq true - expect(api_client.json_mime?('application/json; charset=UTF8')).to eq true - expect(api_client.json_mime?('APPLICATION/JSON')).to eq true - - expect(api_client.json_mime?('application/xml')).to eq false - expect(api_client.json_mime?('text/plain')).to eq false - expect(api_client.json_mime?('application/jsonp')).to eq false - end - end - - describe '#select_header_accept' do - let(:api_client) { OpenapiClient::ApiClient.new } - - it 'works' do - expect(api_client.select_header_accept(nil)).to be_nil - expect(api_client.select_header_accept([])).to be_nil - - expect(api_client.select_header_accept(['application/json'])).to eq('application/json') - expect(api_client.select_header_accept(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') - expect(api_client.select_header_accept(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') - - expect(api_client.select_header_accept(['application/xml'])).to eq('application/xml') - expect(api_client.select_header_accept(['text/html', 'application/xml'])).to eq('text/html,application/xml') - end - end - - describe '#select_header_content_type' do - let(:api_client) { OpenapiClient::ApiClient.new } - - it 'works' do - expect(api_client.select_header_content_type(nil)).to be_nil - expect(api_client.select_header_content_type([])).to be_nil - - expect(api_client.select_header_content_type(['application/json'])).to eq('application/json') - expect(api_client.select_header_content_type(['application/xml', 'application/json; charset=UTF8'])).to eq('application/json; charset=UTF8') - expect(api_client.select_header_content_type(['APPLICATION/JSON', 'text/html'])).to eq('APPLICATION/JSON') - expect(api_client.select_header_content_type(['application/xml'])).to eq('application/xml') - expect(api_client.select_header_content_type(['text/plain', 'application/xml'])).to eq('text/plain') - end - end - - describe '#sanitize_filename' do - let(:api_client) { OpenapiClient::ApiClient.new } - - it 'works' do - expect(api_client.sanitize_filename('sun')).to eq('sun') - expect(api_client.sanitize_filename('sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('../sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('/var/tmp/sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('./sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('..\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('\var\tmp\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('c:\var\tmp\sun.gif')).to eq('sun.gif') - expect(api_client.sanitize_filename('.\sun.gif')).to eq('sun.gif') - end - end -end diff --git a/samples/client/echo_api/ruby-httpx/spec/configuration_spec.rb b/samples/client/echo_api/ruby-httpx/spec/configuration_spec.rb deleted file mode 100644 index a34a7e714fd9..000000000000 --- a/samples/client/echo_api/ruby-httpx/spec/configuration_spec.rb +++ /dev/null @@ -1,75 +0,0 @@ -=begin -#Echo Server API - -#Echo Server API - -The version of the OpenAPI document: 0.1.0 -Contact: team@openapitools.org -Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT - -=end - -require 'spec_helper' - -describe OpenapiClient::Configuration do - let(:config) { OpenapiClient::Configuration.default } - - before(:each) do - # uncomment below to setup host and base_path - # require 'URI' - # uri = URI.parse("http://localhost:3000") - # OpenapiClient.configure do |c| - # c.host = uri.host - # c.base_path = uri.path - # end - end - - describe '#base_url' do - it 'should have the default value' do - # uncomment below to test default value of the base path - # expect(config.base_url).to eq("http://localhost:3000") - end - - it 'should remove trailing slashes' do - [nil, '', '/', '//'].each do |base_path| - config.base_path = base_path - # uncomment below to test trailing slashes - # expect(config.base_url).to eq("http://localhost:3000") - end - end - end - - describe '#configure' do - let(:session) { HTTPX::Session.new } - - before do - module CustomPlugin - module InstanceMethods; end - end - module AnotherCustomPlugin - module InstanceMethods; end - end - - config.configure_session do |session| - session.plugin(CustomPlugin) - end - end - - it 'adds a block that will be used to configure the connection' do - sess = config.configure(session) - - expect(sess.class.ancestors).to include(CustomPlugin::InstanceMethods) - end - - it 'supports multiple configuration blocks' do - config.configure_session do |session| - session.plugin(AnotherCustomPlugin) - end - sess = config.configure(session) - - expect(sess.class.ancestors).to include(CustomPlugin::InstanceMethods) - expect(sess.class.ancestors).to include(AnotherCustomPlugin::InstanceMethods) - end - end -end diff --git a/samples/client/echo_api/ruby-httpx/spec/manual_spec.rb b/samples/client/echo_api/ruby-httpx/spec/manual_spec.rb new file mode 100644 index 000000000000..96db5a92076a --- /dev/null +++ b/samples/client/echo_api/ruby-httpx/spec/manual_spec.rb @@ -0,0 +1,27 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'base64' + +describe "Body API tests" do + describe 'the test_binary_gif method' do + let(:body_api_instance) { OpenapiClient::BodyApi.new } + + it 'can return file response' do + gif_base64 = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\n" + response = body_api_instance.test_binary_gif() + expect(Base64.encode64(File.read(response.path))).to eq(gif_base64) + end + + end +end diff --git a/samples/client/echo_api/ruby-httpx/spec/spec_helper.rb b/samples/client/echo_api/ruby-httpx/spec/spec_helper.rb index cb59b02487e6..6cbca24b26da 100644 --- a/samples/client/echo_api/ruby-httpx/spec/spec_helper.rb +++ b/samples/client/echo_api/ruby-httpx/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 0.1.0 Contact: team@openapitools.org Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/echo_api/ruby-typhoeus/.gitignore b/samples/client/echo_api/ruby-typhoeus/.gitignore new file mode 100644 index 000000000000..05a17cb8f0a0 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.gitignore @@ -0,0 +1,39 @@ +# Generated by: https://openapi-generator.tech +# + +*.gem +*.rbc +/.config +/coverage/ +/InstalledFiles +/pkg/ +/spec/reports/ +/spec/examples.txt +/test/tmp/ +/test/version_tmp/ +/tmp/ + +## Specific to RubyMotion: +.dat* +.repl_history +build/ + +## Documentation cache and generated files: +/.yardoc/ +/_yardoc/ +/doc/ +/rdoc/ + +## Environment normalization: +/.bundle/ +/vendor/bundle +/lib/bundler/man/ + +# for a library or gem, you might want to ignore these files since the code is +# intended to run in multiple environments; otherwise, check them in: +# Gemfile.lock +# .ruby-version +# .ruby-gemset + +# unless supporting rvm < 1.11.0 or doing something fancy, ignore this: +.rvmrc diff --git a/samples/client/echo_api/ruby-typhoeus/.gitlab-ci.yml b/samples/client/echo_api/ruby-typhoeus/.gitlab-ci.yml new file mode 100644 index 000000000000..3a253c45c056 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.gitlab-ci.yml @@ -0,0 +1,26 @@ +.ruby: &ruby + variables: + LANG: "C.UTF-8" + before_script: + - ruby -v + - bundle config set --local deployment true + - bundle install -j $(nproc) + parallel: + matrix: + - RUBY_VERSION: ['2.7', '3.0', '3.1'] + image: "ruby:$RUBY_VERSION" + cache: + paths: + - vendor/ruby + key: 'ruby-$RUBY_VERSION' + +gem: + extends: .ruby + script: + - bundle exec rspec + - bundle exec rake build + - bundle exec rake install + artifacts: + paths: + - pkg/*.gem + diff --git a/samples/client/echo_api/ruby-typhoeus/.openapi-generator-ignore b/samples/client/echo_api/ruby-typhoeus/.openapi-generator-ignore new file mode 100644 index 000000000000..c6690c915802 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.openapi-generator-ignore @@ -0,0 +1,25 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md +spec/api_client_spec.rb +spec/configuration_spec.rb diff --git a/samples/client/echo_api/ruby-typhoeus/.openapi-generator/FILES b/samples/client/echo_api/ruby-typhoeus/.openapi-generator/FILES new file mode 100644 index 000000000000..a54b808c26ff --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.openapi-generator/FILES @@ -0,0 +1,50 @@ +.gitignore +.gitlab-ci.yml +.rspec +.rubocop.yml +.travis.yml +Gemfile +README.md +Rakefile +docs/AuthApi.md +docs/Bird.md +docs/BodyApi.md +docs/Category.md +docs/DataQuery.md +docs/DefaultValue.md +docs/FormApi.md +docs/HeaderApi.md +docs/NumberPropertiesOnly.md +docs/PathApi.md +docs/Pet.md +docs/Query.md +docs/QueryApi.md +docs/StringEnumRef.md +docs/Tag.md +docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md +docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md +git_push.sh +lib/openapi_client.rb +lib/openapi_client/api/auth_api.rb +lib/openapi_client/api/body_api.rb +lib/openapi_client/api/form_api.rb +lib/openapi_client/api/header_api.rb +lib/openapi_client/api/path_api.rb +lib/openapi_client/api/query_api.rb +lib/openapi_client/api_client.rb +lib/openapi_client/api_error.rb +lib/openapi_client/configuration.rb +lib/openapi_client/models/bird.rb +lib/openapi_client/models/category.rb +lib/openapi_client/models/data_query.rb +lib/openapi_client/models/default_value.rb +lib/openapi_client/models/number_properties_only.rb +lib/openapi_client/models/pet.rb +lib/openapi_client/models/query.rb +lib/openapi_client/models/string_enum_ref.rb +lib/openapi_client/models/tag.rb +lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb +lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb +lib/openapi_client/version.rb +openapi_client.gemspec +spec/spec_helper.rb diff --git a/samples/client/echo_api/ruby-typhoeus/.openapi-generator/VERSION b/samples/client/echo_api/ruby-typhoeus/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/ruby-typhoeus/.rspec b/samples/client/echo_api/ruby-typhoeus/.rspec new file mode 100644 index 000000000000..83e16f804474 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.rspec @@ -0,0 +1,2 @@ +--color +--require spec_helper diff --git a/samples/client/echo_api/ruby-typhoeus/.rubocop.yml b/samples/client/echo_api/ruby-typhoeus/.rubocop.yml new file mode 100644 index 000000000000..d32b2b1cdab5 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.rubocop.yml @@ -0,0 +1,148 @@ +# This file is based on https://github.com/rails/rails/blob/master/.rubocop.yml (MIT license) +# Automatically generated by OpenAPI Generator (https://openapi-generator.tech) +AllCops: + TargetRubyVersion: 2.4 + # RuboCop has a bunch of cops enabled by default. This setting tells RuboCop + # to ignore them, so only the ones explicitly set in this file are enabled. + DisabledByDefault: true + Exclude: + - '**/templates/**/*' + - '**/vendor/**/*' + - 'actionpack/lib/action_dispatch/journey/parser.rb' + +# Prefer &&/|| over and/or. +Style/AndOr: + Enabled: true + +# Align `when` with `case`. +Layout/CaseIndentation: + Enabled: true + +# Align comments with method definitions. +Layout/CommentIndentation: + Enabled: true + +Layout/ElseAlignment: + Enabled: true + +Layout/EmptyLineAfterMagicComment: + Enabled: true + +# In a regular class definition, no empty lines around the body. +Layout/EmptyLinesAroundClassBody: + Enabled: true + +# In a regular method definition, no empty lines around the body. +Layout/EmptyLinesAroundMethodBody: + Enabled: true + +# In a regular module definition, no empty lines around the body. +Layout/EmptyLinesAroundModuleBody: + Enabled: true + +Layout/FirstArgumentIndentation: + Enabled: true + +# Use Ruby >= 1.9 syntax for hashes. Prefer { a: :b } over { :a => :b }. +Style/HashSyntax: + Enabled: false + +# Method definitions after `private` or `protected` isolated calls need one +# extra level of indentation. +Layout/IndentationConsistency: + Enabled: true + EnforcedStyle: indented_internal_methods + +# Two spaces, no tabs (for indentation). +Layout/IndentationWidth: + Enabled: true + +Layout/LeadingCommentSpace: + Enabled: true + +Layout/SpaceAfterColon: + Enabled: true + +Layout/SpaceAfterComma: + Enabled: true + +Layout/SpaceAroundEqualsInParameterDefault: + Enabled: true + +Layout/SpaceAroundKeyword: + Enabled: true + +Layout/SpaceAroundOperators: + Enabled: true + +Layout/SpaceBeforeComma: + Enabled: true + +Layout/SpaceBeforeFirstArg: + Enabled: true + +Style/DefWithParentheses: + Enabled: true + +# Defining a method with parameters needs parentheses. +Style/MethodDefParentheses: + Enabled: true + +Style/FrozenStringLiteralComment: + Enabled: false + EnforcedStyle: always + +# Use `foo {}` not `foo{}`. +Layout/SpaceBeforeBlockBraces: + Enabled: true + +# Use `foo { bar }` not `foo {bar}`. +Layout/SpaceInsideBlockBraces: + Enabled: true + +# Use `{ a: 1 }` not `{a:1}`. +Layout/SpaceInsideHashLiteralBraces: + Enabled: true + +Layout/SpaceInsideParens: + Enabled: true + +# Check quotes usage according to lint rule below. +#Style/StringLiterals: +# Enabled: true +# EnforcedStyle: single_quotes + +# Detect hard tabs, no hard tabs. +Layout/IndentationStyle: + Enabled: true + +# Blank lines should not have any spaces. +Layout/TrailingEmptyLines: + Enabled: true + +# No trailing whitespace. +Layout/TrailingWhitespace: + Enabled: false + +# Use quotes for string literals when they are enough. +Style/RedundantPercentQ: + Enabled: true + +# Align `end` with the matching keyword or starting expression except for +# assignments, where it should be aligned with the LHS. +Layout/EndAlignment: + Enabled: true + EnforcedStyleAlignWith: variable + AutoCorrect: true + +# Use my_method(my_arg) not my_method( my_arg ) or my_method my_arg. +Lint/RequireParentheses: + Enabled: true + +Style/RedundantReturn: + Enabled: true + AllowMultipleReturnValues: true + +Style/Semicolon: + Enabled: true + AllowAsExpressionSeparator: true diff --git a/samples/client/echo_api/ruby-typhoeus/.travis.yml b/samples/client/echo_api/ruby-typhoeus/.travis.yml new file mode 100644 index 000000000000..ef5d971f6be8 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/.travis.yml @@ -0,0 +1,11 @@ +language: ruby +cache: bundler +rvm: + - 2.7 + - 3.0 + - 3.1 +script: + - bundle install --path vendor/bundle + - bundle exec rspec + - gem build openapi_client.gemspec + - gem install ./openapi_client-1.0.0.gem diff --git a/samples/client/echo_api/ruby-typhoeus/Gemfile b/samples/client/echo_api/ruby-typhoeus/Gemfile new file mode 100644 index 000000000000..c2e3127cdcfe --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/Gemfile @@ -0,0 +1,9 @@ +source 'https://rubygems.org' + +gemspec + +group :development, :test do + gem 'rake', '~> 13.0.1' + gem 'pry-byebug' + gem 'rubocop', '~> 0.66.0' +end diff --git a/samples/client/echo_api/ruby-typhoeus/README.md b/samples/client/echo_api/ruby-typhoeus/README.md new file mode 100644 index 000000000000..cdaea764c1be --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/README.md @@ -0,0 +1,135 @@ +# openapi_client + +OpenapiClient - the Ruby gem for the Echo Server API + +Echo Server API + +This SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 0.1.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.RubyClientCodegen + +## Installation + +### Build a gem + +To build the Ruby code into a gem: + +```shell +gem build openapi_client.gemspec +``` + +Then either install the gem locally: + +```shell +gem install ./openapi_client-1.0.0.gem +``` + +(for development, run `gem install --dev ./openapi_client-1.0.0.gem` to install the development dependencies) + +or publish the gem to a gem hosting service, e.g. [RubyGems](https://rubygems.org/). + +Finally add this to the Gemfile: + + gem 'openapi_client', '~> 1.0.0' + +### Install from Git + +If the Ruby gem is hosted at a git repository: https://github.com/GIT_USER_ID/GIT_REPO_ID, then add the following in the Gemfile: + + gem 'openapi_client', :git => 'https://github.com/GIT_USER_ID/GIT_REPO_ID.git' + +### Include the Ruby code directly + +Include the Ruby code directly using `-I` as follows: + +```shell +ruby -Ilib script.rb +``` + +## Getting Started + +Please follow the [installation](#installation) procedure and then run the following code: + +```ruby +# Load the gem +require 'openapi_client' + +# Setup authorization +OpenapiClient.configure do |config| + # Configure HTTP basic authorization: http_auth + config.username = 'YOUR_USERNAME' + config.password = 'YOUR_PASSWORD' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + #To test HTTP basic authentication + result = api_instance.test_auth_http_basic + p result +rescue OpenapiClient::ApiError => e + puts "Exception when calling AuthApi->test_auth_http_basic: #{e}" +end + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost:3000* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*OpenapiClient::AuthApi* | [**test_auth_http_basic**](docs/AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication +*OpenapiClient::AuthApi* | [**test_auth_http_bearer**](docs/AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication +*OpenapiClient::BodyApi* | [**test_binary_gif**](docs/BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body +*OpenapiClient::BodyApi* | [**test_body_application_octetstream_binary**](docs/BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_body_multipart_formdata_array_of_binary**](docs/BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime +*OpenapiClient::BodyApi* | [**test_body_multipart_formdata_single_binary**](docs/BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime +*OpenapiClient::BodyApi* | [**test_echo_body_all_of_pet**](docs/BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_echo_body_free_form_object_response_string**](docs/BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object +*OpenapiClient::BodyApi* | [**test_echo_body_pet**](docs/BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) +*OpenapiClient::BodyApi* | [**test_echo_body_pet_response_string**](docs/BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body +*OpenapiClient::BodyApi* | [**test_echo_body_tag_response_string**](docs/BodyApi.md#test_echo_body_tag_response_string) | **POST** /echo/body/Tag/response_string | Test empty json (request body) +*OpenapiClient::FormApi* | [**test_form_integer_boolean_string**](docs/FormApi.md#test_form_integer_boolean_string) | **POST** /form/integer/boolean/string | Test form parameter(s) +*OpenapiClient::FormApi* | [**test_form_oneof**](docs/FormApi.md#test_form_oneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema +*OpenapiClient::HeaderApi* | [**test_header_integer_boolean_string_enums**](docs/HeaderApi.md#test_header_integer_boolean_string_enums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) +*OpenapiClient::PathApi* | [**tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path**](docs/PathApi.md#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) +*OpenapiClient::QueryApi* | [**test_enum_ref_string**](docs/QueryApi.md#test_enum_ref_string) | **GET** /query/enum_ref_string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_datetime_date_string**](docs/QueryApi.md#test_query_datetime_date_string) | **GET** /query/datetime/date/string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_integer_boolean_string**](docs/QueryApi.md#test_query_integer_boolean_string) | **GET** /query/integer/boolean/string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_deep_object_explode_true_object**](docs/QueryApi.md#test_query_style_deep_object_explode_true_object) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_deep_object_explode_true_object_all_of**](docs/QueryApi.md#test_query_style_deep_object_explode_true_object_all_of) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_array_string**](docs/QueryApi.md#test_query_style_form_explode_true_array_string) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_object**](docs/QueryApi.md#test_query_style_form_explode_true_object) | **GET** /query/style_form/explode_true/object | Test query parameter(s) +*OpenapiClient::QueryApi* | [**test_query_style_form_explode_true_object_all_of**](docs/QueryApi.md#test_query_style_form_explode_true_object_all_of) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) + + +## Documentation for Models + + - [OpenapiClient::Bird](docs/Bird.md) + - [OpenapiClient::Category](docs/Category.md) + - [OpenapiClient::DataQuery](docs/DataQuery.md) + - [OpenapiClient::DefaultValue](docs/DefaultValue.md) + - [OpenapiClient::NumberPropertiesOnly](docs/NumberPropertiesOnly.md) + - [OpenapiClient::Pet](docs/Pet.md) + - [OpenapiClient::Query](docs/Query.md) + - [OpenapiClient::StringEnumRef](docs/StringEnumRef.md) + - [OpenapiClient::Tag](docs/Tag.md) + - [OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter](docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md) + - [OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter](docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md) + + +## Documentation for Authorization + + +Authentication schemes defined for the API: +### http_auth + +- **Type**: HTTP basic authentication + +### http_bearer_auth + +- **Type**: Bearer authentication + diff --git a/samples/client/echo_api/ruby-typhoeus/Rakefile b/samples/client/echo_api/ruby-typhoeus/Rakefile new file mode 100644 index 000000000000..c72ca30d454e --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/Rakefile @@ -0,0 +1,10 @@ +require "bundler/gem_tasks" + +begin + require 'rspec/core/rake_task' + + RSpec::Core::RakeTask.new(:spec) + task default: :spec +rescue LoadError + # no rspec available +end diff --git a/samples/client/echo_api/ruby-typhoeus/docs/AuthApi.md b/samples/client/echo_api/ruby-typhoeus/docs/AuthApi.md new file mode 100644 index 000000000000..9d924e77375f --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/AuthApi.md @@ -0,0 +1,142 @@ +# OpenapiClient::AuthApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_auth_http_basic**](AuthApi.md#test_auth_http_basic) | **POST** /auth/http/basic | To test HTTP basic authentication | +| [**test_auth_http_bearer**](AuthApi.md#test_auth_http_bearer) | **POST** /auth/http/bearer | To test HTTP bearer authentication | + + +## test_auth_http_basic + +> String test_auth_http_basic + +To test HTTP basic authentication + +To test HTTP basic authentication + +### Examples + +```ruby +require 'time' +require 'openapi_client' +# setup authorization +OpenapiClient.configure do |config| + # Configure HTTP basic authorization: http_auth + config.username = 'YOUR USERNAME' + config.password = 'YOUR PASSWORD' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + # To test HTTP basic authentication + result = api_instance.test_auth_http_basic + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_basic: #{e}" +end +``` + +#### Using the test_auth_http_basic_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_auth_http_basic_with_http_info + +```ruby +begin + # To test HTTP basic authentication + data, status_code, headers = api_instance.test_auth_http_basic_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_basic_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_auth](../README.md#http_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_auth_http_bearer + +> String test_auth_http_bearer + +To test HTTP bearer authentication + +To test HTTP bearer authentication + +### Examples + +```ruby +require 'time' +require 'openapi_client' +# setup authorization +OpenapiClient.configure do |config| + # Configure Bearer authorization: http_bearer_auth + config.access_token = 'YOUR_BEARER_TOKEN' +end + +api_instance = OpenapiClient::AuthApi.new + +begin + # To test HTTP bearer authentication + result = api_instance.test_auth_http_bearer + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer: #{e}" +end +``` + +#### Using the test_auth_http_bearer_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_auth_http_bearer_with_http_info + +```ruby +begin + # To test HTTP bearer authentication + data, status_code, headers = api_instance.test_auth_http_bearer_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling AuthApi->test_auth_http_bearer_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +[http_bearer_auth](../README.md#http_bearer_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/Bird.md b/samples/client/echo_api/ruby-typhoeus/docs/Bird.md new file mode 100644 index 000000000000..53207a9a2f10 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/Bird.md @@ -0,0 +1,20 @@ +# OpenapiClient::Bird + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **size** | **String** | | [optional] | +| **color** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Bird.new( + size: null, + color: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/BodyApi.md b/samples/client/echo_api/ruby-typhoeus/docs/BodyApi.md new file mode 100644 index 000000000000..f5d6d57479e9 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/BodyApi.md @@ -0,0 +1,603 @@ +# OpenapiClient::BodyApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_binary_gif**](BodyApi.md#test_binary_gif) | **POST** /binary/gif | Test binary (gif) response body | +| [**test_body_application_octetstream_binary**](BodyApi.md#test_body_application_octetstream_binary) | **POST** /body/application/octetstream/binary | Test body parameter(s) | +| [**test_body_multipart_formdata_array_of_binary**](BodyApi.md#test_body_multipart_formdata_array_of_binary) | **POST** /body/application/octetstream/array_of_binary | Test array of binary in multipart mime | +| [**test_body_multipart_formdata_single_binary**](BodyApi.md#test_body_multipart_formdata_single_binary) | **POST** /body/application/octetstream/single_binary | Test single binary in multipart mime | +| [**test_echo_body_all_of_pet**](BodyApi.md#test_echo_body_all_of_pet) | **POST** /echo/body/allOf/Pet | Test body parameter(s) | +| [**test_echo_body_free_form_object_response_string**](BodyApi.md#test_echo_body_free_form_object_response_string) | **POST** /echo/body/FreeFormObject/response_string | Test free form object | +| [**test_echo_body_pet**](BodyApi.md#test_echo_body_pet) | **POST** /echo/body/Pet | Test body parameter(s) | +| [**test_echo_body_pet_response_string**](BodyApi.md#test_echo_body_pet_response_string) | **POST** /echo/body/Pet/response_string | Test empty response body | +| [**test_echo_body_tag_response_string**](BodyApi.md#test_echo_body_tag_response_string) | **POST** /echo/body/Tag/response_string | Test empty json (request body) | + + +## test_binary_gif + +> File test_binary_gif + +Test binary (gif) response body + +Test binary (gif) response body + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new + +begin + # Test binary (gif) response body + result = api_instance.test_binary_gif + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_binary_gif: #{e}" +end +``` + +#### Using the test_binary_gif_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_binary_gif_with_http_info + +```ruby +begin + # Test binary (gif) response body + data, status_code, headers = api_instance.test_binary_gif_with_http_info + p status_code # => 2xx + p headers # => { ... } + p data # => File +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_binary_gif_with_http_info: #{e}" +end +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**File** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: image/gif + + +## test_body_application_octetstream_binary + +> String test_body_application_octetstream_binary(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + body: File.new('/path/to/some/file') # File | +} + +begin + # Test body parameter(s) + result = api_instance.test_body_application_octetstream_binary(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_application_octetstream_binary: #{e}" +end +``` + +#### Using the test_body_application_octetstream_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_application_octetstream_binary_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_body_application_octetstream_binary_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_application_octetstream_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **File** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/octet-stream +- **Accept**: text/plain + + +## test_body_multipart_formdata_array_of_binary + +> String test_body_multipart_formdata_array_of_binary(files) + +Test array of binary in multipart mime + +Test array of binary in multipart mime + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +files = [File.new('/path/to/some/file')] # Array | + +begin + # Test array of binary in multipart mime + result = api_instance.test_body_multipart_formdata_array_of_binary(files) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_array_of_binary: #{e}" +end +``` + +#### Using the test_body_multipart_formdata_array_of_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_multipart_formdata_array_of_binary_with_http_info(files) + +```ruby +begin + # Test array of binary in multipart mime + data, status_code, headers = api_instance.test_body_multipart_formdata_array_of_binary_with_http_info(files) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_array_of_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **files** | **Array<File>** | | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +## test_body_multipart_formdata_single_binary + +> String test_body_multipart_formdata_single_binary(opts) + +Test single binary in multipart mime + +Test single binary in multipart mime + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + my_file: File.new('/path/to/some/file') # File | +} + +begin + # Test single binary in multipart mime + result = api_instance.test_body_multipart_formdata_single_binary(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary: #{e}" +end +``` + +#### Using the test_body_multipart_formdata_single_binary_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_body_multipart_formdata_single_binary_with_http_info(opts) + +```ruby +begin + # Test single binary in multipart mime + data, status_code, headers = api_instance.test_body_multipart_formdata_single_binary_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_body_multipart_formdata_single_binary_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **my_file** | **File** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: text/plain + + +## test_echo_body_all_of_pet + +> test_echo_body_all_of_pet(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test body parameter(s) + result = api_instance.test_echo_body_all_of_pet(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet: #{e}" +end +``` + +#### Using the test_echo_body_all_of_pet_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_echo_body_all_of_pet_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_echo_body_all_of_pet_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_all_of_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## test_echo_body_free_form_object_response_string + +> String test_echo_body_free_form_object_response_string(opts) + +Test free form object + +Test free form object + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + body: { ... } # Object | Free form object +} + +begin + # Test free form object + result = api_instance.test_echo_body_free_form_object_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_free_form_object_response_string: #{e}" +end +``` + +#### Using the test_echo_body_free_form_object_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_free_form_object_response_string_with_http_info(opts) + +```ruby +begin + # Test free form object + data, status_code, headers = api_instance.test_echo_body_free_form_object_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_free_form_object_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **body** | **Object** | Free form object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +## test_echo_body_pet + +> test_echo_body_pet(opts) + +Test body parameter(s) + +Test body parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test body parameter(s) + result = api_instance.test_echo_body_pet(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet: #{e}" +end +``` + +#### Using the test_echo_body_pet_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> , Integer, Hash)> test_echo_body_pet_with_http_info(opts) + +```ruby +begin + # Test body parameter(s) + data, status_code, headers = api_instance.test_echo_body_pet_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/json + + +## test_echo_body_pet_response_string + +> String test_echo_body_pet_response_string(opts) + +Test empty response body + +Test empty response body + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + pet: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | Pet object that needs to be added to the store +} + +begin + # Test empty response body + result = api_instance.test_echo_body_pet_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_response_string: #{e}" +end +``` + +#### Using the test_echo_body_pet_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_pet_response_string_with_http_info(opts) + +```ruby +begin + # Test empty response body + data, status_code, headers = api_instance.test_echo_body_pet_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_pet_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + + +## test_echo_body_tag_response_string + +> String test_echo_body_tag_response_string(opts) + +Test empty json (request body) + +Test empty json (request body) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::BodyApi.new +opts = { + tag: OpenapiClient::Tag.new # Tag | Tag object +} + +begin + # Test empty json (request body) + result = api_instance.test_echo_body_tag_response_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_tag_response_string: #{e}" +end +``` + +#### Using the test_echo_body_tag_response_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_echo_body_tag_response_string_with_http_info(opts) + +```ruby +begin + # Test empty json (request body) + data, status_code, headers = api_instance.test_echo_body_tag_response_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling BodyApi->test_echo_body_tag_response_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **tag** | [**Tag**](Tag.md) | Tag object | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/Category.md b/samples/client/echo_api/ruby-typhoeus/docs/Category.md new file mode 100644 index 000000000000..17adafbed759 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/Category.md @@ -0,0 +1,20 @@ +# OpenapiClient::Category + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Category.new( + id: 1, + name: Dogs +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/DataQuery.md b/samples/client/echo_api/ruby-typhoeus/docs/DataQuery.md new file mode 100644 index 000000000000..2ef4c6b1a0d6 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/DataQuery.md @@ -0,0 +1,22 @@ +# OpenapiClient::DataQuery + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **suffix** | **String** | test suffix | [optional] | +| **text** | **String** | Some text containing white spaces | [optional] | +| **date** | **Time** | A date | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::DataQuery.new( + suffix: null, + text: Some text, + date: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/DefaultValue.md b/samples/client/echo_api/ruby-typhoeus/docs/DefaultValue.md new file mode 100644 index 000000000000..72736b7608dc --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/DefaultValue.md @@ -0,0 +1,32 @@ +# OpenapiClient::DefaultValue + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **array_string_enum_ref_default** | [**Array<StringEnumRef>**](StringEnumRef.md) | | [optional] | +| **array_string_enum_default** | **Array<String>** | | [optional] | +| **array_string_default** | **Array<String>** | | [optional] | +| **array_integer_default** | **Array<Integer>** | | [optional] | +| **array_string** | **Array<String>** | | [optional] | +| **array_string_nullable** | **Array<String>** | | [optional] | +| **array_string_extension_nullable** | **Array<String>** | | [optional] | +| **string_nullable** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::DefaultValue.new( + array_string_enum_ref_default: null, + array_string_enum_default: null, + array_string_default: null, + array_integer_default: null, + array_string: null, + array_string_nullable: null, + array_string_extension_nullable: null, + string_nullable: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/FormApi.md b/samples/client/echo_api/ruby-typhoeus/docs/FormApi.md new file mode 100644 index 000000000000..632949e8b808 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/FormApi.md @@ -0,0 +1,155 @@ +# OpenapiClient::FormApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_form_integer_boolean_string**](FormApi.md#test_form_integer_boolean_string) | **POST** /form/integer/boolean/string | Test form parameter(s) | +| [**test_form_oneof**](FormApi.md#test_form_oneof) | **POST** /form/oneof | Test form parameter(s) for oneOf schema | + + +## test_form_integer_boolean_string + +> String test_form_integer_boolean_string(opts) + +Test form parameter(s) + +Test form parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::FormApi.new +opts = { + integer_form: 56, # Integer | + boolean_form: true, # Boolean | + string_form: 'string_form_example' # String | +} + +begin + # Test form parameter(s) + result = api_instance.test_form_integer_boolean_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_integer_boolean_string: #{e}" +end +``` + +#### Using the test_form_integer_boolean_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_form_integer_boolean_string_with_http_info(opts) + +```ruby +begin + # Test form parameter(s) + data, status_code, headers = api_instance.test_form_integer_boolean_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_integer_boolean_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_form** | **Integer** | | [optional] | +| **boolean_form** | **Boolean** | | [optional] | +| **string_form** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + + +## test_form_oneof + +> String test_form_oneof(opts) + +Test form parameter(s) for oneOf schema + +Test form parameter(s) for oneOf schema + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::FormApi.new +opts = { + form1: 'form1_example', # String | + form2: 56, # Integer | + form3: 'form3_example', # String | + form4: true, # Boolean | + id: 789, # Integer | + name: 'name_example' # String | +} + +begin + # Test form parameter(s) for oneOf schema + result = api_instance.test_form_oneof(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_oneof: #{e}" +end +``` + +#### Using the test_form_oneof_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_form_oneof_with_http_info(opts) + +```ruby +begin + # Test form parameter(s) for oneOf schema + data, status_code, headers = api_instance.test_form_oneof_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling FormApi->test_form_oneof_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **form1** | **String** | | [optional] | +| **form2** | **Integer** | | [optional] | +| **form3** | **String** | | [optional] | +| **form4** | **Boolean** | | [optional] | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/HeaderApi.md b/samples/client/echo_api/ruby-typhoeus/docs/HeaderApi.md new file mode 100644 index 000000000000..cb350e92a9c8 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/HeaderApi.md @@ -0,0 +1,82 @@ +# OpenapiClient::HeaderApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_header_integer_boolean_string_enums**](HeaderApi.md#test_header_integer_boolean_string_enums) | **GET** /header/integer/boolean/string/enums | Test header parameter(s) | + + +## test_header_integer_boolean_string_enums + +> String test_header_integer_boolean_string_enums(opts) + +Test header parameter(s) + +Test header parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::HeaderApi.new +opts = { + integer_header: 56, # Integer | + boolean_header: true, # Boolean | + string_header: 'string_header_example', # String | + enum_nonref_string_header: 'success', # String | + enum_ref_string_header: OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | +} + +begin + # Test header parameter(s) + result = api_instance.test_header_integer_boolean_string_enums(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling HeaderApi->test_header_integer_boolean_string_enums: #{e}" +end +``` + +#### Using the test_header_integer_boolean_string_enums_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_header_integer_boolean_string_enums_with_http_info(opts) + +```ruby +begin + # Test header parameter(s) + data, status_code, headers = api_instance.test_header_integer_boolean_string_enums_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling HeaderApi->test_header_integer_boolean_string_enums_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_header** | **Integer** | | [optional] | +| **boolean_header** | **Boolean** | | [optional] | +| **string_header** | **String** | | [optional] | +| **enum_nonref_string_header** | **String** | | [optional] | +| **enum_ref_string_header** | [**StringEnumRef**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/NumberPropertiesOnly.md b/samples/client/echo_api/ruby-typhoeus/docs/NumberPropertiesOnly.md new file mode 100644 index 000000000000..5040bff00ddd --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/NumberPropertiesOnly.md @@ -0,0 +1,22 @@ +# OpenapiClient::NumberPropertiesOnly + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **number** | **Float** | | [optional] | +| **float** | **Float** | | [optional] | +| **double** | **Float** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::NumberPropertiesOnly.new( + number: null, + float: null, + double: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/PathApi.md b/samples/client/echo_api/ruby-typhoeus/docs/PathApi.md new file mode 100644 index 000000000000..fdaf80f85704 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/PathApi.md @@ -0,0 +1,78 @@ +# OpenapiClient::PathApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path**](PathApi.md#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path) | **GET** /path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path} | Test path parameter(s) | + + +## tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path + +> String tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + +Test path parameter(s) + +Test path parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::PathApi.new +path_string = 'path_string_example' # String | +path_integer = 56 # Integer | +enum_nonref_string_path = 'success' # String | +enum_ref_string_path = OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | + +begin + # Test path parameter(s) + result = api_instance.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling PathApi->tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path: #{e}" +end +``` + +#### Using the tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + +```ruby +begin + # Test path parameter(s) + data, status_code, headers = api_instance.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling PathApi->tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **path_string** | **String** | | | +| **path_integer** | **Integer** | | | +| **enum_nonref_string_path** | **String** | | | +| **enum_ref_string_path** | [**StringEnumRef**](.md) | | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/Pet.md b/samples/client/echo_api/ruby-typhoeus/docs/Pet.md new file mode 100644 index 000000000000..817b46ce714a --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/Pet.md @@ -0,0 +1,28 @@ +# OpenapiClient::Pet + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | | +| **category** | [**Category**](Category.md) | | [optional] | +| **photo_urls** | **Array<String>** | | | +| **tags** | [**Array<Tag>**](Tag.md) | | [optional] | +| **status** | **String** | pet status in the store | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Pet.new( + id: 10, + name: doggie, + category: null, + photo_urls: null, + tags: null, + status: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/Query.md b/samples/client/echo_api/ruby-typhoeus/docs/Query.md new file mode 100644 index 000000000000..e7b670a033da --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/Query.md @@ -0,0 +1,20 @@ +# OpenapiClient::Query + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | Query | [optional] | +| **outcomes** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Query.new( + id: null, + outcomes: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/QueryApi.md b/samples/client/echo_api/ruby-typhoeus/docs/QueryApi.md new file mode 100644 index 000000000000..2dd28c34060b --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/QueryApi.md @@ -0,0 +1,553 @@ +# OpenapiClient::QueryApi + +All URIs are relative to *http://localhost:3000* + +| Method | HTTP request | Description | +| ------ | ------------ | ----------- | +| [**test_enum_ref_string**](QueryApi.md#test_enum_ref_string) | **GET** /query/enum_ref_string | Test query parameter(s) | +| [**test_query_datetime_date_string**](QueryApi.md#test_query_datetime_date_string) | **GET** /query/datetime/date/string | Test query parameter(s) | +| [**test_query_integer_boolean_string**](QueryApi.md#test_query_integer_boolean_string) | **GET** /query/integer/boolean/string | Test query parameter(s) | +| [**test_query_style_deep_object_explode_true_object**](QueryApi.md#test_query_style_deep_object_explode_true_object) | **GET** /query/style_deepObject/explode_true/object | Test query parameter(s) | +| [**test_query_style_deep_object_explode_true_object_all_of**](QueryApi.md#test_query_style_deep_object_explode_true_object_all_of) | **GET** /query/style_deepObject/explode_true/object/allOf | Test query parameter(s) | +| [**test_query_style_form_explode_true_array_string**](QueryApi.md#test_query_style_form_explode_true_array_string) | **GET** /query/style_form/explode_true/array_string | Test query parameter(s) | +| [**test_query_style_form_explode_true_object**](QueryApi.md#test_query_style_form_explode_true_object) | **GET** /query/style_form/explode_true/object | Test query parameter(s) | +| [**test_query_style_form_explode_true_object_all_of**](QueryApi.md#test_query_style_form_explode_true_object_all_of) | **GET** /query/style_form/explode_true/object/allOf | Test query parameter(s) | + + +## test_enum_ref_string + +> String test_enum_ref_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + enum_nonref_string_query: 'success', # String | + enum_ref_string_query: OpenapiClient::StringEnumRef::SUCCESS # StringEnumRef | +} + +begin + # Test query parameter(s) + result = api_instance.test_enum_ref_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_enum_ref_string: #{e}" +end +``` + +#### Using the test_enum_ref_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_enum_ref_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_enum_ref_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_enum_ref_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **enum_nonref_string_query** | **String** | | [optional] | +| **enum_ref_string_query** | [**StringEnumRef**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_datetime_date_string + +> String test_query_datetime_date_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + datetime_query: Time.parse('2013-10-20T19:20:30+01:00'), # Time | + date_query: Date.parse('2013-10-20'), # Date | + string_query: 'string_query_example' # String | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_datetime_date_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_datetime_date_string: #{e}" +end +``` + +#### Using the test_query_datetime_date_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_datetime_date_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_datetime_date_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_datetime_date_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **datetime_query** | **Time** | | [optional] | +| **date_query** | **Date** | | [optional] | +| **string_query** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_integer_boolean_string + +> String test_query_integer_boolean_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + integer_query: 56, # Integer | + boolean_query: true, # Boolean | + string_query: 'string_query_example' # String | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_integer_boolean_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_integer_boolean_string: #{e}" +end +``` + +#### Using the test_query_integer_boolean_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_integer_boolean_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_integer_boolean_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_integer_boolean_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **integer_query** | **Integer** | | [optional] | +| **boolean_query** | **Boolean** | | [optional] | +| **string_query** | **String** | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_deep_object_explode_true_object + +> String test_query_style_deep_object_explode_true_object(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_deep_object_explode_true_object(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object: #{e}" +end +``` + +#### Using the test_query_style_deep_object_explode_true_object_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_deep_object_explode_true_object_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_deep_object_explode_true_object_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**Pet**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_deep_object_explode_true_object_all_of + +> String test_query_style_deep_object_explode_true_object_all_of(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new # TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_deep_object_explode_true_object_all_of(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_all_of: #{e}" +end +``` + +#### Using the test_query_style_deep_object_explode_true_object_all_of_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_deep_object_explode_true_object_all_of_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_array_string + +> String test_query_style_form_explode_true_array_string(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new # TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_array_string(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_array_string: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_array_string_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_array_string_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_array_string_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_array_string_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_object + +> String test_query_style_form_explode_true_object(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::Pet.new({name: 'doggie', photo_urls: ['photo_urls_example']}) # Pet | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_object(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_object_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_object_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_object_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**Pet**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + + +## test_query_style_form_explode_true_object_all_of + +> String test_query_style_form_explode_true_object_all_of(opts) + +Test query parameter(s) + +Test query parameter(s) + +### Examples + +```ruby +require 'time' +require 'openapi_client' + +api_instance = OpenapiClient::QueryApi.new +opts = { + query_object: OpenapiClient::DataQuery.new # DataQuery | +} + +begin + # Test query parameter(s) + result = api_instance.test_query_style_form_explode_true_object_all_of(opts) + p result +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_all_of: #{e}" +end +``` + +#### Using the test_query_style_form_explode_true_object_all_of_with_http_info variant + +This returns an Array which contains the response data, status code and headers. + +> test_query_style_form_explode_true_object_all_of_with_http_info(opts) + +```ruby +begin + # Test query parameter(s) + data, status_code, headers = api_instance.test_query_style_form_explode_true_object_all_of_with_http_info(opts) + p status_code # => 2xx + p headers # => { ... } + p data # => String +rescue OpenapiClient::ApiError => e + puts "Error when calling QueryApi->test_query_style_form_explode_true_object_all_of_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **query_object** | [**DataQuery**](.md) | | [optional] | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: text/plain + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/StringEnumRef.md b/samples/client/echo_api/ruby-typhoeus/docs/StringEnumRef.md new file mode 100644 index 000000000000..169bcb44d76f --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/StringEnumRef.md @@ -0,0 +1,15 @@ +# OpenapiClient::StringEnumRef + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::StringEnumRef.new() +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/Tag.md b/samples/client/echo_api/ruby-typhoeus/docs/Tag.md new file mode 100644 index 000000000000..d3bcb5933abd --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/Tag.md @@ -0,0 +1,20 @@ +# OpenapiClient::Tag + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::Tag.new( + id: null, + name: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md b/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md new file mode 100644 index 000000000000..a0f7cd16fe86 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.md @@ -0,0 +1,24 @@ +# OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **size** | **String** | | [optional] | +| **color** | **String** | | [optional] | +| **id** | **Integer** | | [optional] | +| **name** | **String** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new( + size: null, + color: null, + id: 1, + name: Dogs +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md b/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md new file mode 100644 index 000000000000..b21365f8f3a8 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/docs/TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.md @@ -0,0 +1,18 @@ +# OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **values** | **Array<String>** | | [optional] | + +## Example + +```ruby +require 'openapi_client' + +instance = OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new( + values: null +) +``` + diff --git a/samples/client/echo_api/ruby-typhoeus/git_push.sh b/samples/client/echo_api/ruby-typhoeus/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client.rb new file mode 100644 index 000000000000..b91b0953227a --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client.rb @@ -0,0 +1,56 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +# Common files +require 'openapi_client/api_client' +require 'openapi_client/api_error' +require 'openapi_client/version' +require 'openapi_client/configuration' + +# Models +require 'openapi_client/models/bird' +require 'openapi_client/models/category' +require 'openapi_client/models/default_value' +require 'openapi_client/models/number_properties_only' +require 'openapi_client/models/pet' +require 'openapi_client/models/query' +require 'openapi_client/models/string_enum_ref' +require 'openapi_client/models/tag' +require 'openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter' +require 'openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter' +require 'openapi_client/models/data_query' + +# APIs +require 'openapi_client/api/auth_api' +require 'openapi_client/api/body_api' +require 'openapi_client/api/form_api' +require 'openapi_client/api/header_api' +require 'openapi_client/api/path_api' +require 'openapi_client/api/query_api' + +module OpenapiClient + class << self + # Customize default settings for the SDK using block. + # OpenapiClient.configure do |config| + # config.username = "xxx" + # config.password = "xxx" + # end + # If no block given, return the default Configuration object. + def configure + if block_given? + yield(Configuration.default) + else + Configuration.default + end + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/auth_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/auth_api.rb new file mode 100644 index 000000000000..74395866bb1e --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/auth_api.rb @@ -0,0 +1,136 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class AuthApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [String] + def test_auth_http_basic(opts = {}) + data, _status_code, _headers = test_auth_http_basic_with_http_info(opts) + data + end + + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_auth_http_basic_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AuthApi.test_auth_http_basic ...' + end + # resource path + local_var_path = '/auth/http/basic' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_auth'] + + new_options = opts.merge( + :operation => :"AuthApi.test_auth_http_basic", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AuthApi#test_auth_http_basic\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [String] + def test_auth_http_bearer(opts = {}) + data, _status_code, _headers = test_auth_http_bearer_with_http_info(opts) + data + end + + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_auth_http_bearer_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: AuthApi.test_auth_http_bearer ...' + end + # resource path + local_var_path = '/auth/http/bearer' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || ['http_bearer_auth'] + + new_options = opts.merge( + :operation => :"AuthApi.test_auth_http_bearer", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: AuthApi#test_auth_http_bearer\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/body_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/body_api.rb new file mode 100644 index 000000000000..16dc16b730bd --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/body_api.rb @@ -0,0 +1,597 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class BodyApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [File] + def test_binary_gif(opts = {}) + data, _status_code, _headers = test_binary_gif_with_http_info(opts) + data + end + + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [Array<(File, Integer, Hash)>] File data, response status code and response headers + def test_binary_gif_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_binary_gif ...' + end + # resource path + local_var_path = '/binary/gif' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['image/gif']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'File' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_binary_gif", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_binary_gif\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [String] + def test_body_application_octetstream_binary(opts = {}) + data, _status_code, _headers = test_body_application_octetstream_binary_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_application_octetstream_binary_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_application_octetstream_binary ...' + end + # resource path + local_var_path = '/body/application/octetstream/binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/octet-stream']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_application_octetstream_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_application_octetstream_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files [Array] + # @param [Hash] opts the optional parameters + # @return [String] + def test_body_multipart_formdata_array_of_binary(files, opts = {}) + data, _status_code, _headers = test_body_multipart_formdata_array_of_binary_with_http_info(files, opts) + data + end + + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files [Array] + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_multipart_formdata_array_of_binary_with_http_info(files, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_multipart_formdata_array_of_binary ...' + end + # verify the required parameter 'files' is set + if @api_client.config.client_side_validation && files.nil? + fail ArgumentError, "Missing the required parameter 'files' when calling BodyApi.test_body_multipart_formdata_array_of_binary" + end + # resource path + local_var_path = '/body/application/octetstream/array_of_binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['files'] = @api_client.build_collection_param(files, :csv) + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_multipart_formdata_array_of_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_multipart_formdata_array_of_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [String] + def test_body_multipart_formdata_single_binary(opts = {}) + data, _status_code, _headers = test_body_multipart_formdata_single_binary_with_http_info(opts) + data + end + + # Test single binary in multipart mime + # Test single binary in multipart mime + # @param [Hash] opts the optional parameters + # @option opts [File] :my_file + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_body_multipart_formdata_single_binary_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_body_multipart_formdata_single_binary ...' + end + # resource path + local_var_path = '/body/application/octetstream/single_binary' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['multipart/form-data']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['my-file'] = opts[:'my_file'] if !opts[:'my_file'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_body_multipart_formdata_single_binary", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_body_multipart_formdata_single_binary\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + def test_echo_body_all_of_pet(opts = {}) + data, _status_code, _headers = test_echo_body_all_of_pet_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def test_echo_body_all_of_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_all_of_pet ...' + end + # resource path + local_var_path = '/echo/body/allOf/Pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_all_of_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_all_of_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [String] + def test_echo_body_free_form_object_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_free_form_object_response_string_with_http_info(opts) + data + end + + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_free_form_object_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_free_form_object_response_string ...' + end + # resource path + local_var_path = '/echo/body/FreeFormObject/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'body']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_free_form_object_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_free_form_object_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + def test_echo_body_pet(opts = {}) + data, _status_code, _headers = test_echo_body_pet_with_http_info(opts) + data + end + + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(Pet, Integer, Hash)>] Pet data, response status code and response headers + def test_echo_body_pet_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_pet ...' + end + # resource path + local_var_path = '/echo/body/Pet' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['application/json']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'Pet' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_pet", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_pet\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [String] + def test_echo_body_pet_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_pet_response_string_with_http_info(opts) + data + end + + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_pet_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_pet_response_string ...' + end + # resource path + local_var_path = '/echo/body/Pet/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'pet']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_pet_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_pet_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [String] + def test_echo_body_tag_response_string(opts = {}) + data, _status_code, _headers = test_echo_body_tag_response_string_with_http_info(opts) + data + end + + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_echo_body_tag_response_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: BodyApi.test_echo_body_tag_response_string ...' + end + # resource path + local_var_path = '/echo/body/Tag/response_string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(opts[:'tag']) + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"BodyApi.test_echo_body_tag_response_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: BodyApi#test_echo_body_tag_response_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/form_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/form_api.rb new file mode 100644 index 000000000000..04147499b1b0 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/form_api.rb @@ -0,0 +1,173 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class FormApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [String] + def test_form_integer_boolean_string(opts = {}) + data, _status_code, _headers = test_form_integer_boolean_string_with_http_info(opts) + data + end + + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_form_integer_boolean_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FormApi.test_form_integer_boolean_string ...' + end + # resource path + local_var_path = '/form/integer/boolean/string' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['integer_form'] = opts[:'integer_form'] if !opts[:'integer_form'].nil? + form_params['boolean_form'] = opts[:'boolean_form'] if !opts[:'boolean_form'].nil? + form_params['string_form'] = opts[:'string_form'] if !opts[:'string_form'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FormApi.test_form_integer_boolean_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FormApi#test_form_integer_boolean_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [String] + def test_form_oneof(opts = {}) + data, _status_code, _headers = test_form_oneof_with_http_info(opts) + data + end + + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_form_oneof_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FormApi.test_form_oneof ...' + end + # resource path + local_var_path = '/form/oneof' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/x-www-form-urlencoded']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + form_params['form1'] = opts[:'form1'] if !opts[:'form1'].nil? + form_params['form2'] = opts[:'form2'] if !opts[:'form2'].nil? + form_params['form3'] = opts[:'form3'] if !opts[:'form3'].nil? + form_params['form4'] = opts[:'form4'] if !opts[:'form4'].nil? + form_params['id'] = opts[:'id'] if !opts[:'id'].nil? + form_params['name'] = opts[:'name'] if !opts[:'name'].nil? + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FormApi.test_form_oneof", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FormApi#test_form_oneof\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/header_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/header_api.rb new file mode 100644 index 000000000000..239edb742474 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/header_api.rb @@ -0,0 +1,98 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class HeaderApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [String] + def test_header_integer_boolean_string_enums(opts = {}) + data, _status_code, _headers = test_header_integer_boolean_string_enums_with_http_info(opts) + data + end + + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_header_integer_boolean_string_enums_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: HeaderApi.test_header_integer_boolean_string_enums ...' + end + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && opts[:'enum_nonref_string_header'] && !allowable_values.include?(opts[:'enum_nonref_string_header']) + fail ArgumentError, "invalid value for \"enum_nonref_string_header\", must be one of #{allowable_values}" + end + # resource path + local_var_path = '/header/integer/boolean/string/enums' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + header_params['integer_header'] = opts[:'integer_header'] if !opts[:'integer_header'].nil? + header_params['boolean_header'] = opts[:'boolean_header'] if !opts[:'boolean_header'].nil? + header_params['string_header'] = opts[:'string_header'] if !opts[:'string_header'].nil? + header_params['enum_nonref_string_header'] = opts[:'enum_nonref_string_header'] if !opts[:'enum_nonref_string_header'].nil? + header_params['enum_ref_string_header'] = opts[:'enum_ref_string_header'] if !opts[:'enum_ref_string_header'].nil? + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"HeaderApi.test_header_integer_boolean_string_enums", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: HeaderApi#test_header_integer_boolean_string_enums\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/path_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/path_api.rb new file mode 100644 index 000000000000..4d4838371838 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/path_api.rb @@ -0,0 +1,108 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class PathApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test path parameter(s) + # Test path parameter(s) + # @param path_string [String] + # @param path_integer [Integer] + # @param enum_nonref_string_path [String] + # @param enum_ref_string_path [StringEnumRef] + # @param [Hash] opts the optional parameters + # @return [String] + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts = {}) + data, _status_code, _headers = tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts) + data + end + + # Test path parameter(s) + # Test path parameter(s) + # @param path_string [String] + # @param path_integer [Integer] + # @param enum_nonref_string_path [String] + # @param enum_ref_string_path [StringEnumRef] + # @param [Hash] opts the optional parameters + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path_with_http_info(path_string, path_integer, enum_nonref_string_path, enum_ref_string_path, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path ...' + end + # verify the required parameter 'path_string' is set + if @api_client.config.client_side_validation && path_string.nil? + fail ArgumentError, "Missing the required parameter 'path_string' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify the required parameter 'path_integer' is set + if @api_client.config.client_side_validation && path_integer.nil? + fail ArgumentError, "Missing the required parameter 'path_integer' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify the required parameter 'enum_nonref_string_path' is set + if @api_client.config.client_side_validation && enum_nonref_string_path.nil? + fail ArgumentError, "Missing the required parameter 'enum_nonref_string_path' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # verify enum value + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && !allowable_values.include?(enum_nonref_string_path) + fail ArgumentError, "invalid value for \"enum_nonref_string_path\", must be one of #{allowable_values}" + end + # verify the required parameter 'enum_ref_string_path' is set + if @api_client.config.client_side_validation && enum_ref_string_path.nil? + fail ArgumentError, "Missing the required parameter 'enum_ref_string_path' when calling PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path" + end + # resource path + local_var_path = '/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}'.sub('{' + 'path_string' + '}', CGI.escape(path_string.to_s)).sub('{' + 'path_integer' + '}', CGI.escape(path_integer.to_s)).sub('{' + 'enum_nonref_string_path' + '}', CGI.escape(enum_nonref_string_path.to_s)).sub('{' + 'enum_ref_string_path' + '}', CGI.escape(enum_ref_string_path.to_s)) + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"PathApi.tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: PathApi#tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/query_api.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/query_api.rb new file mode 100644 index 000000000000..5871d351e006 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api/query_api.rb @@ -0,0 +1,521 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'cgi' + +module OpenapiClient + class QueryApi + attr_accessor :api_client + + def initialize(api_client = ApiClient.default) + @api_client = api_client + end + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [String] + def test_enum_ref_string(opts = {}) + data, _status_code, _headers = test_enum_ref_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_enum_ref_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_enum_ref_string ...' + end + allowable_values = ["success", "failure", "unclassified"] + if @api_client.config.client_side_validation && opts[:'enum_nonref_string_query'] && !allowable_values.include?(opts[:'enum_nonref_string_query']) + fail ArgumentError, "invalid value for \"enum_nonref_string_query\", must be one of #{allowable_values}" + end + # resource path + local_var_path = '/query/enum_ref_string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'enum_nonref_string_query'] = opts[:'enum_nonref_string_query'] if !opts[:'enum_nonref_string_query'].nil? + query_params[:'enum_ref_string_query'] = opts[:'enum_ref_string_query'] if !opts[:'enum_ref_string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_enum_ref_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_enum_ref_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [String] + def test_query_datetime_date_string(opts = {}) + data, _status_code, _headers = test_query_datetime_date_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_datetime_date_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_datetime_date_string ...' + end + # resource path + local_var_path = '/query/datetime/date/string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'datetime_query'] = opts[:'datetime_query'] if !opts[:'datetime_query'].nil? + query_params[:'date_query'] = opts[:'date_query'] if !opts[:'date_query'].nil? + query_params[:'string_query'] = opts[:'string_query'] if !opts[:'string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_datetime_date_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_datetime_date_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [String] + def test_query_integer_boolean_string(opts = {}) + data, _status_code, _headers = test_query_integer_boolean_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_integer_boolean_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_integer_boolean_string ...' + end + # resource path + local_var_path = '/query/integer/boolean/string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'integer_query'] = opts[:'integer_query'] if !opts[:'integer_query'].nil? + query_params[:'boolean_query'] = opts[:'boolean_query'] if !opts[:'boolean_query'].nil? + query_params[:'string_query'] = opts[:'string_query'] if !opts[:'string_query'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_integer_boolean_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_integer_boolean_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + def test_query_style_deep_object_explode_true_object(opts = {}) + data, _status_code, _headers = test_query_style_deep_object_explode_true_object_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_deep_object_explode_true_object_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_deep_object_explode_true_object ...' + end + # resource path + local_var_path = '/query/style_deepObject/explode_true/object' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_deep_object_explode_true_object", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_deep_object_explode_true_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [String] + def test_query_style_deep_object_explode_true_object_all_of(opts = {}) + data, _status_code, _headers = test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_deep_object_explode_true_object_all_of_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_deep_object_explode_true_object_all_of ...' + end + # resource path + local_var_path = '/query/style_deepObject/explode_true/object/allOf' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_deep_object_explode_true_object_all_of", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_deep_object_explode_true_object_all_of\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [String] + def test_query_style_form_explode_true_array_string(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_array_string_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_array_string_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_array_string ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/array_string' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_array_string", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_array_string\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + def test_query_style_form_explode_true_object(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_object_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_object_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_object ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/object' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_object", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_object\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [String] + def test_query_style_form_explode_true_object_all_of(opts = {}) + data, _status_code, _headers = test_query_style_form_explode_true_object_all_of_with_http_info(opts) + data + end + + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [Array<(String, Integer, Hash)>] String data, response status code and response headers + def test_query_style_form_explode_true_object_all_of_with_http_info(opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: QueryApi.test_query_style_form_explode_true_object_all_of ...' + end + # resource path + local_var_path = '/query/style_form/explode_true/object/allOf' + + # query parameters + query_params = opts[:query_params] || {} + query_params[:'query_object'] = opts[:'query_object'] if !opts[:'query_object'].nil? + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Accept' (if needed) + header_params['Accept'] = @api_client.select_header_accept(['text/plain']) + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] + + # return_type + return_type = opts[:debug_return_type] || 'String' + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"QueryApi.test_query_style_form_explode_true_object_all_of", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:GET, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: QueryApi#test_query_style_form_explode_true_object_all_of\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_client.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_client.rb new file mode 100644 index 000000000000..b57220434967 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_client.rb @@ -0,0 +1,394 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'json' +require 'logger' +require 'tempfile' +require 'time' +require 'typhoeus' + + +module OpenapiClient + class ApiClient + # The Configuration object holding settings to be used in the API client. + attr_accessor :config + + # Defines the headers to be used in HTTP requests of all API calls by default. + # + # @return [Hash] + attr_accessor :default_headers + + # Initializes the ApiClient + # @option config [Configuration] Configuration for initializing the object, default to Configuration.default + def initialize(config = Configuration.default) + @config = config + @user_agent = "OpenAPI-Generator/#{VERSION}/ruby" + @default_headers = { + 'Content-Type' => 'application/json', + 'User-Agent' => @user_agent + } + end + + def self.default + @@default ||= ApiClient.new + end + + # Call an API with given options. + # + # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. + def call_api(http_method, path, opts = {}) + request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' + response = request.run + + if @config.debugging + @config.logger.debug "HTTP response body ~BEGIN~\n#{response.body}\n~END~\n" + end + + unless response.success? + if response.timed_out? + fail ApiError.new('Connection timed out') + elsif response.code == 0 + # Errors from libcurl will be made visible here + fail ApiError.new(:code => 0, + :message => response.return_message) + else + fail ApiError.new(:code => response.code, + :response_headers => response.headers, + :response_body => response.body), + response.status_message + end + end + + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] + data = deserialize(response, opts[:return_type]) + else + data = nil + end + return data, response.code, response.headers + end + + # Builds the HTTP request + # + # @param [String] http_method HTTP method/verb (e.g. POST) + # @param [String] path URL path (e.g. /account/new) + # @option opts [Hash] :header_params Header parameters + # @option opts [Hash] :query_params Query parameters + # @option opts [Hash] :form_params Query parameters + # @option opts [Object] :body HTTP body (JSON/XML) + # @return [Typhoeus::Request] A Typhoeus Request + def build_request(http_method, path, opts = {}) + url = build_request_url(path, opts) + http_method = http_method.to_sym.downcase + + header_params = @default_headers.merge(opts[:header_params] || {}) + query_params = opts[:query_params] || {} + form_params = opts[:form_params] || {} + follow_location = opts[:follow_location] || true + + update_params_for_auth! header_params, query_params, opts[:auth_names] + + # set ssl_verifyhosts option based on @config.verify_ssl_host (true/false) + _verify_ssl_host = @config.verify_ssl_host ? 2 : 0 + + req_opts = { + :method => http_method, + :headers => header_params, + :params => query_params, + :params_encoding => @config.params_encoding, + :timeout => @config.timeout, + :ssl_verifypeer => @config.verify_ssl, + :ssl_verifyhost => _verify_ssl_host, + :sslcert => @config.cert_file, + :sslkey => @config.key_file, + :verbose => @config.debugging, + :followlocation => follow_location + } + + # set custom cert, if provided + req_opts[:cainfo] = @config.ssl_ca_cert if @config.ssl_ca_cert + + if [:post, :patch, :put, :delete].include?(http_method) + req_body = build_request_body(header_params, form_params, opts[:body]) + req_opts.update :body => req_body + if @config.debugging + @config.logger.debug "HTTP request body param ~BEGIN~\n#{req_body}\n~END~\n" + end + end + + Typhoeus::Request.new(url, req_opts) + end + + # Builds the HTTP request body + # + # @param [Hash] header_params Header parameters + # @param [Hash] form_params Query parameters + # @param [Object] body HTTP body (JSON/XML) + # @return [String] HTTP body data in the form of string + def build_request_body(header_params, form_params, body) + # http form + if header_params['Content-Type'] == 'application/x-www-form-urlencoded' || + header_params['Content-Type'] == 'multipart/form-data' + data = {} + form_params.each do |key, value| + case value + when ::File, ::Array, nil + # let typhoeus handle File, Array and nil parameters + data[key] = value + else + data[key] = value.to_s + end + end + elsif body + data = body.is_a?(String) ? body : body.to_json + else + data = nil + end + data + end + + # Save response body into a file in (the defined) temporary folder, using the filename + # from the "Content-Disposition" header if provided, otherwise a random filename. + # The response body is written to the file in chunks in order to handle files which + # size is larger than maximum Ruby String or even larger than the maximum memory a Ruby + # process can use. + # + # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated + def download_file(request) + tempfile = nil + encoding = nil + request.on_headers do |response| + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + end + request.on_body do |chunk| + chunk.force_encoding(encoding) + tempfile.write(chunk) + end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") + end + + tempfile + end + + # Check if the given MIME is a JSON MIME. + # JSON MIME examples: + # application/json + # application/json; charset=UTF8 + # APPLICATION/JSON + # */* + # @param [String] mime MIME + # @return [Boolean] True if the MIME is application/json + def json_mime?(mime) + (mime == '*/*') || !(mime =~ /Application\/.*json(?!p)(;.*)?/i).nil? + end + + # Deserialize the response to the given return type. + # + # @param [Response] response HTTP response + # @param [String] return_type some examples: "User", "Array", "Hash" + def deserialize(response, return_type) + body = response.body + return nil if body.nil? || body.empty? + + # return response body directly for String return type + return body.to_s if return_type == 'String' + + # ensuring a default content type + content_type = response.headers['Content-Type'] || 'application/json' + + fail "Content-Type is not supported: #{content_type}" unless json_mime?(content_type) + + begin + data = JSON.parse("[#{body}]", :symbolize_names => true)[0] + rescue JSON::ParserError => e + if %w(String Date Time).include?(return_type) + data = body + else + raise e + end + end + + convert_to_type data, return_type + end + + # Convert data to the given return type. + # @param [Object] data Data to be converted + # @param [String] return_type Return type + # @return [Mixed] Data in a particular type + def convert_to_type(data, return_type) + return nil if data.nil? + case return_type + when 'String' + data.to_s + when 'Integer' + data.to_i + when 'Float' + data.to_f + when 'Boolean' + data == true + when 'Time' + # parse date time (expecting ISO 8601 format) + Time.parse data + when 'Date' + # parse date time (expecting ISO 8601 format) + Date.parse data + when 'Object' + # generic object (usually a Hash), return directly + data + when /\AArray<(.+)>\z/ + # e.g. Array + sub_type = $1 + data.map { |item| convert_to_type(item, sub_type) } + when /\AHash\\z/ + # e.g. Hash + sub_type = $1 + {}.tap do |hash| + data.each { |k, v| hash[k] = convert_to_type(v, sub_type) } + end + else + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(return_type) + klass.respond_to?(:openapi_one_of) ? klass.build(data) : klass.build_from_hash(data) + end + end + + # Sanitize filename by removing path. + # e.g. ../../sun.gif becomes sun.gif + # + # @param [String] filename the filename to be sanitized + # @return [String] the sanitized filename + def sanitize_filename(filename) + filename.gsub(/.*[\/\\]/, '') + end + + def build_request_url(path, opts = {}) + # Add leading and trailing slashes to path + path = "/#{path}".gsub(/\/+/, '/') + @config.base_url(opts[:operation]) + path + end + + # Update header and query params based on authentication settings. + # + # @param [Hash] header_params Header parameters + # @param [Hash] query_params Query parameters + # @param [String] auth_names Authentication scheme name + def update_params_for_auth!(header_params, query_params, auth_names) + Array(auth_names).each do |auth_name| + auth_setting = @config.auth_settings[auth_name] + next unless auth_setting + case auth_setting[:in] + when 'header' then header_params[auth_setting[:key]] = auth_setting[:value] + when 'query' then query_params[auth_setting[:key]] = auth_setting[:value] + else fail ArgumentError, 'Authentication token must be in `query` or `header`' + end + end + end + + # Sets user agent in HTTP header + # + # @param [String] user_agent User agent (e.g. openapi-generator/ruby/1.0.0) + def user_agent=(user_agent) + @user_agent = user_agent + @default_headers['User-Agent'] = @user_agent + end + + # Return Accept header based on an array of accepts provided. + # @param [Array] accepts array for Accept + # @return [String] the Accept header (e.g. application/json) + def select_header_accept(accepts) + return nil if accepts.nil? || accepts.empty? + # use JSON when present, otherwise use all of the provided + json_accept = accepts.find { |s| json_mime?(s) } + json_accept || accepts.join(',') + end + + # Return Content-Type header based on an array of content types provided. + # @param [Array] content_types array for Content-Type + # @return [String] the Content-Type header (e.g. application/json) + def select_header_content_type(content_types) + # return nil by default + return if content_types.nil? || content_types.empty? + # use JSON when present, otherwise use the first one + json_content_type = content_types.find { |s| json_mime?(s) } + json_content_type || content_types.first + end + + # Convert object (array, hash, object, etc) to JSON string. + # @param [Object] model object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_http_body(model) + return model if model.nil? || model.is_a?(String) + local_body = nil + if model.is_a?(Array) + local_body = model.map { |m| object_to_hash(m) } + else + local_body = object_to_hash(model) + end + local_body.to_json + end + + # Convert object(non-array) to hash. + # @param [Object] obj object to be converted into JSON string + # @return [String] JSON string representation of the object + def object_to_hash(obj) + if obj.respond_to?(:to_hash) + obj.to_hash + else + obj + end + end + + # Build parameter value according to the given collection format. + # @param [String] collection_format one of :csv, :ssv, :tsv, :pipes and :multi + def build_collection_param(param, collection_format) + case collection_format + when :csv + param.join(',') + when :ssv + param.join(' ') + when :tsv + param.join("\t") + when :pipes + param.join('|') + when :multi + # return the array directly as typhoeus will handle it as expected + param + else + fail "unknown collection format: #{collection_format.inspect}" + end + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_error.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_error.rb new file mode 100644 index 000000000000..c9d0c194a36e --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/api_error.rb @@ -0,0 +1,58 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + class ApiError < StandardError + attr_reader :code, :response_headers, :response_body + + # Usage examples: + # ApiError.new + # ApiError.new("message") + # ApiError.new(:code => 500, :response_headers => {}, :response_body => "") + # ApiError.new(:code => 404, :message => "Not Found") + def initialize(arg = nil) + if arg.is_a? Hash + if arg.key?(:message) || arg.key?('message') + super(arg[:message] || arg['message']) + else + super arg + end + + arg.each do |k, v| + instance_variable_set "@#{k}", v + end + else + super arg + @message = arg + end + end + + # Override to_s to display a friendly error message + def to_s + message + end + + def message + if @message.nil? + msg = "Error message: the server returns an error" + else + msg = @message + end + + msg += "\nHTTP status code: #{code}" if code + msg += "\nResponse headers: #{response_headers}" if response_headers + msg += "\nResponse body: #{response_body}" if response_body + + msg + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/configuration.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/configuration.rb new file mode 100644 index 000000000000..f6eb60e801fd --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/configuration.rb @@ -0,0 +1,305 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + class Configuration + # Defines url scheme + attr_accessor :scheme + + # Defines url host + attr_accessor :host + + # Defines url base path + attr_accessor :base_path + + # Define server configuration index + attr_accessor :server_index + + # Define server operation configuration index + attr_accessor :server_operation_index + + # Default server variables + attr_accessor :server_variables + + # Default server operation variables + attr_accessor :server_operation_variables + + # Defines API keys used with API Key authentications. + # + # @return [Hash] key: parameter name, value: parameter value (API key) + # + # @example parameter name is "api_key", API key is "xxx" (e.g. "api_key=xxx" in query string) + # config.api_key['api_key'] = 'xxx' + attr_accessor :api_key + + # Defines API key prefixes used with API Key authentications. + # + # @return [Hash] key: parameter name, value: API key prefix + # + # @example parameter name is "Authorization", API key prefix is "Token" (e.g. "Authorization: Token xxx" in headers) + # config.api_key_prefix['api_key'] = 'Token' + attr_accessor :api_key_prefix + + # Defines the username used with HTTP basic authentication. + # + # @return [String] + attr_accessor :username + + # Defines the password used with HTTP basic authentication. + # + # @return [String] + attr_accessor :password + + # Defines the access token (Bearer) used with OAuth2. + attr_accessor :access_token + + # Defines a Proc used to fetch or refresh access tokens (Bearer) used with OAuth2. + # Overrides the access_token if set + # @return [Proc] + attr_accessor :access_token_getter + + # Set this to return data as binary instead of downloading a temp file. When enabled (set to true) + # HTTP responses with return type `File` will be returned as a stream of binary data. + # Default to false. + attr_accessor :return_binary_data + + # Set this to enable/disable debugging. When enabled (set to true), HTTP request/response + # details will be logged with `logger.debug` (see the `logger` attribute). + # Default to false. + # + # @return [true, false] + attr_accessor :debugging + + # Defines the logger used for debugging. + # Default to `Rails.logger` (when in Rails) or logging to STDOUT. + # + # @return [#debug] + attr_accessor :logger + + # Defines the temporary folder to store downloaded files + # (for API endpoints that have file response). + # Default to use `Tempfile`. + # + # @return [String] + attr_accessor :temp_folder_path + + # The time limit for HTTP request in seconds. + # Default to 0 (never times out). + attr_accessor :timeout + + # Set this to false to skip client side validation in the operation. + # Default to true. + # @return [true, false] + attr_accessor :client_side_validation + + ### TLS/SSL setting + # Set this to false to skip verifying SSL certificate when calling API from https server. + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl + + ### TLS/SSL setting + # Set this to false to skip verifying SSL host name + # Default to true. + # + # @note Do NOT set it to false in production code, otherwise you would face multiple types of cryptographic attacks. + # + # @return [true, false] + attr_accessor :verify_ssl_host + + ### TLS/SSL setting + # Set this to customize the certificate file to verify the peer. + # + # @return [String] the path to the certificate file + # + # @see The `cainfo` option of Typhoeus, `--cert` option of libcurl. Related source code: + # https://github.com/typhoeus/typhoeus/blob/master/lib/typhoeus/easy_factory.rb#L145 + attr_accessor :ssl_ca_cert + + ### TLS/SSL setting + # Client certificate file (for client certificate) + attr_accessor :cert_file + + ### TLS/SSL setting + # Client private key file (for client certificate) + attr_accessor :key_file + + # Set this to customize parameters encoding of array parameter with multi collectionFormat. + # Default to nil. + # + # @see The params_encoding option of Ethon. Related source code: + # https://github.com/typhoeus/ethon/blob/master/lib/ethon/easy/queryable.rb#L96 + attr_accessor :params_encoding + + + attr_accessor :inject_format + + attr_accessor :force_ending_format + + def initialize + @scheme = 'http' + @host = 'localhost:3000' + @base_path = '' + @server_index = nil + @server_operation_index = {} + @server_variables = {} + @server_operation_variables = {} + @api_key = {} + @api_key_prefix = {} + @client_side_validation = true + @verify_ssl = true + @verify_ssl_host = true + @cert_file = nil + @key_file = nil + @timeout = 0 + @params_encoding = nil + @debugging = false + @inject_format = false + @force_ending_format = false + @logger = defined?(Rails) ? Rails.logger : Logger.new(STDOUT) + + yield(self) if block_given? + end + + # The default Configuration object. + def self.default + @@default ||= Configuration.new + end + + def configure + yield(self) if block_given? + end + + def scheme=(scheme) + # remove :// from scheme + @scheme = scheme.sub(/:\/\//, '') + end + + def host=(host) + # remove http(s):// and anything after a slash + @host = host.sub(/https?:\/\//, '').split('/').first + end + + def base_path=(base_path) + # Add leading and trailing slashes to base_path + @base_path = "/#{base_path}".gsub(/\/+/, '/') + @base_path = '' if @base_path == '/' + end + + # Returns base URL for specified operation based on server settings + def base_url(operation = nil) + if operation_server_settings.key?(operation) then + index = server_operation_index.fetch(operation, server_index) + server_url(index.nil? ? 0 : index, server_operation_variables.fetch(operation, server_variables), operation_server_settings[operation]) + else + server_index.nil? ? "#{scheme}://#{[host, base_path].join('/').gsub(/\/+/, '/')}".sub(/\/+\z/, '') : server_url(server_index, server_variables, nil) + end + end + + # Gets API key (with prefix if set). + # @param [String] param_name the parameter name of API key auth + def api_key_with_prefix(param_name, param_alias = nil) + key = @api_key[param_name] + key = @api_key.fetch(param_alias, key) unless param_alias.nil? + if @api_key_prefix[param_name] + "#{@api_key_prefix[param_name]} #{key}" + else + key + end + end + + # Gets access_token using access_token_getter or uses the static access_token + def access_token_with_refresh + return access_token if access_token_getter.nil? + access_token_getter.call + end + + # Gets Basic Auth token string + def basic_auth_token + 'Basic ' + ["#{username}:#{password}"].pack('m').delete("\r\n") + end + + # Returns Auth Settings hash for api client. + def auth_settings + { + 'http_auth' => + { + type: 'basic', + in: 'header', + key: 'Authorization', + value: basic_auth_token + }, + 'http_bearer_auth' => + { + type: 'bearer', + in: 'header', + key: 'Authorization', + value: "Bearer #{access_token_with_refresh}" + }, + } + end + + # Returns an array of Server setting + def server_settings + [ + { + url: "http://localhost:3000", + description: "No description provided", + } + ] + end + + def operation_server_settings + { + } + end + + # Returns URL based on server settings + # + # @param index array index of the server settings + # @param variables hash of variable and the corresponding value + def server_url(index, variables = {}, servers = nil) + servers = server_settings if servers == nil + + # check array index out of bound + if (index.nil? || index < 0 || index >= servers.size) + fail ArgumentError, "Invalid index #{index} when selecting the server. Must not be nil and must be less than #{servers.size}" + end + + server = servers[index] + url = server[:url] + + return url unless server.key? :variables + + # go through variable and assign a value + server[:variables].each do |name, variable| + if variables.key?(name) + if (!server[:variables][name].key?(:enum_values) || server[:variables][name][:enum_values].include?(variables[name])) + url.gsub! "{" + name.to_s + "}", variables[name] + else + fail ArgumentError, "The variable `#{name}` in the server URL has invalid value #{variables[name]}. Must be #{server[:variables][name][:enum_values]}." + end + else + # use default value + url.gsub! "{" + name.to_s + "}", server[:variables][name][:default_value] + end + end + + url + end + + + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/bird.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/bird.rb new file mode 100644 index 000000000000..a131cb068352 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/bird.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Bird + attr_accessor :size + + attr_accessor :color + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'size' => :'size', + :'color' => :'color' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'size' => :'String', + :'color' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Bird` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Bird`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'size') + self.size = attributes[:'size'] + end + + if attributes.key?(:'color') + self.color = attributes[:'color'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + size == o.size && + color == o.color + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [size, color].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/category.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/category.rb new file mode 100644 index 000000000000..0d1badac1693 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/category.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Category + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Category` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Category`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/data_query.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/data_query.rb new file mode 100644 index 000000000000..8a367642bd13 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/data_query.rb @@ -0,0 +1,268 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class DataQuery < Query + # test suffix + attr_accessor :suffix + + # Some text containing white spaces + attr_accessor :text + + # A date + attr_accessor :date + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'suffix' => :'suffix', + :'text' => :'text', + :'date' => :'date' + } + end + + # Returns all the JSON keys this model knows about, including the ones defined in its parent(s) + def self.acceptable_attributes + attribute_map.values.concat(superclass.acceptable_attributes) + end + + # Attribute type mapping. + def self.openapi_types + { + :'suffix' => :'String', + :'text' => :'String', + :'date' => :'Time' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Query' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::DataQuery` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::DataQuery`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + # call parent's initialize + super(attributes) + + if attributes.key?(:'suffix') + self.suffix = attributes[:'suffix'] + end + + if attributes.key?(:'text') + self.text = attributes[:'text'] + end + + if attributes.key?(:'date') + self.date = attributes[:'date'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = super + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true && super + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + suffix == o.suffix && + text == o.text && + date == o.date && super(o) + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [suffix, text, date].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + super(attributes) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = super + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/default_value.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/default_value.rb new file mode 100644 index 000000000000..20b339e41c48 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/default_value.rb @@ -0,0 +1,317 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + # to test the default value of properties + class DefaultValue + attr_accessor :array_string_enum_ref_default + + attr_accessor :array_string_enum_default + + attr_accessor :array_string_default + + attr_accessor :array_integer_default + + attr_accessor :array_string + + attr_accessor :array_string_nullable + + attr_accessor :array_string_extension_nullable + + attr_accessor :string_nullable + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'array_string_enum_ref_default' => :'array_string_enum_ref_default', + :'array_string_enum_default' => :'array_string_enum_default', + :'array_string_default' => :'array_string_default', + :'array_integer_default' => :'array_integer_default', + :'array_string' => :'array_string', + :'array_string_nullable' => :'array_string_nullable', + :'array_string_extension_nullable' => :'array_string_extension_nullable', + :'string_nullable' => :'string_nullable' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'array_string_enum_ref_default' => :'Array', + :'array_string_enum_default' => :'Array', + :'array_string_default' => :'Array', + :'array_integer_default' => :'Array', + :'array_string' => :'Array', + :'array_string_nullable' => :'Array', + :'array_string_extension_nullable' => :'Array', + :'string_nullable' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + :'array_string_nullable', + :'array_string_extension_nullable', + :'string_nullable' + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::DefaultValue` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::DefaultValue`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'array_string_enum_ref_default') + if (value = attributes[:'array_string_enum_ref_default']).is_a?(Array) + self.array_string_enum_ref_default = value + end + end + + if attributes.key?(:'array_string_enum_default') + if (value = attributes[:'array_string_enum_default']).is_a?(Array) + self.array_string_enum_default = value + end + end + + if attributes.key?(:'array_string_default') + if (value = attributes[:'array_string_default']).is_a?(Array) + self.array_string_default = value + end + end + + if attributes.key?(:'array_integer_default') + if (value = attributes[:'array_integer_default']).is_a?(Array) + self.array_integer_default = value + end + end + + if attributes.key?(:'array_string') + if (value = attributes[:'array_string']).is_a?(Array) + self.array_string = value + end + end + + if attributes.key?(:'array_string_nullable') + if (value = attributes[:'array_string_nullable']).is_a?(Array) + self.array_string_nullable = value + end + end + + if attributes.key?(:'array_string_extension_nullable') + if (value = attributes[:'array_string_extension_nullable']).is_a?(Array) + self.array_string_extension_nullable = value + end + end + + if attributes.key?(:'string_nullable') + self.string_nullable = attributes[:'string_nullable'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + array_string_enum_ref_default == o.array_string_enum_ref_default && + array_string_enum_default == o.array_string_enum_default && + array_string_default == o.array_string_default && + array_integer_default == o.array_integer_default && + array_string == o.array_string && + array_string_nullable == o.array_string_nullable && + array_string_extension_nullable == o.array_string_extension_nullable && + string_nullable == o.string_nullable + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [array_string_enum_ref_default, array_string_enum_default, array_string_default, array_integer_default, array_string, array_string_nullable, array_string_extension_nullable, string_nullable].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/number_properties_only.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/number_properties_only.rb new file mode 100644 index 000000000000..59c453fd378b --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/number_properties_only.rb @@ -0,0 +1,260 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class NumberPropertiesOnly + attr_accessor :number + + attr_accessor :float + + attr_accessor :double + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'number' => :'number', + :'float' => :'float', + :'double' => :'double' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'number' => :'Float', + :'float' => :'Float', + :'double' => :'Float' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::NumberPropertiesOnly` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::NumberPropertiesOnly`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'number') + self.number = attributes[:'number'] + end + + if attributes.key?(:'float') + self.float = attributes[:'float'] + end + + if attributes.key?(:'double') + self.double = attributes[:'double'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + if !@double.nil? && @double > 50.2 + invalid_properties.push('invalid value for "double", must be smaller than or equal to 50.2.') + end + + if !@double.nil? && @double < 0.8 + invalid_properties.push('invalid value for "double", must be greater than or equal to 0.8.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + return false if !@double.nil? && @double > 50.2 + return false if !@double.nil? && @double < 0.8 + true + end + + # Custom attribute writer method with validation + # @param [Object] double Value to be assigned + def double=(double) + if double.nil? + fail ArgumentError, 'double cannot be nil' + end + + if double > 50.2 + fail ArgumentError, 'invalid value for "double", must be smaller than or equal to 50.2.' + end + + if double < 0.8 + fail ArgumentError, 'invalid value for "double", must be greater than or equal to 0.8.' + end + + @double = double + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + number == o.number && + float == o.float && + double == o.double + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [number, float, double].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/pet.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/pet.rb new file mode 100644 index 000000000000..e2d3358a953d --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/pet.rb @@ -0,0 +1,312 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Pet + attr_accessor :id + + attr_accessor :name + + attr_accessor :category + + attr_accessor :photo_urls + + attr_accessor :tags + + # pet status in the store + attr_accessor :status + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name', + :'category' => :'category', + :'photo_urls' => :'photoUrls', + :'tags' => :'tags', + :'status' => :'status' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String', + :'category' => :'Category', + :'photo_urls' => :'Array', + :'tags' => :'Array', + :'status' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Pet` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Pet`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + else + self.name = nil + end + + if attributes.key?(:'category') + self.category = attributes[:'category'] + end + + if attributes.key?(:'photo_urls') + if (value = attributes[:'photo_urls']).is_a?(Array) + self.photo_urls = value + end + else + self.photo_urls = nil + end + + if attributes.key?(:'tags') + if (value = attributes[:'tags']).is_a?(Array) + self.tags = value + end + end + + if attributes.key?(:'status') + self.status = attributes[:'status'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + if @name.nil? + invalid_properties.push('invalid value for "name", name cannot be nil.') + end + + if @photo_urls.nil? + invalid_properties.push('invalid value for "photo_urls", photo_urls cannot be nil.') + end + + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + return false if @name.nil? + return false if @photo_urls.nil? + status_validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + return false unless status_validator.valid?(@status) + true + end + + # Custom attribute writer method checking allowed values (enum). + # @param [Object] status Object to be assigned + def status=(status) + validator = EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + unless validator.valid?(status) + fail ArgumentError, "invalid value for \"status\", must be one of #{validator.allowable_values}." + end + @status = status + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name && + category == o.category && + photo_urls == o.photo_urls && + tags == o.tags && + status == o.status + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name, category, photo_urls, tags, status].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/query.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/query.rb new file mode 100644 index 000000000000..4bddb7bcc412 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/query.rb @@ -0,0 +1,248 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Query + # Query + attr_accessor :id + + attr_accessor :outcomes + + class EnumAttributeValidator + attr_reader :datatype + attr_reader :allowable_values + + def initialize(datatype, allowable_values) + @allowable_values = allowable_values.map do |value| + case datatype.to_s + when /Integer/i + value.to_i + when /Float/i + value.to_f + else + value + end + end + end + + def valid?(value) + !value || allowable_values.include?(value) + end + end + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'outcomes' => :'outcomes' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'outcomes' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Query` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Query`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'outcomes') + if (value = attributes[:'outcomes']).is_a?(Array) + self.outcomes = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + outcomes == o.outcomes + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, outcomes].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/string_enum_ref.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/string_enum_ref.rb new file mode 100644 index 000000000000..5aa83ea64b6c --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/string_enum_ref.rb @@ -0,0 +1,41 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class StringEnumRef + SUCCESS = "success".freeze + FAILURE = "failure".freeze + UNCLASSIFIED = "unclassified".freeze + + def self.all_vars + @all_vars ||= [SUCCESS, FAILURE, UNCLASSIFIED].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if StringEnumRef.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #StringEnumRef" + end + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/tag.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/tag.rb new file mode 100644 index 000000000000..b8496889c787 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/tag.rb @@ -0,0 +1,223 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class Tag + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::Tag` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::Tag`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb new file mode 100644 index 000000000000..65d19fa1a98e --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter.rb @@ -0,0 +1,249 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + attr_accessor :size + + attr_accessor :color + + attr_accessor :id + + attr_accessor :name + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'size' => :'size', + :'color' => :'color', + :'id' => :'id', + :'name' => :'name' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'size' => :'String', + :'color' => :'String', + :'id' => :'Integer', + :'name' => :'String' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # List of class defined in allOf (OpenAPI v3) + def self.openapi_all_of + [ + :'Bird', + :'Category' + ] + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'size') + self.size = attributes[:'size'] + end + + if attributes.key?(:'color') + self.color = attributes[:'color'] + end + + if attributes.key?(:'id') + self.id = attributes[:'id'] + end + + if attributes.key?(:'name') + self.name = attributes[:'name'] + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + size == o.size && + color == o.color && + id == o.id && + name == o.name + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [size, color, id, name].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb new file mode 100644 index 000000000000..5f88a0c939b7 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/models/test_query_style_form_explode_true_array_string_query_object_parameter.rb @@ -0,0 +1,216 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module OpenapiClient + class TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + attr_accessor :values + + # Attribute mapping from ruby-style variable name to JSON key. + def self.attribute_map + { + :'values' => :'values' + } + end + + # Returns all the JSON keys this model knows about + def self.acceptable_attributes + attribute_map.values + end + + # Attribute type mapping. + def self.openapi_types + { + :'values' => :'Array' + } + end + + # List of attributes with nullable: true + def self.openapi_nullable + Set.new([ + ]) + end + + # Initializes the object + # @param [Hash] attributes Model attributes in the form of hash + def initialize(attributes = {}) + if (!attributes.is_a?(Hash)) + fail ArgumentError, "The input argument (attributes) must be a hash in `OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter` initialize method" + end + + # check to see if the attribute exists and convert string to symbol for hash key + attributes = attributes.each_with_object({}) { |(k, v), h| + if (!self.class.attribute_map.key?(k.to_sym)) + fail ArgumentError, "`#{k}` is not a valid attribute in `OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter`. Please check the name to make sure it's valid. List of attributes: " + self.class.attribute_map.keys.inspect + end + h[k.to_sym] = v + } + + if attributes.key?(:'values') + if (value = attributes[:'values']).is_a?(Array) + self.values = value + end + end + end + + # Show invalid properties with the reasons. Usually used together with valid? + # @return Array for valid properties with the reasons + def list_invalid_properties + warn '[DEPRECATED] the `list_invalid_properties` method is obsolete' + invalid_properties = Array.new + invalid_properties + end + + # Check to see if the all the properties in the model are valid + # @return true if the model is valid + def valid? + warn '[DEPRECATED] the `valid?` method is obsolete' + true + end + + # Checks equality by comparing each attribute. + # @param [Object] Object to be compared + def ==(o) + return true if self.equal?(o) + self.class == o.class && + values == o.values + end + + # @see the `==` method + # @param [Object] Object to be compared + def eql?(o) + self == o + end + + # Calculates hash code according to all attributes. + # @return [Integer] Hash code + def hash + [values].hash + end + + # Builds the object from hash + # @param [Hash] attributes Model attributes in the form of hash + # @return [Object] Returns the model itself + def self.build_from_hash(attributes) + return nil unless attributes.is_a?(Hash) + attributes = attributes.transform_keys(&:to_sym) + transformed_hash = {} + openapi_types.each_pair do |key, type| + if attributes.key?(attribute_map[key]) && attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = nil + elsif type =~ /\AArray<(.*)>/i + # check to ensure the input is an array given that the attribute + # is documented as an array but the input is not + if attributes[attribute_map[key]].is_a?(Array) + transformed_hash["#{key}"] = attributes[attribute_map[key]].map { |v| _deserialize($1, v) } + end + elsif !attributes[attribute_map[key]].nil? + transformed_hash["#{key}"] = _deserialize(type, attributes[attribute_map[key]]) + end + end + new(transformed_hash) + end + + # Deserializes the data based on type + # @param string type Data type + # @param string value Value to be deserialized + # @return [Object] Deserialized data + def self._deserialize(type, value) + case type.to_sym + when :Time + Time.parse(value) + when :Date + Date.parse(value) + when :String + value.to_s + when :Integer + value.to_i + when :Float + value.to_f + when :Boolean + if value.to_s =~ /\A(true|t|yes|y|1)\z/i + true + else + false + end + when :Object + # generic object (usually a Hash), return directly + value + when /\AArray<(?.+)>\z/ + inner_type = Regexp.last_match[:inner_type] + value.map { |v| _deserialize(inner_type, v) } + when /\AHash<(?.+?), (?.+)>\z/ + k_type = Regexp.last_match[:k_type] + v_type = Regexp.last_match[:v_type] + {}.tap do |hash| + value.each do |k, v| + hash[_deserialize(k_type, k)] = _deserialize(v_type, v) + end + end + else # model + # models (e.g. Pet) or oneOf + klass = OpenapiClient.const_get(type) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + end + end + + # Returns the string representation of the object + # @return [String] String presentation of the object + def to_s + to_hash.to_s + end + + # to_body is an alias to to_hash (backward compatibility) + # @return [Hash] Returns the object in the form of hash + def to_body + to_hash + end + + # Returns the object in the form of hash + # @return [Hash] Returns the object in the form of hash + def to_hash + hash = {} + self.class.attribute_map.each_pair do |attr, param| + value = self.send(attr) + if value.nil? + is_nullable = self.class.openapi_nullable.include?(attr) + next if !is_nullable || (is_nullable && !instance_variable_defined?(:"@#{attr}")) + end + + hash[param] = _to_hash(value) + end + hash + end + + # Outputs non-array value in the form of hash + # For object, use to_hash. Otherwise, just return the value + # @param [Object] value Any valid value + # @return [Hash] Returns the value in the form of hash + def _to_hash(value) + if value.is_a?(Array) + value.compact.map { |v| _to_hash(v) } + elsif value.is_a?(Hash) + {}.tap do |hash| + value.each { |k, v| hash[k] = _to_hash(v) } + end + elsif value.respond_to? :to_hash + value.to_hash + else + value + end + end + + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/version.rb b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/version.rb new file mode 100644 index 000000000000..e7a852ecb1e5 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/lib/openapi_client/version.rb @@ -0,0 +1,15 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +module OpenapiClient + VERSION = '1.0.0' +end diff --git a/samples/client/echo_api/ruby-typhoeus/openapi_client.gemspec b/samples/client/echo_api/ruby-typhoeus/openapi_client.gemspec new file mode 100644 index 000000000000..4c67945c9486 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/openapi_client.gemspec @@ -0,0 +1,39 @@ +# -*- encoding: utf-8 -*- + +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +$:.push File.expand_path("../lib", __FILE__) +require "openapi_client/version" + +Gem::Specification.new do |s| + s.name = "openapi_client" + s.version = OpenapiClient::VERSION + s.platform = Gem::Platform::RUBY + s.authors = ["OpenAPI-Generator"] + s.email = ["team@openapitools.org"] + s.homepage = "https://openapi-generator.tech" + s.summary = "Echo Server API Ruby Gem" + s.description = "Echo Server API" + s.license = "Unlicense" + s.required_ruby_version = ">= 2.7" + s.metadata = {} + + s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' + + s.add_development_dependency 'rspec', '~> 3.6', '>= 3.6.0' + + s.files = `find *`.split("\n").uniq.sort.select { |f| !f.empty? } + s.test_files = `find spec/*`.split("\n") + s.executables = [] + s.require_paths = ["lib"] +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/auth_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/auth_api_spec.rb new file mode 100644 index 000000000000..565fe5d2a239 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/auth_api_spec.rb @@ -0,0 +1,57 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::AuthApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'AuthApi' do + before do + # run before each test + @api_instance = OpenapiClient::AuthApi.new + end + + after do + # run after each test + end + + describe 'test an instance of AuthApi' do + it 'should create an instance of AuthApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::AuthApi) + end + end + + # unit tests for test_auth_http_basic + # To test HTTP basic authentication + # To test HTTP basic authentication + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_auth_http_basic test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_auth_http_bearer + # To test HTTP bearer authentication + # To test HTTP bearer authentication + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_auth_http_bearer test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/body_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/body_api_spec.rb new file mode 100644 index 000000000000..363e9f8b8b64 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/body_api_spec.rb @@ -0,0 +1,130 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::BodyApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'BodyApi' do + before do + # run before each test + @api_instance = OpenapiClient::BodyApi.new + end + + after do + # run after each test + end + + describe 'test an instance of BodyApi' do + it 'should create an instance of BodyApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::BodyApi) + end + end + + # unit tests for test_binary_gif + # Test binary (gif) response body + # Test binary (gif) response body + # @param [Hash] opts the optional parameters + # @return [File] + describe 'test_binary_gif test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_body_application_octetstream_binary + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [File] :body + # @return [String] + describe 'test_body_application_octetstream_binary test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_body_multipart_formdata_array_of_binary + # Test array of binary in multipart mime + # Test array of binary in multipart mime + # @param files + # @param [Hash] opts the optional parameters + # @return [String] + describe 'test_body_multipart_formdata_array_of_binary test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_all_of_pet + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + describe 'test_echo_body_all_of_pet test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_free_form_object_response_string + # Test free form object + # Test free form object + # @param [Hash] opts the optional parameters + # @option opts [Object] :body Free form object + # @return [String] + describe 'test_echo_body_free_form_object_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_pet + # Test body parameter(s) + # Test body parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [Pet] + describe 'test_echo_body_pet test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_pet_response_string + # Test empty response body + # Test empty response body + # @param [Hash] opts the optional parameters + # @option opts [Pet] :pet Pet object that needs to be added to the store + # @return [String] + describe 'test_echo_body_pet_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_echo_body_tag_response_string + # Test empty json (request body) + # Test empty json (request body) + # @param [Hash] opts the optional parameters + # @option opts [Tag] :tag Tag object + # @return [String] + describe 'test_echo_body_tag_response_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/form_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/form_api_spec.rb new file mode 100644 index 000000000000..c404fc538470 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/form_api_spec.rb @@ -0,0 +1,66 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::FormApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'FormApi' do + before do + # run before each test + @api_instance = OpenapiClient::FormApi.new + end + + after do + # run after each test + end + + describe 'test an instance of FormApi' do + it 'should create an instance of FormApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::FormApi) + end + end + + # unit tests for test_form_integer_boolean_string + # Test form parameter(s) + # Test form parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_form + # @option opts [Boolean] :boolean_form + # @option opts [String] :string_form + # @return [String] + describe 'test_form_integer_boolean_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_form_oneof + # Test form parameter(s) for oneOf schema + # Test form parameter(s) for oneOf schema + # @param [Hash] opts the optional parameters + # @option opts [String] :form1 + # @option opts [Integer] :form2 + # @option opts [String] :form3 + # @option opts [Boolean] :form4 + # @option opts [Integer] :id + # @option opts [String] :name + # @return [String] + describe 'test_form_oneof test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/header_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/header_api_spec.rb new file mode 100644 index 000000000000..e7772849df69 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/header_api_spec.rb @@ -0,0 +1,51 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::HeaderApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'HeaderApi' do + before do + # run before each test + @api_instance = OpenapiClient::HeaderApi.new + end + + after do + # run after each test + end + + describe 'test an instance of HeaderApi' do + it 'should create an instance of HeaderApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::HeaderApi) + end + end + + # unit tests for test_header_integer_boolean_string_enums + # Test header parameter(s) + # Test header parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_header + # @option opts [Boolean] :boolean_header + # @option opts [String] :string_header + # @option opts [String] :enum_nonref_string_header + # @option opts [StringEnumRef] :enum_ref_string_header + # @return [String] + describe 'test_header_integer_boolean_string_enums test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/path_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/path_api_spec.rb new file mode 100644 index 000000000000..6ac30f152f7b --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/path_api_spec.rb @@ -0,0 +1,50 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::PathApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'PathApi' do + before do + # run before each test + @api_instance = OpenapiClient::PathApi.new + end + + after do + # run after each test + end + + describe 'test an instance of PathApi' do + it 'should create an instance of PathApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::PathApi) + end + end + + # unit tests for tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path + # Test path parameter(s) + # Test path parameter(s) + # @param path_string + # @param path_integer + # @param enum_nonref_string_path + # @param enum_ref_string_path + # @param [Hash] opts the optional parameters + # @return [String] + describe 'tests_path_string_path_string_integer_path_integer_enum_nonref_string_path_enum_ref_string_path test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/api/query_api_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/api/query_api_spec.rb new file mode 100644 index 000000000000..f9043d4f8b7b --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/api/query_api_spec.rb @@ -0,0 +1,136 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' + +# Unit tests for OpenapiClient::QueryApi +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe 'QueryApi' do + before do + # run before each test + @api_instance = OpenapiClient::QueryApi.new + end + + after do + # run after each test + end + + describe 'test an instance of QueryApi' do + it 'should create an instance of QueryApi' do + expect(@api_instance).to be_instance_of(OpenapiClient::QueryApi) + end + end + + # unit tests for test_enum_ref_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [String] :enum_nonref_string_query + # @option opts [StringEnumRef] :enum_ref_string_query + # @return [String] + describe 'test_enum_ref_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_datetime_date_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Time] :datetime_query + # @option opts [Date] :date_query + # @option opts [String] :string_query + # @return [String] + describe 'test_query_datetime_date_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_integer_boolean_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Integer] :integer_query + # @option opts [Boolean] :boolean_query + # @option opts [String] :string_query + # @return [String] + describe 'test_query_integer_boolean_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_deep_object_explode_true_object + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + describe 'test_query_style_deep_object_explode_true_object test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_deep_object_explode_true_object_all_of + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter] :query_object + # @return [String] + describe 'test_query_style_deep_object_explode_true_object_all_of test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_array_string + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_array_string test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_object + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [Pet] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_object test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + # unit tests for test_query_style_form_explode_true_object_all_of + # Test query parameter(s) + # Test query parameter(s) + # @param [Hash] opts the optional parameters + # @option opts [DataQuery] :query_object + # @return [String] + describe 'test_query_style_form_explode_true_object_all_of test' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/manual_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/manual_spec.rb new file mode 100644 index 000000000000..96db5a92076a --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/manual_spec.rb @@ -0,0 +1,27 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'base64' + +describe "Body API tests" do + describe 'the test_binary_gif method' do + let(:body_api_instance) { OpenapiClient::BodyApi.new } + + it 'can return file response' do + gif_base64 = "R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==\n" + response = body_api_instance.test_binary_gif() + expect(Base64.encode64(File.read(response.path))).to eq(gif_base64) + end + + end +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/bird_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/bird_spec.rb new file mode 100644 index 000000000000..764ab5329e01 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/bird_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Bird +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Bird do + let(:instance) { OpenapiClient::Bird.new } + + describe 'test an instance of Bird' do + it 'should create an instance of Bird' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Bird) + end + end + + describe 'test attribute "size"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "color"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/category_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/category_spec.rb new file mode 100644 index 000000000000..6bf16df513c7 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/category_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Category +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Category do + let(:instance) { OpenapiClient::Category.new } + + describe 'test an instance of Category' do + it 'should create an instance of Category' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Category) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/data_query_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/data_query_spec.rb new file mode 100644 index 000000000000..616516cd6f18 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/data_query_spec.rb @@ -0,0 +1,48 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::DataQuery +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::DataQuery do + let(:instance) { OpenapiClient::DataQuery.new } + + describe 'test an instance of DataQuery' do + it 'should create an instance of DataQuery' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::DataQuery) + end + end + + describe 'test attribute "suffix"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "text"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "date"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/default_value_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/default_value_spec.rb new file mode 100644 index 000000000000..1601e3bf0be2 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/default_value_spec.rb @@ -0,0 +1,82 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::DefaultValue +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::DefaultValue do + let(:instance) { OpenapiClient::DefaultValue.new } + + describe 'test an instance of DefaultValue' do + it 'should create an instance of DefaultValue' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::DefaultValue) + end + end + + describe 'test attribute "array_string_enum_ref_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_enum_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["success", "failure", "unclassified"]) + # validator.allowable_values.each do |value| + # expect { instance.array_string_enum_default = value }.not_to raise_error + # end + end + end + + describe 'test attribute "array_string_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_integer_default"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "array_string_extension_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "string_nullable"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/number_properties_only_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/number_properties_only_spec.rb new file mode 100644 index 000000000000..c528b0ff2628 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/number_properties_only_spec.rb @@ -0,0 +1,48 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::NumberPropertiesOnly +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::NumberPropertiesOnly do + let(:instance) { OpenapiClient::NumberPropertiesOnly.new } + + describe 'test an instance of NumberPropertiesOnly' do + it 'should create an instance of NumberPropertiesOnly' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::NumberPropertiesOnly) + end + end + + describe 'test attribute "number"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "float"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "double"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/pet_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/pet_spec.rb new file mode 100644 index 000000000000..75d8b5f6079d --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/pet_spec.rb @@ -0,0 +1,70 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Pet +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Pet do + let(:instance) { OpenapiClient::Pet.new } + + describe 'test an instance of Pet' do + it 'should create an instance of Pet' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Pet) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "category"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "photo_urls"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "tags"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "status"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('String', ["available", "pending", "sold"]) + # validator.allowable_values.each do |value| + # expect { instance.status = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/query_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/query_spec.rb new file mode 100644 index 000000000000..893943f3a776 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/query_spec.rb @@ -0,0 +1,46 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Query +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Query do + let(:instance) { OpenapiClient::Query.new } + + describe 'test an instance of Query' do + it 'should create an instance of Query' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Query) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "outcomes"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + # validator = Petstore::EnumTest::EnumAttributeValidator.new('Array', ["SUCCESS", "FAILURE", "SKIPPED"]) + # validator.allowable_values.each do |value| + # expect { instance.outcomes = value }.not_to raise_error + # end + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/string_enum_ref_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/string_enum_ref_spec.rb new file mode 100644 index 000000000000..6bd5883ca5a6 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/string_enum_ref_spec.rb @@ -0,0 +1,30 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::StringEnumRef +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::StringEnumRef do + let(:instance) { OpenapiClient::StringEnumRef.new } + + describe 'test an instance of StringEnumRef' do + it 'should create an instance of StringEnumRef' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::StringEnumRef) + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/tag_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/tag_spec.rb new file mode 100644 index 000000000000..9ee4d2c31c78 --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/tag_spec.rb @@ -0,0 +1,42 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::Tag +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::Tag do + let(:instance) { OpenapiClient::Tag.new } + + describe 'test an instance of Tag' do + it 'should create an instance of Tag' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::Tag) + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb new file mode 100644 index 000000000000..4fd29f1fc78e --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_deep_object_explode_true_object_all_of_query_object_parameter_spec.rb @@ -0,0 +1,54 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter do + let(:instance) { OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter.new } + + describe 'test an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' do + it 'should create an instance of TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter) + end + end + + describe 'test attribute "size"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "color"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "id"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + + describe 'test attribute "name"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb b/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb new file mode 100644 index 000000000000..092ead39ae9c --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/models/test_query_style_form_explode_true_array_string_query_object_parameter_spec.rb @@ -0,0 +1,36 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.2.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter do + let(:instance) { OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter.new } + + describe 'test an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' do + it 'should create an instance of TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(OpenapiClient::TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter) + end + end + + describe 'test attribute "values"' do + it 'should work' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end + +end diff --git a/samples/client/echo_api/ruby-typhoeus/spec/spec_helper.rb b/samples/client/echo_api/ruby-typhoeus/spec/spec_helper.rb new file mode 100644 index 000000000000..6cbca24b26da --- /dev/null +++ b/samples/client/echo_api/ruby-typhoeus/spec/spec_helper.rb @@ -0,0 +1,111 @@ +=begin +#Echo Server API + +#Echo Server API + +The version of the OpenAPI document: 0.1.0 +Contact: team@openapitools.org +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +# load the gem +require 'openapi_client' + +# The following was generated by the `rspec --init` command. Conventionally, all +# specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`. +# The generated `.rspec` file contains `--require spec_helper` which will cause +# this file to always be loaded, without a need to explicitly require it in any +# files. +# +# Given that it is always loaded, you are encouraged to keep this file as +# light-weight as possible. Requiring heavyweight dependencies from this file +# will add to the boot time of your test suite on EVERY test run, even for an +# individual file that may not need all of that loaded. Instead, consider making +# a separate helper file that requires the additional dependencies and performs +# the additional setup, and require it from the spec files that actually need +# it. +# +# The `.rspec` file also contains a few flags that are not defaults but that +# users commonly want. +# +# See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration +RSpec.configure do |config| + # rspec-expectations config goes here. You can use an alternate + # assertion/expectation library such as wrong or the stdlib/minitest + # assertions if you prefer. + config.expect_with :rspec do |expectations| + # This option will default to `true` in RSpec 4. It makes the `description` + # and `failure_message` of custom matchers include text for helper methods + # defined using `chain`, e.g.: + # be_bigger_than(2).and_smaller_than(4).description + # # => "be bigger than 2 and smaller than 4" + # ...rather than: + # # => "be bigger than 2" + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + # rspec-mocks config goes here. You can use an alternate test double + # library (such as bogus or mocha) by changing the `mock_with` option here. + config.mock_with :rspec do |mocks| + # Prevents you from mocking or stubbing a method that does not exist on + # a real object. This is generally recommended, and will default to + # `true` in RSpec 4. + mocks.verify_partial_doubles = true + end + +# The settings below are suggested to provide a good initial experience +# with RSpec, but feel free to customize to your heart's content. +=begin + # These two settings work together to allow you to limit a spec run + # to individual examples or groups you care about by tagging them with + # `:focus` metadata. When nothing is tagged with `:focus`, all examples + # get run. + config.filter_run :focus + config.run_all_when_everything_filtered = true + + # Allows RSpec to persist some state between runs in order to support + # the `--only-failures` and `--next-failure` CLI options. We recommend + # you configure your source control system to ignore this file. + config.example_status_persistence_file_path = "spec/examples.txt" + + # Limits the available syntax to the non-monkey patched syntax that is + # recommended. For more details, see: + # - http://rspec.info/blog/2012/06/rspecs-new-expectation-syntax/ + # - http://www.teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/ + # - http://rspec.info/blog/2014/05/notable-changes-in-rspec-3/#zero-monkey-patching-mode + config.disable_monkey_patching! + + # This setting enables warnings. It's recommended, but in some cases may + # be too noisy due to issues in dependencies. + config.warnings = true + + # Many RSpec users commonly either run the entire suite or an individual + # file, and it's useful to allow more verbose output when running an + # individual spec file. + if config.files_to_run.one? + # Use the documentation formatter for detailed output, + # unless a formatter has already been configured + # (e.g. via a command-line flag). + config.default_formatter = 'doc' + end + + # Print the 10 slowest examples and example groups at the + # end of the spec run, to help surface which specs are running + # particularly slow. + config.profile_examples = 10 + + # Run specs in random order to surface order dependencies. If you find an + # order dependency and want to debug it, you can fix the order by providing + # the seed, which is printed after each run. + # --seed 1234 + config.order = :random + + # Seed global randomization in this process using the `--seed` CLI option. + # Setting this allows you to use `--seed` to deterministically reproduce + # test failures related to randomization by passing the same `--seed` value + # as the one that triggered the failure. + Kernel.srand config.seed +=end +end diff --git a/samples/client/echo_api/typescript-axios/build/.gitignore b/samples/client/echo_api/typescript-axios/build/.gitignore new file mode 100644 index 000000000000..149b57654723 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/.gitignore @@ -0,0 +1,4 @@ +wwwroot/*.js +node_modules +typings +dist diff --git a/samples/client/echo_api/typescript-axios/build/.npmignore b/samples/client/echo_api/typescript-axios/build/.npmignore new file mode 100644 index 000000000000..999d88df6939 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/.npmignore @@ -0,0 +1 @@ +# empty npmignore to ensure all required files (e.g., in the dist folder) are published by npm \ No newline at end of file diff --git a/samples/client/echo_api/typescript-axios/build/.openapi-generator-ignore b/samples/client/echo_api/typescript-axios/build/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/echo_api/typescript-axios/build/.openapi-generator/FILES b/samples/client/echo_api/typescript-axios/build/.openapi-generator/FILES new file mode 100644 index 000000000000..534fae710fba --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/.openapi-generator/FILES @@ -0,0 +1,11 @@ +.gitignore +.npmignore +README.md +api.ts +base.ts +common.ts +configuration.ts +git_push.sh +index.ts +package.json +tsconfig.json diff --git a/samples/client/echo_api/typescript-axios/build/.openapi-generator/VERSION b/samples/client/echo_api/typescript-axios/build/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/echo_api/typescript-axios/build/README.md b/samples/client/echo_api/typescript-axios/build/README.md new file mode 100644 index 000000000000..dee9dba2ad59 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/README.md @@ -0,0 +1,45 @@ +## @openapitools/typescript-axios-echo-api@1.0.0 + +This generator creates TypeScript/JavaScript client that utilizes [axios](https://github.com/axios/axios). The generated Node module can be used in the following environments: + +Environment +* Node.js +* Webpack +* Browserify + +Language level +* ES5 - you must have a Promises/A+ library installed +* ES6 + +Module system +* CommonJS +* ES6 module system + +It can be used in both TypeScript and JavaScript. In TypeScript, the definition should be automatically resolved via `package.json`. ([Reference](http://www.typescriptlang.org/docs/handbook/typings-for-npm-packages.html)) + +### Building + +To build and compile the typescript sources to javascript use: +``` +npm install +npm run build +``` + +### Publishing + +First build the package then run ```npm publish``` + +### Consuming + +navigate to the folder of your consuming project and run one of the following commands. + +_published:_ + +``` +npm install @openapitools/typescript-axios-echo-api@1.0.0 --save +``` + +_unPublished (not recommended):_ + +``` +npm install PATH_TO_GENERATED_PACKAGE --save diff --git a/samples/client/echo_api/typescript-axios/build/api.ts b/samples/client/echo_api/typescript-axios/build/api.ts new file mode 100644 index 000000000000..df7ff8282395 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/api.ts @@ -0,0 +1,2375 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; +// Some imports not used depending on template conditions +// @ts-ignore +import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; +import type { RequestArgs } from './base'; +// @ts-ignore +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; + +/** + * + * @export + * @interface Bird + */ +export interface Bird { + /** + * + * @type {string} + * @memberof Bird + */ + 'size'?: string; + /** + * + * @type {string} + * @memberof Bird + */ + 'color'?: string; +} +/** + * + * @export + * @interface Category + */ +export interface Category { + /** + * + * @type {number} + * @memberof Category + */ + 'id'?: number; + /** + * + * @type {string} + * @memberof Category + */ + 'name'?: string; +} +/** + * + * @export + * @interface DataQuery + */ +export interface DataQuery extends Query { + /** + * test suffix + * @type {string} + * @memberof DataQuery + */ + 'suffix'?: string; + /** + * Some text containing white spaces + * @type {string} + * @memberof DataQuery + */ + 'text'?: string; + /** + * A date + * @type {string} + * @memberof DataQuery + */ + 'date'?: string; +} + + +/** + * to test the default value of properties + * @export + * @interface DefaultValue + */ +export interface DefaultValue { + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string_enum_ref_default'?: Array; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string_enum_default'?: Array; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string_default'?: Array; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_integer_default'?: Array; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string'?: Array; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string_nullable'?: Array | null; + /** + * + * @type {Array} + * @memberof DefaultValue + */ + 'array_string_extension_nullable'?: Array | null; + /** + * + * @type {string} + * @memberof DefaultValue + */ + 'string_nullable'?: string | null; +} + +export const DefaultValueArrayStringEnumDefaultEnum = { + Success: 'success', + Failure: 'failure', + Unclassified: 'unclassified' +} as const; + +export type DefaultValueArrayStringEnumDefaultEnum = typeof DefaultValueArrayStringEnumDefaultEnum[keyof typeof DefaultValueArrayStringEnumDefaultEnum]; + +/** + * + * @export + * @interface NumberPropertiesOnly + */ +export interface NumberPropertiesOnly { + /** + * + * @type {number} + * @memberof NumberPropertiesOnly + */ + 'number'?: number; + /** + * + * @type {number} + * @memberof NumberPropertiesOnly + */ + 'float'?: number; + /** + * + * @type {number} + * @memberof NumberPropertiesOnly + */ + 'double'?: number; +} +/** + * + * @export + * @interface Pet + */ +export interface Pet { + /** + * + * @type {number} + * @memberof Pet + */ + 'id'?: number; + /** + * + * @type {string} + * @memberof Pet + */ + 'name': string; + /** + * + * @type {Category} + * @memberof Pet + */ + 'category'?: Category; + /** + * + * @type {Array} + * @memberof Pet + */ + 'photoUrls': Array; + /** + * + * @type {Array} + * @memberof Pet + */ + 'tags'?: Array; + /** + * pet status in the store + * @type {string} + * @memberof Pet + */ + 'status'?: PetStatusEnum; +} + +export const PetStatusEnum = { + Available: 'available', + Pending: 'pending', + Sold: 'sold' +} as const; + +export type PetStatusEnum = typeof PetStatusEnum[keyof typeof PetStatusEnum]; + +/** + * + * @export + * @interface Query + */ +export interface Query { + /** + * Query + * @type {number} + * @memberof Query + */ + 'id'?: number; + /** + * + * @type {Array} + * @memberof Query + */ + 'outcomes'?: Array; +} + +export const QueryOutcomesEnum = { + Success: 'SUCCESS', + Failure: 'FAILURE', + Skipped: 'SKIPPED' +} as const; + +export type QueryOutcomesEnum = typeof QueryOutcomesEnum[keyof typeof QueryOutcomesEnum]; + +/** + * + * @export + * @enum {string} + */ + +export const StringEnumRef = { + Success: 'success', + Failure: 'failure', + Unclassified: 'unclassified' +} as const; + +export type StringEnumRef = typeof StringEnumRef[keyof typeof StringEnumRef]; + + +/** + * + * @export + * @interface Tag + */ +export interface Tag { + /** + * + * @type {number} + * @memberof Tag + */ + 'id'?: number; + /** + * + * @type {string} + * @memberof Tag + */ + 'name'?: string; +} +/** + * + * @export + * @interface TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ +export interface TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter { + /** + * + * @type {string} + * @memberof TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + 'size'?: string; + /** + * + * @type {string} + * @memberof TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + 'color'?: string; + /** + * + * @type {number} + * @memberof TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + 'id'?: number; + /** + * + * @type {string} + * @memberof TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter + */ + 'name'?: string; +} +/** + * + * @export + * @interface TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ +export interface TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter { + /** + * + * @type {Array} + * @memberof TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter + */ + 'values'?: Array; +} + +/** + * AuthApi - axios parameter creator + * @export + */ +export const AuthApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * To test HTTP basic authentication + * @summary To test HTTP basic authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAuthHttpBasic: async (options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/auth/http/basic`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication http_auth required + // http basic authentication required + setBasicAuthToObject(localVarRequestOptions, configuration) + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * To test HTTP bearer authentication + * @summary To test HTTP bearer authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAuthHttpBearer: async (options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/auth/http/bearer`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + // authentication http_bearer_auth required + // http bearer authentication required + await setBearerAuthToObject(localVarHeaderParameter, configuration) + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * AuthApi - functional programming interface + * @export + */ +export const AuthApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = AuthApiAxiosParamCreator(configuration) + return { + /** + * To test HTTP basic authentication + * @summary To test HTTP basic authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testAuthHttpBasic(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testAuthHttpBasic(options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['AuthApi.testAuthHttpBasic']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * To test HTTP bearer authentication + * @summary To test HTTP bearer authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testAuthHttpBearer(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testAuthHttpBearer(options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['AuthApi.testAuthHttpBearer']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * AuthApi - factory interface + * @export + */ +export const AuthApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = AuthApiFp(configuration) + return { + /** + * To test HTTP basic authentication + * @summary To test HTTP basic authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAuthHttpBasic(options?: any): AxiosPromise { + return localVarFp.testAuthHttpBasic(options).then((request) => request(axios, basePath)); + }, + /** + * To test HTTP bearer authentication + * @summary To test HTTP bearer authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAuthHttpBearer(options?: any): AxiosPromise { + return localVarFp.testAuthHttpBearer(options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * AuthApi - object-oriented interface + * @export + * @class AuthApi + * @extends {BaseAPI} + */ +export class AuthApi extends BaseAPI { + /** + * To test HTTP basic authentication + * @summary To test HTTP basic authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof AuthApi + */ + public testAuthHttpBasic(options?: RawAxiosRequestConfig) { + return AuthApiFp(this.configuration).testAuthHttpBasic(options).then((request) => request(this.axios, this.basePath)); + } + + /** + * To test HTTP bearer authentication + * @summary To test HTTP bearer authentication + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof AuthApi + */ + public testAuthHttpBearer(options?: RawAxiosRequestConfig) { + return AuthApiFp(this.configuration).testAuthHttpBearer(options).then((request) => request(this.axios, this.basePath)); + } +} + + + +/** + * BodyApi - axios parameter creator + * @export + */ +export const BodyApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * Test binary (gif) response body + * @summary Test binary (gif) response body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBinaryGif: async (options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/binary/gif`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {File} [body] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyApplicationOctetstreamBinary: async (body?: File, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/body/application/octetstream/binary`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/octet-stream'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test array of binary in multipart mime + * @summary Test array of binary in multipart mime + * @param {Array} files + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyMultipartFormdataArrayOfBinary: async (files: Array, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'files' is not null or undefined + assertParamExists('testBodyMultipartFormdataArrayOfBinary', 'files', files) + const localVarPath = `/body/application/octetstream/array_of_binary`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)(); + + if (files) { + files.forEach((element) => { + localVarFormParams.append('files', element as any); + }) + } + + + + localVarHeaderParameter['Content-Type'] = 'multipart/form-data'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = localVarFormParams; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test single binary in multipart mime + * @summary Test single binary in multipart mime + * @param {File} [myFile] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyMultipartFormdataSingleBinary: async (myFile?: File, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/body/application/octetstream/single_binary`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new ((configuration && configuration.formDataCtor) || FormData)(); + + + if (myFile !== undefined) { + localVarFormParams.append('my-file', myFile as any); + } + + + localVarHeaderParameter['Content-Type'] = 'multipart/form-data'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = localVarFormParams; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyAllOfPet: async (pet?: Pet, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/echo/body/allOf/Pet`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(pet, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test free form object + * @summary Test free form object + * @param {object} [body] Free form object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyFreeFormObjectResponseString: async (body?: object, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/echo/body/FreeFormObject/response_string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(body, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyPet: async (pet?: Pet, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/echo/body/Pet`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(pet, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test empty response body + * @summary Test empty response body + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyPetResponseString: async (pet?: Pet, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/echo/body/Pet/response_string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(pet, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test empty json (request body) + * @summary Test empty json (request body) + * @param {Tag} [tag] Tag object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyTagResponseString: async (tag?: Tag, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/echo/body/Tag/response_string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(tag, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * BodyApi - functional programming interface + * @export + */ +export const BodyApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = BodyApiAxiosParamCreator(configuration) + return { + /** + * Test binary (gif) response body + * @summary Test binary (gif) response body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testBinaryGif(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testBinaryGif(options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testBinaryGif']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {File} [body] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testBodyApplicationOctetstreamBinary(body?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyApplicationOctetstreamBinary(body, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testBodyApplicationOctetstreamBinary']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test array of binary in multipart mime + * @summary Test array of binary in multipart mime + * @param {Array} files + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testBodyMultipartFormdataArrayOfBinary(files: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyMultipartFormdataArrayOfBinary(files, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testBodyMultipartFormdataArrayOfBinary']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test single binary in multipart mime + * @summary Test single binary in multipart mime + * @param {File} [myFile] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testBodyMultipartFormdataSingleBinary(myFile?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyMultipartFormdataSingleBinary(myFile, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testBodyMultipartFormdataSingleBinary']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEchoBodyAllOfPet(pet?: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEchoBodyAllOfPet(pet, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testEchoBodyAllOfPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test free form object + * @summary Test free form object + * @param {object} [body] Free form object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEchoBodyFreeFormObjectResponseString(body?: object, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEchoBodyFreeFormObjectResponseString(body, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testEchoBodyFreeFormObjectResponseString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEchoBodyPet(pet?: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEchoBodyPet(pet, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testEchoBodyPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test empty response body + * @summary Test empty response body + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEchoBodyPetResponseString(pet?: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEchoBodyPetResponseString(pet, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testEchoBodyPetResponseString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test empty json (request body) + * @summary Test empty json (request body) + * @param {Tag} [tag] Tag object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEchoBodyTagResponseString(tag?: Tag, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEchoBodyTagResponseString(tag, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['BodyApi.testEchoBodyTagResponseString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * BodyApi - factory interface + * @export + */ +export const BodyApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = BodyApiFp(configuration) + return { + /** + * Test binary (gif) response body + * @summary Test binary (gif) response body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBinaryGif(options?: any): AxiosPromise { + return localVarFp.testBinaryGif(options).then((request) => request(axios, basePath)); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {File} [body] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyApplicationOctetstreamBinary(body?: File, options?: any): AxiosPromise { + return localVarFp.testBodyApplicationOctetstreamBinary(body, options).then((request) => request(axios, basePath)); + }, + /** + * Test array of binary in multipart mime + * @summary Test array of binary in multipart mime + * @param {Array} files + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyMultipartFormdataArrayOfBinary(files: Array, options?: any): AxiosPromise { + return localVarFp.testBodyMultipartFormdataArrayOfBinary(files, options).then((request) => request(axios, basePath)); + }, + /** + * Test single binary in multipart mime + * @summary Test single binary in multipart mime + * @param {File} [myFile] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testBodyMultipartFormdataSingleBinary(myFile?: File, options?: any): AxiosPromise { + return localVarFp.testBodyMultipartFormdataSingleBinary(myFile, options).then((request) => request(axios, basePath)); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyAllOfPet(pet?: Pet, options?: any): AxiosPromise { + return localVarFp.testEchoBodyAllOfPet(pet, options).then((request) => request(axios, basePath)); + }, + /** + * Test free form object + * @summary Test free form object + * @param {object} [body] Free form object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyFreeFormObjectResponseString(body?: object, options?: any): AxiosPromise { + return localVarFp.testEchoBodyFreeFormObjectResponseString(body, options).then((request) => request(axios, basePath)); + }, + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyPet(pet?: Pet, options?: any): AxiosPromise { + return localVarFp.testEchoBodyPet(pet, options).then((request) => request(axios, basePath)); + }, + /** + * Test empty response body + * @summary Test empty response body + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyPetResponseString(pet?: Pet, options?: any): AxiosPromise { + return localVarFp.testEchoBodyPetResponseString(pet, options).then((request) => request(axios, basePath)); + }, + /** + * Test empty json (request body) + * @summary Test empty json (request body) + * @param {Tag} [tag] Tag object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEchoBodyTagResponseString(tag?: Tag, options?: any): AxiosPromise { + return localVarFp.testEchoBodyTagResponseString(tag, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * BodyApi - object-oriented interface + * @export + * @class BodyApi + * @extends {BaseAPI} + */ +export class BodyApi extends BaseAPI { + /** + * Test binary (gif) response body + * @summary Test binary (gif) response body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testBinaryGif(options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testBinaryGif(options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {File} [body] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testBodyApplicationOctetstreamBinary(body?: File, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testBodyApplicationOctetstreamBinary(body, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test array of binary in multipart mime + * @summary Test array of binary in multipart mime + * @param {Array} files + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testBodyMultipartFormdataArrayOfBinary(files: Array, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testBodyMultipartFormdataArrayOfBinary(files, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test single binary in multipart mime + * @summary Test single binary in multipart mime + * @param {File} [myFile] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testBodyMultipartFormdataSingleBinary(myFile?: File, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testBodyMultipartFormdataSingleBinary(myFile, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testEchoBodyAllOfPet(pet?: Pet, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testEchoBodyAllOfPet(pet, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test free form object + * @summary Test free form object + * @param {object} [body] Free form object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testEchoBodyFreeFormObjectResponseString(body?: object, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testEchoBodyFreeFormObjectResponseString(body, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test body parameter(s) + * @summary Test body parameter(s) + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testEchoBodyPet(pet?: Pet, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testEchoBodyPet(pet, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test empty response body + * @summary Test empty response body + * @param {Pet} [pet] Pet object that needs to be added to the store + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testEchoBodyPetResponseString(pet?: Pet, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testEchoBodyPetResponseString(pet, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test empty json (request body) + * @summary Test empty json (request body) + * @param {Tag} [tag] Tag object + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof BodyApi + */ + public testEchoBodyTagResponseString(tag?: Tag, options?: RawAxiosRequestConfig) { + return BodyApiFp(this.configuration).testEchoBodyTagResponseString(tag, options).then((request) => request(this.axios, this.basePath)); + } +} + + + +/** + * FormApi - axios parameter creator + * @export + */ +export const FormApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * Test form parameter(s) + * @summary Test form parameter(s) + * @param {number} [integerForm] + * @param {boolean} [booleanForm] + * @param {string} [stringForm] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testFormIntegerBooleanString: async (integerForm?: number, booleanForm?: boolean, stringForm?: string, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/form/integer/boolean/string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new URLSearchParams(); + + + if (integerForm !== undefined) { + localVarFormParams.set('integer_form', integerForm as any); + } + + if (booleanForm !== undefined) { + localVarFormParams.set('boolean_form', booleanForm as any); + } + + if (stringForm !== undefined) { + localVarFormParams.set('string_form', stringForm as any); + } + + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = localVarFormParams.toString(); + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test form parameter(s) for oneOf schema + * @summary Test form parameter(s) for oneOf schema + * @param {string} [form1] + * @param {number} [form2] + * @param {string} [form3] + * @param {boolean} [form4] + * @param {number} [id] + * @param {string} [name] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testFormOneof: async (form1?: string, form2?: number, form3?: string, form4?: boolean, id?: number, name?: string, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/form/oneof`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + const localVarFormParams = new URLSearchParams(); + + + if (form1 !== undefined) { + localVarFormParams.set('form1', form1 as any); + } + + if (form2 !== undefined) { + localVarFormParams.set('form2', form2 as any); + } + + if (form3 !== undefined) { + localVarFormParams.set('form3', form3 as any); + } + + if (form4 !== undefined) { + localVarFormParams.set('form4', form4 as any); + } + + if (id !== undefined) { + localVarFormParams.set('id', id as any); + } + + if (name !== undefined) { + localVarFormParams.set('name', name as any); + } + + + localVarHeaderParameter['Content-Type'] = 'application/x-www-form-urlencoded'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = localVarFormParams.toString(); + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * FormApi - functional programming interface + * @export + */ +export const FormApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = FormApiAxiosParamCreator(configuration) + return { + /** + * Test form parameter(s) + * @summary Test form parameter(s) + * @param {number} [integerForm] + * @param {boolean} [booleanForm] + * @param {string} [stringForm] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testFormIntegerBooleanString(integerForm?: number, booleanForm?: boolean, stringForm?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testFormIntegerBooleanString(integerForm, booleanForm, stringForm, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FormApi.testFormIntegerBooleanString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test form parameter(s) for oneOf schema + * @summary Test form parameter(s) for oneOf schema + * @param {string} [form1] + * @param {number} [form2] + * @param {string} [form3] + * @param {boolean} [form4] + * @param {number} [id] + * @param {string} [name] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testFormOneof(form1?: string, form2?: number, form3?: string, form4?: boolean, id?: number, name?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testFormOneof(form1, form2, form3, form4, id, name, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FormApi.testFormOneof']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * FormApi - factory interface + * @export + */ +export const FormApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = FormApiFp(configuration) + return { + /** + * Test form parameter(s) + * @summary Test form parameter(s) + * @param {number} [integerForm] + * @param {boolean} [booleanForm] + * @param {string} [stringForm] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testFormIntegerBooleanString(integerForm?: number, booleanForm?: boolean, stringForm?: string, options?: any): AxiosPromise { + return localVarFp.testFormIntegerBooleanString(integerForm, booleanForm, stringForm, options).then((request) => request(axios, basePath)); + }, + /** + * Test form parameter(s) for oneOf schema + * @summary Test form parameter(s) for oneOf schema + * @param {string} [form1] + * @param {number} [form2] + * @param {string} [form3] + * @param {boolean} [form4] + * @param {number} [id] + * @param {string} [name] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testFormOneof(form1?: string, form2?: number, form3?: string, form4?: boolean, id?: number, name?: string, options?: any): AxiosPromise { + return localVarFp.testFormOneof(form1, form2, form3, form4, id, name, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * FormApi - object-oriented interface + * @export + * @class FormApi + * @extends {BaseAPI} + */ +export class FormApi extends BaseAPI { + /** + * Test form parameter(s) + * @summary Test form parameter(s) + * @param {number} [integerForm] + * @param {boolean} [booleanForm] + * @param {string} [stringForm] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof FormApi + */ + public testFormIntegerBooleanString(integerForm?: number, booleanForm?: boolean, stringForm?: string, options?: RawAxiosRequestConfig) { + return FormApiFp(this.configuration).testFormIntegerBooleanString(integerForm, booleanForm, stringForm, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test form parameter(s) for oneOf schema + * @summary Test form parameter(s) for oneOf schema + * @param {string} [form1] + * @param {number} [form2] + * @param {string} [form3] + * @param {boolean} [form4] + * @param {number} [id] + * @param {string} [name] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof FormApi + */ + public testFormOneof(form1?: string, form2?: number, form3?: string, form4?: boolean, id?: number, name?: string, options?: RawAxiosRequestConfig) { + return FormApiFp(this.configuration).testFormOneof(form1, form2, form3, form4, id, name, options).then((request) => request(this.axios, this.basePath)); + } +} + + + +/** + * HeaderApi - axios parameter creator + * @export + */ +export const HeaderApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * Test header parameter(s) + * @summary Test header parameter(s) + * @param {number} [integerHeader] + * @param {boolean} [booleanHeader] + * @param {string} [stringHeader] + * @param {TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum} [enumNonrefStringHeader] + * @param {StringEnumRef} [enumRefStringHeader] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testHeaderIntegerBooleanStringEnums: async (integerHeader?: number, booleanHeader?: boolean, stringHeader?: string, enumNonrefStringHeader?: TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum, enumRefStringHeader?: StringEnumRef, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/header/integer/boolean/string/enums`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (integerHeader != null) { + localVarHeaderParameter['integer_header'] = typeof integerHeader === 'string' + ? integerHeader + : JSON.stringify(integerHeader); + } + + if (booleanHeader != null) { + localVarHeaderParameter['boolean_header'] = typeof booleanHeader === 'string' + ? booleanHeader + : JSON.stringify(booleanHeader); + } + + if (stringHeader != null) { + localVarHeaderParameter['string_header'] = String(stringHeader); + } + + if (enumNonrefStringHeader != null) { + localVarHeaderParameter['enum_nonref_string_header'] = String(enumNonrefStringHeader); + } + + if (enumRefStringHeader != null) { + localVarHeaderParameter['enum_ref_string_header'] = typeof enumRefStringHeader === 'string' + ? enumRefStringHeader + : JSON.stringify(enumRefStringHeader); + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * HeaderApi - functional programming interface + * @export + */ +export const HeaderApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = HeaderApiAxiosParamCreator(configuration) + return { + /** + * Test header parameter(s) + * @summary Test header parameter(s) + * @param {number} [integerHeader] + * @param {boolean} [booleanHeader] + * @param {string} [stringHeader] + * @param {TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum} [enumNonrefStringHeader] + * @param {StringEnumRef} [enumRefStringHeader] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testHeaderIntegerBooleanStringEnums(integerHeader?: number, booleanHeader?: boolean, stringHeader?: string, enumNonrefStringHeader?: TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum, enumRefStringHeader?: StringEnumRef, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['HeaderApi.testHeaderIntegerBooleanStringEnums']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * HeaderApi - factory interface + * @export + */ +export const HeaderApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = HeaderApiFp(configuration) + return { + /** + * Test header parameter(s) + * @summary Test header parameter(s) + * @param {number} [integerHeader] + * @param {boolean} [booleanHeader] + * @param {string} [stringHeader] + * @param {TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum} [enumNonrefStringHeader] + * @param {StringEnumRef} [enumRefStringHeader] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testHeaderIntegerBooleanStringEnums(integerHeader?: number, booleanHeader?: boolean, stringHeader?: string, enumNonrefStringHeader?: TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum, enumRefStringHeader?: StringEnumRef, options?: any): AxiosPromise { + return localVarFp.testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * HeaderApi - object-oriented interface + * @export + * @class HeaderApi + * @extends {BaseAPI} + */ +export class HeaderApi extends BaseAPI { + /** + * Test header parameter(s) + * @summary Test header parameter(s) + * @param {number} [integerHeader] + * @param {boolean} [booleanHeader] + * @param {string} [stringHeader] + * @param {TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum} [enumNonrefStringHeader] + * @param {StringEnumRef} [enumRefStringHeader] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof HeaderApi + */ + public testHeaderIntegerBooleanStringEnums(integerHeader?: number, booleanHeader?: boolean, stringHeader?: string, enumNonrefStringHeader?: TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum, enumRefStringHeader?: StringEnumRef, options?: RawAxiosRequestConfig) { + return HeaderApiFp(this.configuration).testHeaderIntegerBooleanStringEnums(integerHeader, booleanHeader, stringHeader, enumNonrefStringHeader, enumRefStringHeader, options).then((request) => request(this.axios, this.basePath)); + } +} + +/** + * @export + */ +export const TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum = { + Success: 'success', + Failure: 'failure', + Unclassified: 'unclassified' +} as const; +export type TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum = typeof TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum[keyof typeof TestHeaderIntegerBooleanStringEnumsEnumNonrefStringHeaderEnum]; + + +/** + * PathApi - axios parameter creator + * @export + */ +export const PathApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * Test path parameter(s) + * @summary Test path parameter(s) + * @param {string} pathString + * @param {number} pathInteger + * @param {TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum} enumNonrefStringPath + * @param {StringEnumRef} enumRefStringPath + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath: async (pathString: string, pathInteger: number, enumNonrefStringPath: TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum, enumRefStringPath: StringEnumRef, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'pathString' is not null or undefined + assertParamExists('testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath', 'pathString', pathString) + // verify required parameter 'pathInteger' is not null or undefined + assertParamExists('testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath', 'pathInteger', pathInteger) + // verify required parameter 'enumNonrefStringPath' is not null or undefined + assertParamExists('testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath', 'enumNonrefStringPath', enumNonrefStringPath) + // verify required parameter 'enumRefStringPath' is not null or undefined + assertParamExists('testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath', 'enumRefStringPath', enumRefStringPath) + const localVarPath = `/path/string/{path_string}/integer/{path_integer}/{enum_nonref_string_path}/{enum_ref_string_path}` + .replace(`{${"path_string"}}`, encodeURIComponent(String(pathString))) + .replace(`{${"path_integer"}}`, encodeURIComponent(String(pathInteger))) + .replace(`{${"enum_nonref_string_path"}}`, encodeURIComponent(String(enumNonrefStringPath))) + .replace(`{${"enum_ref_string_path"}}`, encodeURIComponent(String(enumRefStringPath))); + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * PathApi - functional programming interface + * @export + */ +export const PathApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = PathApiAxiosParamCreator(configuration) + return { + /** + * Test path parameter(s) + * @summary Test path parameter(s) + * @param {string} pathString + * @param {number} pathInteger + * @param {TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum} enumNonrefStringPath + * @param {StringEnumRef} enumRefStringPath + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString: string, pathInteger: number, enumNonrefStringPath: TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum, enumRefStringPath: StringEnumRef, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PathApi.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * PathApi - factory interface + * @export + */ +export const PathApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = PathApiFp(configuration) + return { + /** + * Test path parameter(s) + * @summary Test path parameter(s) + * @param {string} pathString + * @param {number} pathInteger + * @param {TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum} enumNonrefStringPath + * @param {StringEnumRef} enumRefStringPath + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString: string, pathInteger: number, enumNonrefStringPath: TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum, enumRefStringPath: StringEnumRef, options?: any): AxiosPromise { + return localVarFp.testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * PathApi - object-oriented interface + * @export + * @class PathApi + * @extends {BaseAPI} + */ +export class PathApi extends BaseAPI { + /** + * Test path parameter(s) + * @summary Test path parameter(s) + * @param {string} pathString + * @param {number} pathInteger + * @param {TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum} enumNonrefStringPath + * @param {StringEnumRef} enumRefStringPath + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof PathApi + */ + public testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString: string, pathInteger: number, enumNonrefStringPath: TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum, enumRefStringPath: StringEnumRef, options?: RawAxiosRequestConfig) { + return PathApiFp(this.configuration).testsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPath(pathString, pathInteger, enumNonrefStringPath, enumRefStringPath, options).then((request) => request(this.axios, this.basePath)); + } +} + +/** + * @export + */ +export const TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum = { + Success: 'success', + Failure: 'failure', + Unclassified: 'unclassified' +} as const; +export type TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum = typeof TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum[keyof typeof TestsPathStringPathStringIntegerPathIntegerEnumNonrefStringPathEnumRefStringPathEnumNonrefStringPathEnum]; + + +/** + * QueryApi - axios parameter creator + * @export + */ +export const QueryApiAxiosParamCreator = function (configuration?: Configuration) { + return { + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestEnumRefStringEnumNonrefStringQueryEnum} [enumNonrefStringQuery] + * @param {StringEnumRef} [enumRefStringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEnumRefString: async (enumNonrefStringQuery?: TestEnumRefStringEnumNonrefStringQueryEnum, enumRefStringQuery?: StringEnumRef, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/enum_ref_string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (enumNonrefStringQuery !== undefined) { + localVarQueryParameter['enum_nonref_string_query'] = enumNonrefStringQuery; + } + + if (enumRefStringQuery !== undefined) { + localVarQueryParameter['enum_ref_string_query'] = enumRefStringQuery; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {string} [datetimeQuery] + * @param {string} [dateQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryDatetimeDateString: async (datetimeQuery?: string, dateQuery?: string, stringQuery?: string, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/datetime/date/string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (datetimeQuery !== undefined) { + localVarQueryParameter['datetime_query'] = (datetimeQuery as any instanceof Date) ? + (datetimeQuery as any).toISOString() : + datetimeQuery; + } + + if (dateQuery !== undefined) { + localVarQueryParameter['date_query'] = (dateQuery as any instanceof Date) ? + (dateQuery as any).toISOString().substring(0,10) : + dateQuery; + } + + if (stringQuery !== undefined) { + localVarQueryParameter['string_query'] = stringQuery; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {number} [integerQuery] + * @param {boolean} [booleanQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryIntegerBooleanString: async (integerQuery?: number, booleanQuery?: boolean, stringQuery?: string, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/integer/boolean/string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (integerQuery !== undefined) { + localVarQueryParameter['integer_query'] = integerQuery; + } + + if (booleanQuery !== undefined) { + localVarQueryParameter['boolean_query'] = booleanQuery; + } + + if (stringQuery !== undefined) { + localVarQueryParameter['string_query'] = stringQuery; + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleDeepObjectExplodeTrueObject: async (queryObject?: Pet, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/style_deepObject/explode_true/object`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (queryObject !== undefined) { + for (const [key, value] of Object.entries(queryObject)) { + localVarQueryParameter[key] = value; + } + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleDeepObjectExplodeTrueObjectAllOf: async (queryObject?: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/style_deepObject/explode_true/object/allOf`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (queryObject !== undefined) { + for (const [key, value] of Object.entries(queryObject)) { + localVarQueryParameter[key] = value; + } + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueArrayString: async (queryObject?: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/style_form/explode_true/array_string`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (queryObject !== undefined) { + for (const [key, value] of Object.entries(queryObject)) { + localVarQueryParameter[key] = value; + } + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueObject: async (queryObject?: Pet, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/style_form/explode_true/object`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (queryObject !== undefined) { + for (const [key, value] of Object.entries(queryObject)) { + localVarQueryParameter[key] = value; + } + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {DataQuery} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueObjectAllOf: async (queryObject?: DataQuery, options: RawAxiosRequestConfig = {}): Promise => { + const localVarPath = `/query/style_form/explode_true/object/allOf`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'GET', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + if (queryObject !== undefined) { + for (const [key, value] of Object.entries(queryObject)) { + localVarQueryParameter[key] = value; + } + } + + + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, + } +}; + +/** + * QueryApi - functional programming interface + * @export + */ +export const QueryApiFp = function(configuration?: Configuration) { + const localVarAxiosParamCreator = QueryApiAxiosParamCreator(configuration) + return { + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestEnumRefStringEnumNonrefStringQueryEnum} [enumNonrefStringQuery] + * @param {StringEnumRef} [enumRefStringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testEnumRefString(enumNonrefStringQuery?: TestEnumRefStringEnumNonrefStringQueryEnum, enumRefStringQuery?: StringEnumRef, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testEnumRefString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {string} [datetimeQuery] + * @param {string} [dateQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryDatetimeDateString(datetimeQuery?: string, dateQuery?: string, stringQuery?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryDatetimeDateString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {number} [integerQuery] + * @param {boolean} [booleanQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryIntegerBooleanString(integerQuery?: number, booleanQuery?: boolean, stringQuery?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryIntegerBooleanString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryStyleDeepObjectExplodeTrueObject(queryObject?: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryStyleDeepObjectExplodeTrueObject(queryObject, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryStyleDeepObjectExplodeTrueObject']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject?: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryStyleDeepObjectExplodeTrueObjectAllOf']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryStyleFormExplodeTrueArrayString(queryObject?: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryStyleFormExplodeTrueArrayString(queryObject, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryStyleFormExplodeTrueArrayString']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryStyleFormExplodeTrueObject(queryObject?: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryStyleFormExplodeTrueObject(queryObject, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryStyleFormExplodeTrueObject']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {DataQuery} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testQueryStyleFormExplodeTrueObjectAllOf(queryObject?: DataQuery, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryStyleFormExplodeTrueObjectAllOf(queryObject, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['QueryApi.testQueryStyleFormExplodeTrueObjectAllOf']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + } +}; + +/** + * QueryApi - factory interface + * @export + */ +export const QueryApiFactory = function (configuration?: Configuration, basePath?: string, axios?: AxiosInstance) { + const localVarFp = QueryApiFp(configuration) + return { + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestEnumRefStringEnumNonrefStringQueryEnum} [enumNonrefStringQuery] + * @param {StringEnumRef} [enumRefStringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testEnumRefString(enumNonrefStringQuery?: TestEnumRefStringEnumNonrefStringQueryEnum, enumRefStringQuery?: StringEnumRef, options?: any): AxiosPromise { + return localVarFp.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {string} [datetimeQuery] + * @param {string} [dateQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryDatetimeDateString(datetimeQuery?: string, dateQuery?: string, stringQuery?: string, options?: any): AxiosPromise { + return localVarFp.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {number} [integerQuery] + * @param {boolean} [booleanQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryIntegerBooleanString(integerQuery?: number, booleanQuery?: boolean, stringQuery?: string, options?: any): AxiosPromise { + return localVarFp.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleDeepObjectExplodeTrueObject(queryObject?: Pet, options?: any): AxiosPromise { + return localVarFp.testQueryStyleDeepObjectExplodeTrueObject(queryObject, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject?: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter, options?: any): AxiosPromise { + return localVarFp.testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueArrayString(queryObject?: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter, options?: any): AxiosPromise { + return localVarFp.testQueryStyleFormExplodeTrueArrayString(queryObject, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueObject(queryObject?: Pet, options?: any): AxiosPromise { + return localVarFp.testQueryStyleFormExplodeTrueObject(queryObject, options).then((request) => request(axios, basePath)); + }, + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {DataQuery} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testQueryStyleFormExplodeTrueObjectAllOf(queryObject?: DataQuery, options?: any): AxiosPromise { + return localVarFp.testQueryStyleFormExplodeTrueObjectAllOf(queryObject, options).then((request) => request(axios, basePath)); + }, + }; +}; + +/** + * QueryApi - object-oriented interface + * @export + * @class QueryApi + * @extends {BaseAPI} + */ +export class QueryApi extends BaseAPI { + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestEnumRefStringEnumNonrefStringQueryEnum} [enumNonrefStringQuery] + * @param {StringEnumRef} [enumRefStringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testEnumRefString(enumNonrefStringQuery?: TestEnumRefStringEnumNonrefStringQueryEnum, enumRefStringQuery?: StringEnumRef, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testEnumRefString(enumNonrefStringQuery, enumRefStringQuery, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {string} [datetimeQuery] + * @param {string} [dateQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryDatetimeDateString(datetimeQuery?: string, dateQuery?: string, stringQuery?: string, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {number} [integerQuery] + * @param {boolean} [booleanQuery] + * @param {string} [stringQuery] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryIntegerBooleanString(integerQuery?: number, booleanQuery?: boolean, stringQuery?: string, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryStyleDeepObjectExplodeTrueObject(queryObject?: Pet, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryStyleDeepObjectExplodeTrueObject(queryObject, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject?: TestQueryStyleDeepObjectExplodeTrueObjectAllOfQueryObjectParameter, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryStyleDeepObjectExplodeTrueObjectAllOf(queryObject, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryStyleFormExplodeTrueArrayString(queryObject?: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryStyleFormExplodeTrueArrayString(queryObject, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {Pet} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryStyleFormExplodeTrueObject(queryObject?: Pet, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryStyleFormExplodeTrueObject(queryObject, options).then((request) => request(this.axios, this.basePath)); + } + + /** + * Test query parameter(s) + * @summary Test query parameter(s) + * @param {DataQuery} [queryObject] + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof QueryApi + */ + public testQueryStyleFormExplodeTrueObjectAllOf(queryObject?: DataQuery, options?: RawAxiosRequestConfig) { + return QueryApiFp(this.configuration).testQueryStyleFormExplodeTrueObjectAllOf(queryObject, options).then((request) => request(this.axios, this.basePath)); + } +} + +/** + * @export + */ +export const TestEnumRefStringEnumNonrefStringQueryEnum = { + Success: 'success', + Failure: 'failure', + Unclassified: 'unclassified' +} as const; +export type TestEnumRefStringEnumNonrefStringQueryEnum = typeof TestEnumRefStringEnumNonrefStringQueryEnum[keyof typeof TestEnumRefStringEnumNonrefStringQueryEnum]; + + diff --git a/samples/client/echo_api/typescript-axios/build/base.ts b/samples/client/echo_api/typescript-axios/build/base.ts new file mode 100644 index 000000000000..b95cd69a9ed8 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/base.ts @@ -0,0 +1,86 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from './configuration'; +// Some imports not used depending on template conditions +// @ts-ignore +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; +import globalAxios from 'axios'; + +export const BASE_PATH = "http://localhost:3000".replace(/\/+$/, ""); + +/** + * + * @export + */ +export const COLLECTION_FORMATS = { + csv: ",", + ssv: " ", + tsv: "\t", + pipes: "|", +}; + +/** + * + * @export + * @interface RequestArgs + */ +export interface RequestArgs { + url: string; + options: RawAxiosRequestConfig; +} + +/** + * + * @export + * @class BaseAPI + */ +export class BaseAPI { + protected configuration: Configuration | undefined; + + constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { + if (configuration) { + this.configuration = configuration; + this.basePath = configuration.basePath ?? basePath; + } + } +}; + +/** + * + * @export + * @class RequiredError + * @extends {Error} + */ +export class RequiredError extends Error { + constructor(public field: string, msg?: string) { + super(msg); + this.name = "RequiredError" + } +} + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/echo_api/typescript-axios/build/common.ts b/samples/client/echo_api/typescript-axios/build/common.ts new file mode 100644 index 000000000000..fc1881f27b35 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/common.ts @@ -0,0 +1,150 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +import type { Configuration } from "./configuration"; +import type { RequestArgs } from "./base"; +import type { AxiosInstance, AxiosResponse } from 'axios'; +import { RequiredError } from "./base"; + +/** + * + * @export + */ +export const DUMMY_BASE_URL = 'https://example.com' + +/** + * + * @throws {RequiredError} + * @export + */ +export const assertParamExists = function (functionName: string, paramName: string, paramValue: unknown) { + if (paramValue === null || paramValue === undefined) { + throw new RequiredError(paramName, `Required parameter ${paramName} was null or undefined when calling ${functionName}.`); + } +} + +/** + * + * @export + */ +export const setApiKeyToObject = async function (object: any, keyParamName: string, configuration?: Configuration) { + if (configuration && configuration.apiKey) { + const localVarApiKeyValue = typeof configuration.apiKey === 'function' + ? await configuration.apiKey(keyParamName) + : await configuration.apiKey; + object[keyParamName] = localVarApiKeyValue; + } +} + +/** + * + * @export + */ +export const setBasicAuthToObject = function (object: any, configuration?: Configuration) { + if (configuration && (configuration.username || configuration.password)) { + object["auth"] = { username: configuration.username, password: configuration.password }; + } +} + +/** + * + * @export + */ +export const setBearerAuthToObject = async function (object: any, configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const accessToken = typeof configuration.accessToken === 'function' + ? await configuration.accessToken() + : await configuration.accessToken; + object["Authorization"] = "Bearer " + accessToken; + } +} + +/** + * + * @export + */ +export const setOAuthToObject = async function (object: any, name: string, scopes: string[], configuration?: Configuration) { + if (configuration && configuration.accessToken) { + const localVarAccessTokenValue = typeof configuration.accessToken === 'function' + ? await configuration.accessToken(name, scopes) + : await configuration.accessToken; + object["Authorization"] = "Bearer " + localVarAccessTokenValue; + } +} + +function setFlattenedQueryParams(urlSearchParams: URLSearchParams, parameter: any, key: string = ""): void { + if (parameter == null) return; + if (typeof parameter === "object") { + if (Array.isArray(parameter)) { + (parameter as any[]).forEach(item => setFlattenedQueryParams(urlSearchParams, item, key)); + } + else { + Object.keys(parameter).forEach(currentKey => + setFlattenedQueryParams(urlSearchParams, parameter[currentKey], `${key}${key !== '' ? '.' : ''}${currentKey}`) + ); + } + } + else { + if (urlSearchParams.has(key)) { + urlSearchParams.append(key, parameter); + } + else { + urlSearchParams.set(key, parameter); + } + } +} + +/** + * + * @export + */ +export const setSearchParams = function (url: URL, ...objects: any[]) { + const searchParams = new URLSearchParams(url.search); + setFlattenedQueryParams(searchParams, objects); + url.search = searchParams.toString(); +} + +/** + * + * @export + */ +export const serializeDataIfNeeded = function (value: any, requestOptions: any, configuration?: Configuration) { + const nonString = typeof value !== 'string'; + const needsSerialization = nonString && configuration && configuration.isJsonMime + ? configuration.isJsonMime(requestOptions.headers['Content-Type']) + : nonString; + return needsSerialization + ? JSON.stringify(value !== undefined ? value : {}) + : (value || ""); +} + +/** + * + * @export + */ +export const toPathString = function (url: URL) { + return url.pathname + url.search + url.hash +} + +/** + * + * @export + */ +export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { + return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; + return axios.request(axiosRequestArgs); + }; +} diff --git a/samples/client/echo_api/typescript-axios/build/configuration.ts b/samples/client/echo_api/typescript-axios/build/configuration.ts new file mode 100644 index 000000000000..c952b7aefd76 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/configuration.ts @@ -0,0 +1,110 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export interface ConfigurationParameters { + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + username?: string; + password?: string; + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + basePath?: string; + serverIndex?: number; + baseOptions?: any; + formDataCtor?: new () => any; +} + +export class Configuration { + /** + * parameter for apiKey security + * @param name security name + * @memberof Configuration + */ + apiKey?: string | Promise | ((name: string) => string) | ((name: string) => Promise); + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + username?: string; + /** + * parameter for basic security + * + * @type {string} + * @memberof Configuration + */ + password?: string; + /** + * parameter for oauth2 security + * @param name security name + * @param scopes oauth2 scope + * @memberof Configuration + */ + accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); + /** + * override base path + * + * @type {string} + * @memberof Configuration + */ + basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; + /** + * base options for axios calls + * + * @type {any} + * @memberof Configuration + */ + baseOptions?: any; + /** + * The FormData constructor that will be used to create multipart form data + * requests. You can inject this here so that execution environments that + * do not support the FormData class can still run the generated client. + * + * @type {new () => FormData} + */ + formDataCtor?: new () => any; + + constructor(param: ConfigurationParameters = {}) { + this.apiKey = param.apiKey; + this.username = param.username; + this.password = param.password; + this.accessToken = param.accessToken; + this.basePath = param.basePath; + this.serverIndex = param.serverIndex; + this.baseOptions = param.baseOptions; + this.formDataCtor = param.formDataCtor; + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * @param mime - MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public isJsonMime(mime: string): boolean { + const jsonMime: RegExp = new RegExp('^(application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(;.*)?$', 'i'); + return mime !== null && (jsonMime.test(mime) || mime.toLowerCase() === 'application/json-patch+json'); + } +} diff --git a/samples/client/echo_api/typescript-axios/build/git_push.sh b/samples/client/echo_api/typescript-axios/build/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/echo_api/typescript-axios/build/index.ts b/samples/client/echo_api/typescript-axios/build/index.ts new file mode 100644 index 000000000000..99df53bd2b8a --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/index.ts @@ -0,0 +1,18 @@ +/* tslint:disable */ +/* eslint-disable */ +/** + * Echo Server API + * Echo Server API + * + * The version of the OpenAPI document: 0.1.0 + * Contact: team@openapitools.org + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +export * from "./api"; +export * from "./configuration"; + diff --git a/samples/client/echo_api/typescript-axios/build/package.json b/samples/client/echo_api/typescript-axios/build/package.json new file mode 100644 index 000000000000..fc256cc498a5 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/package.json @@ -0,0 +1,31 @@ +{ + "name": "@openapitools/typescript-axios-echo-api", + "version": "1.0.0", + "description": "OpenAPI client for @openapitools/typescript-axios-echo-api", + "author": "OpenAPI-Generator Contributors", + "repository": { + "type": "git", + "url": "https://github.com/GIT_USER_ID/GIT_REPO_ID.git" + }, + "keywords": [ + "axios", + "typescript", + "openapi-client", + "openapi-generator", + "@openapitools/typescript-axios-echo-api" + ], + "license": "Unlicense", + "main": "./dist/index.js", + "typings": "./dist/index.d.ts", + "scripts": { + "build": "tsc", + "prepare": "npm run build" + }, + "dependencies": { + "axios": "^1.6.1" + }, + "devDependencies": { + "@types/node": "^12.11.5", + "typescript": "^4.0" + } +} diff --git a/samples/client/echo_api/typescript-axios/build/tsconfig.json b/samples/client/echo_api/typescript-axios/build/tsconfig.json new file mode 100644 index 000000000000..d953a374d812 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/build/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "declaration": true, + "target": "ES5", + "module": "commonjs", + "noImplicitAny": true, + "outDir": "dist", + "rootDir": ".", + "lib": [ + "es6", + "dom" + ], + "typeRoots": [ + "node_modules/@types" + ] + }, + "exclude": [ + "dist", + "node_modules" + ] +} diff --git a/samples/client/echo_api/typescript-axios/test/.gitignore b/samples/client/echo_api/typescript-axios/test/.gitignore new file mode 100644 index 000000000000..de4d1f007dd1 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/.gitignore @@ -0,0 +1,2 @@ +dist +node_modules diff --git a/samples/client/echo_api/typescript-axios/test/package-lock.json b/samples/client/echo_api/typescript-axios/test/package-lock.json new file mode 100644 index 000000000000..ffc620f4c24d --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/package-lock.json @@ -0,0 +1,1198 @@ +{ + "name": "typescript-axios-echo-api-test", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "typescript-axios-echo-api-test", + "version": "1.0.0", + "hasInstallScript": true, + "license": "ISC", + "dependencies": { + "@openapitools/typescript-axios-echo-api": "file:../build", + "@types/chai": "^4.3.0", + "@types/mocha": "^10.0.0", + "@types/node": "^16.6.2", + "chai": "^4.3.0", + "mocha": "^10.2.0", + "ts-node": "^10.9.0", + "typescript": "^5.2.2" + } + }, + "../build": { + "name": "@openapitools/typescript-axios-echo-api", + "version": "1.0.0", + "license": "Unlicense", + "dependencies": { + "axios": "^0.27.2" + }, + "devDependencies": { + "@types/node": "^12.11.5", + "typescript": "^4.0" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.8.1", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.8.1.tgz", + "integrity": "sha512-IchNf6dN4tHoMFIn/7OE8LWZ19Y6q/67Bmf6vnGREv8RSbBVb9LPJxEcnwrcwX6ixSvaiGoomAUvu4YSxXrVgw==", + "dependencies": { + "@jridgewell/trace-mapping": "0.3.9" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.1.tgz", + "integrity": "sha512-dSYZh7HhCDtCKm4QakX0xFpsRDqjjtZf/kjI/v3T3Nwt5r8/qz/M19F9ySyOqU94SXBmeG9ttTul+YnR4LOxFA==", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.4.15", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.4.15.tgz", + "integrity": "sha512-eF2rxCRulEKXHTRiDrDy6erMYWqNw4LPdQ8UQA4huuxaQsVeRPFl2oM8oDGxMFhJUWZf9McpLtJasDDZb/Bpeg==" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.9", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.9.tgz", + "integrity": "sha512-3Belt6tdc8bPgAtbcmdtNJlirVoTmEb5e2gC94PnkwEW9jI6CAHUeoG85tjWP5WquqfavoMtMwiG4P926ZKKuQ==", + "dependencies": { + "@jridgewell/resolve-uri": "^3.0.3", + "@jridgewell/sourcemap-codec": "^1.4.10" + } + }, + "node_modules/@openapitools/typescript-axios-echo-api": { + "resolved": "../build", + "link": true + }, + "node_modules/@tsconfig/node10": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.9.tgz", + "integrity": "sha512-jNsYVVxU8v5g43Erja32laIDHXeoNvFEpX33OK4d6hljo3jDhCBDhx5dhCCTMWUojscpAagGiRkBKxpdl9fxqA==" + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.11", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.11.tgz", + "integrity": "sha512-cqefuRsh12pWyGsIoBKJA9luFu3mRxCA+ORZvA4ktLSzIuCUtWVxGIuXigEwO5/ywWFMZ2QEGKWvkZG1zDMTag==" + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.3.tgz", + "integrity": "sha512-ysT8mhdixWK6Hw3i1V2AeRqZ5WfXg1G43mqoYlM2nc6388Fq5jcXyr5mRsqViLx/GJYdoL0bfXD8nmF+Zn/Iow==" + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.4", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.4.tgz", + "integrity": "sha512-vxhUy4J8lyeyinH7Azl1pdd43GJhZH/tP2weN8TntQblOY+A0XbT8DJk1/oCPuOOyg/Ja757rG0CgHcWC8OfMA==" + }, + "node_modules/@types/chai": { + "version": "4.3.9", + "resolved": "https://registry.npmjs.org/@types/chai/-/chai-4.3.9.tgz", + "integrity": "sha512-69TtiDzu0bcmKQv3yg1Zx409/Kd7r0b5F1PfpYJfSHzLGtB53547V4u+9iqKYsTu/O2ai6KTb0TInNpvuQ3qmg==" + }, + "node_modules/@types/mocha": { + "version": "10.0.3", + "resolved": "https://registry.npmjs.org/@types/mocha/-/mocha-10.0.3.tgz", + "integrity": "sha512-RsOPImTriV/OE4A9qKjMtk2MnXiuLLbcO3nCXK+kvq4nr0iMfFgpjaX3MPLb6f7+EL1FGSelYvuJMV6REH+ZPQ==" + }, + "node_modules/@types/node": { + "version": "16.18.59", + "resolved": "https://registry.npmjs.org/@types/node/-/node-16.18.59.tgz", + "integrity": "sha512-PJ1w2cNeKUEdey4LiPra0ZuxZFOGvetswE8qHRriV/sUkL5Al4tTmPV9D2+Y/TPIxTHHgxTfRjZVKWhPw/ORhQ==" + }, + "node_modules/ansi-colors": { + "version": "4.1.1", + "resolved": "https://registry.npmjs.org/ansi-colors/-/ansi-colors-4.1.1.tgz", + "integrity": "sha512-JoX0apGbHaUJBNl6yF+p6JAFYZ666/hhCGKN5t9QFjbJQKUU/g8MNbFDbvfrgKXvI1QpZplPOnwIo99lX/AAmA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/anymatch": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/anymatch/-/anymatch-3.1.3.tgz", + "integrity": "sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw==", + "dependencies": { + "normalize-path": "^3.0.0", + "picomatch": "^2.0.4" + }, + "engines": { + "node": ">= 8" + } + }, + "node_modules/arg": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/arg/-/arg-4.1.3.tgz", + "integrity": "sha512-58S9QDqG0Xx27YwPSt9fJxivjYl432YCwfDMfZ+71RAqUrZef7LrKQZ3LHLOwCS4FLNBplP533Zx895SeOCHvA==" + }, + "node_modules/argparse": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/argparse/-/argparse-2.0.1.tgz", + "integrity": "sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==" + }, + "node_modules/assertion-error": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-1.1.0.tgz", + "integrity": "sha512-jgsaNduz+ndvGyFt3uSuWqvy4lCnIJiovtouQN5JZHOKCS2QuhEdbcQHFhVksz2N2U9hXJo8odG7ETyWlEeuDw==", + "engines": { + "node": "*" + } + }, + "node_modules/balanced-match": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", + "integrity": "sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==" + }, + "node_modules/binary-extensions": { + "version": "2.2.0", + "resolved": "https://registry.npmjs.org/binary-extensions/-/binary-extensions-2.2.0.tgz", + "integrity": "sha512-jDctJ/IVQbZoJykoeHbhXpOlNBqGNcwXJKJog42E5HDPUwQTSdjCHdihjj0DlnheQ7blbT6dHOafNAiS8ooQKA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/brace-expansion": { + "version": "1.1.11", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-1.1.11.tgz", + "integrity": "sha512-iCuPHDFgrHX7H2vEI/5xpz07zSHB00TpugqhmYtVmMO6518mCuRMoOYFldEBl0g187ufozdaHgWKcYFb61qGiA==", + "dependencies": { + "balanced-match": "^1.0.0", + "concat-map": "0.0.1" + } + }, + "node_modules/braces": { + "version": "3.0.2", + "resolved": "https://registry.npmjs.org/braces/-/braces-3.0.2.tgz", + "integrity": "sha512-b8um+L1RzM3WDSzvhm6gIz1yfTbBt6YTlcEKAvsmqCZZFw46z626lVj9j1yEPW33H5H+lBQpZMP1k8l+78Ha0A==", + "dependencies": { + "fill-range": "^7.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/browser-stdout": { + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/browser-stdout/-/browser-stdout-1.3.1.tgz", + "integrity": "sha512-qhAVI1+Av2X7qelOfAIYwXONood6XlZE/fXaBSmW/T5SzLAmCgzi+eiWE7fUvbHaeNBQH13UftjpXxsfLkMpgw==" + }, + "node_modules/camelcase": { + "version": "6.3.0", + "resolved": "https://registry.npmjs.org/camelcase/-/camelcase-6.3.0.tgz", + "integrity": "sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/chai": { + "version": "4.3.10", + "resolved": "https://registry.npmjs.org/chai/-/chai-4.3.10.tgz", + "integrity": "sha512-0UXG04VuVbruMUYbJ6JctvH0YnC/4q3/AkT18q4NaITo91CUm0liMS9VqzT9vZhVQ/1eqPanMWjBM+Juhfb/9g==", + "dependencies": { + "assertion-error": "^1.1.0", + "check-error": "^1.0.3", + "deep-eql": "^4.1.3", + "get-func-name": "^2.0.2", + "loupe": "^2.3.6", + "pathval": "^1.1.1", + "type-detect": "^4.0.8" + }, + "engines": { + "node": ">=4" + } + }, + "node_modules/chalk": { + "version": "4.1.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-4.1.2.tgz", + "integrity": "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==", + "dependencies": { + "ansi-styles": "^4.1.0", + "supports-color": "^7.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/chalk/node_modules/supports-color": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-7.2.0.tgz", + "integrity": "sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/check-error": { + "version": "1.0.3", + "resolved": "https://registry.npmjs.org/check-error/-/check-error-1.0.3.tgz", + "integrity": "sha512-iKEoDYaRmd1mxM90a2OEfWhjsjPpYPuQ+lMYsoxB126+t8fw7ySEO48nmDg5COTjxDI65/Y2OWpeEHk3ZOe8zg==", + "dependencies": { + "get-func-name": "^2.0.2" + }, + "engines": { + "node": "*" + } + }, + "node_modules/chokidar": { + "version": "3.5.3", + "resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.5.3.tgz", + "integrity": "sha512-Dr3sfKRP6oTcjf2JmUmFJfeVMvXBdegxB0iVQ5eb2V10uFJUCAS8OByZdVAyVb8xXNz3GjjTgj9kLWsZTqE6kw==", + "funding": [ + { + "type": "individual", + "url": "https://paulmillr.com/funding/" + } + ], + "dependencies": { + "anymatch": "~3.1.2", + "braces": "~3.0.2", + "glob-parent": "~5.1.2", + "is-binary-path": "~2.1.0", + "is-glob": "~4.0.1", + "normalize-path": "~3.0.0", + "readdirp": "~3.6.0" + }, + "engines": { + "node": ">= 8.10.0" + }, + "optionalDependencies": { + "fsevents": "~2.3.2" + } + }, + "node_modules/cliui": { + "version": "7.0.4", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-7.0.4.tgz", + "integrity": "sha512-OcRE68cOsVMXp1Yvonl/fzkQOyjLSu/8bhPDfQt0e0/Eb283TKP20Fs2MqoPsr9SwA595rRCA+QMzYc9nBP+JQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.0", + "wrap-ansi": "^7.0.0" + } + }, + "node_modules/cliui/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/cliui/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/concat-map": { + "version": "0.0.1", + "resolved": "https://registry.npmjs.org/concat-map/-/concat-map-0.0.1.tgz", + "integrity": "sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg==" + }, + "node_modules/create-require": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/create-require/-/create-require-1.1.1.tgz", + "integrity": "sha512-dcKFX3jn0MpIaXjisoRvexIJVEKzaq7z2rZKxf+MSr9TkdmHmsU4m2lcLojrj/FHl8mk5VxMmYA+ftRkP/3oKQ==" + }, + "node_modules/debug": { + "version": "4.3.4", + "resolved": "https://registry.npmjs.org/debug/-/debug-4.3.4.tgz", + "integrity": "sha512-PRWFHuSU3eDtQJPvnNY7Jcket1j0t5OuOsFzPPzsekD52Zl8qUfFIPEiswXqIvHWGVHOgX+7G/vCNNhehwxfkQ==", + "dependencies": { + "ms": "2.1.2" + }, + "engines": { + "node": ">=6.0" + }, + "peerDependenciesMeta": { + "supports-color": { + "optional": true + } + } + }, + "node_modules/debug/node_modules/ms": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.2.tgz", + "integrity": "sha512-sGkPx+VjMtmA6MX27oA4FBFELFCZZ4S4XqeGOXCv68tT+jb3vk/RyaKWP0PTKyWtmLSM0b+adUTEvbs1PEaH2w==" + }, + "node_modules/decamelize": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/decamelize/-/decamelize-4.0.0.tgz", + "integrity": "sha512-9iE1PgSik9HeIIw2JO94IidnE3eBoQrFJ3w7sFuzSX4DpmZ3v5sZpUiV5Swcf6mQEF+Y0ru8Neo+p+nyh2J+hQ==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/deep-eql": { + "version": "4.1.3", + "resolved": "https://registry.npmjs.org/deep-eql/-/deep-eql-4.1.3.tgz", + "integrity": "sha512-WaEtAOpRA1MQ0eohqZjpGD8zdI0Ovsm8mmFhaDN8dvDZzyoUMcYDnf5Y6iu7HTXxf8JDS23qWa4a+hKCDyOPzw==", + "dependencies": { + "type-detect": "^4.0.0" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/diff": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/diff/-/diff-5.0.0.tgz", + "integrity": "sha512-/VTCrvm5Z0JGty/BWHljh+BAiw3IK+2j87NGMu8Nwc/f48WoDAC395uomO9ZD117ZOBaHmkX1oyLvkVM/aIT3w==", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/escalade": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.1.tgz", + "integrity": "sha512-k0er2gUkLf8O0zKJiAhmkTnJlTvINGv7ygDNPbeIsX/TJjGJZHuh9B2UxbsaEkmlEo9MfhrSzmhIlhRlI2GXnw==", + "engines": { + "node": ">=6" + } + }, + "node_modules/escape-string-regexp": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz", + "integrity": "sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/fill-range": { + "version": "7.0.1", + "resolved": "https://registry.npmjs.org/fill-range/-/fill-range-7.0.1.tgz", + "integrity": "sha512-qOo9F+dMUmC2Lcb4BbVvnKJxTPjCm+RRpe4gDuGrzkL7mEVl/djYSu2OdQ2Pa302N4oqkSg9ir6jaLWJ2USVpQ==", + "dependencies": { + "to-regex-range": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/find-up": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/find-up/-/find-up-5.0.0.tgz", + "integrity": "sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng==", + "dependencies": { + "locate-path": "^6.0.0", + "path-exists": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/flat": { + "version": "5.0.2", + "resolved": "https://registry.npmjs.org/flat/-/flat-5.0.2.tgz", + "integrity": "sha512-b6suED+5/3rTpUBdG1gupIl8MPFCAMA0QXwmljLhvCUKcUvdE4gWky9zpuGCcXHOsz4J9wPGNWq6OKpmIzz3hQ==", + "bin": { + "flat": "cli.js" + } + }, + "node_modules/fs.realpath": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/fs.realpath/-/fs.realpath-1.0.0.tgz", + "integrity": "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw==" + }, + "node_modules/fsevents": { + "version": "2.3.3", + "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.3.tgz", + "integrity": "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==", + "hasInstallScript": true, + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": "^8.16.0 || ^10.6.0 || >=11.0.0" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/get-func-name": { + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/get-func-name/-/get-func-name-2.0.2.tgz", + "integrity": "sha512-8vXOvuE167CtIc3OyItco7N/dpRtBbYOsPsXCz7X/PMnlGjYjSGuZJgM1Y7mmew7BKf9BqvLX2tnOVy1BBUsxQ==", + "engines": { + "node": "*" + } + }, + "node_modules/glob-parent": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-5.1.2.tgz", + "integrity": "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow==", + "dependencies": { + "is-glob": "^4.0.1" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/has-flag": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/has-flag/-/has-flag-4.0.0.tgz", + "integrity": "sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/he": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/he/-/he-1.2.0.tgz", + "integrity": "sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==", + "bin": { + "he": "bin/he" + } + }, + "node_modules/inflight": { + "version": "1.0.6", + "resolved": "https://registry.npmjs.org/inflight/-/inflight-1.0.6.tgz", + "integrity": "sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA==", + "dependencies": { + "once": "^1.3.0", + "wrappy": "1" + } + }, + "node_modules/inherits": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/inherits/-/inherits-2.0.4.tgz", + "integrity": "sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ==" + }, + "node_modules/is-binary-path": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-binary-path/-/is-binary-path-2.1.0.tgz", + "integrity": "sha512-ZMERYes6pDydyuGidse7OsHxtbI7WVeUEozgR/g7rd0xUimYNlvZRE/K2MgZTjWy725IfelLeVcEM97mmtRGXw==", + "dependencies": { + "binary-extensions": "^2.0.0" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-number": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", + "integrity": "sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng==", + "engines": { + "node": ">=0.12.0" + } + }, + "node_modules/is-plain-obj": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/is-plain-obj/-/is-plain-obj-2.1.0.tgz", + "integrity": "sha512-YWnfyRwxL/+SsrWYfOpUtz5b3YD+nyfkHvjbcanzk8zgyO4ASD67uVMRt8k5bM4lLMDnXfriRhOpemw+NfT1eA==", + "engines": { + "node": ">=8" + } + }, + "node_modules/is-unicode-supported": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/is-unicode-supported/-/is-unicode-supported-0.1.0.tgz", + "integrity": "sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/js-yaml": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/js-yaml/-/js-yaml-4.1.0.tgz", + "integrity": "sha512-wpxZs9NoxZaJESJGIZTyDEaYpl0FKSA+FB9aJiyemKhMwkxQg63h4T1KJgUGHpTqPDNRcmmYLugrRjJlBtWvRA==", + "dependencies": { + "argparse": "^2.0.1" + }, + "bin": { + "js-yaml": "bin/js-yaml.js" + } + }, + "node_modules/locate-path": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/locate-path/-/locate-path-6.0.0.tgz", + "integrity": "sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw==", + "dependencies": { + "p-locate": "^5.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/log-symbols": { + "version": "4.1.0", + "resolved": "https://registry.npmjs.org/log-symbols/-/log-symbols-4.1.0.tgz", + "integrity": "sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==", + "dependencies": { + "chalk": "^4.1.0", + "is-unicode-supported": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/loupe": { + "version": "2.3.7", + "resolved": "https://registry.npmjs.org/loupe/-/loupe-2.3.7.tgz", + "integrity": "sha512-zSMINGVYkdpYSOBmLi0D1Uo7JU9nVdQKrHxC8eYlV+9YKK9WePqAlL7lSlorG/U2Fw1w0hTBmaa/jrQ3UbPHtA==", + "dependencies": { + "get-func-name": "^2.0.1" + } + }, + "node_modules/make-error": { + "version": "1.3.6", + "resolved": "https://registry.npmjs.org/make-error/-/make-error-1.3.6.tgz", + "integrity": "sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw==" + }, + "node_modules/mocha": { + "version": "10.2.0", + "resolved": "https://registry.npmjs.org/mocha/-/mocha-10.2.0.tgz", + "integrity": "sha512-IDY7fl/BecMwFHzoqF2sg/SHHANeBoMMXFlS9r0OXKDssYE1M5O43wUY/9BVPeIvfH2zmEbBfseqN9gBQZzXkg==", + "dependencies": { + "ansi-colors": "4.1.1", + "browser-stdout": "1.3.1", + "chokidar": "3.5.3", + "debug": "4.3.4", + "diff": "5.0.0", + "escape-string-regexp": "4.0.0", + "find-up": "5.0.0", + "glob": "7.2.0", + "he": "1.2.0", + "js-yaml": "4.1.0", + "log-symbols": "4.1.0", + "minimatch": "5.0.1", + "ms": "2.1.3", + "nanoid": "3.3.3", + "serialize-javascript": "6.0.0", + "strip-json-comments": "3.1.1", + "supports-color": "8.1.1", + "workerpool": "6.2.1", + "yargs": "16.2.0", + "yargs-parser": "20.2.4", + "yargs-unparser": "2.0.0" + }, + "bin": { + "_mocha": "bin/_mocha", + "mocha": "bin/mocha.js" + }, + "engines": { + "node": ">= 14.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/mochajs" + } + }, + "node_modules/mocha/node_modules/glob": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/glob/-/glob-7.2.0.tgz", + "integrity": "sha512-lmLf6gtyrPq8tTjSmrO94wBeQbFR3HbLHbuyD69wuyQkImp2hWqMGB47OX65FBkPffO641IP9jWa1z4ivqG26Q==", + "dependencies": { + "fs.realpath": "^1.0.0", + "inflight": "^1.0.4", + "inherits": "2", + "minimatch": "^3.0.4", + "once": "^1.3.0", + "path-is-absolute": "^1.0.0" + }, + "engines": { + "node": "*" + }, + "funding": { + "url": "https://github.com/sponsors/isaacs" + } + }, + "node_modules/mocha/node_modules/glob/node_modules/minimatch": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.2.tgz", + "integrity": "sha512-J7p63hRiAjw1NDEww1W7i37+ByIrOWO5XQQAzZ3VOcL0PNybwpfmV/N05zFAzwQ9USyEcX6t3UO+K5aqBQOIHw==", + "dependencies": { + "brace-expansion": "^1.1.7" + }, + "engines": { + "node": "*" + } + }, + "node_modules/mocha/node_modules/minimatch": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-5.0.1.tgz", + "integrity": "sha512-nLDxIFRyhDblz3qMuq+SoRZED4+miJ/G+tdDrjkkkRnjAsBexeGpgjLEQ0blJy7rHhR2b93rhQY4SvyWu9v03g==", + "dependencies": { + "brace-expansion": "^2.0.1" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/mocha/node_modules/minimatch/node_modules/brace-expansion": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/brace-expansion/-/brace-expansion-2.0.1.tgz", + "integrity": "sha512-XnAIvQ8eM+kC6aULx6wuQiwVsnzsi9d3WxzV3FpWTGA19F621kwdbsAcFKXgKUHZWsy+mY6iL1sHTxWEFCytDA==", + "dependencies": { + "balanced-match": "^1.0.0" + } + }, + "node_modules/ms": { + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz", + "integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==" + }, + "node_modules/nanoid": { + "version": "3.3.3", + "resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.3.tgz", + "integrity": "sha512-p1sjXuopFs0xg+fPASzQ28agW1oHD7xDsd9Xkf3T15H3c/cifrFHVwrh74PdoklAPi+i7MdRsE47vm2r6JoB+w==", + "bin": { + "nanoid": "bin/nanoid.cjs" + }, + "engines": { + "node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1" + } + }, + "node_modules/normalize-path": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/normalize-path/-/normalize-path-3.0.0.tgz", + "integrity": "sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/once": { + "version": "1.4.0", + "resolved": "https://registry.npmjs.org/once/-/once-1.4.0.tgz", + "integrity": "sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w==", + "dependencies": { + "wrappy": "1" + } + }, + "node_modules/p-limit": { + "version": "3.1.0", + "resolved": "https://registry.npmjs.org/p-limit/-/p-limit-3.1.0.tgz", + "integrity": "sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ==", + "dependencies": { + "yocto-queue": "^0.1.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/p-locate": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/p-locate/-/p-locate-5.0.0.tgz", + "integrity": "sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw==", + "dependencies": { + "p-limit": "^3.0.2" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/path-exists": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", + "integrity": "sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==", + "engines": { + "node": ">=8" + } + }, + "node_modules/path-is-absolute": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/path-is-absolute/-/path-is-absolute-1.0.1.tgz", + "integrity": "sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/pathval": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/pathval/-/pathval-1.1.1.tgz", + "integrity": "sha512-Dp6zGqpTdETdR63lehJYPeIOqpiNBNtc7BpWSLrOje7UaIsE5aY92r/AunQA7rsXvet3lrJ3JnZX29UPTKXyKQ==", + "engines": { + "node": "*" + } + }, + "node_modules/picomatch": { + "version": "2.3.1", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-2.3.1.tgz", + "integrity": "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA==", + "engines": { + "node": ">=8.6" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/randombytes": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/randombytes/-/randombytes-2.1.0.tgz", + "integrity": "sha512-vYl3iOX+4CKUWuxGi9Ukhie6fsqXqS9FE2Zaic4tNFD2N2QQaXOMFbuKK4QmDHC0JO6B1Zp41J0LpT0oR68amQ==", + "dependencies": { + "safe-buffer": "^5.1.0" + } + }, + "node_modules/readdirp": { + "version": "3.6.0", + "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-3.6.0.tgz", + "integrity": "sha512-hOS089on8RduqdbhvQ5Z37A0ESjsqz6qnRcffsMU3495FuTdqSm+7bhJ29JvIOsBDEEnan5DPu9t3To9VRlMzA==", + "dependencies": { + "picomatch": "^2.2.1" + }, + "engines": { + "node": ">=8.10.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/safe-buffer": { + "version": "5.2.1", + "resolved": "https://registry.npmjs.org/safe-buffer/-/safe-buffer-5.2.1.tgz", + "integrity": "sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/feross" + }, + { + "type": "patreon", + "url": "https://www.patreon.com/feross" + }, + { + "type": "consulting", + "url": "https://feross.org/support" + } + ] + }, + "node_modules/serialize-javascript": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/serialize-javascript/-/serialize-javascript-6.0.0.tgz", + "integrity": "sha512-Qr3TosvguFt8ePWqsvRfrKyQXIiW+nGbYpy8XK24NQHE83caxWt+mIymTT19DGFbNWNLfEwsrkSmN64lVWB9ag==", + "dependencies": { + "randombytes": "^2.1.0" + } + }, + "node_modules/strip-json-comments": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", + "integrity": "sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig==", + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/supports-color": { + "version": "8.1.1", + "resolved": "https://registry.npmjs.org/supports-color/-/supports-color-8.1.1.tgz", + "integrity": "sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q==", + "dependencies": { + "has-flag": "^4.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/supports-color?sponsor=1" + } + }, + "node_modules/to-regex-range": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz", + "integrity": "sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ==", + "dependencies": { + "is-number": "^7.0.0" + }, + "engines": { + "node": ">=8.0" + } + }, + "node_modules/ts-node": { + "version": "10.9.1", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.9.1.tgz", + "integrity": "sha512-NtVysVPkxxrwFGUUxGYhfux8k78pQB3JqYBXlLRZgdGUqTO5wU/UyHop5p70iEbGhB7q5KmiZiU0Y3KlJrScEw==", + "dependencies": { + "@cspotcode/source-map-support": "^0.8.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", + "arg": "^4.1.0", + "create-require": "^1.1.0", + "diff": "^4.0.1", + "make-error": "^1.1.1", + "v8-compile-cache-lib": "^3.0.1", + "yn": "3.1.1" + }, + "bin": { + "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", + "ts-node-esm": "dist/bin-esm.js", + "ts-node-script": "dist/bin-script.js", + "ts-node-transpile-only": "dist/bin-transpile.js", + "ts-script": "dist/bin-script-deprecated.js" + }, + "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", + "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } + } + }, + "node_modules/ts-node/node_modules/acorn": { + "version": "8.11.2", + "resolved": "https://registry.npmjs.org/acorn/-/acorn-8.11.2.tgz", + "integrity": "sha512-nc0Axzp/0FILLEVsm4fNwLCwMttvhEI263QtVPQcbpfZZ3ts0hLsZGOpE6czNlid7CJ9MlyH8reXkpsf3YUY4w==", + "bin": { + "acorn": "bin/acorn" + }, + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ts-node/node_modules/acorn-walk": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.3.0.tgz", + "integrity": "sha512-FS7hV565M5l1R08MXqo8odwMTB02C2UqzB17RVgu9EyuYFBqJZ3/ZY97sQD5FewVu1UyDFc1yztUDrAwT0EypA==", + "engines": { + "node": ">=0.4.0" + } + }, + "node_modules/ts-node/node_modules/diff": { + "version": "4.0.2", + "resolved": "https://registry.npmjs.org/diff/-/diff-4.0.2.tgz", + "integrity": "sha512-58lmxKSA4BNyLz+HHMUzlOEpg09FV+ev6ZMe3vJihgdxzgcwZ8VoEEPmALCZG9LmqfVoNMMKpttIYTVG6uDY7A==", + "engines": { + "node": ">=0.3.1" + } + }, + "node_modules/type-detect": { + "version": "4.0.8", + "resolved": "https://registry.npmjs.org/type-detect/-/type-detect-4.0.8.tgz", + "integrity": "sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g==", + "engines": { + "node": ">=4" + } + }, + "node_modules/typescript": { + "version": "5.2.2", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.2.2.tgz", + "integrity": "sha512-mI4WrpHsbCIcwT9cF4FZvr80QUeKvsUsUvKDoR+X/7XHQH98xYD8YHZg7ANtz2GtZt/CBq2QJ0thkGJMHfqc1w==", + "bin": { + "tsc": "bin/tsc", + "tsserver": "bin/tsserver" + }, + "engines": { + "node": ">=14.17" + } + }, + "node_modules/v8-compile-cache-lib": { + "version": "3.0.1", + "resolved": "https://registry.npmjs.org/v8-compile-cache-lib/-/v8-compile-cache-lib-3.0.1.tgz", + "integrity": "sha512-wa7YjyUGfNZngI/vtK0UHAN+lgDCxBPCylVXGp0zu59Fz5aiGtNXaq3DhIov063MorB+VfufLh3JlF2KdTK3xg==" + }, + "node_modules/workerpool": { + "version": "6.2.1", + "resolved": "https://registry.npmjs.org/workerpool/-/workerpool-6.2.1.tgz", + "integrity": "sha512-ILEIE97kDZvF9Wb9f6h5aXK4swSlKGUcOEGiIYb2OOu/IrDU9iwj0fD//SsA6E5ibwJxpEvhullJY4Sl4GcpAw==" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrap-ansi/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/wrappy": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/wrappy/-/wrappy-1.0.2.tgz", + "integrity": "sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==" + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "16.2.0", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-16.2.0.tgz", + "integrity": "sha512-D1mvvtDG0L5ft/jGWkLpG1+m0eQxOfaBvTNELraWj22wSVUMWxZUvYgJYcKh6jGGIkJFhH4IZPQhR4TKpc8mBw==", + "dependencies": { + "cliui": "^7.0.2", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.0", + "y18n": "^5.0.5", + "yargs-parser": "^20.2.2" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-parser": { + "version": "20.2.4", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-20.2.4.tgz", + "integrity": "sha512-WOkpgNhPTlE73h4VFAFsOnomJVaovO8VqLDzy5saChRBFQFBoMYirowyW+Q9HB4HFF4Z7VZTiG3iSzJJA29yRA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs-unparser": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/yargs-unparser/-/yargs-unparser-2.0.0.tgz", + "integrity": "sha512-7pRTIA9Qc1caZ0bZ6RYRGbHJthJWuakf+WmHK0rVeLkNrrGhfoabBNdue6kdINI6r4if7ocq9aD/n7xwKOdzOA==", + "dependencies": { + "camelcase": "^6.0.0", + "decamelize": "^4.0.0", + "flat": "^5.0.2", + "is-plain-obj": "^2.1.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs/node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yargs/node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/yn": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/yn/-/yn-3.1.1.tgz", + "integrity": "sha512-Ux4ygGWsu2c7isFWe8Yu1YluJmqVhxqK2cLXNQA5AcC3QfbGNpM7fu0Y8b/z16pXLnFxZYvWhd3fhBY9DLmC6Q==", + "engines": { + "node": ">=6" + } + }, + "node_modules/yocto-queue": { + "version": "0.1.0", + "resolved": "https://registry.npmjs.org/yocto-queue/-/yocto-queue-0.1.0.tgz", + "integrity": "sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q==", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + } + } +} diff --git a/samples/client/echo_api/typescript-axios/test/package.json b/samples/client/echo_api/typescript-axios/test/package.json new file mode 100644 index 000000000000..f70ca539b3d7 --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/package.json @@ -0,0 +1,26 @@ +{ + "private": true, + "dependencies": { + "@openapitools/typescript-axios-echo-api": "file:../build", + "@types/chai": "^4.3.0", + "@types/mocha": "^10.0.0", + "@types/node": "^16.6.2", + "chai": "^4.3.0", + "mocha": "^10.2.0", + "ts-node": "^10.9.0", + "typescript": "^5.2.2" + }, + "scripts": { + "preinstall": "npm --prefix ../build install && npm run build", + "test": "mocha test/*.ts --require ts-node/register --timeout 10000", + "build": "" + }, + "name": "typescript-axios-echo-api-test", + "version": "1.0.0", + "directories": { + "test": "test" + }, + "author": "", + "license": "ISC", + "description": "" +} diff --git a/samples/client/echo_api/typescript-axios/test/test/api.ts b/samples/client/echo_api/typescript-axios/test/test/api.ts new file mode 100644 index 000000000000..123526e660ae --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/test/api.ts @@ -0,0 +1,61 @@ +import { + QueryApi, + Pet, + StringEnumRef, + TestEnumRefStringEnumNonrefStringQueryEnum, + TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter +} from '@openapitools/typescript-axios-echo-api'; +import { expect } from 'chai'; + +describe('QueryApi', () => { + const api = new QueryApi(); + + it('testEnumRefString', async () => { + const enumNonrefStringQuery = TestEnumRefStringEnumNonrefStringQueryEnum.Success; + const enumRefStringQuery = StringEnumRef.Unclassified; + + const { request } = await api.testEnumRefString(enumNonrefStringQuery, enumRefStringQuery); + expect(request.path).to.equal('/query/enum_ref_string?enum_nonref_string_query=success&enum_ref_string_query=unclassified'); + }); + + it('testQueryDatetimeDateString', async () => { + const dateTime = new Date('2023-10-30T10:11:12.000Z'); + const datetimeQuery = dateTime.toISOString(); + const dateQuery = `${dateTime.getFullYear()}-${dateTime.getMonth() + 1}-${dateTime.getDate()}`; + const stringQuery = 'Hello World'; + + const { request } = await api.testQueryDatetimeDateString(datetimeQuery, dateQuery, stringQuery); + expect(request.path).to.equal('/query/datetime/date/string?datetime_query=2023-10-30T10%3A11%3A12.000Z&date_query=2023-10-30&string_query=Hello+World'); + }); + + it('testQueryIntegerBooleanString', async () => { + const integerQuery = 12345; + const booleanQuery = true; + const stringQuery = 'Hello World'; + + const { request } = await api.testQueryIntegerBooleanString(integerQuery, booleanQuery, stringQuery); + expect(request.path).to.equal('/query/integer/boolean/string?integer_query=12345&boolean_query=true&string_query=Hello+World'); + }); + + it('testQueryStyleFormExplodeTrueArrayString', async () => { + const arrayStringQuery: TestQueryStyleFormExplodeTrueArrayStringQueryObjectParameter = { + values: ['hello world 1', 'hello world 2'] + }; + + const { request } = await api.testQueryStyleFormExplodeTrueArrayString(arrayStringQuery); + expect(request.path).to.equal('/query/style_form/explode_true/array_string?values=hello+world+1&values=hello+world+2'); + }); + + it('testQueryStyleFormExplodeTrueObject', async () => { + const queryObject: Pet = { + id: 12345, + name: 'Hello World', + photoUrls: ['http://a.com', 'http://b.com'] + }; + + const { request } = await api.testQueryStyleFormExplodeTrueObject(queryObject); + expect(request.path).to.equal('/query/style_form/explode_true/object?id=12345&name=Hello+World&photoUrls=http%3A%2F%2Fa.com&photoUrls=http%3A%2F%2Fb.com'); + }); + +}); +1 diff --git a/samples/client/echo_api/typescript-axios/test/test/index.ts b/samples/client/echo_api/typescript-axios/test/test/index.ts new file mode 100644 index 000000000000..d884bec16b6c --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/test/index.ts @@ -0,0 +1 @@ +import './api' diff --git a/samples/client/echo_api/typescript-axios/test/tsconfig.json b/samples/client/echo_api/typescript-axios/test/tsconfig.json new file mode 100644 index 000000000000..e4f8bee09a0b --- /dev/null +++ b/samples/client/echo_api/typescript-axios/test/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "moduleResolution": "node", + "module": "CommonJS", + "target": "ES5", + "noImplicitAny": true, + "sourceMap": false, + "outDir": "dist", + "types": [ + "mocha" + ], + "lib": [ + "es6", + "dom" + ] + }, + "exclude": [ + "node_modules" + ] +} diff --git a/samples/client/others/csharp-complex-files/.openapi-generator/VERSION b/samples/client/others/csharp-complex-files/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/csharp-complex-files/.openapi-generator/VERSION +++ b/samples/client/others/csharp-complex-files/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs index b7433a27b7a8..a5389ded4f2e 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ApiClient.cs @@ -546,7 +546,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; using (RestClient client = new RestClient(clientOptions, diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs index 3bcd98df7caa..4596346983f6 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj index c040fee79765..6064f45f6dd4 100644 --- a/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/others/csharp-complex-files/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/others/java/okhttp-gson-oneOf/.github/workflows/maven.yml b/samples/client/others/java/okhttp-gson-oneOf/.github/workflows/maven.yml new file mode 100644 index 000000000000..21bfa60a6854 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.github/workflows/maven.yml @@ -0,0 +1,30 @@ +# This workflow will build a Java project with Maven, and cache/restore any dependencies to improve the workflow execution time +# For more information see: https://help.github.com/actions/language-and-framework-guides/building-and-testing-java-with-maven +# +# This file is auto-generated by OpenAPI Generator (https://openapi-generator.tech) + +name: Java CI with Maven + +on: + push: + branches: [ main, master ] + pull_request: + branches: [ main, master ] + +jobs: + build: + name: Build oneOf two primitives + runs-on: ubuntu-latest + strategy: + matrix: + java: [ '8' ] + steps: + - uses: actions/checkout@v2 + - name: Set up JDK + uses: actions/setup-java@v2 + with: + java-version: ${{ matrix.java }} + distribution: 'temurin' + cache: maven + - name: Build with Maven + run: mvn -B package --no-transfer-progress --file pom.xml diff --git a/samples/client/others/java/okhttp-gson-oneOf/.gitignore b/samples/client/others/java/okhttp-gson-oneOf/.gitignore new file mode 100644 index 000000000000..a530464afa1b --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.gitignore @@ -0,0 +1,21 @@ +*.class + +# Mobile Tools for Java (J2ME) +.mtj.tmp/ + +# Package Files # +*.jar +*.war +*.ear + +# exclude jar for gradle wrapper +!gradle/wrapper/*.jar + +# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml +hs_err_pid* + +# build files +**/target +target +.gradle +build diff --git a/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator-ignore b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/FILES b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/FILES new file mode 100644 index 000000000000..3c5f20ae02c8 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/FILES @@ -0,0 +1,38 @@ +.github/workflows/maven.yml +.gitignore +.travis.yml +README.md +api/openapi.yaml +build.gradle +build.sbt +docs/DefaultApi.md +docs/MyExamplePostRequest.md +git_push.sh +gradle.properties +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +pom.xml +settings.gradle +src/main/AndroidManifest.xml +src/main/java/org/openapitools/client/ApiCallback.java +src/main/java/org/openapitools/client/ApiClient.java +src/main/java/org/openapitools/client/ApiException.java +src/main/java/org/openapitools/client/ApiResponse.java +src/main/java/org/openapitools/client/Configuration.java +src/main/java/org/openapitools/client/GzipRequestInterceptor.java +src/main/java/org/openapitools/client/JSON.java +src/main/java/org/openapitools/client/Pair.java +src/main/java/org/openapitools/client/ProgressRequestBody.java +src/main/java/org/openapitools/client/ProgressResponseBody.java +src/main/java/org/openapitools/client/ServerConfiguration.java +src/main/java/org/openapitools/client/ServerVariable.java +src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/DefaultApi.java +src/main/java/org/openapitools/client/auth/ApiKeyAuth.java +src/main/java/org/openapitools/client/auth/Authentication.java +src/main/java/org/openapitools/client/auth/HttpBasicAuth.java +src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +src/main/java/org/openapitools/client/model/MyExamplePostRequest.java diff --git a/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/VERSION b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/java/okhttp-gson-oneOf/.travis.yml b/samples/client/others/java/okhttp-gson-oneOf/.travis.yml new file mode 100644 index 000000000000..1b6741c083c7 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/.travis.yml @@ -0,0 +1,22 @@ +# +# Generated by OpenAPI Generator: https://openapi-generator.tech +# +# Ref: https://docs.travis-ci.com/user/languages/java/ +# +language: java +jdk: + - openjdk12 + - openjdk11 + - openjdk10 + - openjdk9 + - openjdk8 +before_install: + # ensure gradlew has proper permission + - chmod a+x ./gradlew +script: + # test using maven + #- mvn test + # test using gradle + - gradle test + # test using sbt + # - sbt test diff --git a/samples/client/others/java/okhttp-gson-oneOf/README.md b/samples/client/others/java/okhttp-gson-oneOf/README.md new file mode 100644 index 000000000000..bb34f7620fa7 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/README.md @@ -0,0 +1,136 @@ +# openapi-java-client + +oneOf two primitives +- API version: 1.0.0 + +oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + + +## Requirements + +Building the API client library requires: +1. Java 1.8+ +2. Maven (3.8.3+)/Gradle (7.2+) + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + openapi-java-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy + repositories { + mavenCentral() // Needed if the 'openapi-java-client' jar has been published to maven central. + mavenLocal() // Needed if the 'openapi-java-client' jar has been published to the local maven repo. + } + + dependencies { + implementation "org.openapitools:openapi-java-client:1.0.0" + } +``` + +### Others + +At first generate the JAR by executing: + +```shell +mvn clean package +``` + +Then manually install the following JARs: + +* `target/openapi-java-client-1.0.0.jar` +* `target/lib/*.jar` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```java + +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + MyExamplePostRequest myExamplePostRequest = new MyExamplePostRequest(); // MyExamplePostRequest | + try { + apiInstance.myExamplePost(myExamplePostRequest); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#myExamplePost"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**myExamplePost**](docs/DefaultApi.md#myExamplePost) | **POST** /myExample | + + +## Documentation for Models + + - [MyExamplePostRequest](docs/MyExamplePostRequest.md) + + + +## Documentation for Authorization + +Endpoints do not require authorization. + + +## Recommendation + +It's recommended to create an instance of `ApiClient` per thread in a multithreaded environment to avoid any potential issues. + +## Author + + + diff --git a/samples/client/others/java/okhttp-gson-oneOf/api/openapi.yaml b/samples/client/others/java/okhttp-gson-oneOf/api/openapi.yaml new file mode 100644 index 000000000000..d44f09fc0476 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/api/openapi.yaml @@ -0,0 +1,29 @@ +openapi: 3.0.3 +info: + description: "oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450" + title: oneOf two primitives + version: 1.0.0 +servers: +- url: / +paths: + /myExample: + post: + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/_myExample_post_request' + responses: + "200": + description: OK + x-content-type: application/json + x-accepts: application/json +components: + schemas: + _myExample_post_request: + oneOf: + - format: ipv4 + type: string + - format: ipv6 + type: string + diff --git a/samples/client/others/java/okhttp-gson-oneOf/build.gradle b/samples/client/others/java/okhttp-gson-oneOf/build.gradle new file mode 100644 index 000000000000..0a72788e7797 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/build.gradle @@ -0,0 +1,168 @@ +apply plugin: 'idea' +apply plugin: 'eclipse' +apply plugin: 'java' +apply plugin: 'com.diffplug.spotless' + +group = 'org.openapitools' +version = '1.0.0' + +buildscript { + repositories { + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:2.3.+' + classpath 'com.github.dcendents:android-maven-gradle-plugin:2.1' + classpath 'com.diffplug.spotless:spotless-plugin-gradle:6.11.0' + } +} + +repositories { + mavenCentral() +} +sourceSets { + main.java.srcDirs = ['src/main/java'] +} + +if(hasProperty('target') && target == 'android') { + + apply plugin: 'com.android.library' + apply plugin: 'com.github.dcendents.android-maven' + + android { + compileSdkVersion 25 + buildToolsVersion '25.0.2' + defaultConfig { + minSdkVersion 14 + targetSdkVersion 25 + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + // Rename the aar correctly + libraryVariants.all { variant -> + variant.outputs.each { output -> + def outputFile = output.outputFile + if (outputFile != null && outputFile.name.endsWith('.aar')) { + def fileName = "${project.name}-${variant.baseName}-${version}.aar" + output.outputFile = new File(outputFile.parent, fileName) + } + } + } + + dependencies { + provided "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + } + } + + afterEvaluate { + android.libraryVariants.all { variant -> + def task = project.tasks.create "jar${variant.name.capitalize()}", Jar + task.description = "Create jar artifact for ${variant.name}" + task.dependsOn variant.javaCompile + task.from variant.javaCompile.destinationDirectory + task.destinationDirectory = project.file("${project.buildDir}/outputs/jar") + task.archiveFileName = "${project.name}-${variant.baseName}-${version}.jar" + artifacts.add('archives', task) + } + } + + task sourcesJar(type: Jar) { + from android.sourceSets.main.java.srcDirs + classifier = 'sources' + } + + artifacts { + archives sourcesJar + } + +} else { + + apply plugin: 'java' + apply plugin: 'maven-publish' + + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + publishing { + publications { + maven(MavenPublication) { + artifactId = 'openapi-java-client' + from components.java + } + } + } + + task execute(type:JavaExec) { + main = System.getProperty('mainClass') + classpath = sourceSets.main.runtimeClasspath + } +} + +ext { + jakarta_annotation_version = "1.3.5" +} + +dependencies { + implementation 'io.swagger:swagger-annotations:1.6.8' + implementation "com.google.code.findbugs:jsr305:3.0.2" + implementation 'com.squareup.okhttp3:okhttp:4.10.0' + implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' + implementation 'com.google.code.gson:gson:2.9.1' + implementation 'io.gsonfire:gson-fire:1.9.0' + implementation 'javax.ws.rs:jsr311-api:1.1.1' + implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' + implementation 'org.openapitools:jackson-databind-nullable:0.2.6' + implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0' + implementation "jakarta.annotation:jakarta.annotation-api:$jakarta_annotation_version" + testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.1' + testImplementation 'org.mockito:mockito-core:3.12.4' + testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.1' +} + +javadoc { + options.tags = [ "http.response.details:a:Http Response Details" ] +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + java { + // don't need to set target, it is inferred from java + + // apply a specific flavor of google-java-format + googleJavaFormat('1.8').aosp().reflowLongStrings() + + removeUnusedImports() + importOrder() + } +} + +test { + // Enable JUnit 5 (Gradle 4.6+). + useJUnitPlatform() + + // Always run tests, even when nothing changed. + dependsOn 'cleanTest' + + // Show test results. + testLogging { + events "passed", "skipped", "failed" + } + +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/build.sbt b/samples/client/others/java/okhttp-gson-oneOf/build.sbt new file mode 100644 index 000000000000..3a409fcd9a8c --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/build.sbt @@ -0,0 +1,28 @@ +lazy val root = (project in file(".")). + settings( + organization := "org.openapitools", + name := "openapi-java-client", + version := "1.0.0", + scalaVersion := "2.11.4", + scalacOptions ++= Seq("-feature"), + javacOptions in compile ++= Seq("-Xlint:deprecation"), + publishArtifact in (Compile, packageDoc) := false, + resolvers += Resolver.mavenLocal, + libraryDependencies ++= Seq( + "io.swagger" % "swagger-annotations" % "1.6.5", + "com.squareup.okhttp3" % "okhttp" % "4.10.0", + "com.squareup.okhttp3" % "logging-interceptor" % "4.10.0", + "com.google.code.gson" % "gson" % "2.9.1", + "org.apache.commons" % "commons-lang3" % "3.12.0", + "javax.ws.rs" % "jsr311-api" % "1.1.1", + "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", + "org.openapitools" % "jackson-databind-nullable" % "0.2.6", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", + "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", + "org.junit.jupiter" % "junit-jupiter-api" % "5.9.1" % "test", + "com.novocode" % "junit-interface" % "0.10" % "test", + "org.mockito" % "mockito-core" % "3.12.4" % "test" + ) + ) diff --git a/samples/client/others/java/okhttp-gson-oneOf/docs/DefaultApi.md b/samples/client/others/java/okhttp-gson-oneOf/docs/DefaultApi.md new file mode 100644 index 000000000000..e536ad85876c --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/docs/DefaultApi.md @@ -0,0 +1,68 @@ +# DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**myExamplePost**](DefaultApi.md#myExamplePost) | **POST** /myExample | | + + + +# **myExamplePost** +> myExamplePost(myExamplePostRequest) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.DefaultApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://localhost"); + + DefaultApi apiInstance = new DefaultApi(defaultClient); + MyExamplePostRequest myExamplePostRequest = new MyExamplePostRequest(); // MyExamplePostRequest | + try { + apiInstance.myExamplePost(myExamplePostRequest); + } catch (ApiException e) { + System.err.println("Exception when calling DefaultApi#myExamplePost"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **myExamplePostRequest** | [**MyExamplePostRequest**](MyExamplePostRequest.md)| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | OK | - | + diff --git a/samples/client/others/java/okhttp-gson-oneOf/docs/MyExamplePostRequest.md b/samples/client/others/java/okhttp-gson-oneOf/docs/MyExamplePostRequest.md new file mode 100644 index 000000000000..0912191d18be --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/docs/MyExamplePostRequest.md @@ -0,0 +1,12 @@ + + +# MyExamplePostRequest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| + + + diff --git a/samples/client/others/java/okhttp-gson-oneOf/git_push.sh b/samples/client/others/java/okhttp-gson-oneOf/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/others/java/okhttp-gson-oneOf/gradle.properties b/samples/client/others/java/okhttp-gson-oneOf/gradle.properties new file mode 100644 index 000000000000..a3408578278a --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/gradle.properties @@ -0,0 +1,6 @@ +# This file is automatically generated by OpenAPI Generator (https://github.com/openAPITools/openapi-generator). +# To include other gradle properties as part of the code generation process, please use the `gradleProperties` option. +# +# Gradle properties reference: https://docs.gradle.org/current/userguide/build_environment.html#sec:gradle_configuration_properties +# For example, uncomment below to build for Android +#target = android diff --git a/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.jar b/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..7454180f2ae8 Binary files /dev/null and b/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.properties b/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..ffed3a254e91 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-7.2-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/others/java/okhttp-gson-oneOf/gradlew b/samples/client/others/java/okhttp-gson-oneOf/gradlew new file mode 100644 index 000000000000..005bcde04284 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/others/java/okhttp-gson-oneOf/gradlew.bat b/samples/client/others/java/okhttp-gson-oneOf/gradlew.bat new file mode 100644 index 000000000000..6a68175eb70f --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS=-Dfile.encoding=UTF-8 "-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/others/java/okhttp-gson-oneOf/pom.xml b/samples/client/others/java/okhttp-gson-oneOf/pom.xml new file mode 100644 index 000000000000..fbb495936314 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/pom.xml @@ -0,0 +1,344 @@ + + 4.0.0 + org.openapitools + openapi-java-client + jar + openapi-java-client + 1.0.0 + https://github.com/openapitools/openapi-generator + OpenAPI Java + + scm:git:git@github.com:openapitools/openapi-generator.git + scm:git:git@github.com:openapitools/openapi-generator.git + https://github.com/openapitools/openapi-generator + + + + + Unlicense + http://unlicense.org + repo + + + + + + OpenAPI-Generator Contributors + team@openapitools.org + OpenAPITools.org + http://openapitools.org + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + true + 128m + 512m + + -Xlint:all + -J-Xss4m + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.1.0 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 2.22.2 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 10 + + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + + + + + maven-dependency-plugin + 3.3.0 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.3.0 + + + + test-jar + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.3.0 + + + add_sources + generate-sources + + add-source + + + + src/main/java + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + src/test/java + + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.4.1 + + + attach-javadocs + + jar + + + + + none + + + http.response.details + a + Http Response Details: + + + + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + attach-sources + + jar-no-fork + + + + + + + com.diffplug.spotless + spotless-maven-plugin + ${spotless.version} + + + + + + + .gitignore + + + + + + true + 4 + + + + + + + + + + 1.8 + + true + + + + + + + + + + + + + + sign-artifacts + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + + + + + + + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + com.squareup.okhttp3 + okhttp + ${okhttp-version} + + + com.squareup.okhttp3 + logging-interceptor + ${okhttp-version} + + + com.google.code.gson + gson + ${gson-version} + + + io.gsonfire + gson-fire + ${gson-fire-version} + + + org.apache.commons + commons-lang3 + ${commons-lang3-version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation-version} + provided + + + org.openapitools + jackson-databind-nullable + ${jackson-databind-nullable-version} + + + javax.ws.rs + jsr311-api + ${jsr311-api-version} + + + javax.ws.rs + javax.ws.rs-api + ${javax.ws.rs-api-version} + + + + org.junit.jupiter + junit-jupiter-engine + ${junit-version} + test + + + org.junit.platform + junit-platform-runner + ${junit-platform-runner.version} + test + + + + 1.8 + ${java.version} + ${java.version} + 1.9.0 + 4.11.0 + 2.10.1 + 3.13.0 + 0.2.6 + 1.3.5 + 5.10.0 + 1.10.0 + 2.1.1 + 1.1.1 + UTF-8 + 2.27.2 + + diff --git a/samples/client/others/java/okhttp-gson-oneOf/settings.gradle b/samples/client/others/java/okhttp-gson-oneOf/settings.gradle new file mode 100644 index 000000000000..369ba54a9e06 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/settings.gradle @@ -0,0 +1 @@ +rootProject.name = "openapi-java-client" \ No newline at end of file diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/AndroidManifest.xml b/samples/client/others/java/okhttp-gson-oneOf/src/main/AndroidManifest.xml new file mode 100644 index 000000000000..54fbcb3da1e8 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/AndroidManifest.xml @@ -0,0 +1,3 @@ + + + diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiCallback.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiCallback.java new file mode 100644 index 000000000000..d80e18a02d7f --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiCallback.java @@ -0,0 +1,62 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.io.IOException; + +import java.util.Map; +import java.util.List; + +/** + * Callback for asynchronous API call. + * + * @param The return type + */ +public interface ApiCallback { + /** + * This is called when the API call fails. + * + * @param e The exception causing the failure + * @param statusCode Status code of the response if available, otherwise it would be 0 + * @param responseHeaders Headers of the response if available, otherwise it would be null + */ + void onFailure(ApiException e, int statusCode, Map> responseHeaders); + + /** + * This is called when the API call succeeded. + * + * @param result The result deserialized from response + * @param statusCode Status code of the response + * @param responseHeaders Headers of the response + */ + void onSuccess(T result, int statusCode, Map> responseHeaders); + + /** + * This is called when the API upload processing. + * + * @param bytesWritten bytes Written + * @param contentLength content length of request body + * @param done write end + */ + void onUploadProgress(long bytesWritten, long contentLength, boolean done); + + /** + * This is called when the API download processing. + * + * @param bytesRead bytes Read + * @param contentLength content length of the response + * @param done Read end + */ + void onDownloadProgress(long bytesRead, long contentLength, boolean done); +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiClient.java new file mode 100644 index 000000000000..ccbf706598db --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiClient.java @@ -0,0 +1,1551 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okhttp3.internal.http.HttpMethod; +import okhttp3.internal.tls.OkHostnameVerifier; +import okhttp3.logging.HttpLoggingInterceptor; +import okhttp3.logging.HttpLoggingInterceptor.Level; +import okio.Buffer; +import okio.BufferedSink; +import okio.Okio; + +import javax.net.ssl.*; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.Type; +import java.net.URI; +import java.net.URLConnection; +import java.net.URLEncoder; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.security.GeneralSecurityException; +import java.security.KeyStore; +import java.security.SecureRandom; +import java.security.cert.Certificate; +import java.security.cert.CertificateException; +import java.security.cert.CertificateFactory; +import java.security.cert.X509Certificate; +import java.text.DateFormat; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.*; +import java.util.Map.Entry; +import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import org.openapitools.client.auth.Authentication; +import org.openapitools.client.auth.HttpBasicAuth; +import org.openapitools.client.auth.HttpBearerAuth; +import org.openapitools.client.auth.ApiKeyAuth; + +/** + *

              ApiClient class.

              + */ +public class ApiClient { + + private String basePath = "http://localhost"; + protected List servers = new ArrayList(Arrays.asList( + new ServerConfiguration( + "", + "No description provided", + new HashMap() + ) + )); + protected Integer serverIndex = 0; + protected Map serverVariables = null; + private boolean debugging = false; + private Map defaultHeaderMap = new HashMap(); + private Map defaultCookieMap = new HashMap(); + private String tempFolderPath = null; + + private Map authentications; + + private DateFormat dateFormat; + private DateFormat datetimeFormat; + private boolean lenientDatetimeFormat; + private int dateLength; + + private InputStream sslCaCert; + private boolean verifyingSsl; + private KeyManager[] keyManagers; + + private OkHttpClient httpClient; + private JSON json; + + private HttpLoggingInterceptor loggingInterceptor; + + /** + * Basic constructor for ApiClient + */ + public ApiClient() { + init(); + initHttpClient(); + + // Setup authentications (key: authentication name, value: authentication). + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + /** + * Basic constructor with custom OkHttpClient + * + * @param client a {@link okhttp3.OkHttpClient} object + */ + public ApiClient(OkHttpClient client) { + init(); + + httpClient = client; + + // Setup authentications (key: authentication name, value: authentication). + // Prevent the authentications from being modified. + authentications = Collections.unmodifiableMap(authentications); + } + + private void initHttpClient() { + initHttpClient(Collections.emptyList()); + } + + private void initHttpClient(List interceptors) { + OkHttpClient.Builder builder = new OkHttpClient.Builder(); + builder.addNetworkInterceptor(getProgressInterceptor()); + for (Interceptor interceptor: interceptors) { + builder.addInterceptor(interceptor); + } + + httpClient = builder.build(); + } + + private void init() { + verifyingSsl = true; + + json = new JSON(); + + // Set default User-Agent. + setUserAgent("OpenAPI-Generator/1.0.0/java"); + + authentications = new HashMap(); + } + + /** + * Get base path + * + * @return Base path + */ + public String getBasePath() { + return basePath; + } + + /** + * Set base path + * + * @param basePath Base path of the URL (e.g http://localhost + * @return An instance of OkHttpClient + */ + public ApiClient setBasePath(String basePath) { + this.basePath = basePath; + this.serverIndex = null; + return this; + } + + public List getServers() { + return servers; + } + + public ApiClient setServers(List servers) { + this.servers = servers; + return this; + } + + public Integer getServerIndex() { + return serverIndex; + } + + public ApiClient setServerIndex(Integer serverIndex) { + this.serverIndex = serverIndex; + return this; + } + + public Map getServerVariables() { + return serverVariables; + } + + public ApiClient setServerVariables(Map serverVariables) { + this.serverVariables = serverVariables; + return this; + } + + /** + * Get HTTP client + * + * @return An instance of OkHttpClient + */ + public OkHttpClient getHttpClient() { + return httpClient; + } + + /** + * Set HTTP client, which must never be null. + * + * @param newHttpClient An instance of OkHttpClient + * @return Api Client + * @throws java.lang.NullPointerException when newHttpClient is null + */ + public ApiClient setHttpClient(OkHttpClient newHttpClient) { + this.httpClient = Objects.requireNonNull(newHttpClient, "HttpClient must not be null!"); + return this; + } + + /** + * Get JSON + * + * @return JSON object + */ + public JSON getJSON() { + return json; + } + + /** + * Set JSON + * + * @param json JSON object + * @return Api client + */ + public ApiClient setJSON(JSON json) { + this.json = json; + return this; + } + + /** + * True if isVerifyingSsl flag is on + * + * @return True if isVerifySsl flag is on + */ + public boolean isVerifyingSsl() { + return verifyingSsl; + } + + /** + * Configure whether to verify certificate and hostname when making https requests. + * Default to true. + * NOTE: Do NOT set to false in production code, otherwise you would face multiple types of cryptographic attacks. + * + * @param verifyingSsl True to verify TLS/SSL connection + * @return ApiClient + */ + public ApiClient setVerifyingSsl(boolean verifyingSsl) { + this.verifyingSsl = verifyingSsl; + applySslSettings(); + return this; + } + + /** + * Get SSL CA cert. + * + * @return Input stream to the SSL CA cert + */ + public InputStream getSslCaCert() { + return sslCaCert; + } + + /** + * Configure the CA certificate to be trusted when making https requests. + * Use null to reset to default. + * + * @param sslCaCert input stream for SSL CA cert + * @return ApiClient + */ + public ApiClient setSslCaCert(InputStream sslCaCert) { + this.sslCaCert = sslCaCert; + applySslSettings(); + return this; + } + + /** + *

              Getter for the field keyManagers.

              + * + * @return an array of {@link javax.net.ssl.KeyManager} objects + */ + public KeyManager[] getKeyManagers() { + return keyManagers; + } + + /** + * Configure client keys to use for authorization in an SSL session. + * Use null to reset to default. + * + * @param managers The KeyManagers to use + * @return ApiClient + */ + public ApiClient setKeyManagers(KeyManager[] managers) { + this.keyManagers = managers; + applySslSettings(); + return this; + } + + /** + *

              Getter for the field dateFormat.

              + * + * @return a {@link java.text.DateFormat} object + */ + public DateFormat getDateFormat() { + return dateFormat; + } + + /** + *

              Setter for the field dateFormat.

              + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setDateFormat(DateFormat dateFormat) { + JSON.setDateFormat(dateFormat); + return this; + } + + /** + *

              Set SqlDateFormat.

              + * + * @param dateFormat a {@link java.text.DateFormat} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setSqlDateFormat(DateFormat dateFormat) { + JSON.setSqlDateFormat(dateFormat); + return this; + } + + /** + *

              Set OffsetDateTimeFormat.

              + * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + JSON.setOffsetDateTimeFormat(dateFormat); + return this; + } + + /** + *

              Set LocalDateFormat.

              + * + * @param dateFormat a {@link java.time.format.DateTimeFormatter} object + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLocalDateFormat(DateTimeFormatter dateFormat) { + JSON.setLocalDateFormat(dateFormat); + return this; + } + + /** + *

              Set LenientOnJson.

              + * + * @param lenientOnJson a boolean + * @return a {@link org.openapitools.client.ApiClient} object + */ + public ApiClient setLenientOnJson(boolean lenientOnJson) { + JSON.setLenientOnJson(lenientOnJson); + return this; + } + + /** + * Get authentications (key: authentication name, value: authentication). + * + * @return Map of authentication objects + */ + public Map getAuthentications() { + return authentications; + } + + /** + * Get authentication for the given name. + * + * @param authName The authentication name + * @return The authentication, null if not found + */ + public Authentication getAuthentication(String authName) { + return authentications.get(authName); + } + + + /** + * Helper method to set username for the first HTTP basic authentication. + * + * @param username Username + */ + public void setUsername(String username) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setUsername(username); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set password for the first HTTP basic authentication. + * + * @param password Password + */ + public void setPassword(String password) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBasicAuth) { + ((HttpBasicAuth) auth).setPassword(password); + return; + } + } + throw new RuntimeException("No HTTP basic authentication configured!"); + } + + /** + * Helper method to set API key value for the first API key authentication. + * + * @param apiKey API key + */ + public void setApiKey(String apiKey) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKey(apiKey); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + */ + public void setApiKeyPrefix(String apiKeyPrefix) { + for (Authentication auth : authentications.values()) { + if (auth instanceof ApiKeyAuth) { + ((ApiKeyAuth) auth).setApiKeyPrefix(apiKeyPrefix); + return; + } + } + throw new RuntimeException("No API key authentication configured!"); + } + + /** + * Helper method to set access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + public void setAccessToken(String accessToken) { + throw new RuntimeException("No OAuth2 authentication configured!"); + } + + /** + * Helper method to set credentials for AWSV4 Signature + * + * @param accessKey Access Key + * @param secretKey Secret Key + * @param region Region + * @param service Service to access to + */ + public void setAWS4Configuration(String accessKey, String secretKey, String region, String service) { + throw new RuntimeException("No AWS4 authentication configured!"); + } + + /** + * Set the User-Agent header's value (by adding to the default header map). + * + * @param userAgent HTTP request's user agent + * @return ApiClient + */ + public ApiClient setUserAgent(String userAgent) { + addDefaultHeader("User-Agent", userAgent); + return this; + } + + /** + * Add a default header. + * + * @param key The header's key + * @param value The header's value + * @return ApiClient + */ + public ApiClient addDefaultHeader(String key, String value) { + defaultHeaderMap.put(key, value); + return this; + } + + /** + * Add a default cookie. + * + * @param key The cookie's key + * @param value The cookie's value + * @return ApiClient + */ + public ApiClient addDefaultCookie(String key, String value) { + defaultCookieMap.put(key, value); + return this; + } + + /** + * Check that whether debugging is enabled for this API client. + * + * @return True if debugging is enabled, false otherwise. + */ + public boolean isDebugging() { + return debugging; + } + + /** + * Enable/disable debugging for this API client. + * + * @param debugging To enable (true) or disable (false) debugging + * @return ApiClient + */ + public ApiClient setDebugging(boolean debugging) { + if (debugging != this.debugging) { + if (debugging) { + loggingInterceptor = new HttpLoggingInterceptor(); + loggingInterceptor.setLevel(Level.BODY); + httpClient = httpClient.newBuilder().addInterceptor(loggingInterceptor).build(); + } else { + final OkHttpClient.Builder builder = httpClient.newBuilder(); + builder.interceptors().remove(loggingInterceptor); + httpClient = builder.build(); + loggingInterceptor = null; + } + } + this.debugging = debugging; + return this; + } + + /** + * The path of temporary folder used to store downloaded files from endpoints + * with file response. The default value is null, i.e. using + * the system's default temporary folder. + * + * @see createTempFile + * @return Temporary folder path + */ + public String getTempFolderPath() { + return tempFolderPath; + } + + /** + * Set the temporary folder path (for downloading files) + * + * @param tempFolderPath Temporary folder path + * @return ApiClient + */ + public ApiClient setTempFolderPath(String tempFolderPath) { + this.tempFolderPath = tempFolderPath; + return this; + } + + /** + * Get connection timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getConnectTimeout() { + return httpClient.connectTimeoutMillis(); + } + + /** + * Sets the connect timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param connectionTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setConnectTimeout(int connectionTimeout) { + httpClient = httpClient.newBuilder().connectTimeout(connectionTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get read timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getReadTimeout() { + return httpClient.readTimeoutMillis(); + } + + /** + * Sets the read timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param readTimeout read timeout in milliseconds + * @return Api client + */ + public ApiClient setReadTimeout(int readTimeout) { + httpClient = httpClient.newBuilder().readTimeout(readTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + /** + * Get write timeout (in milliseconds). + * + * @return Timeout in milliseconds + */ + public int getWriteTimeout() { + return httpClient.writeTimeoutMillis(); + } + + /** + * Sets the write timeout (in milliseconds). + * A value of 0 means no timeout, otherwise values must be between 1 and + * {@link java.lang.Integer#MAX_VALUE}. + * + * @param writeTimeout connection timeout in milliseconds + * @return Api client + */ + public ApiClient setWriteTimeout(int writeTimeout) { + httpClient = httpClient.newBuilder().writeTimeout(writeTimeout, TimeUnit.MILLISECONDS).build(); + return this; + } + + + /** + * Format the given parameter object into string. + * + * @param param Parameter + * @return String representation of the parameter + */ + public String parameterToString(Object param) { + if (param == null) { + return ""; + } else if (param instanceof Date || param instanceof OffsetDateTime || param instanceof LocalDate) { + //Serialize to json string and remove the " enclosing characters + String jsonStr = JSON.serialize(param); + return jsonStr.substring(1, jsonStr.length() - 1); + } else if (param instanceof Collection) { + StringBuilder b = new StringBuilder(); + for (Object o : (Collection) param) { + if (b.length() > 0) { + b.append(","); + } + b.append(o); + } + return b.toString(); + } else { + return String.valueOf(param); + } + } + + /** + * Formats the specified query parameter to a list containing a single {@code Pair} object. + * + * Note that {@code value} must not be a collection. + * + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list containing a single {@code Pair} object. + */ + public List parameterToPair(String name, Object value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value instanceof Collection) { + return params; + } + + params.add(new Pair(name, parameterToString(value))); + return params; + } + + /** + * Formats the specified collection query parameters to a list of {@code Pair} objects. + * + * Note that the values of each of the returned Pair objects are percent-encoded. + * + * @param collectionFormat The collection format of the parameter. + * @param name The name of the parameter. + * @param value The value of the parameter. + * @return A list of {@code Pair} objects. + */ + public List parameterToPairs(String collectionFormat, String name, Collection value) { + List params = new ArrayList(); + + // preconditions + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { + return params; + } + + // create the params based on the collection format + if ("multi".equals(collectionFormat)) { + for (Object item : value) { + params.add(new Pair(name, escapeString(parameterToString(item)))); + } + return params; + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + // escape all delimiters except commas, which are URI reserved + // characters + if ("ssv".equals(collectionFormat)) { + delimiter = escapeString(" "); + } else if ("tsv".equals(collectionFormat)) { + delimiter = escapeString("\t"); + } else if ("pipes".equals(collectionFormat)) { + delimiter = escapeString("|"); + } + + StringBuilder sb = new StringBuilder(); + for (Object item : value) { + sb.append(delimiter); + sb.append(escapeString(parameterToString(item))); + } + + params.add(new Pair(name, sb.substring(delimiter.length()))); + + return params; + } + + /** + * Formats the specified collection path parameter to a string value. + * + * @param collectionFormat The collection format of the parameter. + * @param value The value of the parameter. + * @return String representation of the parameter + */ + public String collectionPathParameterToString(String collectionFormat, Collection value) { + // create the value based on the collection format + if ("multi".equals(collectionFormat)) { + // not valid for path params + return parameterToString(value); + } + + // collectionFormat is assumed to be "csv" by default + String delimiter = ","; + + if ("ssv".equals(collectionFormat)) { + delimiter = " "; + } else if ("tsv".equals(collectionFormat)) { + delimiter = "\t"; + } else if ("pipes".equals(collectionFormat)) { + delimiter = "|"; + } + + StringBuilder sb = new StringBuilder() ; + for (Object item : value) { + sb.append(delimiter); + sb.append(parameterToString(item)); + } + + return sb.substring(delimiter.length()); + } + + /** + * Sanitize filename by removing path. + * e.g. ../../sun.gif becomes sun.gif + * + * @param filename The filename to be sanitized + * @return The sanitized filename + */ + public String sanitizeFilename(String filename) { + return filename.replaceAll(".*[/\\\\]", ""); + } + + /** + * Check if the given MIME is a JSON MIME. + * JSON MIME examples: + * application/json + * application/json; charset=UTF8 + * APPLICATION/JSON + * application/vnd.company+json + * "* / *" is also default to JSON + * @param mime MIME (Multipurpose Internet Mail Extensions) + * @return True if the given MIME is JSON, false otherwise. + */ + public boolean isJsonMime(String mime) { + String jsonMime = "(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"; + return mime != null && (mime.matches(jsonMime) || mime.equals("*/*")); + } + + /** + * Select the Accept header's value from the given accepts array: + * if JSON exists in the given array, use it; + * otherwise use all of them (joining into a string) + * + * @param accepts The accepts array to select from + * @return The Accept header to use. If the given array is empty, + * null will be returned (not to set the Accept header explicitly). + */ + public String selectHeaderAccept(String[] accepts) { + if (accepts.length == 0) { + return null; + } + for (String accept : accepts) { + if (isJsonMime(accept)) { + return accept; + } + } + return StringUtil.join(accepts, ","); + } + + /** + * Select the Content-Type header's value from the given array: + * if JSON exists in the given array, use it; + * otherwise use the first one of the array. + * + * @param contentTypes The Content-Type array to select from + * @return The Content-Type header to use. If the given array is empty, + * returns null. If it matches "any", JSON will be used. + */ + public String selectHeaderContentType(String[] contentTypes) { + if (contentTypes.length == 0) { + return null; + } + + if (contentTypes[0].equals("*/*")) { + return "application/json"; + } + + for (String contentType : contentTypes) { + if (isJsonMime(contentType)) { + return contentType; + } + } + + return contentTypes[0]; + } + + /** + * Escape the given string to be used as URL query value. + * + * @param str String to be escaped + * @return Escaped string + */ + public String escapeString(String str) { + try { + return URLEncoder.encode(str, "utf8").replaceAll("\\+", "%20"); + } catch (UnsupportedEncodingException e) { + return str; + } + } + + /** + * Deserialize response body to Java object, according to the return type and + * the Content-Type response header. + * + * @param Type + * @param response HTTP response + * @param returnType The type of the Java object + * @return The deserialized Java object + * @throws org.openapitools.client.ApiException If fail to deserialize response body, i.e. cannot read response body + * or the Content-Type of the response is not supported. + */ + @SuppressWarnings("unchecked") + public T deserialize(Response response, Type returnType) throws ApiException { + if (response == null || returnType == null) { + return null; + } + + if ("byte[]".equals(returnType.toString())) { + // Handle binary response (byte array). + try { + return (T) response.body().bytes(); + } catch (IOException e) { + throw new ApiException(e); + } + } else if (returnType.equals(File.class)) { + // Handle file downloading. + return (T) downloadFileFromResponse(response); + } + + String respBody; + try { + if (response.body() != null) + respBody = response.body().string(); + else + respBody = null; + } catch (IOException e) { + throw new ApiException(e); + } + + if (respBody == null || "".equals(respBody)) { + return null; + } + + String contentType = response.headers().get("Content-Type"); + if (contentType == null) { + // ensuring a default content type + contentType = "application/json"; + } + if (isJsonMime(contentType)) { + return JSON.deserialize(respBody, returnType); + } else if (returnType.equals(String.class)) { + // Expecting string, return the raw response body. + return (T) respBody; + } else { + throw new ApiException( + "Content type \"" + contentType + "\" is not supported for type: " + returnType, + response.code(), + response.headers().toMultimap(), + respBody); + } + } + + /** + * Serialize the given Java object into request body according to the object's + * class and the request Content-Type. + * + * @param obj The Java object + * @param contentType The request Content-Type + * @return The serialized request body + * @throws org.openapitools.client.ApiException If fail to serialize the given object + */ + public RequestBody serialize(Object obj, String contentType) throws ApiException { + if (obj instanceof byte[]) { + // Binary (byte array) body parameter support. + return RequestBody.create((byte[]) obj, MediaType.parse(contentType)); + } else if (obj instanceof File) { + // File body parameter support. + return RequestBody.create((File) obj, MediaType.parse(contentType)); + } else if ("text/plain".equals(contentType) && obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else if (isJsonMime(contentType)) { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + return RequestBody.create(content, MediaType.parse(contentType)); + } else if (obj instanceof String) { + return RequestBody.create((String) obj, MediaType.parse(contentType)); + } else { + throw new ApiException("Content type \"" + contentType + "\" is not supported"); + } + } + + /** + * Download file from the given response. + * + * @param response An instance of the Response object + * @throws org.openapitools.client.ApiException If fail to read file content from response and write to disk + * @return Downloaded file + */ + public File downloadFileFromResponse(Response response) throws ApiException { + try { + File file = prepareDownloadFile(response); + BufferedSink sink = Okio.buffer(Okio.sink(file)); + sink.writeAll(response.body().source()); + sink.close(); + return file; + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * Prepare file for download + * + * @param response An instance of the Response object + * @return Prepared file for the download + * @throws java.io.IOException If fail to prepare file for download + */ + public File prepareDownloadFile(Response response) throws IOException { + String filename = null; + String contentDisposition = response.header("Content-Disposition"); + if (contentDisposition != null && !"".equals(contentDisposition)) { + // Get filename from the Content-Disposition header. + Pattern pattern = Pattern.compile("filename=['\"]?([^'\"\\s]+)['\"]?"); + Matcher matcher = pattern.matcher(contentDisposition); + if (matcher.find()) { + filename = sanitizeFilename(matcher.group(1)); + } + } + + String prefix = null; + String suffix = null; + if (filename == null) { + prefix = "download-"; + suffix = ""; + } else { + int pos = filename.lastIndexOf("."); + if (pos == -1) { + prefix = filename + "-"; + } else { + prefix = filename.substring(0, pos) + "-"; + suffix = filename.substring(pos); + } + // Files.createTempFile requires the prefix to be at least three characters long + if (prefix.length() < 3) + prefix = "download-"; + } + + if (tempFolderPath == null) + return Files.createTempFile(prefix, suffix).toFile(); + else + return Files.createTempFile(Paths.get(tempFolderPath), prefix, suffix).toFile(); + } + + /** + * {@link #execute(Call, Type)} + * + * @param Type + * @param call An instance of the Call object + * @return ApiResponse<T> + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call) throws ApiException { + return execute(call, null); + } + + /** + * Execute HTTP call and deserialize the HTTP response body into the given return type. + * + * @param returnType The return type used to deserialize HTTP response body + * @param The return type corresponding to (same with) returnType + * @param call Call + * @return ApiResponse object containing response status, headers and + * data, which is a Java object deserialized from response body and would be null + * when returnType is null. + * @throws org.openapitools.client.ApiException If fail to execute the call + */ + public ApiResponse execute(Call call, Type returnType) throws ApiException { + try { + Response response = call.execute(); + T data = handleResponse(response, returnType); + return new ApiResponse(response.code(), response.headers().toMultimap(), data); + } catch (IOException e) { + throw new ApiException(e); + } + } + + /** + * {@link #executeAsync(Call, Type, ApiCallback)} + * + * @param Type + * @param call An instance of the Call object + * @param callback ApiCallback<T> + */ + public void executeAsync(Call call, ApiCallback callback) { + executeAsync(call, null, callback); + } + + /** + * Execute HTTP call asynchronously. + * + * @param Type + * @param call The callback to be executed when the API call finishes + * @param returnType Return type + * @param callback ApiCallback + * @see #execute(Call, Type) + */ + @SuppressWarnings("unchecked") + public void executeAsync(Call call, final Type returnType, final ApiCallback callback) { + call.enqueue(new Callback() { + @Override + public void onFailure(Call call, IOException e) { + callback.onFailure(new ApiException(e), 0, null); + } + + @Override + public void onResponse(Call call, Response response) throws IOException { + T result; + try { + result = (T) handleResponse(response, returnType); + } catch (ApiException e) { + callback.onFailure(e, response.code(), response.headers().toMultimap()); + return; + } catch (Exception e) { + callback.onFailure(new ApiException(e), response.code(), response.headers().toMultimap()); + return; + } + callback.onSuccess(result, response.code(), response.headers().toMultimap()); + } + }); + } + + /** + * Handle the given response, return the deserialized object when the response is successful. + * + * @param Type + * @param response Response + * @param returnType Return type + * @return Type + * @throws org.openapitools.client.ApiException If the response has an unsuccessful status code or + * fail to deserialize the response body + */ + public T handleResponse(Response response, Type returnType) throws ApiException { + if (response.isSuccessful()) { + if (returnType == null || response.code() == 204) { + // returning null if the returnType is not defined, + // or the status code is 204 (No Content) + if (response.body() != null) { + try { + response.body().close(); + } catch (Exception e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + return null; + } else { + return deserialize(response, returnType); + } + } else { + String respBody = null; + if (response.body() != null) { + try { + respBody = response.body().string(); + } catch (IOException e) { + throw new ApiException(response.message(), e, response.code(), response.headers().toMultimap()); + } + } + throw new ApiException(response.message(), response.code(), response.headers().toMultimap(), respBody); + } + } + + /** + * Build HTTP call with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP call + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Call buildCall(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + Request request = buildRequest(baseUrl, path, method, queryParams, collectionQueryParams, body, headerParams, cookieParams, formParams, authNames, callback); + + return httpClient.newCall(request); + } + + /** + * Build an HTTP request with the given options. + * + * @param baseUrl The base URL + * @param path The sub-path of the HTTP URL + * @param method The request method, one of "GET", "HEAD", "OPTIONS", "POST", "PUT", "PATCH" and "DELETE" + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @param body The request body object + * @param headerParams The header parameters + * @param cookieParams The cookie parameters + * @param formParams The form parameters + * @param authNames The authentications to apply + * @param callback Callback for upload/download progress + * @return The HTTP request + * @throws org.openapitools.client.ApiException If fail to serialize the request body object + */ + public Request buildRequest(String baseUrl, String path, String method, List queryParams, List collectionQueryParams, Object body, Map headerParams, Map cookieParams, Map formParams, String[] authNames, ApiCallback callback) throws ApiException { + // aggregate queryParams (non-collection) and collectionQueryParams into allQueryParams + List allQueryParams = new ArrayList(queryParams); + allQueryParams.addAll(collectionQueryParams); + + final String url = buildUrl(baseUrl, path, queryParams, collectionQueryParams); + + // prepare HTTP request body + RequestBody reqBody; + String contentType = headerParams.get("Content-Type"); + String contentTypePure = contentType; + if (contentTypePure != null && contentTypePure.contains(";")) { + contentTypePure = contentType.substring(0, contentType.indexOf(";")); + } + if (!HttpMethod.permitsRequestBody(method)) { + reqBody = null; + } else if ("application/x-www-form-urlencoded".equals(contentTypePure)) { + reqBody = buildRequestBodyFormEncoding(formParams); + } else if ("multipart/form-data".equals(contentTypePure)) { + reqBody = buildRequestBodyMultipart(formParams); + } else if (body == null) { + if ("DELETE".equals(method)) { + // allow calling DELETE without sending a request body + reqBody = null; + } else { + // use an empty request body (for POST, PUT and PATCH) + reqBody = RequestBody.create("", contentType == null ? null : MediaType.parse(contentType)); + } + } else { + reqBody = serialize(body, contentType); + } + + // update parameters with authentication settings + updateParamsForAuth(authNames, allQueryParams, headerParams, cookieParams, requestBodyToString(reqBody), method, URI.create(url)); + + final Request.Builder reqBuilder = new Request.Builder().url(url); + processHeaderParams(headerParams, reqBuilder); + processCookieParams(cookieParams, reqBuilder); + + // Associate callback with request (if not null) so interceptor can + // access it when creating ProgressResponseBody + reqBuilder.tag(callback); + + Request request = null; + + if (callback != null && reqBody != null) { + ProgressRequestBody progressRequestBody = new ProgressRequestBody(reqBody, callback); + request = reqBuilder.method(method, progressRequestBody).build(); + } else { + request = reqBuilder.method(method, reqBody).build(); + } + + return request; + } + + /** + * Build full URL by concatenating base path, the given sub path and query parameters. + * + * @param baseUrl The base URL + * @param path The sub path + * @param queryParams The query parameters + * @param collectionQueryParams The collection query parameters + * @return The full URL + */ + public String buildUrl(String baseUrl, String path, List queryParams, List collectionQueryParams) { + final StringBuilder url = new StringBuilder(); + if (baseUrl != null) { + url.append(baseUrl).append(path); + } else { + String baseURL; + if (serverIndex != null) { + if (serverIndex < 0 || serverIndex >= servers.size()) { + throw new ArrayIndexOutOfBoundsException(String.format( + "Invalid index %d when selecting the host settings. Must be less than %d", serverIndex, servers.size() + )); + } + baseURL = servers.get(serverIndex).URL(serverVariables); + } else { + baseURL = basePath; + } + url.append(baseURL).append(path); + } + + if (queryParams != null && !queryParams.isEmpty()) { + // support (constant) query string in `path`, e.g. "/posts?draft=1" + String prefix = path.contains("?") ? "&" : "?"; + for (Pair param : queryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + url.append(escapeString(param.getName())).append("=").append(escapeString(value)); + } + } + } + + if (collectionQueryParams != null && !collectionQueryParams.isEmpty()) { + String prefix = url.toString().contains("?") ? "&" : "?"; + for (Pair param : collectionQueryParams) { + if (param.getValue() != null) { + if (prefix != null) { + url.append(prefix); + prefix = null; + } else { + url.append("&"); + } + String value = parameterToString(param.getValue()); + // collection query parameter value already escaped as part of parameterToPairs + url.append(escapeString(param.getName())).append("=").append(value); + } + } + } + + return url.toString(); + } + + /** + * Set header parameters to the request builder, including default headers. + * + * @param headerParams Header parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processHeaderParams(Map headerParams, Request.Builder reqBuilder) { + for (Entry param : headerParams.entrySet()) { + reqBuilder.header(param.getKey(), parameterToString(param.getValue())); + } + for (Entry header : defaultHeaderMap.entrySet()) { + if (!headerParams.containsKey(header.getKey())) { + reqBuilder.header(header.getKey(), parameterToString(header.getValue())); + } + } + } + + /** + * Set cookie parameters to the request builder, including default cookies. + * + * @param cookieParams Cookie parameters in the form of Map + * @param reqBuilder Request.Builder + */ + public void processCookieParams(Map cookieParams, Request.Builder reqBuilder) { + for (Entry param : cookieParams.entrySet()) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + for (Entry param : defaultCookieMap.entrySet()) { + if (!cookieParams.containsKey(param.getKey())) { + reqBuilder.addHeader("Cookie", String.format("%s=%s", param.getKey(), param.getValue())); + } + } + } + + /** + * Update query and header parameters based on authentication settings. + * + * @param authNames The authentications to apply + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws org.openapitools.client.ApiException If fails to update the parameters + */ + public void updateParamsForAuth(String[] authNames, List queryParams, Map headerParams, + Map cookieParams, String payload, String method, URI uri) throws ApiException { + for (String authName : authNames) { + Authentication auth = authentications.get(authName); + if (auth == null) { + throw new RuntimeException("Authentication undefined: " + authName); + } + auth.applyToParams(queryParams, headerParams, cookieParams, payload, method, uri); + } + } + + /** + * Build a form-encoding request body with the given form parameters. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyFormEncoding(Map formParams) { + okhttp3.FormBody.Builder formBuilder = new okhttp3.FormBody.Builder(); + for (Entry param : formParams.entrySet()) { + formBuilder.add(param.getKey(), parameterToString(param.getValue())); + } + return formBuilder.build(); + } + + /** + * Build a multipart (file uploading) request body with the given form parameters, + * which could contain text fields and file fields. + * + * @param formParams Form parameters in the form of Map + * @return RequestBody + */ + public RequestBody buildRequestBodyMultipart(Map formParams) { + MultipartBody.Builder mpBuilder = new MultipartBody.Builder().setType(MultipartBody.FORM); + for (Entry param : formParams.entrySet()) { + if (param.getValue() instanceof File) { + File file = (File) param.getValue(); + addPartToMultiPartBuilder(mpBuilder, param.getKey(), file); + } else if (param.getValue() instanceof List) { + List list = (List) param.getValue(); + for (Object item: list) { + if (item instanceof File) { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), (File) item); + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + } else { + addPartToMultiPartBuilder(mpBuilder, param.getKey(), param.getValue()); + } + } + return mpBuilder.build(); + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + public String guessContentTypeFromFile(File file) { + String contentType = URLConnection.guessContentTypeFromName(file.getName()); + if (contentType == null) { + return "application/octet-stream"; + } else { + return contentType; + } + } + + /** + * Add a Content-Disposition Header for the given key and file to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param file The file to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, File file) { + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\"; filename=\"" + file.getName() + "\""); + MediaType mediaType = MediaType.parse(guessContentTypeFromFile(file)); + mpBuilder.addPart(partHeaders, RequestBody.create(file, mediaType)); + } + + /** + * Add a Content-Disposition Header for the given key and complex object to the MultipartBody Builder. + * + * @param mpBuilder MultipartBody.Builder + * @param key The key of the Header element + * @param obj The complex object to add to the Header + */ + private void addPartToMultiPartBuilder(MultipartBody.Builder mpBuilder, String key, Object obj) { + RequestBody requestBody; + if (obj instanceof String) { + requestBody = RequestBody.create((String) obj, MediaType.parse("text/plain")); + } else { + String content; + if (obj != null) { + content = JSON.serialize(obj); + } else { + content = null; + } + requestBody = RequestBody.create(content, MediaType.parse("application/json")); + } + + Headers partHeaders = Headers.of("Content-Disposition", "form-data; name=\"" + key + "\""); + mpBuilder.addPart(partHeaders, requestBody); + } + + /** + * Get network interceptor to add it to the httpClient to track download progress for + * async requests. + */ + private Interceptor getProgressInterceptor() { + return new Interceptor() { + @Override + public Response intercept(Interceptor.Chain chain) throws IOException { + final Request request = chain.request(); + final Response originalResponse = chain.proceed(request); + if (request.tag() instanceof ApiCallback) { + final ApiCallback callback = (ApiCallback) request.tag(); + return originalResponse.newBuilder() + .body(new ProgressResponseBody(originalResponse.body(), callback)) + .build(); + } + return originalResponse; + } + }; + } + + /** + * Apply SSL related settings to httpClient according to the current values of + * verifyingSsl and sslCaCert. + */ + private void applySslSettings() { + try { + TrustManager[] trustManagers; + HostnameVerifier hostnameVerifier; + if (!verifyingSsl) { + trustManagers = new TrustManager[]{ + new X509TrustManager() { + @Override + public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException { + } + + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return new java.security.cert.X509Certificate[]{}; + } + } + }; + hostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(String hostname, SSLSession session) { + return true; + } + }; + } else { + TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm()); + + if (sslCaCert == null) { + trustManagerFactory.init((KeyStore) null); + } else { + char[] password = null; // Any password will work. + CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); + Collection certificates = certificateFactory.generateCertificates(sslCaCert); + if (certificates.isEmpty()) { + throw new IllegalArgumentException("expected non-empty set of trusted certificates"); + } + KeyStore caKeyStore = newEmptyKeyStore(password); + int index = 0; + for (Certificate certificate : certificates) { + String certificateAlias = "ca" + (index++); + caKeyStore.setCertificateEntry(certificateAlias, certificate); + } + trustManagerFactory.init(caKeyStore); + } + trustManagers = trustManagerFactory.getTrustManagers(); + hostnameVerifier = OkHostnameVerifier.INSTANCE; + } + + SSLContext sslContext = SSLContext.getInstance("TLS"); + sslContext.init(keyManagers, trustManagers, new SecureRandom()); + httpClient = httpClient.newBuilder() + .sslSocketFactory(sslContext.getSocketFactory(), (X509TrustManager) trustManagers[0]) + .hostnameVerifier(hostnameVerifier) + .build(); + } catch (GeneralSecurityException e) { + throw new RuntimeException(e); + } + } + + private KeyStore newEmptyKeyStore(char[] password) throws GeneralSecurityException { + try { + KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType()); + keyStore.load(null, password); + return keyStore; + } catch (IOException e) { + throw new AssertionError(e); + } + } + + /** + * Convert the HTTP request body to a string. + * + * @param requestBody The HTTP request object + * @return The string representation of the HTTP request body + * @throws org.openapitools.client.ApiException If fail to serialize the request body object into a string + */ + private String requestBodyToString(RequestBody requestBody) throws ApiException { + if (requestBody != null) { + try { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return buffer.readUtf8(); + } catch (final IOException e) { + throw new ApiException(e); + } + } + + // empty http request body + return ""; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiException.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiException.java new file mode 100644 index 000000000000..d2969de6563c --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiException.java @@ -0,0 +1,165 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Map; +import java.util.List; + + +/** + *

              ApiException class.

              + */ +@SuppressWarnings("serial") +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiException extends Exception { + private int code = 0; + private Map> responseHeaders = null; + private String responseBody = null; + + /** + *

              Constructor for ApiException.

              + */ + public ApiException() {} + + /** + *

              Constructor for ApiException.

              + * + * @param throwable a {@link java.lang.Throwable} object + */ + public ApiException(Throwable throwable) { + super(throwable); + } + + /** + *

              Constructor for ApiException.

              + * + * @param message the error message + */ + public ApiException(String message) { + super(message); + } + + /** + *

              Constructor for ApiException.

              + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders, String responseBody) { + super(message, throwable); + this.code = code; + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + *

              Constructor for ApiException.

              + * + * @param message the error message + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(String message, int code, Map> responseHeaders, String responseBody) { + this(message, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

              Constructor for ApiException.

              + * + * @param message the error message + * @param throwable a {@link java.lang.Throwable} object + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + */ + public ApiException(String message, Throwable throwable, int code, Map> responseHeaders) { + this(message, throwable, code, responseHeaders, null); + } + + /** + *

              Constructor for ApiException.

              + * + * @param code HTTP status code + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, Map> responseHeaders, String responseBody) { + this("Response Code: " + code + " Response Body: " + responseBody, (Throwable) null, code, responseHeaders, responseBody); + } + + /** + *

              Constructor for ApiException.

              + * + * @param code HTTP status code + * @param message a {@link java.lang.String} object + */ + public ApiException(int code, String message) { + super(message); + this.code = code; + } + + /** + *

              Constructor for ApiException.

              + * + * @param code HTTP status code + * @param message the error message + * @param responseHeaders a {@link java.util.Map} of HTTP response headers + * @param responseBody the response body + */ + public ApiException(int code, String message, Map> responseHeaders, String responseBody) { + this(code, message); + this.responseHeaders = responseHeaders; + this.responseBody = responseBody; + } + + /** + * Get the HTTP status code. + * + * @return HTTP status code + */ + public int getCode() { + return code; + } + + /** + * Get the HTTP response headers. + * + * @return A map of list of string + */ + public Map> getResponseHeaders() { + return responseHeaders; + } + + /** + * Get the HTTP response body. + * + * @return Response body in the form of string + */ + public String getResponseBody() { + return responseBody; + } + + /** + * Get the exception message including HTTP response data. + * + * @return The exception message + */ + public String getMessage() { + return String.format("Message: %s%nHTTP response code: %s%nHTTP response body: %s%nHTTP response headers: %s", + super.getMessage(), this.getCode(), this.getResponseBody(), this.getResponseHeaders()); + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiResponse.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiResponse.java new file mode 100644 index 000000000000..251f85ee0c2a --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ApiResponse.java @@ -0,0 +1,76 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.List; +import java.util.Map; + +/** + * API response returned by API call. + */ +public class ApiResponse { + final private int statusCode; + final private Map> headers; + final private T data; + + /** + *

              Constructor for ApiResponse.

              + * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + */ + public ApiResponse(int statusCode, Map> headers) { + this(statusCode, headers, null); + } + + /** + *

              Constructor for ApiResponse.

              + * + * @param statusCode The status code of HTTP response + * @param headers The headers of HTTP response + * @param data The object deserialized from response bod + */ + public ApiResponse(int statusCode, Map> headers, T data) { + this.statusCode = statusCode; + this.headers = headers; + this.data = data; + } + + /** + *

              Get the status code.

              + * + * @return the status code + */ + public int getStatusCode() { + return statusCode; + } + + /** + *

              Get the headers.

              + * + * @return a {@link java.util.Map} of headers + */ + public Map> getHeaders() { + return headers; + } + + /** + *

              Get the data.

              + * + * @return the data + */ + public T getData() { + return data; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Configuration.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Configuration.java new file mode 100644 index 000000000000..5a3e60c9e010 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Configuration.java @@ -0,0 +1,41 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Configuration { + public static final String VERSION = "1.0.0"; + + private static ApiClient defaultApiClient = new ApiClient(); + + /** + * Get the default API client, which would be used when creating API + * instances without providing an API client. + * + * @return Default API client + */ + public static ApiClient getDefaultApiClient() { + return defaultApiClient; + } + + /** + * Set the default API client, which would be used when creating API + * instances without providing an API client. + * + * @param apiClient API client + */ + public static void setDefaultApiClient(ApiClient apiClient) { + defaultApiClient = apiClient; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/GzipRequestInterceptor.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/GzipRequestInterceptor.java new file mode 100644 index 000000000000..691c3106a5c9 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/GzipRequestInterceptor.java @@ -0,0 +1,85 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.*; +import okio.Buffer; +import okio.BufferedSink; +import okio.GzipSink; +import okio.Okio; + +import java.io.IOException; + +/** + * Encodes request bodies using gzip. + * + * Taken from https://github.com/square/okhttp/issues/350 + */ +class GzipRequestInterceptor implements Interceptor { + @Override + public Response intercept(Chain chain) throws IOException { + Request originalRequest = chain.request(); + if (originalRequest.body() == null || originalRequest.header("Content-Encoding") != null) { + return chain.proceed(originalRequest); + } + + Request compressedRequest = originalRequest.newBuilder() + .header("Content-Encoding", "gzip") + .method(originalRequest.method(), forceContentLength(gzip(originalRequest.body()))) + .build(); + return chain.proceed(compressedRequest); + } + + private RequestBody forceContentLength(final RequestBody requestBody) throws IOException { + final Buffer buffer = new Buffer(); + requestBody.writeTo(buffer); + return new RequestBody() { + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() { + return buffer.size(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + sink.write(buffer.snapshot()); + } + }; + } + + private RequestBody gzip(final RequestBody body) { + return new RequestBody() { + @Override + public MediaType contentType() { + return body.contentType(); + } + + @Override + public long contentLength() { + return -1; // We don't know the compressed length in advance! + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink gzipSink = Okio.buffer(new GzipSink(sink)); + body.writeTo(gzipSink); + gzipSink.close(); + } + }; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java new file mode 100644 index 000000000000..3fc3f4c62307 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/JSON.java @@ -0,0 +1,401 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.internal.bind.util.ISO8601Utils; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonElement; +import io.gsonfire.GsonFireBuilder; +import io.gsonfire.TypeSelector; + +import okio.ByteString; + +import java.io.IOException; +import java.io.StringReader; +import java.lang.reflect.Type; +import java.text.DateFormat; +import java.text.ParseException; +import java.text.ParsePosition; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.format.DateTimeFormatter; +import java.util.Date; +import java.util.Locale; +import java.util.Map; +import java.util.HashMap; + +/* + * A JSON utility class + * + * NOTE: in the future, this class may be converted to static, which may break + * backward-compatibility + */ +public class JSON { + private static Gson gson; + private static boolean isLenientOnJson = false; + private static DateTypeAdapter dateTypeAdapter = new DateTypeAdapter(); + private static SqlDateTypeAdapter sqlDateTypeAdapter = new SqlDateTypeAdapter(); + private static OffsetDateTimeTypeAdapter offsetDateTimeTypeAdapter = new OffsetDateTimeTypeAdapter(); + private static LocalDateTypeAdapter localDateTypeAdapter = new LocalDateTypeAdapter(); + private static ByteArrayAdapter byteArrayAdapter = new ByteArrayAdapter(); + + @SuppressWarnings("unchecked") + public static GsonBuilder createGson() { + GsonFireBuilder fireBuilder = new GsonFireBuilder() + ; + GsonBuilder builder = fireBuilder.createGsonBuilder(); + return builder; + } + + private static String getDiscriminatorValue(JsonElement readElement, String discriminatorField) { + JsonElement element = readElement.getAsJsonObject().get(discriminatorField); + if (null == element) { + throw new IllegalArgumentException("missing discriminator field: <" + discriminatorField + ">"); + } + return element.getAsString(); + } + + /** + * Returns the Java class that implements the OpenAPI schema for the specified discriminator value. + * + * @param classByDiscriminatorValue The map of discriminator values to Java classes. + * @param discriminatorValue The value of the OpenAPI discriminator in the input data. + * @return The Java class that implements the OpenAPI schema + */ + private static Class getClassByDiscriminator(Map classByDiscriminatorValue, String discriminatorValue) { + Class clazz = (Class) classByDiscriminatorValue.get(discriminatorValue); + if (null == clazz) { + throw new IllegalArgumentException("cannot determine model class of name: <" + discriminatorValue + ">"); + } + return clazz; + } + + { + GsonBuilder gsonBuilder = createGson(); + gsonBuilder.registerTypeAdapter(Date.class, dateTypeAdapter); + gsonBuilder.registerTypeAdapter(java.sql.Date.class, sqlDateTypeAdapter); + gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); + gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); + gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.MyExamplePostRequest.CustomTypeAdapterFactory()); + gson = gsonBuilder.create(); + } + + /** + * Get Gson. + * + * @return Gson + */ + public static Gson getGson() { + return gson; + } + + /** + * Set Gson. + * + * @param gson Gson + */ + public static void setGson(Gson gson) { + JSON.gson = gson; + } + + public static void setLenientOnJson(boolean lenientOnJson) { + isLenientOnJson = lenientOnJson; + } + + /** + * Serialize the given Java object into JSON string. + * + * @param obj Object + * @return String representation of the JSON + */ + public static String serialize(Object obj) { + return gson.toJson(obj); + } + + /** + * Deserialize the given JSON string to Java object. + * + * @param Type + * @param body The JSON string + * @param returnType The type to deserialize into + * @return The deserialized Java object + */ + @SuppressWarnings("unchecked") + public static T deserialize(String body, Type returnType) { + try { + if (isLenientOnJson) { + JsonReader jsonReader = new JsonReader(new StringReader(body)); + // see https://google-gson.googlecode.com/svn/trunk/gson/docs/javadocs/com/google/gson/stream/JsonReader.html#setLenient(boolean) + jsonReader.setLenient(true); + return gson.fromJson(jsonReader, returnType); + } else { + return gson.fromJson(body, returnType); + } + } catch (JsonParseException e) { + // Fallback processing when failed to parse JSON form response body: + // return the response body string directly for the String return type; + if (returnType.equals(String.class)) { + return (T) body; + } else { + throw (e); + } + } + } + + /** + * Gson TypeAdapter for Byte Array type + */ + public static class ByteArrayAdapter extends TypeAdapter { + + @Override + public void write(JsonWriter out, byte[] value) throws IOException { + if (value == null) { + out.nullValue(); + } else { + out.value(ByteString.of(value).base64()); + } + } + + @Override + public byte[] read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String bytesAsBase64 = in.nextString(); + ByteString byteString = ByteString.decodeBase64(bytesAsBase64); + return byteString.toByteArray(); + } + } + } + + /** + * Gson TypeAdapter for JSR310 OffsetDateTime type + */ + public static class OffsetDateTimeTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public OffsetDateTimeTypeAdapter() { + this(DateTimeFormatter.ISO_OFFSET_DATE_TIME); + } + + public OffsetDateTimeTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, OffsetDateTime date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public OffsetDateTime read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + if (date.endsWith("+0000")) { + date = date.substring(0, date.length()-5) + "Z"; + } + return OffsetDateTime.parse(date, formatter); + } + } + } + + /** + * Gson TypeAdapter for JSR310 LocalDate type + */ + public static class LocalDateTypeAdapter extends TypeAdapter { + + private DateTimeFormatter formatter; + + public LocalDateTypeAdapter() { + this(DateTimeFormatter.ISO_LOCAL_DATE); + } + + public LocalDateTypeAdapter(DateTimeFormatter formatter) { + this.formatter = formatter; + } + + public void setFormat(DateTimeFormatter dateFormat) { + this.formatter = dateFormat; + } + + @Override + public void write(JsonWriter out, LocalDate date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + out.value(formatter.format(date)); + } + } + + @Override + public LocalDate read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + return LocalDate.parse(date, formatter); + } + } + } + + public static void setOffsetDateTimeFormat(DateTimeFormatter dateFormat) { + offsetDateTimeTypeAdapter.setFormat(dateFormat); + } + + public static void setLocalDateFormat(DateTimeFormatter dateFormat) { + localDateTypeAdapter.setFormat(dateFormat); + } + + /** + * Gson TypeAdapter for java.sql.Date type + * If the dateFormat is null, a simple "yyyy-MM-dd" format will be used + * (more efficient than SimpleDateFormat). + */ + public static class SqlDateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public SqlDateTypeAdapter() {} + + public SqlDateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, java.sql.Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = date.toString(); + } + out.value(value); + } + } + + @Override + public java.sql.Date read(JsonReader in) throws IOException { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return new java.sql.Date(dateFormat.parse(date).getTime()); + } + return new java.sql.Date(ISO8601Utils.parse(date, new ParsePosition(0)).getTime()); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } + } + + /** + * Gson TypeAdapter for java.util.Date type + * If the dateFormat is null, ISO8601Utils will be used. + */ + public static class DateTypeAdapter extends TypeAdapter { + + private DateFormat dateFormat; + + public DateTypeAdapter() {} + + public DateTypeAdapter(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + public void setFormat(DateFormat dateFormat) { + this.dateFormat = dateFormat; + } + + @Override + public void write(JsonWriter out, Date date) throws IOException { + if (date == null) { + out.nullValue(); + } else { + String value; + if (dateFormat != null) { + value = dateFormat.format(date); + } else { + value = ISO8601Utils.format(date, true); + } + out.value(value); + } + } + + @Override + public Date read(JsonReader in) throws IOException { + try { + switch (in.peek()) { + case NULL: + in.nextNull(); + return null; + default: + String date = in.nextString(); + try { + if (dateFormat != null) { + return dateFormat.parse(date); + } + return ISO8601Utils.parse(date, new ParsePosition(0)); + } catch (ParseException e) { + throw new JsonParseException(e); + } + } + } catch (IllegalArgumentException e) { + throw new JsonParseException(e); + } + } + } + + public static void setDateFormat(DateFormat dateFormat) { + dateTypeAdapter.setFormat(dateFormat); + } + + public static void setSqlDateFormat(DateFormat dateFormat) { + sqlDateTypeAdapter.setFormat(dateFormat); + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Pair.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Pair.java new file mode 100644 index 000000000000..f38f869f830e --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/Pair.java @@ -0,0 +1,57 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class Pair { + private String name = ""; + private String value = ""; + + public Pair (String name, String value) { + setName(name); + setValue(value); + } + + private void setName(String name) { + if (!isValidString(name)) { + return; + } + + this.name = name; + } + + private void setValue(String value) { + if (!isValidString(value)) { + return; + } + + this.value = value; + } + + public String getName() { + return this.name; + } + + public String getValue() { + return this.value; + } + + private boolean isValidString(String arg) { + if (arg == null) { + return false; + } + + return true; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressRequestBody.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressRequestBody.java new file mode 100644 index 000000000000..7f4f2fc244de --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressRequestBody.java @@ -0,0 +1,73 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.RequestBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSink; +import okio.ForwardingSink; +import okio.Okio; +import okio.Sink; + +public class ProgressRequestBody extends RequestBody { + + private final RequestBody requestBody; + + private final ApiCallback callback; + + public ProgressRequestBody(RequestBody requestBody, ApiCallback callback) { + this.requestBody = requestBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return requestBody.contentType(); + } + + @Override + public long contentLength() throws IOException { + return requestBody.contentLength(); + } + + @Override + public void writeTo(BufferedSink sink) throws IOException { + BufferedSink bufferedSink = Okio.buffer(sink(sink)); + requestBody.writeTo(bufferedSink); + bufferedSink.flush(); + } + + private Sink sink(Sink sink) { + return new ForwardingSink(sink) { + + long bytesWritten = 0L; + long contentLength = 0L; + + @Override + public void write(Buffer source, long byteCount) throws IOException { + super.write(source, byteCount); + if (contentLength == 0) { + contentLength = contentLength(); + } + + bytesWritten += byteCount; + callback.onUploadProgress(bytesWritten, contentLength, bytesWritten == contentLength); + } + }; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressResponseBody.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressResponseBody.java new file mode 100644 index 000000000000..b8a228071b86 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ProgressResponseBody.java @@ -0,0 +1,70 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import okhttp3.MediaType; +import okhttp3.ResponseBody; + +import java.io.IOException; + +import okio.Buffer; +import okio.BufferedSource; +import okio.ForwardingSource; +import okio.Okio; +import okio.Source; + +public class ProgressResponseBody extends ResponseBody { + + private final ResponseBody responseBody; + private final ApiCallback callback; + private BufferedSource bufferedSource; + + public ProgressResponseBody(ResponseBody responseBody, ApiCallback callback) { + this.responseBody = responseBody; + this.callback = callback; + } + + @Override + public MediaType contentType() { + return responseBody.contentType(); + } + + @Override + public long contentLength() { + return responseBody.contentLength(); + } + + @Override + public BufferedSource source() { + if (bufferedSource == null) { + bufferedSource = Okio.buffer(source(responseBody.source())); + } + return bufferedSource; + } + + private Source source(Source source) { + return new ForwardingSource(source) { + long totalBytesRead = 0L; + + @Override + public long read(Buffer sink, long byteCount) throws IOException { + long bytesRead = super.read(sink, byteCount); + // read() returns the number of bytes read, or -1 if this source is exhausted. + totalBytesRead += bytesRead != -1 ? bytesRead : 0; + callback.onDownloadProgress(totalBytesRead, responseBody.contentLength(), bytesRead == -1); + return bytesRead; + } + }; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerConfiguration.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerConfiguration.java new file mode 100644 index 000000000000..59edc528a446 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerConfiguration.java @@ -0,0 +1,58 @@ +package org.openapitools.client; + +import java.util.Map; + +/** + * Representing a Server configuration. + */ +public class ServerConfiguration { + public String URL; + public String description; + public Map variables; + + /** + * @param URL A URL to the target host. + * @param description A description of the host designated by the URL. + * @param variables A map between a variable name and its value. The value is used for substitution in the server's URL template. + */ + public ServerConfiguration(String URL, String description, Map variables) { + this.URL = URL; + this.description = description; + this.variables = variables; + } + + /** + * Format URL template using given variables. + * + * @param variables A map between a variable name and its value. + * @return Formatted URL. + */ + public String URL(Map variables) { + String url = this.URL; + + // go through variables and replace placeholders + for (Map.Entry variable: this.variables.entrySet()) { + String name = variable.getKey(); + ServerVariable serverVariable = variable.getValue(); + String value = serverVariable.defaultValue; + + if (variables != null && variables.containsKey(name)) { + value = variables.get(name); + if (serverVariable.enumValues.size() > 0 && !serverVariable.enumValues.contains(value)) { + throw new IllegalArgumentException("The variable " + name + " in the server URL has invalid value " + value + "."); + } + } + url = url.replace("{" + name + "}", value); + } + return url; + } + + /** + * Format URL template using default server variables. + * + * @return Formatted URL. + */ + public String URL() { + return URL(null); + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerVariable.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerVariable.java new file mode 100644 index 000000000000..c2f13e216662 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/ServerVariable.java @@ -0,0 +1,23 @@ +package org.openapitools.client; + +import java.util.HashSet; + +/** + * Representing a Server Variable for server URL template substitution. + */ +public class ServerVariable { + public String description; + public String defaultValue; + public HashSet enumValues = null; + + /** + * @param description A description for the server variable. + * @param defaultValue The default value to use for substitution. + * @param enumValues An enumeration of string values to be used if the substitution options are from a limited set. + */ + public ServerVariable(String description, String defaultValue, HashSet enumValues) { + this.description = description; + this.defaultValue = defaultValue; + this.enumValues = enumValues; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/StringUtil.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/StringUtil.java new file mode 100644 index 000000000000..837766846b77 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/StringUtil.java @@ -0,0 +1,83 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client; + +import java.util.Collection; +import java.util.Iterator; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class StringUtil { + /** + * Check if the given array contains the given value (with case-insensitive comparison). + * + * @param array The array + * @param value The value to search + * @return true if the array contains the value + */ + public static boolean containsIgnoreCase(String[] array, String value) { + for (String str : array) { + if (value == null && str == null) { + return true; + } + if (value != null && value.equalsIgnoreCase(str)) { + return true; + } + } + return false; + } + + /** + * Join an array of strings with the given separator. + *

              + * Note: This might be replaced by utility method from commons-lang or guava someday + * if one of those libraries is added as dependency. + *

              + * + * @param array The array of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(String[] array, String separator) { + int len = array.length; + if (len == 0) { + return ""; + } + + StringBuilder out = new StringBuilder(); + out.append(array[0]); + for (int i = 1; i < len; i++) { + out.append(separator).append(array[i]); + } + return out.toString(); + } + + /** + * Join a list of strings with the given separator. + * + * @param list The list of strings + * @param separator The separator + * @return the resulting string + */ + public static String join(Collection list, String separator) { + Iterator iterator = list.iterator(); + StringBuilder out = new StringBuilder(); + if (iterator.hasNext()) { + out.append(iterator.next()); + } + while (iterator.hasNext()) { + out.append(separator).append(iterator.next()); + } + return out.toString(); + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/api/DefaultApi.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/api/DefaultApi.java new file mode 100644 index 000000000000..f8bb92cfdc4e --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/api/DefaultApi.java @@ -0,0 +1,188 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import org.openapitools.client.model.MyExamplePostRequest; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class DefaultApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public DefaultApi() { + this(Configuration.getDefaultApiClient()); + } + + public DefaultApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for myExamplePost + * @param myExamplePostRequest (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 OK -
              + */ + public okhttp3.Call myExamplePostCall(MyExamplePostRequest myExamplePostRequest, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = myExamplePostRequest; + + // create path and map variables + String localVarPath = "/myExample"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call myExamplePostValidateBeforeCall(MyExamplePostRequest myExamplePostRequest, final ApiCallback _callback) throws ApiException { + return myExamplePostCall(myExamplePostRequest, _callback); + + } + + /** + * + * + * @param myExamplePostRequest (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 OK -
              + */ + public void myExamplePost(MyExamplePostRequest myExamplePostRequest) throws ApiException { + myExamplePostWithHttpInfo(myExamplePostRequest); + } + + /** + * + * + * @param myExamplePostRequest (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 OK -
              + */ + public ApiResponse myExamplePostWithHttpInfo(MyExamplePostRequest myExamplePostRequest) throws ApiException { + okhttp3.Call localVarCall = myExamplePostValidateBeforeCall(myExamplePostRequest, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * (asynchronously) + * + * @param myExamplePostRequest (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 OK -
              + */ + public okhttp3.Call myExamplePostAsync(MyExamplePostRequest myExamplePostRequest, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = myExamplePostValidateBeforeCall(myExamplePostRequest, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java new file mode 100644 index 000000000000..85ce809ed20f --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/ApiKeyAuth.java @@ -0,0 +1,80 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class ApiKeyAuth implements Authentication { + private final String location; + private final String paramName; + + private String apiKey; + private String apiKeyPrefix; + + public ApiKeyAuth(String location, String paramName) { + this.location = location; + this.paramName = paramName; + } + + public String getLocation() { + return location; + } + + public String getParamName() { + return paramName; + } + + public String getApiKey() { + return apiKey; + } + + public void setApiKey(String apiKey) { + this.apiKey = apiKey; + } + + public String getApiKeyPrefix() { + return apiKeyPrefix; + } + + public void setApiKeyPrefix(String apiKeyPrefix) { + this.apiKeyPrefix = apiKeyPrefix; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (apiKey == null) { + return; + } + String value; + if (apiKeyPrefix != null) { + value = apiKeyPrefix + " " + apiKey; + } else { + value = apiKey; + } + if ("query".equals(location)) { + queryParams.add(new Pair(paramName, value)); + } else if ("header".equals(location)) { + headerParams.put(paramName, value); + } else if ("cookie".equals(location)) { + cookieParams.put(paramName, value); + } + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/Authentication.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/Authentication.java new file mode 100644 index 000000000000..926eb3df5952 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/Authentication.java @@ -0,0 +1,36 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +public interface Authentication { + /** + * Apply authentication settings to header and query params. + * + * @param queryParams List of query parameters + * @param headerParams Map of header parameters + * @param cookieParams Map of cookie parameters + * @param payload HTTP request body + * @param method HTTP method + * @param uri URI + * @throws ApiException if failed to update the parameters + */ + void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException; +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java new file mode 100644 index 000000000000..1d8e5987be0a --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBasicAuth.java @@ -0,0 +1,57 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.Pair; +import org.openapitools.client.ApiException; + +import okhttp3.Credentials; + +import java.net.URI; +import java.util.Map; +import java.util.List; + +import java.io.UnsupportedEncodingException; + +public class HttpBasicAuth implements Authentication { + private String username; + private String password; + + public String getUsername() { + return username; + } + + public void setUsername(String username) { + this.username = username; + } + + public String getPassword() { + return password; + } + + public void setPassword(String password) { + this.password = password; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + if (username == null && password == null) { + return; + } + headerParams.put("Authorization", Credentials.basic( + username == null ? "" : username, + password == null ? "" : password)); + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java new file mode 100644 index 000000000000..255c1d77d45f --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -0,0 +1,75 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.auth; + +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +import java.net.URI; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class HttpBearerAuth implements Authentication { + private final String scheme; + private Supplier tokenSupplier; + + public HttpBearerAuth(String scheme) { + this.scheme = scheme; + } + + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ + public String getBearerToken() { + return tokenSupplier.get(); + } + + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ + public void setBearerToken(String bearerToken) { + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; + } + + @Override + public void applyToParams(List queryParams, Map headerParams, Map cookieParams, + String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { + return; + } + + headerParams.put("Authorization", (scheme != null ? upperCaseBearer(scheme) + " " : "") + bearerToken); + } + + private static String upperCaseBearer(String scheme) { + return ("bearer".equalsIgnoreCase(scheme)) ? "Bearer" : scheme; + } +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java new file mode 100644 index 000000000000..db1100f03d6e --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -0,0 +1,146 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.openapitools.client.ApiException; +import java.util.Objects; +import java.lang.reflect.Type; +import java.util.Map; + +/** + * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public abstract class AbstractOpenApiSchema { + + // store the actual instance of the schema/object + private Object instance; + + // is nullable + private Boolean isNullable; + + // schema type (e.g. oneOf, anyOf) + private final String schemaType; + + public AbstractOpenApiSchema(String schemaType, Boolean isNullable) { + this.schemaType = schemaType; + this.isNullable = isNullable; + } + + /** + * Get the list of oneOf/anyOf composed schemas allowed to be stored in this object + * + * @return an instance of the actual schema/object + */ + public abstract Map> getSchemas(); + + /** + * Get the actual instance + * + * @return an instance of the actual schema/object + */ + //@JsonValue + public Object getActualInstance() {return instance;} + + /** + * Set the actual instance + * + * @param instance the actual instance of the schema/object + */ + public void setActualInstance(Object instance) {this.instance = instance;} + + /** + * Get the instant recursively when the schemas defined in oneOf/anyof happen to be oneOf/anyOf schema as well + * + * @return an instance of the actual schema/object + */ + public Object getActualInstanceRecursively() { + return getActualInstanceRecursively(this); + } + + private Object getActualInstanceRecursively(AbstractOpenApiSchema object) { + if (object.getActualInstance() == null) { + return null; + } else if (object.getActualInstance() instanceof AbstractOpenApiSchema) { + return getActualInstanceRecursively((AbstractOpenApiSchema)object.getActualInstance()); + } else { + return object.getActualInstance(); + } + } + + /** + * Get the schema type (e.g. anyOf, oneOf) + * + * @return the schema type + */ + public String getSchemaType() { + return schemaType; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ").append(getClass()).append(" {\n"); + sb.append(" instance: ").append(toIndentedString(instance)).append("\n"); + sb.append(" isNullable: ").append(toIndentedString(isNullable)).append("\n"); + sb.append(" schemaType: ").append(toIndentedString(schemaType)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AbstractOpenApiSchema a = (AbstractOpenApiSchema) o; + return Objects.equals(this.instance, a.instance) && + Objects.equals(this.isNullable, a.isNullable) && + Objects.equals(this.schemaType, a.schemaType); + } + + @Override + public int hashCode() { + return Objects.hash(instance, isNullable, schemaType); + } + + /** + * Is nullable + * + * @return true if it's nullable + */ + public Boolean isNullable() { + if (Boolean.TRUE.equals(isNullable)) { + return Boolean.TRUE; + } else { + return Boolean.FALSE; + } + } + + + +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/MyExamplePostRequest.java b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/MyExamplePostRequest.java new file mode 100644 index 000000000000..86b3558d0204 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/main/java/org/openapitools/client/model/MyExamplePostRequest.java @@ -0,0 +1,225 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; + + + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class MyExamplePostRequest extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(MyExamplePostRequest.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!MyExamplePostRequest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'MyExamplePostRequest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterString = gson.getDelegateAdapter(this, TypeToken.get(String.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, MyExamplePostRequest value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type `String` + if (value.getActualInstance() instanceof String) { + JsonPrimitive primitive = adapterString.toJsonTree((String)value.getActualInstance()).getAsJsonPrimitive(); + elementAdapter.write(out, primitive); + return; + } + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: String"); + } + + @Override + public MyExamplePostRequest read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize String + try { + // validate the JSON object to see if any exception is thrown + if(!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + actualAdapter = adapterString; + match++; + log.log(Level.FINER, "Input data matches schema 'String'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'String'", e); + } + + if (match == 1) { + MyExamplePostRequest ret = new MyExamplePostRequest(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for MyExamplePostRequest: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap>(); + + public MyExamplePostRequest() { + super("oneOf", Boolean.FALSE); + } + + public MyExamplePostRequest(String o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("String", String.class); + } + + @Override + public Map> getSchemas() { + return MyExamplePostRequest.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * String + * + * It could be an instance of the 'oneOf' schemas. + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof String) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be String"); + } + + /** + * Get the actual instance, which can be the following: + * String + * + * @return The actual instance (String) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `String`. If the actual instance is not `String`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `String` + * @throws ClassCastException if the instance is not `String` + */ + public String getString() throws ClassCastException { + return (String)super.getActualInstance(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to MyExamplePostRequest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with String + try { + if(!jsonElement.getAsJsonPrimitive().isString()) { + throw new IllegalArgumentException(String.format("Expected json element to be of type String in the JSON string but got `%s`", jsonElement.toString())); + } + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for String failed with `%s`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for MyExamplePostRequest with oneOf schemas: String. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString())); + } + } + + /** + * Create an instance of MyExamplePostRequest given an JSON string + * + * @param jsonString JSON string + * @return An instance of MyExamplePostRequest + * @throws IOException if the JSON string is invalid with respect to MyExamplePostRequest + */ + public static MyExamplePostRequest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, MyExamplePostRequest.class); + } + + /** + * Convert an instance of MyExamplePostRequest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/api/DefaultApiTest.java b/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/api/DefaultApiTest.java new file mode 100644 index 000000000000..5b11dea07b55 --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/api/DefaultApiTest.java @@ -0,0 +1,44 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.openapitools.client.model.MyExamplePostRequest; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for DefaultApi + */ +@Disabled +public class DefaultApiTest { + + private final DefaultApi api = new DefaultApi(); + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void myExamplePostTest() throws ApiException { + MyExamplePostRequest myExamplePostRequest = null; + api.myExamplePost(myExamplePostRequest); + // TODO: test validations + } + +} diff --git a/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/model/MyExamplePostRequestTest.java b/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/model/MyExamplePostRequestTest.java new file mode 100644 index 000000000000..fe1f03c3e62c --- /dev/null +++ b/samples/client/others/java/okhttp-gson-oneOf/src/test/java/org/openapitools/client/model/MyExamplePostRequestTest.java @@ -0,0 +1,33 @@ +/* + * oneOf two primitives + * oneOf with two entries of type string, see https://github.com/OpenAPITools/openapi-generator/issues/10450 + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for MyExamplePostRequest + */ +public class MyExamplePostRequestTest { + private final MyExamplePostRequest model = new MyExamplePostRequest(); + + /** + * Model tests for MyExamplePostRequest + */ + @Test + public void testMyExamplePostRequest() { + // TODO: test MyExamplePostRequest + } + +} diff --git a/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/VERSION b/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/VERSION +++ b/samples/client/others/java/okhttp-gson-streaming/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/java/okhttp-gson-streaming/build.gradle b/samples/client/others/java/okhttp-gson-streaming/build.gradle index 07a8fbaeea1d..e607dfa53dd0 100644 --- a/samples/client/others/java/okhttp-gson-streaming/build.gradle +++ b/samples/client/others/java/okhttp-gson-streaming/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/others/java/okhttp-gson-streaming/build.sbt b/samples/client/others/java/okhttp-gson-streaming/build.sbt index 0b1b63a821f9..d7080aa288ef 100644 --- a/samples/client/others/java/okhttp-gson-streaming/build.sbt +++ b/samples/client/others/java/okhttp-gson-streaming/build.sbt @@ -17,7 +17,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "jsr311-api" % "1.1.1", "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/others/java/okhttp-gson-streaming/pom.xml b/samples/client/others/java/okhttp-gson-streaming/pom.xml index 83b674ec384c..27f69b2a27cd 100644 --- a/samples/client/others/java/okhttp-gson-streaming/pom.xml +++ b/samples/client/others/java/okhttp-gson-streaming/pom.xml @@ -328,7 +328,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java index b382d2da2c9d..f61594f02b96 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/ApiClient.java @@ -47,6 +47,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 96f57427e9fd..ba32ab551f31 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index 9f9baa8434ec..71f91cca2d83 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java index 5ae1a3adf775..a267982e2ca2 100644 --- a/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java +++ b/samples/client/others/java/okhttp-gson-streaming/src/main/java/org/openapitools/client/model/SomeObj.java @@ -97,6 +97,11 @@ public TypeEnum read(final JsonReader jsonReader) throws IOException { return TypeEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + TypeEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_$_TYPE = "$_type"; @@ -123,7 +128,6 @@ public SomeObj() { } public SomeObj $type(TypeEnum $type) { - this.$type = $type; return this; } @@ -137,14 +141,12 @@ public SomeObj() { return $type; } - public void set$Type(TypeEnum $type) { this.$type = $type; } public SomeObj id(Long id) { - this.id = id; return this; } @@ -158,14 +160,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public SomeObj name(String name) { - this.name = name; return this; } @@ -179,14 +179,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public SomeObj active(Boolean active) { - this.active = active; return this; } @@ -200,14 +198,12 @@ public Boolean getActive() { return active; } - public void setActive(Boolean active) { this.active = active; } public SomeObj type(String type) { - this.type = type; return this; } @@ -221,7 +217,6 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } @@ -314,6 +309,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("$_type") != null && !jsonObj.get("$_type").isJsonNull()) && !jsonObj.get("$_type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `$_type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("$_type").toString())); } + // validate the optional field `$_type` + if (jsonObj.get("$_type") != null && !jsonObj.get("$_type").isJsonNull()) { + TypeEnum.validateJsonElement(jsonObj.get("$_type")); + } if ((jsonObj.get("name") != null && !jsonObj.get("name").isJsonNull()) && !jsonObj.get("name").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); } diff --git a/samples/client/others/java/resttemplate-useAbstractionForFiles/.openapi-generator/VERSION b/samples/client/others/java/resttemplate-useAbstractionForFiles/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/java/resttemplate-useAbstractionForFiles/.openapi-generator/VERSION +++ b/samples/client/others/java/resttemplate-useAbstractionForFiles/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java index 6fb215e298d6..8f9ff52066bf 100644 --- a/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java @@ -22,6 +22,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -77,6 +79,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://localhost"; private RestTemplate restTemplate; @@ -132,6 +138,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -580,7 +626,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -688,7 +763,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 51d5e3278ef7..4678c06efd7c 100644 --- a/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/others/java/resttemplate-useAbstractionForFiles/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/others/java/webclient-useAbstractionForFiles/.openapi-generator/VERSION b/samples/client/others/java/webclient-useAbstractionForFiles/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/java/webclient-useAbstractionForFiles/.openapi-generator/VERSION +++ b/samples/client/others/java/webclient-useAbstractionForFiles/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/java/webclient-useAbstractionForFiles/build.gradle b/samples/client/others/java/webclient-useAbstractionForFiles/build.gradle index e034c7fbc4eb..559d51536ef2 100644 --- a/samples/client/others/java/webclient-useAbstractionForFiles/build.gradle +++ b/samples/client/others/java/webclient-useAbstractionForFiles/build.gradle @@ -112,10 +112,10 @@ if(hasProperty('target') && target == 'android') { } ext { - spring_boot_version = "2.6.6" + spring_boot_version = "2.7.17" jakarta_annotation_version = "1.3.5" - reactor_version = "3.4.3" - reactor_netty_version = "1.0.4" + reactor_version = "3.4.34" + reactor_netty_version = "1.0.39" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" diff --git a/samples/client/others/java/webclient-useAbstractionForFiles/pom.xml b/samples/client/others/java/webclient-useAbstractionForFiles/pom.xml index d3249097db87..8a0d4efccb11 100644 --- a/samples/client/others/java/webclient-useAbstractionForFiles/pom.xml +++ b/samples/client/others/java/webclient-useAbstractionForFiles/pom.xml @@ -123,10 +123,10 @@ 2.15.2 2.15.2 0.2.6 - 2.6.6 + 2.7.17 1.3.5 - 3.4.3 - 1.0.4 + 3.4.34 + 1.0.39 4.13.2 diff --git a/samples/client/others/java/webclient-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/others/java/webclient-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java index cba5137810b8..07ce47ab2cde 100644 --- a/samples/client/others/java/webclient-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/others/java/webclient-useAbstractionForFiles/src/main/java/org/openapitools/client/ApiClient.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.jackson.nullable.JsonNullableModule; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/.openapi-generator/VERSION b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/.openapi-generator/VERSION +++ b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/others/kotlin-jvm-okhttp-parameter-tests/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/others/rust/reqwest-regression-16119/.openapi-generator/VERSION b/samples/client/others/rust/reqwest-regression-16119/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/rust/reqwest-regression-16119/.openapi-generator/VERSION +++ b/samples/client/others/rust/reqwest-regression-16119/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/rust/reqwest-regression-16119/Cargo.toml b/samples/client/others/rust/reqwest-regression-16119/Cargo.toml index 7b07dbb56819..e7287efb32b0 100644 --- a/samples/client/others/rust/reqwest-regression-16119/Cargo.toml +++ b/samples/client/others/rust/reqwest-regression-16119/Cargo.toml @@ -13,4 +13,6 @@ serde_with = "^2.0" serde_json = "^1.0" url = "^2.2" uuid = { version = "^1.0", features = ["serde", "v4"] } -reqwest = "~0.9" +[dependencies.reqwest] +version = "^0.11" +features = ["json", "blocking", "multipart"] diff --git a/samples/client/others/rust/reqwest-regression-16119/src/apis/configuration.rs b/samples/client/others/rust/reqwest-regression-16119/src/apis/configuration.rs index 68a1939de2f9..d1b488dc8b82 100644 --- a/samples/client/others/rust/reqwest-regression-16119/src/apis/configuration.rs +++ b/samples/client/others/rust/reqwest-regression-16119/src/apis/configuration.rs @@ -14,7 +14,7 @@ pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest::blocking::Client, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, @@ -42,7 +42,7 @@ impl Default for Configuration { Configuration { base_path: "http://api.example.xyz/v1".to_owned(), user_agent: Some("OpenAPI-Generator/0.1.0/rust".to_owned()), - client: reqwest::Client::new(), + client: reqwest::blocking::Client::new(), basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/samples/client/others/typescript-angular/builds/composed-schemas-tagged-unions/.openapi-generator/VERSION b/samples/client/others/typescript-angular/builds/composed-schemas-tagged-unions/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/typescript-angular/builds/composed-schemas-tagged-unions/.openapi-generator/VERSION +++ b/samples/client/others/typescript-angular/builds/composed-schemas-tagged-unions/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript-angular/builds/composed-schemas/.openapi-generator/VERSION b/samples/client/others/typescript-angular/builds/composed-schemas/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/typescript-angular/builds/composed-schemas/.openapi-generator/VERSION +++ b/samples/client/others/typescript-angular/builds/composed-schemas/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts index 0f9241761b2f..208ec53dda46 100644 --- a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://localhost".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts index 80881f485559..95d62a0dcddb 100644 --- a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts index 51125503002c..2b516f9129ed 100644 --- a/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts +++ b/samples/client/others/typescript-axios/with-separate-models-and-api-inheritance/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/others/typescript-rxjs/allOf-composition/.openapi-generator/VERSION b/samples/client/others/typescript-rxjs/allOf-composition/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/typescript-rxjs/allOf-composition/.openapi-generator/VERSION +++ b/samples/client/others/typescript-rxjs/allOf-composition/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript/builds/with-unique-items/.openapi-generator/VERSION b/samples/client/others/typescript/builds/with-unique-items/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/others/typescript/builds/with-unique-items/.openapi-generator/VERSION +++ b/samples/client/others/typescript/builds/with-unique-items/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts b/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts index 6d4db8b98668..d994fd35e982 100644 --- a/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts +++ b/samples/client/others/typescript/builds/with-unique-items/models/ObjectSerializer.ts @@ -14,16 +14,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ ]); @@ -31,6 +21,58 @@ let typeMap: {[index: string]: any} = { "Response": Response, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -176,31 +218,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -215,18 +253,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION +++ b/samples/client/petstore/R-httr2-wrapper/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/R-httr2/.openapi-generator/VERSION b/samples/client/petstore/R-httr2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/R-httr2/.openapi-generator/VERSION +++ b/samples/client/petstore/R-httr2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/R/.openapi-generator/VERSION b/samples/client/petstore/R/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/R/.openapi-generator/VERSION +++ b/samples/client/petstore/R/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ada/.openapi-generator/VERSION b/samples/client/petstore/ada/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/ada/.openapi-generator/VERSION +++ b/samples/client/petstore/ada/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ada/config.gpr b/samples/client/petstore/ada/config.gpr index 0567eb7cb9fd..6e7c4514bfa0 100644 --- a/samples/client/petstore/ada/config.gpr +++ b/samples/client/petstore/ada/config.gpr @@ -45,7 +45,7 @@ abstract project Config is when "debug" => for Default_Switches ("Ada") use ("-E"); - when others => + when others => for Default_Switches ("Ada") use ("-E"); end case; @@ -64,12 +64,12 @@ abstract project Config is when "coverage" => for Default_Switches ("ada") use ("-fprofile-arcs"); - - when others => - null; + + when others => + null; end case; - end linker; + end linker; package Ide is for VCS_Kind use "git"; diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb index 92b1c8cd7349..2be05f462014 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.adb +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads index acd279390685..9d7886859466 100644 --- a/samples/client/petstore/ada/src/client/samples-petstore-clients.ads +++ b/samples/client/petstore/ada/src/client/samples-petstore-clients.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.adb b/samples/client/petstore/ada/src/model/samples-petstore-models.adb index db9a2fcfde17..aa08efdd6472 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.adb +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.adb @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. @@ -15,6 +15,75 @@ package body Samples.Petstore.Models is use Swagger.Streams; + + function To_AnotherStatus_Type (Value : in String) return Samples.Petstore.Models.AnotherStatus_Type is + begin + if Value = "available" then + return AVAILABLE; + end if; + if Value = "pending" then + return PENDING; + end if; + if Value = "sold" then + return UNAVAILABLE; + end if; + raise Constraint_Error; + end To_AnotherStatus_Type; + + function To_String (Value : in Samples.Petstore.Models.AnotherStatus_Type) return String is + begin + case Value is + when AVAILABLE => + return "available"; + + when PENDING => + return "pending"; + + when UNAVAILABLE => + return "sold"; + + end case; + end To_String; + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Samples.Petstore.Models.AnotherStatus_Type) is + begin + Into.Write_Entity (Name, To_String (Value)); end Serialize; + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in AnotherStatus_Type_Vectors.Vector) is + begin + Into.Start_Array (Name); + for Item of Value loop + Serialize (Into, "", Item); + end loop; + Into.End_Array (Name); + end Serialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Samples.Petstore.Models.AnotherStatus_Type) is + Object : Swagger.Value_Type; + begin + Swagger.Streams.Deserialize (From, Name, Object); + Value := To_AnotherStatus_Type (Swagger.To_String (Object)); + end Deserialize; + + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : in out AnotherStatus_Type_Vectors.Vector) is + List : Swagger.Value_Array_Type; + Item : Samples.Petstore.Models.AnotherStatus_Type; + begin + Value.Clear; + Swagger.Streams.Deserialize (From, Name, List); + for Data of List loop + Deserialize (Data, "", Item); + Value.Append (Item); + end loop; + end Deserialize; + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; Name : in String; Value : in Samples.Petstore.Models.ApiResponse_Type) is diff --git a/samples/client/petstore/ada/src/model/samples-petstore-models.ads b/samples/client/petstore/ada/src/model/samples-petstore-models.ads index 5c4f7dd1a162..2a778ed27d92 100644 --- a/samples/client/petstore/ada/src/model/samples-petstore-models.ads +++ b/samples/client/petstore/ada/src/model/samples-petstore-models.ads @@ -4,7 +4,7 @@ -- The version of the OpenAPI document: 1.0.0 -- -- --- NOTE: This package is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. +-- NOTE: This package is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. -- https://openapi-generator.tech -- Do not edit the class manually. @@ -14,6 +14,32 @@ package Samples.Petstore.Models is pragma Style_Checks ("-bmrIu"); + + type AnotherStatus_Type is (AVAILABLE,PENDING,UNAVAILABLE); + + function To_AnotherStatus_Type (Value : in String) return Samples.Petstore.Models.AnotherStatus_Type; + + function To_String (Value : in AnotherStatus_Type) return String; + + + package AnotherStatus_Type_Vectors is + new Ada.Containers.Vectors (Index_Type => Positive, + Element_Type => Samples.Petstore.Models.AnotherStatus_Type); + + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in Samples.Petstore.Models.AnotherStatus_Type); + procedure Serialize (Into : in out Swagger.Streams.Output_Stream'Class; + Name : in String; + Value : in AnotherStatus_Type_Vectors.Vector); + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : out Samples.Petstore.Models.AnotherStatus_Type); + procedure Deserialize (From : in Swagger.Value_Type; + Name : in String; + Value : in out AnotherStatus_Type_Vectors.Vector); + + -- ------------------------------ -- An uploaded response -- Describes the result of uploading an image resource diff --git a/samples/client/petstore/apex/.openapi-generator/VERSION b/samples/client/petstore/apex/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/apex/.openapi-generator/VERSION +++ b/samples/client/petstore/apex/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/bash/.openapi-generator/VERSION b/samples/client/petstore/bash/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/bash/.openapi-generator/VERSION +++ b/samples/client/petstore/bash/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/c/.openapi-generator/VERSION b/samples/client/petstore/c/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/c/.openapi-generator/VERSION +++ b/samples/client/petstore/c/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/c/api/PetAPI.c b/samples/client/petstore/c/api/PetAPI.c index 515146a12ba2..36303a0ef5e0 100644 --- a/samples/client/petstore/c/api/PetAPI.c +++ b/samples/client/petstore/c/api/PetAPI.c @@ -58,7 +58,7 @@ static openapi_petstore_findPetsByStatus_status_e findPetsByStatus_STATUS_parseF // Add a new pet to the store // void -PetAPI_addPet(apiClient_t *apiClient, pet_t * body ) +PetAPI_addPet(apiClient_t *apiClient, pet_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -123,7 +123,7 @@ PetAPI_addPet(apiClient_t *apiClient, pet_t * body ) // Deletes a pet // void -PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ) +PetAPI_deletePet(apiClient_t *apiClient, long petId, char *api_key) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = list_createList(); @@ -210,7 +210,7 @@ PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ) // Multiple status values can be provided with comma separated strings // list_t* -PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status ) +PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t *status) { list_t *localVarQueryParameters = list_createList(); list_t *localVarHeaderParameters = NULL; @@ -294,7 +294,7 @@ PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status ) // Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. // list_t* -PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags ) +PetAPI_findPetsByTags(apiClient_t *apiClient, list_t *tags) { list_t *localVarQueryParameters = list_createList(); list_t *localVarHeaderParameters = NULL; @@ -378,7 +378,7 @@ PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags ) // Returns a single pet // pet_t* -PetAPI_getPetById(apiClient_t *apiClient, long petId ) +PetAPI_getPetById(apiClient_t *apiClient, long petId) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -463,7 +463,7 @@ PetAPI_getPetById(apiClient_t *apiClient, long petId ) // Update an existing pet // void -PetAPI_updatePet(apiClient_t *apiClient, pet_t * body ) +PetAPI_updatePet(apiClient_t *apiClient, pet_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -536,7 +536,7 @@ PetAPI_updatePet(apiClient_t *apiClient, pet_t * body ) // Updates a pet in the store with form data // void -PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char * status ) +PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId, char *name, char *status) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -643,7 +643,7 @@ PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char // uploads an image // api_response_t* -PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata , binary_t* file ) +PetAPI_uploadFile(apiClient_t *apiClient, long petId, char *additionalMetadata, binary_t* file) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; diff --git a/samples/client/petstore/c/api/PetAPI.h b/samples/client/petstore/c/api/PetAPI.h index f223b60a0b8d..9b5c586fda78 100644 --- a/samples/client/petstore/c/api/PetAPI.h +++ b/samples/client/petstore/c/api/PetAPI.h @@ -15,13 +15,13 @@ typedef enum { openapi_petstore_findPetsByStatus_STATUS_NULL = 0, openapi_petst // Add a new pet to the store // void -PetAPI_addPet(apiClient_t *apiClient, pet_t * body ); +PetAPI_addPet(apiClient_t *apiClient, pet_t *body); // Deletes a pet // void -PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ); +PetAPI_deletePet(apiClient_t *apiClient, long petId, char *api_key); // Finds Pets by status @@ -29,7 +29,7 @@ PetAPI_deletePet(apiClient_t *apiClient, long petId , char * api_key ); // Multiple status values can be provided with comma separated strings // list_t* -PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status ); +PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t *status); // Finds Pets by tags @@ -37,7 +37,7 @@ PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status ); // Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. // list_t* -PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags ); +PetAPI_findPetsByTags(apiClient_t *apiClient, list_t *tags); // Find pet by ID @@ -45,24 +45,24 @@ PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags ); // Returns a single pet // pet_t* -PetAPI_getPetById(apiClient_t *apiClient, long petId ); +PetAPI_getPetById(apiClient_t *apiClient, long petId); // Update an existing pet // void -PetAPI_updatePet(apiClient_t *apiClient, pet_t * body ); +PetAPI_updatePet(apiClient_t *apiClient, pet_t *body); // Updates a pet in the store with form data // void -PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId , char * name , char * status ); +PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId, char *name, char *status); // uploads an image // api_response_t* -PetAPI_uploadFile(apiClient_t *apiClient, long petId , char * additionalMetadata , binary_t* file ); +PetAPI_uploadFile(apiClient_t *apiClient, long petId, char *additionalMetadata, binary_t* file); diff --git a/samples/client/petstore/c/api/StoreAPI.c b/samples/client/petstore/c/api/StoreAPI.c index c91a9d709dcf..a42780f567ac 100644 --- a/samples/client/petstore/c/api/StoreAPI.c +++ b/samples/client/petstore/c/api/StoreAPI.c @@ -17,7 +17,7 @@ // For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors // void -StoreAPI_deleteOrder(apiClient_t *apiClient, char * orderId ) +StoreAPI_deleteOrder(apiClient_t *apiClient, char *orderId) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -147,7 +147,7 @@ StoreAPI_getInventory(apiClient_t *apiClient) // For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions // order_t* -StoreAPI_getOrderById(apiClient_t *apiClient, long orderId ) +StoreAPI_getOrderById(apiClient_t *apiClient, long orderId) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -232,7 +232,7 @@ StoreAPI_getOrderById(apiClient_t *apiClient, long orderId ) // Place an order for a pet // order_t* -StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body ) +StoreAPI_placeOrder(apiClient_t *apiClient, order_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; diff --git a/samples/client/petstore/c/api/StoreAPI.h b/samples/client/petstore/c/api/StoreAPI.h index 99e4f25d37dd..1b44158d21f3 100644 --- a/samples/client/petstore/c/api/StoreAPI.h +++ b/samples/client/petstore/c/api/StoreAPI.h @@ -13,7 +13,7 @@ // For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors // void -StoreAPI_deleteOrder(apiClient_t *apiClient, char * orderId ); +StoreAPI_deleteOrder(apiClient_t *apiClient, char *orderId); // Returns pet inventories by status @@ -29,12 +29,12 @@ StoreAPI_getInventory(apiClient_t *apiClient); // For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions // order_t* -StoreAPI_getOrderById(apiClient_t *apiClient, long orderId ); +StoreAPI_getOrderById(apiClient_t *apiClient, long orderId); // Place an order for a pet // order_t* -StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body ); +StoreAPI_placeOrder(apiClient_t *apiClient, order_t *body); diff --git a/samples/client/petstore/c/api/UserAPI.c b/samples/client/petstore/c/api/UserAPI.c index 4eca7ca26ce3..3f5af05c8094 100644 --- a/samples/client/petstore/c/api/UserAPI.c +++ b/samples/client/petstore/c/api/UserAPI.c @@ -17,7 +17,7 @@ // This can only be done by the logged in user. // void -UserAPI_createUser(apiClient_t *apiClient, user_t * body ) +UserAPI_createUser(apiClient_t *apiClient, user_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -80,7 +80,7 @@ UserAPI_createUser(apiClient_t *apiClient, user_t * body ) // Creates list of users with given input array // void -UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body ) +UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -171,7 +171,7 @@ UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body ) // Creates list of users with given input array // void -UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ) +UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -264,7 +264,7 @@ UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ) // This can only be done by the logged in user. // void -UserAPI_deleteUser(apiClient_t *apiClient, char * username ) +UserAPI_deleteUser(apiClient_t *apiClient, char *username) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -328,7 +328,7 @@ UserAPI_deleteUser(apiClient_t *apiClient, char * username ) // Get user by user name // user_t* -UserAPI_getUserByName(apiClient_t *apiClient, char * username ) +UserAPI_getUserByName(apiClient_t *apiClient, char *username) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; @@ -409,7 +409,7 @@ UserAPI_getUserByName(apiClient_t *apiClient, char * username ) // Logs user into the system // char* -UserAPI_loginUser(apiClient_t *apiClient, char * username , char * password ) +UserAPI_loginUser(apiClient_t *apiClient, char *username, char *password) { list_t *localVarQueryParameters = list_createList(); list_t *localVarHeaderParameters = NULL; @@ -568,7 +568,7 @@ UserAPI_logoutUser(apiClient_t *apiClient) // This can test integer and boolean query parameters in API. // void -UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ) +UserAPI_testIntAndBool(apiClient_t *apiClient, int *keep, int *keepDay) { list_t *localVarQueryParameters = list_createList(); list_t *localVarHeaderParameters = NULL; @@ -589,11 +589,11 @@ UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ) char *keyQuery_keep = NULL; char * valueQuery_keep = NULL; keyValuePair_t *keyPairQuery_keep = 0; - if (1) // Always send boolean parameters to the API server + if (keep) { keyQuery_keep = strdup("keep"); valueQuery_keep = calloc(1,MAX_NUMBER_LENGTH); - snprintf(valueQuery_keep, MAX_NUMBER_LENGTH, "%d", keep); + snprintf(valueQuery_keep, MAX_NUMBER_LENGTH, "%d", *keep); keyPairQuery_keep = keyValuePair_create(keyQuery_keep, valueQuery_keep); list_addElement(localVarQueryParameters,keyPairQuery_keep); } @@ -602,11 +602,11 @@ UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ) char *keyQuery_keepDay = NULL; char * valueQuery_keepDay = NULL; keyValuePair_t *keyPairQuery_keepDay = 0; - if (1) // Always send integer parameters to the API server + if (keepDay) { keyQuery_keepDay = strdup("keepDay"); valueQuery_keepDay = calloc(1,MAX_NUMBER_LENGTH); - snprintf(valueQuery_keepDay, MAX_NUMBER_LENGTH, "%d", keepDay); + snprintf(valueQuery_keepDay, MAX_NUMBER_LENGTH, "%d", *keepDay); keyPairQuery_keepDay = keyValuePair_create(keyQuery_keepDay, valueQuery_keepDay); list_addElement(localVarQueryParameters,keyPairQuery_keepDay); } @@ -645,7 +645,7 @@ UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ) // This can only be done by the logged in user. // void -UserAPI_updateUser(apiClient_t *apiClient, char * username , user_t * body ) +UserAPI_updateUser(apiClient_t *apiClient, char *username, user_t *body) { list_t *localVarQueryParameters = NULL; list_t *localVarHeaderParameters = NULL; diff --git a/samples/client/petstore/c/api/UserAPI.h b/samples/client/petstore/c/api/UserAPI.h index 1a061b9904ed..ed59519a639a 100644 --- a/samples/client/petstore/c/api/UserAPI.h +++ b/samples/client/petstore/c/api/UserAPI.h @@ -13,19 +13,19 @@ // This can only be done by the logged in user. // void -UserAPI_createUser(apiClient_t *apiClient, user_t * body ); +UserAPI_createUser(apiClient_t *apiClient, user_t *body); // Creates list of users with given input array // void -UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body ); +UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t *body); // Creates list of users with given input array // void -UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ); +UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t *body); // Delete user @@ -33,19 +33,19 @@ UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body ); // This can only be done by the logged in user. // void -UserAPI_deleteUser(apiClient_t *apiClient, char * username ); +UserAPI_deleteUser(apiClient_t *apiClient, char *username); // Get user by user name // user_t* -UserAPI_getUserByName(apiClient_t *apiClient, char * username ); +UserAPI_getUserByName(apiClient_t *apiClient, char *username); // Logs user into the system // char* -UserAPI_loginUser(apiClient_t *apiClient, char * username , char * password ); +UserAPI_loginUser(apiClient_t *apiClient, char *username, char *password); // Logs out current logged in user session @@ -59,7 +59,7 @@ UserAPI_logoutUser(apiClient_t *apiClient); // This can test integer and boolean query parameters in API. // void -UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ); +UserAPI_testIntAndBool(apiClient_t *apiClient, int *keep, int *keepDay); // Updated user @@ -67,6 +67,6 @@ UserAPI_testIntAndBool(apiClient_t *apiClient, int keep , int keepDay ); // This can only be done by the logged in user. // void -UserAPI_updateUser(apiClient_t *apiClient, char * username , user_t * body ); +UserAPI_updateUser(apiClient_t *apiClient, char *username, user_t *body); diff --git a/samples/client/petstore/c/docs/PetAPI.md b/samples/client/petstore/c/docs/PetAPI.md index b509819fa251..392ef4d08a7d 100644 --- a/samples/client/petstore/c/docs/PetAPI.md +++ b/samples/client/petstore/c/docs/PetAPI.md @@ -18,7 +18,7 @@ Method | HTTP request | Description ```c // Add a new pet to the store // -void PetAPI_addPet(apiClient_t *apiClient, pet_t * body); +void PetAPI_addPet(apiClient_t *apiClient, pet_t *body); ``` ### Parameters @@ -46,7 +46,7 @@ void ```c // Deletes a pet // -void PetAPI_deletePet(apiClient_t *apiClient, long petId, char * api_key); +void PetAPI_deletePet(apiClient_t *apiClient, long petId, char *api_key); ``` ### Parameters @@ -77,7 +77,7 @@ void // // Multiple status values can be provided with comma separated strings // -list_t* PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t * status); +list_t* PetAPI_findPetsByStatus(apiClient_t *apiClient, list_t *status); ``` ### Parameters @@ -108,7 +108,7 @@ Name | Type | Description | Notes // // Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. // -list_t* PetAPI_findPetsByTags(apiClient_t *apiClient, list_t * tags); +list_t* PetAPI_findPetsByTags(apiClient_t *apiClient, list_t *tags); ``` ### Parameters @@ -168,7 +168,7 @@ Name | Type | Description | Notes ```c // Update an existing pet // -void PetAPI_updatePet(apiClient_t *apiClient, pet_t * body); +void PetAPI_updatePet(apiClient_t *apiClient, pet_t *body); ``` ### Parameters @@ -196,7 +196,7 @@ void ```c // Updates a pet in the store with form data // -void PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId, char * name, char * status); +void PetAPI_updatePetWithForm(apiClient_t *apiClient, long petId, char *name, char *status); ``` ### Parameters @@ -226,7 +226,7 @@ void ```c // uploads an image // -api_response_t* PetAPI_uploadFile(apiClient_t *apiClient, long petId, char * additionalMetadata, binary_t* file); +api_response_t* PetAPI_uploadFile(apiClient_t *apiClient, long petId, char *additionalMetadata, binary_t* file); ``` ### Parameters diff --git a/samples/client/petstore/c/docs/StoreAPI.md b/samples/client/petstore/c/docs/StoreAPI.md index 45462990e055..b5ea0864bd3c 100644 --- a/samples/client/petstore/c/docs/StoreAPI.md +++ b/samples/client/petstore/c/docs/StoreAPI.md @@ -16,7 +16,7 @@ Method | HTTP request | Description // // For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors // -void StoreAPI_deleteOrder(apiClient_t *apiClient, char * orderId); +void StoreAPI_deleteOrder(apiClient_t *apiClient, char *orderId); ``` ### Parameters @@ -108,7 +108,7 @@ No authorization required ```c // Place an order for a pet // -order_t* StoreAPI_placeOrder(apiClient_t *apiClient, order_t * body); +order_t* StoreAPI_placeOrder(apiClient_t *apiClient, order_t *body); ``` ### Parameters diff --git a/samples/client/petstore/c/docs/UserAPI.md b/samples/client/petstore/c/docs/UserAPI.md index 11d1de4d7f20..de82b9f10ab6 100644 --- a/samples/client/petstore/c/docs/UserAPI.md +++ b/samples/client/petstore/c/docs/UserAPI.md @@ -21,7 +21,7 @@ Method | HTTP request | Description // // This can only be done by the logged in user. // -void UserAPI_createUser(apiClient_t *apiClient, user_t * body); +void UserAPI_createUser(apiClient_t *apiClient, user_t *body); ``` ### Parameters @@ -49,7 +49,7 @@ No authorization required ```c // Creates list of users with given input array // -void UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t * body); +void UserAPI_createUsersWithArrayInput(apiClient_t *apiClient, list_t *body); ``` ### Parameters @@ -77,7 +77,7 @@ No authorization required ```c // Creates list of users with given input array // -void UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t * body); +void UserAPI_createUsersWithListInput(apiClient_t *apiClient, list_t *body); ``` ### Parameters @@ -107,7 +107,7 @@ No authorization required // // This can only be done by the logged in user. // -void UserAPI_deleteUser(apiClient_t *apiClient, char * username); +void UserAPI_deleteUser(apiClient_t *apiClient, char *username); ``` ### Parameters @@ -135,7 +135,7 @@ No authorization required ```c // Get user by user name // -user_t* UserAPI_getUserByName(apiClient_t *apiClient, char * username); +user_t* UserAPI_getUserByName(apiClient_t *apiClient, char *username); ``` ### Parameters @@ -164,7 +164,7 @@ No authorization required ```c // Logs user into the system // -char* UserAPI_loginUser(apiClient_t *apiClient, char * username, char * password); +char* UserAPI_loginUser(apiClient_t *apiClient, char *username, char *password); ``` ### Parameters @@ -224,15 +224,15 @@ No authorization required // // This can test integer and boolean query parameters in API. // -void UserAPI_testIntAndBool(apiClient_t *apiClient, int keep, int keepDay); +void UserAPI_testIntAndBool(apiClient_t *apiClient, int *keep, int *keepDay); ``` ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **apiClient** | **apiClient_t \*** | context containing the client configuration | -**keep** | **int** | Whether to keep user data after deletion | [optional] -**keepDay** | **int** | how many days user data is kept after deletion | [optional] +**keep** | **int \*** | Whether to keep user data after deletion | [optional] +**keepDay** | **int \*** | how many days user data is kept after deletion | [optional] ### Return type @@ -255,7 +255,7 @@ No authorization required // // This can only be done by the logged in user. // -void UserAPI_updateUser(apiClient_t *apiClient, char * username, user_t * body); +void UserAPI_updateUser(apiClient_t *apiClient, char *username, user_t *body); ``` ### Parameters diff --git a/samples/client/petstore/c/model/order.c b/samples/client/petstore/c/model/order.c index ec8688127116..734ff110252c 100644 --- a/samples/client/petstore/c/model/order.c +++ b/samples/client/petstore/c/model/order.c @@ -4,12 +4,12 @@ #include "order.h" -char* statusorder_ToString(openapi_petstore_order_STATUS_e status) { +char* order_status_ToString(openapi_petstore_order_STATUS_e status) { char* statusArray[] = { "NULL", "placed", "approved", "delivered" }; - return statusArray[status]; + return statusArray[status]; } -openapi_petstore_order_STATUS_e statusorder_FromString(char* status){ +openapi_petstore_order_STATUS_e order_status_FromString(char* status){ int stringToReturn = 0; char *statusArray[] = { "NULL", "placed", "approved", "delivered" }; size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); @@ -164,7 +164,7 @@ order_t *order_parseFromJSON(cJSON *orderJSON){ { goto end; //Enum } - statusVariable = statusorder_FromString(status->valuestring); + statusVariable = order_status_FromString(status->valuestring); } // order->complete diff --git a/samples/client/petstore/c/model/pet.c b/samples/client/petstore/c/model/pet.c index d46ad06b1014..7ca8b7a422a2 100644 --- a/samples/client/petstore/c/model/pet.c +++ b/samples/client/petstore/c/model/pet.c @@ -4,12 +4,12 @@ #include "pet.h" -char* statuspet_ToString(openapi_petstore_pet_STATUS_e status) { +char* pet_status_ToString(openapi_petstore_pet_STATUS_e status) { char* statusArray[] = { "NULL", "available", "pending", "sold" }; - return statusArray[status]; + return statusArray[status]; } -openapi_petstore_pet_STATUS_e statuspet_FromString(char* status){ +openapi_petstore_pet_STATUS_e pet_status_FromString(char* status){ int stringToReturn = 0; char *statusArray[] = { "NULL", "available", "pending", "sold" }; size_t sizeofArray = sizeof(statusArray) / sizeof(statusArray[0]); @@ -253,7 +253,7 @@ pet_t *pet_parseFromJSON(cJSON *petJSON){ { goto end; //Enum } - statusVariable = statuspet_FromString(status->valuestring); + statusVariable = pet_status_FromString(status->valuestring); } diff --git a/samples/client/petstore/c/src/apiKey.c b/samples/client/petstore/c/src/apiKey.c index eae9b75f3b47..c65d91c8e9f9 100644 --- a/samples/client/petstore/c/src/apiKey.c +++ b/samples/client/petstore/c/src/apiKey.c @@ -10,9 +10,9 @@ keyValuePair_t *keyValuePair_create(char *key, void *value) { } keyValuePair_t* keyValuePair_create_allocate(char* key, double value) { - double* boolpointer = malloc(sizeof(value)); - memcpy(boolpointer, &value, sizeof(value)); - return keyValuePair_create(key, boolpointer); + double* boolpointer = malloc(sizeof(value)); + memcpy(boolpointer, &value, sizeof(value)); + return keyValuePair_create(key, boolpointer); } void keyValuePair_free(keyValuePair_t *keyValuePair) { diff --git a/samples/client/petstore/cpp-qt/.openapi-generator/VERSION b/samples/client/petstore/cpp-qt/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/cpp-qt/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-qt/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp index f27d76e8ed1e..223debe59588 100644 --- a/samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp +++ b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.cpp @@ -24,7 +24,7 @@ void PetApiTests::findPetsByStatusTest() { } QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::findPetsByStatusSignalE, [&](QList, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::findPetsByStatusSignalError, [&](QList, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -47,7 +47,7 @@ void PetApiTests::createAndGetPetTest() { petCreated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::addPetSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -69,7 +69,7 @@ void PetApiTests::createAndGetPetTest() { // QVERIFY(pet.getStatus().compare("freaky") == 0); petFetched = true; }); - connect(&api, &PFXPetApi::getPetByIdSignalE, [&](PFXPet, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -92,7 +92,7 @@ void PetApiTests::updatePetTest() { petAdded = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::addPetSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -110,7 +110,7 @@ void PetApiTests::updatePetTest() { petToCheck = pet; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::getPetByIdSignalE, this, [&](PFXPet, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::getPetByIdSignalError, this, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -126,7 +126,7 @@ void PetApiTests::updatePetTest() { petUpdated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::updatePetSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::updatePetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -146,7 +146,7 @@ void PetApiTests::updatePetTest() { QVERIFY(pet.getStatus().compare(petToCheck.getStatus()) == 0); QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::getPetByIdSignalE, [&](PFXPet, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -170,7 +170,7 @@ void PetApiTests::updatePetWithFormTest() { petAdded = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::addPetSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::addPetSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -187,7 +187,7 @@ void PetApiTests::updatePetWithFormTest() { petToCheck = pet; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::getPetByIdSignalE, [&](PFXPet, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -203,7 +203,7 @@ void PetApiTests::updatePetWithFormTest() { petUpdated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::updatePetWithFormSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::updatePetWithFormSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -222,7 +222,7 @@ void PetApiTests::updatePetWithFormTest() { // QVERIFY(pet.getName().compare(QString("gorilla")) == 0); QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXPetApi::getPetByIdSignalE, [&](PFXPet, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXPetApi::getPetByIdSignalError, [&](PFXPet, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); diff --git a/samples/client/petstore/cpp-qt/PetStore/PetApiTests.h b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.h index 98989c51d251..77b6bd48ae39 100644 --- a/samples/client/petstore/cpp-qt/PetStore/PetApiTests.h +++ b/samples/client/petstore/cpp-qt/PetStore/PetApiTests.h @@ -9,7 +9,7 @@ class PetApiTests : public QObject { PFXPet createRandomPet(); -private slots: +private Q_SLOTS: void findPetsByStatusTest(); void createAndGetPetTest(); void updatePetTest(); diff --git a/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp index 5bb1fbd82b77..982121fc9dae 100644 --- a/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp +++ b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.cpp @@ -18,7 +18,7 @@ void StoreApiTests::placeOrderTest() { qDebug() << order.getShipDate(); QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXStoreApi::placeOrderSignalE, [&](PFXOrder, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXStoreApi::placeOrderSignalError, [&](PFXOrder, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -49,7 +49,7 @@ void StoreApiTests::getOrderByIdTest() { qDebug() << order.getShipDate(); QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXStoreApi::getOrderByIdSignalE, [&](PFXOrder, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXStoreApi::getOrderByIdSignalError, [&](PFXOrder, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -73,7 +73,7 @@ void StoreApiTests::getInventoryTest() { } QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXStoreApi::getInventorySignalE, [&](QMap, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXStoreApi::getInventorySignalError, [&](QMap, QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); diff --git a/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h index f2c9391afcb8..b1ca91b3b924 100644 --- a/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h +++ b/samples/client/petstore/cpp-qt/PetStore/StoreApiTests.h @@ -7,7 +7,7 @@ using namespace test_namespace; class StoreApiTests : public QObject { Q_OBJECT -private slots: +private Q_SLOTS: void placeOrderTest(); void getOrderByIdTest(); void getInventoryTest(); diff --git a/samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp index f55df89de43e..4665a1a4d208 100644 --- a/samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp +++ b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.cpp @@ -26,7 +26,7 @@ void UserApiTests::createUserTest() { userCreated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::createUserSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::createUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -46,7 +46,7 @@ void UserApiTests::createUsersWithArrayInputTest() { usersCreated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::createUsersWithArrayInputSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::createUsersWithArrayInputSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -70,7 +70,7 @@ void UserApiTests::createUsersWithListInputTest() { usersCreated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::createUsersWithListInputSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::createUsersWithListInputSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -98,7 +98,7 @@ void UserApiTests::deleteUserTest() { userDeleted = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::deleteUserSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::deleteUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { userDeleted = true; qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); @@ -121,7 +121,7 @@ void UserApiTests::getUserByNameTest() { // QVERIFY(summary.getUsername() == "johndoe"); QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::getUserByNameSignalE, [&](PFXUser, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::getUserByNameSignalError, [&](PFXUser, QNetworkReply::NetworkError, const QString &error_str) { userFetched = true; qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); @@ -143,7 +143,7 @@ void UserApiTests::loginUserTest() { qDebug() << summary; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::loginUserSignalE, [&](QString, QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::loginUserSignalError, [&](QString, QNetworkReply::NetworkError, const QString &error_str) { userLogged = true; qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); @@ -164,7 +164,7 @@ void UserApiTests::logoutUserTest() { userLoggedOut = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::logoutUserSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::logoutUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); @@ -184,7 +184,7 @@ void UserApiTests::updateUserTest() { userUpdated = true; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); - connect(&api, &PFXUserApi::updateUserSignalE, [&](QNetworkReply::NetworkError, QString error_str) { + connect(&api, &PFXUserApi::updateUserSignalError, [&](QNetworkReply::NetworkError, const QString &error_str) { qDebug() << "Error happened while issuing request : " << error_str; QTimer::singleShot(0, &loop, &QEventLoop::quit); }); diff --git a/samples/client/petstore/cpp-qt/PetStore/UserApiTests.h b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.h index 8917d6a7c0ce..23df1a62ebdd 100644 --- a/samples/client/petstore/cpp-qt/PetStore/UserApiTests.h +++ b/samples/client/petstore/cpp-qt/PetStore/UserApiTests.h @@ -9,7 +9,7 @@ class UserApiTests : public QObject { PFXUser createRandomUser(); -private slots: +private Q_SLOTS: void createUserTest(); void createUsersWithArrayInputTest(); void createUsersWithListInputTest(); diff --git a/samples/client/petstore/cpp-qt/README.md b/samples/client/petstore/cpp-qt/README.md index 4c2cf2ccc78e..f70e14f4b989 100644 --- a/samples/client/petstore/cpp-qt/README.md +++ b/samples/client/petstore/cpp-qt/README.md @@ -33,7 +33,7 @@ using namespace test_namespace; class Example : public QObject { Q_OBJECT PFXPet create(); -public slots: +public Q_SLOTS: void exampleFunction1(); }; diff --git a/samples/client/petstore/cpp-qt/client/CMakeLists.txt b/samples/client/petstore/cpp-qt/client/CMakeLists.txt index fb37e4dc2d50..cf6ea32ab3b4 100644 --- a/samples/client/petstore/cpp-qt/client/CMakeLists.txt +++ b/samples/client/petstore/cpp-qt/client/CMakeLists.txt @@ -1,4 +1,4 @@ -cmake_minimum_required(VERSION 3.2) +cmake_minimum_required(VERSION 3.5) project(CppQtPetstoreClient) diff --git a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp index 6ceed1516100..4664b9a399b6 100644 --- a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.cpp @@ -416,7 +416,7 @@ void PFXHttpRequestWorker::on_reply_finished(QNetworkReply *reply) { } process_response(reply); reply->deleteLater(); - emit on_execution_finished(this); + Q_EMIT on_execution_finished(this); } void PFXHttpRequestWorker::on_reply_timeout(QNetworkReply *reply) { @@ -426,7 +426,7 @@ void PFXHttpRequestWorker::on_reply_timeout(QNetworkReply *reply) { disconnect(reply, nullptr, nullptr, nullptr); reply->abort(); reply->deleteLater(); - emit on_execution_finished(this); + Q_EMIT on_execution_finished(this); } void PFXHttpRequestWorker::process_response(QNetworkReply *reply) { diff --git a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h index 022d97adcb6a..31e2ec823af2 100644 --- a/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h +++ b/samples/client/petstore/cpp-qt/client/PFXHttpRequest.h @@ -80,7 +80,7 @@ class PFXHttpRequestWorker : public QObject { void setRequestCompressionEnabled(bool enable); int getHttpResponseCode() const; -signals: +Q_SIGNALS: void on_execution_finished(PFXHttpRequestWorker *worker); private: diff --git a/samples/client/petstore/cpp-qt/client/PFXOauth.cpp b/samples/client/petstore/cpp-qt/client/PFXOauth.cpp index 2c349ea5fc29..c22d3a849997 100644 --- a/samples/client/petstore/cpp-qt/client/PFXOauth.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXOauth.cpp @@ -29,7 +29,7 @@ oauthToken OauthBase::getToken(QString scope) void OauthBase::addToken(oauthToken token) { m_oauthTokenMap.insert(token.getScope(),token); - emit tokenReceived(); + Q_EMIT tokenReceived(); } @@ -339,7 +339,7 @@ void ReplyServer::read() } socket->close(); - emit dataReceived(queryParams); + Q_EMIT dataReceived(queryParams); } } // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt/client/PFXOauth.h b/samples/client/petstore/cpp-qt/client/PFXOauth.h index 3c3ad8c1c3d5..9038d05940c2 100644 --- a/samples/client/petstore/cpp-qt/client/PFXOauth.h +++ b/samples/client/petstore/cpp-qt/client/PFXOauth.h @@ -66,10 +66,10 @@ class ReplyServer : public QTcpServer private: QByteArray m_reply; -signals: +Q_SIGNALS: void dataReceived(QMap); -public slots: +public Q_SLOTS: void onConnected(); void read(); void start(); @@ -96,11 +96,11 @@ class OauthBase : public QObject QString m_scope, m_accessType, m_state, m_redirectUri, m_clientId, m_clientSecret; bool m_linked; -public slots: +public Q_SLOTS: virtual void authenticationNeededCallback()=0; void onFinish(QNetworkReply *rep); -signals: +Q_SIGNALS: void authenticationNeeded(); void tokenReceived(); }; @@ -118,7 +118,7 @@ class OauthCode : public OauthBase private: ReplyServer m_server; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; void onVerificationReceived(const QMap response); @@ -137,7 +137,7 @@ class OauthImplicit : public OauthBase private: ReplyServer m_server; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; void ImplicitTokenReceived(const QMap response); }; @@ -152,7 +152,7 @@ class OauthCredentials : public OauthBase void unlink() override; void setVariables(QString tokenUrl, QString scope, QString clientId, QString clientSecret); -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; }; @@ -170,7 +170,7 @@ class OauthPassword : public OauthBase private: QString m_username, m_password; -public slots: +public Q_SLOTS: void authenticationNeededCallback() override; }; diff --git a/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp index e1822961fa89..3aad8a2e9e3f 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXPetApi.cpp @@ -162,7 +162,7 @@ void PFXPetApi::enableResponseCompression() { } void PFXPetApi::abortRequests() { - emit abortRequestsSignal(); + Q_EMIT abortRequestsSignal(); } QString PFXPetApi::getParamStylePrefix(const QString &style) { @@ -256,7 +256,7 @@ void PFXPetApi::addPet(const PFXPet &pfx_pet) { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -279,7 +279,7 @@ void PFXPetApi::addPet(const PFXPet &pfx_pet) { connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -301,8 +301,8 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit addPetSignal(); - emit addPetSignalFull(worker); + Q_EMIT addPetSignal(); + Q_EMIT addPetSignalFull(worker); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -312,12 +312,38 @@ void PFXPetApi::addPetCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit addPetSignalE(error_type, error_str); - emit addPetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT addPetSignalE(error_type, error_str); + Q_EMIT addPetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT addPetSignalError(error_type, error_str); + Q_EMIT addPetSignalErrorFull(worker, error_type, error_str); } } @@ -344,7 +370,7 @@ void PFXPetApi::allPets() { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -371,11 +397,37 @@ void PFXPetApi::allPetsCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit allPetsSignal(output); - emit allPetsSignalFull(worker, output); + Q_EMIT allPetsSignal(output); + Q_EMIT allPetsSignalFull(worker, output); } else { - emit allPetsSignalE(output, error_type, error_str); - emit allPetsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT allPetsSignalE(output, error_type, error_str); + Q_EMIT allPetsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT allPetsSignalError(output, error_type, error_str); + Q_EMIT allPetsSignalErrorFull(worker, error_type, error_str); } } @@ -422,7 +474,7 @@ void PFXPetApi::deletePet(const qint64 &pet_id, const ::test_namespace::Optional connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -445,7 +497,7 @@ void PFXPetApi::deletePet(const qint64 &pet_id, const ::test_namespace::Optional connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -467,8 +519,8 @@ void PFXPetApi::deletePetCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit deletePetSignal(); - emit deletePetSignalFull(worker); + Q_EMIT deletePetSignal(); + Q_EMIT deletePetSignalFull(worker); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -478,12 +530,38 @@ void PFXPetApi::deletePetCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit deletePetSignalE(error_type, error_str); - emit deletePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deletePetSignalE(error_type, error_str); + Q_EMIT deletePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deletePetSignalError(error_type, error_str); + Q_EMIT deletePetSignalErrorFull(worker, error_type, error_str); } } @@ -596,7 +674,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -619,7 +697,7 @@ void PFXPetApi::findPetsByStatus(const QList &status) { connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -651,8 +729,8 @@ void PFXPetApi::findPetsByStatusCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit findPetsByStatusSignal(output); - emit findPetsByStatusSignalFull(worker, output); + Q_EMIT findPetsByStatusSignal(output); + Q_EMIT findPetsByStatusSignalFull(worker, output); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -662,12 +740,38 @@ void PFXPetApi::findPetsByStatusCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit findPetsByStatusSignalE(output, error_type, error_str); - emit findPetsByStatusSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT findPetsByStatusSignalE(output, error_type, error_str); + Q_EMIT findPetsByStatusSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT findPetsByStatusSignalError(output, error_type, error_str); + Q_EMIT findPetsByStatusSignalErrorFull(worker, error_type, error_str); } } @@ -780,7 +884,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -803,7 +907,7 @@ void PFXPetApi::findPetsByTags(const QList &tags) { connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -835,8 +939,8 @@ void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit findPetsByTagsSignal(output); - emit findPetsByTagsSignalFull(worker, output); + Q_EMIT findPetsByTagsSignal(output); + Q_EMIT findPetsByTagsSignalFull(worker, output); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -846,12 +950,38 @@ void PFXPetApi::findPetsByTagsCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit findPetsByTagsSignalE(output, error_type, error_str); - emit findPetsByTagsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT findPetsByTagsSignalE(output, error_type, error_str); + Q_EMIT findPetsByTagsSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT findPetsByTagsSignalError(output, error_type, error_str); + Q_EMIT findPetsByTagsSignalErrorFull(worker, error_type, error_str); } } @@ -896,7 +1026,7 @@ void PFXPetApi::getPetById(const qint64 &pet_id) { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -914,11 +1044,37 @@ void PFXPetApi::getPetByIdCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit getPetByIdSignal(output); - emit getPetByIdSignalFull(worker, output); + Q_EMIT getPetByIdSignal(output); + Q_EMIT getPetByIdSignalFull(worker, output); } else { - emit getPetByIdSignalE(output, error_type, error_str); - emit getPetByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getPetByIdSignalE(output, error_type, error_str); + Q_EMIT getPetByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getPetByIdSignalError(output, error_type, error_str); + Q_EMIT getPetByIdSignalErrorFull(worker, error_type, error_str); } } @@ -950,7 +1106,7 @@ void PFXPetApi::updatePet(const PFXPet &pfx_pet) { connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -973,7 +1129,7 @@ void PFXPetApi::updatePet(const PFXPet &pfx_pet) { connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -995,8 +1151,8 @@ void PFXPetApi::updatePetCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit updatePetSignal(); - emit updatePetSignalFull(worker); + Q_EMIT updatePetSignal(); + Q_EMIT updatePetSignalFull(worker); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -1006,12 +1162,38 @@ void PFXPetApi::updatePetCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit updatePetSignalE(error_type, error_str); - emit updatePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updatePetSignalE(error_type, error_str); + Q_EMIT updatePetSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updatePetSignalError(error_type, error_str); + Q_EMIT updatePetSignalErrorFull(worker, error_type, error_str); } } @@ -1060,7 +1242,7 @@ void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const ::test_namespace:: connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -1083,7 +1265,7 @@ void PFXPetApi::updatePetWithForm(const qint64 &pet_id, const ::test_namespace:: connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -1105,8 +1287,8 @@ void PFXPetApi::updatePetWithFormCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit updatePetWithFormSignal(); - emit updatePetWithFormSignalFull(worker); + Q_EMIT updatePetWithFormSignal(); + Q_EMIT updatePetWithFormSignalFull(worker); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -1116,12 +1298,38 @@ void PFXPetApi::updatePetWithFormCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit updatePetWithFormSignalE(error_type, error_str); - emit updatePetWithFormSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updatePetWithFormSignalE(error_type, error_str); + Q_EMIT updatePetWithFormSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updatePetWithFormSignalError(error_type, error_str); + Q_EMIT updatePetWithFormSignalErrorFull(worker, error_type, error_str); } } @@ -1170,7 +1378,7 @@ void PFXPetApi::uploadFile(const qint64 &pet_id, const ::test_namespace::Optiona connect(this, &PFXPetApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); _OauthMethod = 1; @@ -1193,7 +1401,7 @@ void PFXPetApi::uploadFile(const qint64 &pet_id, const ::test_namespace::Optiona connect(this, &PFXPetApi::abortRequestsSignal, _latestWorker, &QObject::deleteLater); connect(_latestWorker, &QObject::destroyed, [this](){ if(findChildren().count() == 0){ - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -1216,8 +1424,8 @@ void PFXPetApi::uploadFileCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit uploadFileSignal(output); - emit uploadFileSignalFull(worker, output); + Q_EMIT uploadFileSignal(output); + Q_EMIT uploadFileSignalFull(worker, output); } else if(worker->error_type == QNetworkReply::AuthenticationRequiredError){ connect(&_implicitFlow, SIGNAL(tokenReceived()), this, SLOT(tokenAvailable())); QStringList scope; @@ -1227,12 +1435,38 @@ void PFXPetApi::uploadFileCallback(PFXHttpRequestWorker *worker) { QString authorizationUrl("http://petstore.swagger.io/api/oauth/dialog"); //TODO get clientID and Secret and state in the config? https://swagger.io/docs/specification/authentication/oauth2/ states that you should do as you like _implicitFlow.setVariables(authorizationUrl, scopeStr, "state" , "http://127.0.0.1:9999", "clientId"); - emit _implicitFlow.authenticationNeeded(); + Q_EMIT _implicitFlow.authenticationNeeded(); } else { - emit uploadFileSignalE(output, error_type, error_str); - emit uploadFileSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT uploadFileSignalE(output, error_type, error_str); + Q_EMIT uploadFileSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT uploadFileSignalError(output, error_type, error_str); + Q_EMIT uploadFileSignalErrorFull(worker, error_type, error_str); } } diff --git a/samples/client/petstore/cpp-qt/client/PFXPetApi.h b/samples/client/petstore/cpp-qt/client/PFXPetApi.h index 004050016f97..ba85ac3b95e9 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPetApi.h +++ b/samples/client/petstore/cpp-qt/client/PFXPetApi.h @@ -140,7 +140,7 @@ class PFXPetApi : public QObject { void updatePetWithFormCallback(PFXHttpRequestWorker *worker); void uploadFileCallback(PFXHttpRequestWorker *worker); -signals: +Q_SIGNALS: void addPetSignal(); void allPetsSignal(QSet summary); @@ -162,32 +162,67 @@ class PFXPetApi : public QObject { void updatePetWithFormSignalFull(PFXHttpRequestWorker *worker); void uploadFileSignalFull(PFXHttpRequestWorker *worker, PFXApiResponse summary); + Q_DECL_DEPRECATED_X("Use addPetSignalError() instead") void addPetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void addPetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use allPetsSignalError() instead") void allPetsSignalE(QSet summary, QNetworkReply::NetworkError error_type, QString error_str); + void allPetsSignalError(QSet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deletePetSignalError() instead") void deletePetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deletePetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByStatusSignalError() instead") void findPetsByStatusSignalE(QList summary, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByStatusSignalError(QList summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByTagsSignalError() instead") void findPetsByTagsSignalE(QList summary, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByTagsSignalError(QList summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getPetByIdSignalError() instead") void getPetByIdSignalE(PFXPet summary, QNetworkReply::NetworkError error_type, QString error_str); + void getPetByIdSignalError(PFXPet summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetSignalError() instead") void updatePetSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updatePetSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetWithFormSignalError() instead") void updatePetWithFormSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updatePetWithFormSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use uploadFileSignalError() instead") void uploadFileSignalE(PFXApiResponse summary, QNetworkReply::NetworkError error_type, QString error_str); + void uploadFileSignalError(PFXApiResponse summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use addPetSignalErrorFull() instead") void addPetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void addPetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use allPetsSignalErrorFull() instead") void allPetsSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void allPetsSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deletePetSignalErrorFull() instead") void deletePetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deletePetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByStatusSignalErrorFull() instead") void findPetsByStatusSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByStatusSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use findPetsByTagsSignalErrorFull() instead") void findPetsByTagsSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void findPetsByTagsSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getPetByIdSignalErrorFull() instead") void getPetByIdSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getPetByIdSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetSignalErrorFull() instead") void updatePetSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updatePetSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updatePetWithFormSignalErrorFull() instead") void updatePetWithFormSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updatePetWithFormSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use uploadFileSignalErrorFull() instead") void uploadFileSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void uploadFileSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); void abortRequestsSignal(); void allPendingRequestsCompleted(); -public slots: +public Q_SLOTS: void tokenAvailable(); - }; } // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp index 792128b66f62..6badeb2c05f7 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.cpp @@ -148,7 +148,7 @@ void PFXPrimitivesApi::enableResponseCompression() { } void PFXPrimitivesApi::abortRequests() { - emit abortRequestsSignal(); + Q_EMIT abortRequestsSignal(); } QString PFXPrimitivesApi::getParamStylePrefix(const QString &style) { @@ -241,7 +241,7 @@ void PFXPrimitivesApi::primitivesIntegerPost(const ::test_namespace::OptionalPar connect(this, &PFXPrimitivesApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -258,11 +258,37 @@ void PFXPrimitivesApi::primitivesIntegerPostCallback(PFXHttpRequestWorker *worke worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit primitivesIntegerPostSignal(); - emit primitivesIntegerPostSignalFull(worker); + Q_EMIT primitivesIntegerPostSignal(); + Q_EMIT primitivesIntegerPostSignalFull(worker); } else { - emit primitivesIntegerPostSignalE(error_type, error_str); - emit primitivesIntegerPostSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT primitivesIntegerPostSignalE(error_type, error_str); + Q_EMIT primitivesIntegerPostSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT primitivesIntegerPostSignalError(error_type, error_str); + Q_EMIT primitivesIntegerPostSignalErrorFull(worker, error_type, error_str); } } @@ -293,7 +319,7 @@ void PFXPrimitivesApi::primitivesNumberPut(const ::test_namespace::OptionalParam connect(this, &PFXPrimitivesApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -310,11 +336,37 @@ void PFXPrimitivesApi::primitivesNumberPutCallback(PFXHttpRequestWorker *worker) worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit primitivesNumberPutSignal(); - emit primitivesNumberPutSignalFull(worker); + Q_EMIT primitivesNumberPutSignal(); + Q_EMIT primitivesNumberPutSignalFull(worker); } else { - emit primitivesNumberPutSignalE(error_type, error_str); - emit primitivesNumberPutSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT primitivesNumberPutSignalE(error_type, error_str); + Q_EMIT primitivesNumberPutSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT primitivesNumberPutSignalError(error_type, error_str); + Q_EMIT primitivesNumberPutSignalErrorFull(worker, error_type, error_str); } } diff --git a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.h b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.h index 3c7d4d2bd651..7ecebdef01d9 100644 --- a/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.h +++ b/samples/client/petstore/cpp-qt/client/PFXPrimitivesApi.h @@ -91,7 +91,7 @@ class PFXPrimitivesApi : public QObject { void primitivesIntegerPostCallback(PFXHttpRequestWorker *worker); void primitivesNumberPutCallback(PFXHttpRequestWorker *worker); -signals: +Q_SIGNALS: void primitivesIntegerPostSignal(); void primitivesNumberPutSignal(); @@ -99,18 +99,25 @@ class PFXPrimitivesApi : public QObject { void primitivesIntegerPostSignalFull(PFXHttpRequestWorker *worker); void primitivesNumberPutSignalFull(PFXHttpRequestWorker *worker); + Q_DECL_DEPRECATED_X("Use primitivesIntegerPostSignalError() instead") void primitivesIntegerPostSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void primitivesIntegerPostSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use primitivesNumberPutSignalError() instead") void primitivesNumberPutSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void primitivesNumberPutSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use primitivesIntegerPostSignalErrorFull() instead") void primitivesIntegerPostSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void primitivesIntegerPostSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use primitivesNumberPutSignalErrorFull() instead") void primitivesNumberPutSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void primitivesNumberPutSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); void abortRequestsSignal(); void allPendingRequestsCompleted(); -public slots: +public Q_SLOTS: void tokenAvailable(); - }; } // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp index 77a98da9c75a..af5cdb421e01 100644 --- a/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXStoreApi.cpp @@ -152,7 +152,7 @@ void PFXStoreApi::enableResponseCompression() { } void PFXStoreApi::abortRequests() { - emit abortRequestsSignal(); + Q_EMIT abortRequestsSignal(); } QString PFXStoreApi::getParamStylePrefix(const QString &style) { @@ -255,7 +255,7 @@ void PFXStoreApi::deleteOrder(const QString &order_id) { connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -272,11 +272,37 @@ void PFXStoreApi::deleteOrderCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit deleteOrderSignal(); - emit deleteOrderSignalFull(worker); + Q_EMIT deleteOrderSignal(); + Q_EMIT deleteOrderSignalFull(worker); } else { - emit deleteOrderSignalE(error_type, error_str); - emit deleteOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deleteOrderSignalE(error_type, error_str); + Q_EMIT deleteOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deleteOrderSignalError(error_type, error_str); + Q_EMIT deleteOrderSignalErrorFull(worker, error_type, error_str); } } @@ -307,7 +333,7 @@ void PFXStoreApi::getInventory() { connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -334,11 +360,37 @@ void PFXStoreApi::getInventoryCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit getInventorySignal(output); - emit getInventorySignalFull(worker, output); + Q_EMIT getInventorySignal(output); + Q_EMIT getInventorySignalFull(worker, output); } else { - emit getInventorySignalE(output, error_type, error_str); - emit getInventorySignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getInventorySignalE(output, error_type, error_str); + Q_EMIT getInventorySignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getInventorySignalError(output, error_type, error_str); + Q_EMIT getInventorySignalErrorFull(worker, error_type, error_str); } } @@ -379,7 +431,7 @@ void PFXStoreApi::getOrderById(const qint64 &order_id) { connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -397,11 +449,37 @@ void PFXStoreApi::getOrderByIdCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit getOrderByIdSignal(output); - emit getOrderByIdSignalFull(worker, output); + Q_EMIT getOrderByIdSignal(output); + Q_EMIT getOrderByIdSignalFull(worker, output); } else { - emit getOrderByIdSignalE(output, error_type, error_str); - emit getOrderByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getOrderByIdSignalE(output, error_type, error_str); + Q_EMIT getOrderByIdSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getOrderByIdSignalError(output, error_type, error_str); + Q_EMIT getOrderByIdSignalErrorFull(worker, error_type, error_str); } } @@ -433,7 +511,7 @@ void PFXStoreApi::placeOrder(const PFXOrder &pfx_order) { connect(this, &PFXStoreApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -451,11 +529,37 @@ void PFXStoreApi::placeOrderCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit placeOrderSignal(output); - emit placeOrderSignalFull(worker, output); + Q_EMIT placeOrderSignal(output); + Q_EMIT placeOrderSignalFull(worker, output); } else { - emit placeOrderSignalE(output, error_type, error_str); - emit placeOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT placeOrderSignalE(output, error_type, error_str); + Q_EMIT placeOrderSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT placeOrderSignalError(output, error_type, error_str); + Q_EMIT placeOrderSignalErrorFull(worker, error_type, error_str); } } diff --git a/samples/client/petstore/cpp-qt/client/PFXStoreApi.h b/samples/client/petstore/cpp-qt/client/PFXStoreApi.h index 43bf25f4ea51..a9ac689d36d0 100644 --- a/samples/client/petstore/cpp-qt/client/PFXStoreApi.h +++ b/samples/client/petstore/cpp-qt/client/PFXStoreApi.h @@ -103,7 +103,7 @@ class PFXStoreApi : public QObject { void getOrderByIdCallback(PFXHttpRequestWorker *worker); void placeOrderCallback(PFXHttpRequestWorker *worker); -signals: +Q_SIGNALS: void deleteOrderSignal(); void getInventorySignal(QMap summary); @@ -115,22 +115,37 @@ class PFXStoreApi : public QObject { void getOrderByIdSignalFull(PFXHttpRequestWorker *worker, PFXOrder summary); void placeOrderSignalFull(PFXHttpRequestWorker *worker, PFXOrder summary); + Q_DECL_DEPRECATED_X("Use deleteOrderSignalError() instead") void deleteOrderSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deleteOrderSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getInventorySignalError() instead") void getInventorySignalE(QMap summary, QNetworkReply::NetworkError error_type, QString error_str); + void getInventorySignalError(QMap summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getOrderByIdSignalError() instead") void getOrderByIdSignalE(PFXOrder summary, QNetworkReply::NetworkError error_type, QString error_str); + void getOrderByIdSignalError(PFXOrder summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use placeOrderSignalError() instead") void placeOrderSignalE(PFXOrder summary, QNetworkReply::NetworkError error_type, QString error_str); + void placeOrderSignalError(PFXOrder summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deleteOrderSignalErrorFull() instead") void deleteOrderSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deleteOrderSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getInventorySignalErrorFull() instead") void getInventorySignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getInventorySignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getOrderByIdSignalErrorFull() instead") void getOrderByIdSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getOrderByIdSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use placeOrderSignalErrorFull() instead") void placeOrderSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void placeOrderSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); void abortRequestsSignal(); void allPendingRequestsCompleted(); -public slots: +public Q_SLOTS: void tokenAvailable(); - }; } // namespace test_namespace diff --git a/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp index 197825fd0375..86c362b90a80 100644 --- a/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp +++ b/samples/client/petstore/cpp-qt/client/PFXUserApi.cpp @@ -160,7 +160,7 @@ void PFXUserApi::enableResponseCompression() { } void PFXUserApi::abortRequests() { - emit abortRequestsSignal(); + Q_EMIT abortRequestsSignal(); } QString PFXUserApi::getParamStylePrefix(const QString &style) { @@ -254,7 +254,7 @@ void PFXUserApi::createUser(const PFXUser &pfx_user) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -271,11 +271,37 @@ void PFXUserApi::createUserCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit createUserSignal(); - emit createUserSignalFull(worker); + Q_EMIT createUserSignal(); + Q_EMIT createUserSignalFull(worker); } else { - emit createUserSignalE(error_type, error_str); - emit createUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUserSignalE(error_type, error_str); + Q_EMIT createUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUserSignalError(error_type, error_str); + Q_EMIT createUserSignalErrorFull(worker, error_type, error_str); } } @@ -306,7 +332,7 @@ void PFXUserApi::createUsersWithArrayInput(const QList &pfx_user) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -323,11 +349,37 @@ void PFXUserApi::createUsersWithArrayInputCallback(PFXHttpRequestWorker *worker) worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit createUsersWithArrayInputSignal(); - emit createUsersWithArrayInputSignalFull(worker); + Q_EMIT createUsersWithArrayInputSignal(); + Q_EMIT createUsersWithArrayInputSignalFull(worker); } else { - emit createUsersWithArrayInputSignalE(error_type, error_str); - emit createUsersWithArrayInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUsersWithArrayInputSignalE(error_type, error_str); + Q_EMIT createUsersWithArrayInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUsersWithArrayInputSignalError(error_type, error_str); + Q_EMIT createUsersWithArrayInputSignalErrorFull(worker, error_type, error_str); } } @@ -358,7 +410,7 @@ void PFXUserApi::createUsersWithListInput(const QList &pfx_user) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -375,11 +427,37 @@ void PFXUserApi::createUsersWithListInputCallback(PFXHttpRequestWorker *worker) worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit createUsersWithListInputSignal(); - emit createUsersWithListInputSignalFull(worker); + Q_EMIT createUsersWithListInputSignal(); + Q_EMIT createUsersWithListInputSignalFull(worker); } else { - emit createUsersWithListInputSignalE(error_type, error_str); - emit createUsersWithListInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT createUsersWithListInputSignalE(error_type, error_str); + Q_EMIT createUsersWithListInputSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT createUsersWithListInputSignalError(error_type, error_str); + Q_EMIT createUsersWithListInputSignalErrorFull(worker, error_type, error_str); } } @@ -420,7 +498,7 @@ void PFXUserApi::deleteUser(const QString &username) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -437,11 +515,37 @@ void PFXUserApi::deleteUserCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit deleteUserSignal(); - emit deleteUserSignalFull(worker); + Q_EMIT deleteUserSignal(); + Q_EMIT deleteUserSignalFull(worker); } else { - emit deleteUserSignalE(error_type, error_str); - emit deleteUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT deleteUserSignalE(error_type, error_str); + Q_EMIT deleteUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT deleteUserSignalError(error_type, error_str); + Q_EMIT deleteUserSignalErrorFull(worker, error_type, error_str); } } @@ -482,7 +586,7 @@ void PFXUserApi::getUserByName(const QString &username) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -500,11 +604,37 @@ void PFXUserApi::getUserByNameCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit getUserByNameSignal(output); - emit getUserByNameSignalFull(worker, output); + Q_EMIT getUserByNameSignal(output); + Q_EMIT getUserByNameSignalFull(worker, output); } else { - emit getUserByNameSignalE(output, error_type, error_str); - emit getUserByNameSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT getUserByNameSignalE(output, error_type, error_str); + Q_EMIT getUserByNameSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT getUserByNameSignalError(output, error_type, error_str); + Q_EMIT getUserByNameSignalErrorFull(worker, error_type, error_str); } } @@ -562,7 +692,7 @@ void PFXUserApi::loginUser(const QString &username, const QString &password) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -581,11 +711,37 @@ void PFXUserApi::loginUserCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit loginUserSignal(output); - emit loginUserSignalFull(worker, output); + Q_EMIT loginUserSignal(output); + Q_EMIT loginUserSignalFull(worker, output); } else { - emit loginUserSignalE(output, error_type, error_str); - emit loginUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT loginUserSignalE(output, error_type, error_str); + Q_EMIT loginUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT loginUserSignalError(output, error_type, error_str); + Q_EMIT loginUserSignalErrorFull(worker, error_type, error_str); } } @@ -612,7 +768,7 @@ void PFXUserApi::logoutUser() { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -629,11 +785,37 @@ void PFXUserApi::logoutUserCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit logoutUserSignal(); - emit logoutUserSignalFull(worker); + Q_EMIT logoutUserSignal(); + Q_EMIT logoutUserSignalFull(worker); } else { - emit logoutUserSignalE(error_type, error_str); - emit logoutUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT logoutUserSignalE(error_type, error_str); + Q_EMIT logoutUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT logoutUserSignalError(error_type, error_str); + Q_EMIT logoutUserSignalErrorFull(worker, error_type, error_str); } } @@ -679,7 +861,7 @@ void PFXUserApi::updateUser(const QString &username, const PFXUser &pfx_user) { connect(this, &PFXUserApi::abortRequestsSignal, worker, &QObject::deleteLater); connect(worker, &QObject::destroyed, this, [this]() { if (findChildren().count() == 0) { - emit allPendingRequestsCompleted(); + Q_EMIT allPendingRequestsCompleted(); } }); @@ -696,11 +878,37 @@ void PFXUserApi::updateUserCallback(PFXHttpRequestWorker *worker) { worker->deleteLater(); if (worker->error_type == QNetworkReply::NoError) { - emit updateUserSignal(); - emit updateUserSignalFull(worker); + Q_EMIT updateUserSignal(); + Q_EMIT updateUserSignalFull(worker); } else { - emit updateUserSignalE(error_type, error_str); - emit updateUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +// For MSVC +#pragma warning(push) +#pragma warning(disable : 4996) +#elif defined(__clang__) +// For Clang +#pragma clang diagnostic push +#pragma clang diagnostic ignored "-Wdeprecated-declarations" +#elif defined(__GNUC__) +// For GCC +#pragma GCC diagnostic push +#pragma GCC diagnostic ignored "-Wdeprecated-declarations" +#endif + + Q_EMIT updateUserSignalE(error_type, error_str); + Q_EMIT updateUserSignalEFull(worker, error_type, error_str); + +#if defined(_MSC_VER) +#pragma warning(pop) +#elif defined(__clang__) +#pragma clang diagnostic pop +#elif defined(__GNUC__) +#pragma GCC diagnostic pop +#endif + + Q_EMIT updateUserSignalError(error_type, error_str); + Q_EMIT updateUserSignalErrorFull(worker, error_type, error_str); } } diff --git a/samples/client/petstore/cpp-qt/client/PFXUserApi.h b/samples/client/petstore/cpp-qt/client/PFXUserApi.h index 52e790b2e791..552a683e142e 100644 --- a/samples/client/petstore/cpp-qt/client/PFXUserApi.h +++ b/samples/client/petstore/cpp-qt/client/PFXUserApi.h @@ -128,7 +128,7 @@ class PFXUserApi : public QObject { void logoutUserCallback(PFXHttpRequestWorker *worker); void updateUserCallback(PFXHttpRequestWorker *worker); -signals: +Q_SIGNALS: void createUserSignal(); void createUsersWithArrayInputSignal(); @@ -148,30 +148,61 @@ class PFXUserApi : public QObject { void logoutUserSignalFull(PFXHttpRequestWorker *worker); void updateUserSignalFull(PFXHttpRequestWorker *worker); + Q_DECL_DEPRECATED_X("Use createUserSignalError() instead") void createUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithArrayInputSignalError() instead") void createUsersWithArrayInputSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithArrayInputSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithListInputSignalError() instead") void createUsersWithListInputSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithListInputSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deleteUserSignalError() instead") void deleteUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void deleteUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getUserByNameSignalError() instead") void getUserByNameSignalE(PFXUser summary, QNetworkReply::NetworkError error_type, QString error_str); + void getUserByNameSignalError(PFXUser summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use loginUserSignalError() instead") void loginUserSignalE(QString summary, QNetworkReply::NetworkError error_type, QString error_str); + void loginUserSignalError(QString summary, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use logoutUserSignalError() instead") void logoutUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void logoutUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updateUserSignalError() instead") void updateUserSignalE(QNetworkReply::NetworkError error_type, QString error_str); + void updateUserSignalError(QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUserSignalErrorFull() instead") void createUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithArrayInputSignalErrorFull() instead") void createUsersWithArrayInputSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithArrayInputSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use createUsersWithListInputSignalErrorFull() instead") void createUsersWithListInputSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void createUsersWithListInputSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use deleteUserSignalErrorFull() instead") void deleteUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void deleteUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use getUserByNameSignalErrorFull() instead") void getUserByNameSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void getUserByNameSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use loginUserSignalErrorFull() instead") void loginUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void loginUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use logoutUserSignalErrorFull() instead") void logoutUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void logoutUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); + Q_DECL_DEPRECATED_X("Use updateUserSignalErrorFull() instead") void updateUserSignalEFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, QString error_str); + void updateUserSignalErrorFull(PFXHttpRequestWorker *worker, QNetworkReply::NetworkError error_type, const QString &error_str); void abortRequestsSignal(); void allPendingRequestsCompleted(); -public slots: +public Q_SLOTS: void tokenAvailable(); - }; } // namespace test_namespace diff --git a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-restsdk/client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiClient.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiClient.h index 284b8fc9d562..26554600b7ee 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiClient.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiClient.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiConfiguration.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiConfiguration.h index 99d17bf97ff3..123b0e0954e3 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiConfiguration.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiConfiguration.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiException.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiException.h index 56473cbab111..fe7d05b7f728 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiException.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ApiException.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/HttpContent.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/HttpContent.h index d31a36207ed5..713c99dee7a4 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/HttpContent.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/HttpContent.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/IHttpBody.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/IHttpBody.h index 6cdc358efb24..8cc77217da57 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/IHttpBody.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/IHttpBody.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/JsonBody.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/JsonBody.h index f72e6b0e3142..1a1a1172eba8 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/JsonBody.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/JsonBody.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ModelBase.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ModelBase.h index 0a949deda70e..a1ef7b698818 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ModelBase.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/ModelBase.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/MultipartFormData.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/MultipartFormData.h index 359d5724b820..8d6440750986 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/MultipartFormData.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/MultipartFormData.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/Object.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/Object.h index 2442c30215e0..5f5ca5994d85 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/Object.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/Object.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/PetApi.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/PetApi.h index 46ea7c76f6b6..61caed6a6e2a 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/PetApi.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/PetApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/StoreApi.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/StoreApi.h index 10035ddec3e1..1fb17a840d2b 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/StoreApi.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/StoreApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/UserApi.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/UserApi.h index 56e0a3781c8f..7feaf05e2631 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/UserApi.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/api/UserApi.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/ApiResponse.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/ApiResponse.h index 91d184ad6442..f423dd7de51e 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/ApiResponse.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/ApiResponse.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Category.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Category.h index 298c8e91b7f7..063c8cf2d1ce 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Category.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Category.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Order.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Order.h index b3e7522e93cb..4509008abd6f 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Order.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Order.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Pet.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Pet.h index 8e2a561850d1..a28c527cfa2f 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Pet.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Pet.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Tag.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Tag.h index 07277a065361..24df8c4837a7 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Tag.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/Tag.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/User.h b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/User.h index a007708179d2..5e339c55b1cf 100644 --- a/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/User.h +++ b/samples/client/petstore/cpp-restsdk/client/include/CppRestPetstoreClient/model/User.h @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/ApiClient.cpp b/samples/client/petstore/cpp-restsdk/client/src/ApiClient.cpp index 018a525ddcfa..d9644ed6a631 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/ApiClient.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/ApiClient.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/ApiConfiguration.cpp b/samples/client/petstore/cpp-restsdk/client/src/ApiConfiguration.cpp index f846b798d104..48f85526a91f 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/ApiConfiguration.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/ApiConfiguration.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/ApiException.cpp b/samples/client/petstore/cpp-restsdk/client/src/ApiException.cpp index 532f1e4170b8..379e0e845059 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/ApiException.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/ApiException.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/HttpContent.cpp b/samples/client/petstore/cpp-restsdk/client/src/HttpContent.cpp index 09e73ff9a255..fe532f8828b1 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/HttpContent.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/HttpContent.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/JsonBody.cpp b/samples/client/petstore/cpp-restsdk/client/src/JsonBody.cpp index f95a480ac278..a5314ea07308 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/JsonBody.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/JsonBody.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/ModelBase.cpp b/samples/client/petstore/cpp-restsdk/client/src/ModelBase.cpp index fcf0205f2bb6..329714daa25a 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/ModelBase.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/ModelBase.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/MultipartFormData.cpp b/samples/client/petstore/cpp-restsdk/client/src/MultipartFormData.cpp index 08fbc30f9c2d..dc29e58246dc 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/MultipartFormData.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/MultipartFormData.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/Object.cpp b/samples/client/petstore/cpp-restsdk/client/src/Object.cpp index fb7551a948a8..035d13e7a959 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/Object.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/Object.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/api/PetApi.cpp b/samples/client/petstore/cpp-restsdk/client/src/api/PetApi.cpp index 2a285b939202..27ba521a4da9 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/api/PetApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/api/PetApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/api/StoreApi.cpp b/samples/client/petstore/cpp-restsdk/client/src/api/StoreApi.cpp index b2bafc2f2604..06ba088ce1c5 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/api/StoreApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/api/StoreApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/api/UserApi.cpp b/samples/client/petstore/cpp-restsdk/client/src/api/UserApi.cpp index 831ce76515af..f7775414d435 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/api/UserApi.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/api/UserApi.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/ApiResponse.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/ApiResponse.cpp index 9a4a5bb02b5b..75b8b4915e40 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/ApiResponse.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/ApiResponse.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/Category.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/Category.cpp index 76a3418a22f7..4e28e431e1ac 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/Category.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/Category.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/Order.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/Order.cpp index 8378b61e1d8e..3da423f695ae 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/Order.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/Order.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/Pet.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/Pet.cpp index a09ea47067bc..3ce1deae09a4 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/Pet.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/Pet.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/Tag.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/Tag.cpp index 6de95c5dc3e4..3aca24721697 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/Tag.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/Tag.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-restsdk/client/src/model/User.cpp b/samples/client/petstore/cpp-restsdk/client/src/model/User.cpp index e334238b7356..19be018fc6c4 100644 --- a/samples/client/petstore/cpp-restsdk/client/src/model/User.cpp +++ b/samples/client/petstore/cpp-restsdk/client/src/model/User.cpp @@ -4,7 +4,7 @@ * * The version of the OpenAPI document: 1.0.0 * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-tiny/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION b/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION +++ b/samples/client/petstore/cpp-ue4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/crystal/.openapi-generator/VERSION b/samples/client/petstore/crystal/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/crystal/.openapi-generator/VERSION +++ b/samples/client/petstore/crystal/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/crystal/.travis.yml b/samples/client/petstore/crystal/.travis.yml index c285c4e30e95..ace4a218edf5 100644 --- a/samples/client/petstore/crystal/.travis.yml +++ b/samples/client/petstore/crystal/.travis.yml @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # language: crystal diff --git a/samples/client/petstore/crystal/spec/spec_helper.cr b/samples/client/petstore/crystal/spec/spec_helper.cr index 755af40f6404..8d5ecb0a7a28 100644 --- a/samples/client/petstore/crystal/spec/spec_helper.cr +++ b/samples/client/petstore/crystal/spec/spec_helper.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # # load modules diff --git a/samples/client/petstore/crystal/src/petstore.cr b/samples/client/petstore/crystal/src/petstore.cr index caa91d8003e5..2bbebc17d7eb 100644 --- a/samples/client/petstore/crystal/src/petstore.cr +++ b/samples/client/petstore/crystal/src/petstore.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # # Dependencies diff --git a/samples/client/petstore/crystal/src/petstore/api/fake_api.cr b/samples/client/petstore/crystal/src/petstore/api/fake_api.cr index d7e9f086c972..dce59bcfc4a2 100644 --- a/samples/client/petstore/crystal/src/petstore/api/fake_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/fake_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "uri" diff --git a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr index d7a07d9f3b84..249c89dcff47 100644 --- a/samples/client/petstore/crystal/src/petstore/api/pet_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/pet_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "uri" diff --git a/samples/client/petstore/crystal/src/petstore/api/store_api.cr b/samples/client/petstore/crystal/src/petstore/api/store_api.cr index d3442846c9c3..cfff5013383c 100644 --- a/samples/client/petstore/crystal/src/petstore/api/store_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/store_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "uri" diff --git a/samples/client/petstore/crystal/src/petstore/api/user_api.cr b/samples/client/petstore/crystal/src/petstore/api/user_api.cr index 5b026d093e0f..260c010f9f00 100644 --- a/samples/client/petstore/crystal/src/petstore/api/user_api.cr +++ b/samples/client/petstore/crystal/src/petstore/api/user_api.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "uri" diff --git a/samples/client/petstore/crystal/src/petstore/api_client.cr b/samples/client/petstore/crystal/src/petstore/api_client.cr index 8eb88a4aff03..d40fd18cca99 100644 --- a/samples/client/petstore/crystal/src/petstore/api_client.cr +++ b/samples/client/petstore/crystal/src/petstore/api_client.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "json" diff --git a/samples/client/petstore/crystal/src/petstore/api_error.cr b/samples/client/petstore/crystal/src/petstore/api_error.cr index 0c7c05edce90..6d630d21c885 100644 --- a/samples/client/petstore/crystal/src/petstore/api_error.cr +++ b/samples/client/petstore/crystal/src/petstore/api_error.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # module Petstore diff --git a/samples/client/petstore/crystal/src/petstore/configuration.cr b/samples/client/petstore/crystal/src/petstore/configuration.cr index f5180e27ae17..760751d64ba1 100644 --- a/samples/client/petstore/crystal/src/petstore/configuration.cr +++ b/samples/client/petstore/crystal/src/petstore/configuration.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "log" diff --git a/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr b/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr index 5e4d51f40d92..b08bce18fc2e 100644 --- a/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr +++ b/samples/client/petstore/crystal/src/petstore/models/another_property_name_mapping.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/api_response.cr b/samples/client/petstore/crystal/src/petstore/models/api_response.cr index d27fcc91c870..ea11e3af2e38 100644 --- a/samples/client/petstore/crystal/src/petstore/models/api_response.cr +++ b/samples/client/petstore/crystal/src/petstore/models/api_response.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/category.cr b/samples/client/petstore/crystal/src/petstore/models/category.cr index 3b4413c68886..128427143863 100644 --- a/samples/client/petstore/crystal/src/petstore/models/category.cr +++ b/samples/client/petstore/crystal/src/petstore/models/category.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/format_test.cr b/samples/client/petstore/crystal/src/petstore/models/format_test.cr index d6cdd192f76f..6750407e05c3 100644 --- a/samples/client/petstore/crystal/src/petstore/models/format_test.cr +++ b/samples/client/petstore/crystal/src/petstore/models/format_test.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/order.cr b/samples/client/petstore/crystal/src/petstore/models/order.cr index d6336cdfc81c..ffe596629e60 100644 --- a/samples/client/petstore/crystal/src/petstore/models/order.cr +++ b/samples/client/petstore/crystal/src/petstore/models/order.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/pet.cr b/samples/client/petstore/crystal/src/petstore/models/pet.cr index e13b80441bc4..44021a42a9c4 100644 --- a/samples/client/petstore/crystal/src/petstore/models/pet.cr +++ b/samples/client/petstore/crystal/src/petstore/models/pet.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/tag.cr b/samples/client/petstore/crystal/src/petstore/models/tag.cr index 6b4a1270bc8c..cb687ddae4f8 100644 --- a/samples/client/petstore/crystal/src/petstore/models/tag.cr +++ b/samples/client/petstore/crystal/src/petstore/models/tag.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/crystal/src/petstore/models/user.cr b/samples/client/petstore/crystal/src/petstore/models/user.cr index e1c9102df6e9..459260fe8f7d 100644 --- a/samples/client/petstore/crystal/src/petstore/models/user.cr +++ b/samples/client/petstore/crystal/src/petstore/models/user.cr @@ -5,7 +5,7 @@ #The version of the OpenAPI document: 1.0.0 # #Generated by: https://openapi-generator.tech -#OpenAPI Generator version: 7.1.0-SNAPSHOT +#OpenAPI Generator version: 7.3.0-SNAPSHOT # require "big" diff --git a/samples/client/petstore/csharp-functions/.openapi-generator/VERSION b/samples/client/petstore/csharp-functions/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp-functions/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-functions/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/PetApi.cs b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/PetApi.cs index 2e606b0a8c12..330b31105f64 100644 --- a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/PetApi.cs +++ b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/PetApi.cs @@ -21,88 +21,72 @@ public partial class PetApi public async Task> _AddPet([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2pet")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("AddPet"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_DeletePet")] public async Task> _DeletePet([HttpTrigger(AuthorizationLevel.Anonymous, "Delete", Route = "v2pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) { var method = this.GetType().GetMethod("DeletePet"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context, petId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_FindPetsByStatus")] public async Task>> _FindPetsByStatus([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2pet/findByStatus")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("FindPetsByStatus"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_FindPetsByTags")] public async Task>> _FindPetsByTags([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2pet/findByTags")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("FindPetsByTags"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_GetPetById")] public async Task> _GetPetById([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) { var method = this.GetType().GetMethod("GetPetById"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, petId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_UpdatePet")] public async Task> _UpdatePet([HttpTrigger(AuthorizationLevel.Anonymous, "Put", Route = "v2pet")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("UpdatePet"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_UpdatePetWithForm")] public async Task> _UpdatePetWithForm([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2pet/{petId}")]HttpRequest req, ExecutionContext context, long petId) { var method = this.GetType().GetMethod("UpdatePetWithForm"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context, petId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("PetApi_UploadFile")] public async Task> _UploadFile([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2pet/{petId}/uploadImage")]HttpRequest req, ExecutionContext context, long petId) { var method = this.GetType().GetMethod("UploadFile"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, petId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } } } diff --git a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/StoreApi.cs b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/StoreApi.cs index 560582f3374f..47e383d46310 100644 --- a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/StoreApi.cs +++ b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/StoreApi.cs @@ -21,44 +21,36 @@ public partial class StoreApi public async Task> _DeleteOrder([HttpTrigger(AuthorizationLevel.Anonymous, "Delete", Route = "v2store/order/{orderId}")]HttpRequest req, ExecutionContext context, string orderId) { var method = this.GetType().GetMethod("DeleteOrder"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context, orderId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("StoreApi_GetInventory")] public async Task>> _GetInventory([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2store/inventory")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("GetInventory"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("StoreApi_GetOrderById")] public async Task> _GetOrderById([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2store/order/{orderId}")]HttpRequest req, ExecutionContext context, [Range(1, 5)]long orderId) { var method = this.GetType().GetMethod("GetOrderById"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, orderId })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("StoreApi_PlaceOrder")] public async Task> _PlaceOrder([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2store/order")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("PlaceOrder"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } } } diff --git a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/UserApi.cs b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/UserApi.cs index a4219eb43ce8..4f39d98f3f0d 100644 --- a/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/UserApi.cs +++ b/samples/client/petstore/csharp-functions/src/Org.OpenAPITools/Functions/UserApi.cs @@ -21,88 +21,72 @@ public partial class UserApi public async Task> _CreateUser([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2user")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("CreateUser"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_CreateUsersWithArrayInput")] public async Task> _CreateUsersWithArrayInput([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2user/createWithArray")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("CreateUsersWithArrayInput"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_CreateUsersWithListInput")] public async Task> _CreateUsersWithListInput([HttpTrigger(AuthorizationLevel.Anonymous, "Post", Route = "v2user/createWithList")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("CreateUsersWithListInput"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_DeleteUser")] public async Task> _DeleteUser([HttpTrigger(AuthorizationLevel.Anonymous, "Delete", Route = "v2user/{username}")]HttpRequest req, ExecutionContext context, string username) { var method = this.GetType().GetMethod("DeleteUser"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context, username })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_GetUserByName")] public async Task> _GetUserByName([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2user/{username}")]HttpRequest req, ExecutionContext context, string username) { var method = this.GetType().GetMethod("GetUserByName"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context, username })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_LoginUser")] public async Task> _LoginUser([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2user/login")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("LoginUser"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_LogoutUser")] public async Task> _LogoutUser([HttpTrigger(AuthorizationLevel.Anonymous, "Get", Route = "v2user/logout")]HttpRequest req, ExecutionContext context) { var method = this.GetType().GetMethod("LogoutUser"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } [FunctionName("UserApi_UpdateUser")] public async Task> _UpdateUser([HttpTrigger(AuthorizationLevel.Anonymous, "Put", Route = "v2user/{username}")]HttpRequest req, ExecutionContext context, string username) { var method = this.GetType().GetMethod("UpdateUser"); - if(method == null) - { - return new StatusCodeResult((int)HttpStatusCode.NotImplemented); - } - return (await ((Task<>)method.Invoke(this, new object[] { req, context, id })).ConfigureAwait(false)); + return method != null + ? (await ((Task<>)method.Invoke(this, new object[] { req, context, username })).ConfigureAwait(false)) + : new StatusCodeResult((int)HttpStatusCode.NotImplemented); } } } diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/VERSION b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index ebda386b94da..acda1cdef8ff 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Client/ApiClient.cs index d5e70ad3cdc7..6c224944b4c7 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Client/ApiClient.cs @@ -547,7 +547,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; using (RestClient client = new RestClient(clientOptions, diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs index f540de64f58f..4d30dcc37ec3 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Model/Env.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Model /// /// Env /// - [DataContract(Name = "Environment")] + [DataContract(Name = "varEnvironment")] public partial class Env : IEquatable, IValidatableObject { /// diff --git a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 89948381e2ee..addc6411ef6b 100644 --- a/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp-restsharp-name-parameter-mappings/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -24,7 +24,7 @@ - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES index ddeca89d213f..1e54de3472d2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -198,6 +199,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/README.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/README.md index af827f28641e..1670f76c1a89 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/README.md @@ -115,6 +115,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -221,6 +222,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md index c8a21d2e25c6..1debc2b6564d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/PetApi.md index ad44daac69e1..220b1ae30105 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs index 7282ba7821b9..ce37acaec65f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs index 22b4eeeea76e..7a34dc4fe192 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs index cb5abc941b1c..3c0762f55399 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ApiClient.cs @@ -561,7 +561,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..5e20b7408d46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs index 72f70b8f77cf..2db03d53e05a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/ChildCat.cs @@ -52,8 +52,8 @@ public enum PetTypeEnum /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get{ return _PetType;} set @@ -62,7 +62,7 @@ public PetTypeEnum? PetType _flagPetType = true; } } - private PetTypeEnum? _PetType; + private PetTypeEnum _PetType; private bool _flagPetType; /// @@ -76,10 +76,19 @@ public bool ShouldSerializePetType() /// /// Initializes a new instance of the class. /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { + this._PetType = petType; this._Name = name; if (this.Name != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs index 13e9311fab62..de3cbafa9e36 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this._MainShape = mainShape; if (this.MainShape != null) @@ -174,7 +174,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -188,7 +187,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -221,7 +220,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -252,16 +251,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs index b05622141cc2..66a80d29a0ab 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this._IntegerProp = integerProp; if (this.IntegerProp != null) @@ -415,7 +415,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -437,7 +436,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -470,7 +469,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -533,16 +532,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..a3bfdf702066 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1954 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger + { + get{ return _RequiredNullableEnumInteger;} + set + { + _RequiredNullableEnumInteger = value; + _flagRequiredNullableEnumInteger = true; + } + } + private RequiredNullableEnumIntegerEnum _RequiredNullableEnumInteger; + private bool _flagRequiredNullableEnumInteger; + + /// + /// Returns false as RequiredNullableEnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableEnumInteger() + { + return _flagRequiredNullableEnumInteger; + } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger + { + get{ return _RequiredNotnullableEnumInteger;} + set + { + _RequiredNotnullableEnumInteger = value; + _flagRequiredNotnullableEnumInteger = true; + } + } + private RequiredNotnullableEnumIntegerEnum _RequiredNotnullableEnumInteger; + private bool _flagRequiredNotnullableEnumInteger; + + /// + /// Returns false as RequiredNotnullableEnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableEnumInteger() + { + return _flagRequiredNotnullableEnumInteger; + } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger + { + get{ return _NotrequiredNullableEnumInteger;} + set + { + _NotrequiredNullableEnumInteger = value; + _flagNotrequiredNullableEnumInteger = true; + } + } + private NotrequiredNullableEnumIntegerEnum? _NotrequiredNullableEnumInteger; + private bool _flagNotrequiredNullableEnumInteger; + + /// + /// Returns false as NotrequiredNullableEnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableEnumInteger() + { + return _flagNotrequiredNullableEnumInteger; + } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger + { + get{ return _NotrequiredNotnullableEnumInteger;} + set + { + _NotrequiredNotnullableEnumInteger = value; + _flagNotrequiredNotnullableEnumInteger = true; + } + } + private NotrequiredNotnullableEnumIntegerEnum? _NotrequiredNotnullableEnumInteger; + private bool _flagNotrequiredNotnullableEnumInteger; + + /// + /// Returns false as NotrequiredNotnullableEnumInteger should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableEnumInteger() + { + return _flagNotrequiredNotnullableEnumInteger; + } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly + { + get{ return _RequiredNullableEnumIntegerOnly;} + set + { + _RequiredNullableEnumIntegerOnly = value; + _flagRequiredNullableEnumIntegerOnly = true; + } + } + private RequiredNullableEnumIntegerOnlyEnum _RequiredNullableEnumIntegerOnly; + private bool _flagRequiredNullableEnumIntegerOnly; + + /// + /// Returns false as RequiredNullableEnumIntegerOnly should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableEnumIntegerOnly() + { + return _flagRequiredNullableEnumIntegerOnly; + } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly + { + get{ return _RequiredNotnullableEnumIntegerOnly;} + set + { + _RequiredNotnullableEnumIntegerOnly = value; + _flagRequiredNotnullableEnumIntegerOnly = true; + } + } + private RequiredNotnullableEnumIntegerOnlyEnum _RequiredNotnullableEnumIntegerOnly; + private bool _flagRequiredNotnullableEnumIntegerOnly; + + /// + /// Returns false as RequiredNotnullableEnumIntegerOnly should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableEnumIntegerOnly() + { + return _flagRequiredNotnullableEnumIntegerOnly; + } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly + { + get{ return _NotrequiredNullableEnumIntegerOnly;} + set + { + _NotrequiredNullableEnumIntegerOnly = value; + _flagNotrequiredNullableEnumIntegerOnly = true; + } + } + private NotrequiredNullableEnumIntegerOnlyEnum? _NotrequiredNullableEnumIntegerOnly; + private bool _flagNotrequiredNullableEnumIntegerOnly; + + /// + /// Returns false as NotrequiredNullableEnumIntegerOnly should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableEnumIntegerOnly() + { + return _flagNotrequiredNullableEnumIntegerOnly; + } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly + { + get{ return _NotrequiredNotnullableEnumIntegerOnly;} + set + { + _NotrequiredNotnullableEnumIntegerOnly = value; + _flagNotrequiredNotnullableEnumIntegerOnly = true; + } + } + private NotrequiredNotnullableEnumIntegerOnlyEnum? _NotrequiredNotnullableEnumIntegerOnly; + private bool _flagNotrequiredNotnullableEnumIntegerOnly; + + /// + /// Returns false as NotrequiredNotnullableEnumIntegerOnly should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableEnumIntegerOnly() + { + return _flagNotrequiredNotnullableEnumIntegerOnly; + } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString + { + get{ return _RequiredNotnullableEnumString;} + set + { + _RequiredNotnullableEnumString = value; + _flagRequiredNotnullableEnumString = true; + } + } + private RequiredNotnullableEnumStringEnum _RequiredNotnullableEnumString; + private bool _flagRequiredNotnullableEnumString; + + /// + /// Returns false as RequiredNotnullableEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableEnumString() + { + return _flagRequiredNotnullableEnumString; + } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString + { + get{ return _RequiredNullableEnumString;} + set + { + _RequiredNullableEnumString = value; + _flagRequiredNullableEnumString = true; + } + } + private RequiredNullableEnumStringEnum _RequiredNullableEnumString; + private bool _flagRequiredNullableEnumString; + + /// + /// Returns false as RequiredNullableEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableEnumString() + { + return _flagRequiredNullableEnumString; + } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString + { + get{ return _NotrequiredNullableEnumString;} + set + { + _NotrequiredNullableEnumString = value; + _flagNotrequiredNullableEnumString = true; + } + } + private NotrequiredNullableEnumStringEnum? _NotrequiredNullableEnumString; + private bool _flagNotrequiredNullableEnumString; + + /// + /// Returns false as NotrequiredNullableEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableEnumString() + { + return _flagNotrequiredNullableEnumString; + } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString + { + get{ return _NotrequiredNotnullableEnumString;} + set + { + _NotrequiredNotnullableEnumString = value; + _flagNotrequiredNotnullableEnumString = true; + } + } + private NotrequiredNotnullableEnumStringEnum? _NotrequiredNotnullableEnumString; + private bool _flagNotrequiredNotnullableEnumString; + + /// + /// Returns false as NotrequiredNotnullableEnumString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableEnumString() + { + return _flagNotrequiredNotnullableEnumString; + } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue + { + get{ return _RequiredNullableOuterEnumDefaultValue;} + set + { + _RequiredNullableOuterEnumDefaultValue = value; + _flagRequiredNullableOuterEnumDefaultValue = true; + } + } + private OuterEnumDefaultValue _RequiredNullableOuterEnumDefaultValue; + private bool _flagRequiredNullableOuterEnumDefaultValue; + + /// + /// Returns false as RequiredNullableOuterEnumDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableOuterEnumDefaultValue() + { + return _flagRequiredNullableOuterEnumDefaultValue; + } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue + { + get{ return _RequiredNotnullableOuterEnumDefaultValue;} + set + { + _RequiredNotnullableOuterEnumDefaultValue = value; + _flagRequiredNotnullableOuterEnumDefaultValue = true; + } + } + private OuterEnumDefaultValue _RequiredNotnullableOuterEnumDefaultValue; + private bool _flagRequiredNotnullableOuterEnumDefaultValue; + + /// + /// Returns false as RequiredNotnullableOuterEnumDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableOuterEnumDefaultValue() + { + return _flagRequiredNotnullableOuterEnumDefaultValue; + } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue + { + get{ return _NotrequiredNullableOuterEnumDefaultValue;} + set + { + _NotrequiredNullableOuterEnumDefaultValue = value; + _flagNotrequiredNullableOuterEnumDefaultValue = true; + } + } + private OuterEnumDefaultValue? _NotrequiredNullableOuterEnumDefaultValue; + private bool _flagNotrequiredNullableOuterEnumDefaultValue; + + /// + /// Returns false as NotrequiredNullableOuterEnumDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableOuterEnumDefaultValue() + { + return _flagNotrequiredNullableOuterEnumDefaultValue; + } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue + { + get{ return _NotrequiredNotnullableOuterEnumDefaultValue;} + set + { + _NotrequiredNotnullableOuterEnumDefaultValue = value; + _flagNotrequiredNotnullableOuterEnumDefaultValue = true; + } + } + private OuterEnumDefaultValue? _NotrequiredNotnullableOuterEnumDefaultValue; + private bool _flagNotrequiredNotnullableOuterEnumDefaultValue; + + /// + /// Returns false as NotrequiredNotnullableOuterEnumDefaultValue should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableOuterEnumDefaultValue() + { + return _flagNotrequiredNotnullableOuterEnumDefaultValue; + } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableIntegerProp = requiredNullableIntegerProp; + this._RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableBooleanProp = requiredNullableBooleanProp; + this._RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableDateProp = requiredNullableDateProp; + this._RequiredNotNullableDateProp = requiredNotNullableDateProp; + this._RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this._RequiredNullableEnumInteger = requiredNullableEnumInteger; + this._RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this._RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this._RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this._RequiredNotnullableEnumString = requiredNotnullableEnumString; + this._RequiredNullableEnumString = requiredNullableEnumString; + this._RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this._RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableUuid = requiredNullableUuid; + this._RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this._RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this._RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this._NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + if (this.NotRequiredNullableIntegerProp != null) + { + this._flagNotRequiredNullableIntegerProp = true; + } + this._NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + if (this.NotRequiredNotnullableintegerProp != null) + { + this._flagNotRequiredNotnullableintegerProp = true; + } + this._NotrequiredNullableStringProp = notrequiredNullableStringProp; + if (this.NotrequiredNullableStringProp != null) + { + this._flagNotrequiredNullableStringProp = true; + } + this._NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + if (this.NotrequiredNotnullableStringProp != null) + { + this._flagNotrequiredNotnullableStringProp = true; + } + this._NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + if (this.NotrequiredNullableBooleanProp != null) + { + this._flagNotrequiredNullableBooleanProp = true; + } + this._NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + if (this.NotrequiredNotnullableBooleanProp != null) + { + this._flagNotrequiredNotnullableBooleanProp = true; + } + this._NotRequiredNullableDateProp = notRequiredNullableDateProp; + if (this.NotRequiredNullableDateProp != null) + { + this._flagNotRequiredNullableDateProp = true; + } + this._NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + if (this.NotRequiredNotnullableDateProp != null) + { + this._flagNotRequiredNotnullableDateProp = true; + } + this._NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + if (this.NotrequiredNullableDatetimeProp != null) + { + this._flagNotrequiredNullableDatetimeProp = true; + } + this._NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + if (this.NotrequiredNotnullableDatetimeProp != null) + { + this._flagNotrequiredNotnullableDatetimeProp = true; + } + this._NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + if (this.NotrequiredNullableEnumInteger != null) + { + this._flagNotrequiredNullableEnumInteger = true; + } + this._NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + if (this.NotrequiredNotnullableEnumInteger != null) + { + this._flagNotrequiredNotnullableEnumInteger = true; + } + this._NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + if (this.NotrequiredNullableEnumIntegerOnly != null) + { + this._flagNotrequiredNullableEnumIntegerOnly = true; + } + this._NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + if (this.NotrequiredNotnullableEnumIntegerOnly != null) + { + this._flagNotrequiredNotnullableEnumIntegerOnly = true; + } + this._NotrequiredNullableEnumString = notrequiredNullableEnumString; + if (this.NotrequiredNullableEnumString != null) + { + this._flagNotrequiredNullableEnumString = true; + } + this._NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + if (this.NotrequiredNotnullableEnumString != null) + { + this._flagNotrequiredNotnullableEnumString = true; + } + this._NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + if (this.NotrequiredNullableOuterEnumDefaultValue != null) + { + this._flagNotrequiredNullableOuterEnumDefaultValue = true; + } + this._NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + if (this.NotrequiredNotnullableOuterEnumDefaultValue != null) + { + this._flagNotrequiredNotnullableOuterEnumDefaultValue = true; + } + this._NotrequiredNullableUuid = notrequiredNullableUuid; + if (this.NotrequiredNullableUuid != null) + { + this._flagNotrequiredNullableUuid = true; + } + this._NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + if (this.NotrequiredNotnullableUuid != null) + { + this._flagNotrequiredNotnullableUuid = true; + } + this._NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + if (this.NotrequiredNullableArrayOfString != null) + { + this._flagNotrequiredNullableArrayOfString = true; + } + this._NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + if (this.NotrequiredNotnullableArrayOfString != null) + { + this._flagNotrequiredNotnullableArrayOfString = true; + } + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp + { + get{ return _RequiredNullableIntegerProp;} + set + { + _RequiredNullableIntegerProp = value; + _flagRequiredNullableIntegerProp = true; + } + } + private int? _RequiredNullableIntegerProp; + private bool _flagRequiredNullableIntegerProp; + + /// + /// Returns false as RequiredNullableIntegerProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableIntegerProp() + { + return _flagRequiredNullableIntegerProp; + } + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp + { + get{ return _RequiredNotnullableintegerProp;} + set + { + _RequiredNotnullableintegerProp = value; + _flagRequiredNotnullableintegerProp = true; + } + } + private int _RequiredNotnullableintegerProp; + private bool _flagRequiredNotnullableintegerProp; + + /// + /// Returns false as RequiredNotnullableintegerProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableintegerProp() + { + return _flagRequiredNotnullableintegerProp; + } + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp + { + get{ return _NotRequiredNullableIntegerProp;} + set + { + _NotRequiredNullableIntegerProp = value; + _flagNotRequiredNullableIntegerProp = true; + } + } + private int? _NotRequiredNullableIntegerProp; + private bool _flagNotRequiredNullableIntegerProp; + + /// + /// Returns false as NotRequiredNullableIntegerProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotRequiredNullableIntegerProp() + { + return _flagNotRequiredNullableIntegerProp; + } + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp + { + get{ return _NotRequiredNotnullableintegerProp;} + set + { + _NotRequiredNotnullableintegerProp = value; + _flagNotRequiredNotnullableintegerProp = true; + } + } + private int _NotRequiredNotnullableintegerProp; + private bool _flagNotRequiredNotnullableintegerProp; + + /// + /// Returns false as NotRequiredNotnullableintegerProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotRequiredNotnullableintegerProp() + { + return _flagNotRequiredNotnullableintegerProp; + } + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp + { + get{ return _RequiredNullableStringProp;} + set + { + _RequiredNullableStringProp = value; + _flagRequiredNullableStringProp = true; + } + } + private string _RequiredNullableStringProp; + private bool _flagRequiredNullableStringProp; + + /// + /// Returns false as RequiredNullableStringProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableStringProp() + { + return _flagRequiredNullableStringProp; + } + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp + { + get{ return _RequiredNotnullableStringProp;} + set + { + _RequiredNotnullableStringProp = value; + _flagRequiredNotnullableStringProp = true; + } + } + private string _RequiredNotnullableStringProp; + private bool _flagRequiredNotnullableStringProp; + + /// + /// Returns false as RequiredNotnullableStringProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableStringProp() + { + return _flagRequiredNotnullableStringProp; + } + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp + { + get{ return _NotrequiredNullableStringProp;} + set + { + _NotrequiredNullableStringProp = value; + _flagNotrequiredNullableStringProp = true; + } + } + private string _NotrequiredNullableStringProp; + private bool _flagNotrequiredNullableStringProp; + + /// + /// Returns false as NotrequiredNullableStringProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableStringProp() + { + return _flagNotrequiredNullableStringProp; + } + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp + { + get{ return _NotrequiredNotnullableStringProp;} + set + { + _NotrequiredNotnullableStringProp = value; + _flagNotrequiredNotnullableStringProp = true; + } + } + private string _NotrequiredNotnullableStringProp; + private bool _flagNotrequiredNotnullableStringProp; + + /// + /// Returns false as NotrequiredNotnullableStringProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableStringProp() + { + return _flagNotrequiredNotnullableStringProp; + } + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp + { + get{ return _RequiredNullableBooleanProp;} + set + { + _RequiredNullableBooleanProp = value; + _flagRequiredNullableBooleanProp = true; + } + } + private bool? _RequiredNullableBooleanProp; + private bool _flagRequiredNullableBooleanProp; + + /// + /// Returns false as RequiredNullableBooleanProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableBooleanProp() + { + return _flagRequiredNullableBooleanProp; + } + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp + { + get{ return _RequiredNotnullableBooleanProp;} + set + { + _RequiredNotnullableBooleanProp = value; + _flagRequiredNotnullableBooleanProp = true; + } + } + private bool _RequiredNotnullableBooleanProp; + private bool _flagRequiredNotnullableBooleanProp; + + /// + /// Returns false as RequiredNotnullableBooleanProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableBooleanProp() + { + return _flagRequiredNotnullableBooleanProp; + } + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp + { + get{ return _NotrequiredNullableBooleanProp;} + set + { + _NotrequiredNullableBooleanProp = value; + _flagNotrequiredNullableBooleanProp = true; + } + } + private bool? _NotrequiredNullableBooleanProp; + private bool _flagNotrequiredNullableBooleanProp; + + /// + /// Returns false as NotrequiredNullableBooleanProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableBooleanProp() + { + return _flagNotrequiredNullableBooleanProp; + } + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp + { + get{ return _NotrequiredNotnullableBooleanProp;} + set + { + _NotrequiredNotnullableBooleanProp = value; + _flagNotrequiredNotnullableBooleanProp = true; + } + } + private bool _NotrequiredNotnullableBooleanProp; + private bool _flagNotrequiredNotnullableBooleanProp; + + /// + /// Returns false as NotrequiredNotnullableBooleanProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableBooleanProp() + { + return _flagNotrequiredNotnullableBooleanProp; + } + /// + /// Gets or Sets RequiredNullableDateProp + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDateProp + { + get{ return _RequiredNullableDateProp;} + set + { + _RequiredNullableDateProp = value; + _flagRequiredNullableDateProp = true; + } + } + private DateTime? _RequiredNullableDateProp; + private bool _flagRequiredNullableDateProp; + + /// + /// Returns false as RequiredNullableDateProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableDateProp() + { + return _flagRequiredNullableDateProp; + } + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotNullableDateProp + { + get{ return _RequiredNotNullableDateProp;} + set + { + _RequiredNotNullableDateProp = value; + _flagRequiredNotNullableDateProp = true; + } + } + private DateTime _RequiredNotNullableDateProp; + private bool _flagRequiredNotNullableDateProp; + + /// + /// Returns false as RequiredNotNullableDateProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotNullableDateProp() + { + return _flagRequiredNotNullableDateProp; + } + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + public DateTime? NotRequiredNullableDateProp + { + get{ return _NotRequiredNullableDateProp;} + set + { + _NotRequiredNullableDateProp = value; + _flagNotRequiredNullableDateProp = true; + } + } + private DateTime? _NotRequiredNullableDateProp; + private bool _flagNotRequiredNullableDateProp; + + /// + /// Returns false as NotRequiredNullableDateProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotRequiredNullableDateProp() + { + return _flagNotRequiredNullableDateProp; + } + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [JsonConverter(typeof(OpenAPIDateConverter))] + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + public DateTime NotRequiredNotnullableDateProp + { + get{ return _NotRequiredNotnullableDateProp;} + set + { + _NotRequiredNotnullableDateProp = value; + _flagNotRequiredNotnullableDateProp = true; + } + } + private DateTime _NotRequiredNotnullableDateProp; + private bool _flagNotRequiredNotnullableDateProp; + + /// + /// Returns false as NotRequiredNotnullableDateProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotRequiredNotnullableDateProp() + { + return _flagNotRequiredNotnullableDateProp; + } + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp + { + get{ return _RequiredNotnullableDatetimeProp;} + set + { + _RequiredNotnullableDatetimeProp = value; + _flagRequiredNotnullableDatetimeProp = true; + } + } + private DateTime _RequiredNotnullableDatetimeProp; + private bool _flagRequiredNotnullableDatetimeProp; + + /// + /// Returns false as RequiredNotnullableDatetimeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableDatetimeProp() + { + return _flagRequiredNotnullableDatetimeProp; + } + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp + { + get{ return _RequiredNullableDatetimeProp;} + set + { + _RequiredNullableDatetimeProp = value; + _flagRequiredNullableDatetimeProp = true; + } + } + private DateTime? _RequiredNullableDatetimeProp; + private bool _flagRequiredNullableDatetimeProp; + + /// + /// Returns false as RequiredNullableDatetimeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableDatetimeProp() + { + return _flagRequiredNullableDatetimeProp; + } + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp + { + get{ return _NotrequiredNullableDatetimeProp;} + set + { + _NotrequiredNullableDatetimeProp = value; + _flagNotrequiredNullableDatetimeProp = true; + } + } + private DateTime? _NotrequiredNullableDatetimeProp; + private bool _flagNotrequiredNullableDatetimeProp; + + /// + /// Returns false as NotrequiredNullableDatetimeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableDatetimeProp() + { + return _flagNotrequiredNullableDatetimeProp; + } + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp + { + get{ return _NotrequiredNotnullableDatetimeProp;} + set + { + _NotrequiredNotnullableDatetimeProp = value; + _flagNotrequiredNotnullableDatetimeProp = true; + } + } + private DateTime _NotrequiredNotnullableDatetimeProp; + private bool _flagNotrequiredNotnullableDatetimeProp; + + /// + /// Returns false as NotrequiredNotnullableDatetimeProp should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableDatetimeProp() + { + return _flagNotrequiredNotnullableDatetimeProp; + } + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid + { + get{ return _RequiredNullableUuid;} + set + { + _RequiredNullableUuid = value; + _flagRequiredNullableUuid = true; + } + } + private Guid? _RequiredNullableUuid; + private bool _flagRequiredNullableUuid; + + /// + /// Returns false as RequiredNullableUuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableUuid() + { + return _flagRequiredNullableUuid; + } + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid + { + get{ return _RequiredNotnullableUuid;} + set + { + _RequiredNotnullableUuid = value; + _flagRequiredNotnullableUuid = true; + } + } + private Guid _RequiredNotnullableUuid; + private bool _flagRequiredNotnullableUuid; + + /// + /// Returns false as RequiredNotnullableUuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableUuid() + { + return _flagRequiredNotnullableUuid; + } + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid + { + get{ return _NotrequiredNullableUuid;} + set + { + _NotrequiredNullableUuid = value; + _flagNotrequiredNullableUuid = true; + } + } + private Guid? _NotrequiredNullableUuid; + private bool _flagNotrequiredNullableUuid; + + /// + /// Returns false as NotrequiredNullableUuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableUuid() + { + return _flagNotrequiredNullableUuid; + } + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid + { + get{ return _NotrequiredNotnullableUuid;} + set + { + _NotrequiredNotnullableUuid = value; + _flagNotrequiredNotnullableUuid = true; + } + } + private Guid _NotrequiredNotnullableUuid; + private bool _flagNotrequiredNotnullableUuid; + + /// + /// Returns false as NotrequiredNotnullableUuid should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableUuid() + { + return _flagNotrequiredNotnullableUuid; + } + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString + { + get{ return _RequiredNullableArrayOfString;} + set + { + _RequiredNullableArrayOfString = value; + _flagRequiredNullableArrayOfString = true; + } + } + private List _RequiredNullableArrayOfString; + private bool _flagRequiredNullableArrayOfString; + + /// + /// Returns false as RequiredNullableArrayOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNullableArrayOfString() + { + return _flagRequiredNullableArrayOfString; + } + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString + { + get{ return _RequiredNotnullableArrayOfString;} + set + { + _RequiredNotnullableArrayOfString = value; + _flagRequiredNotnullableArrayOfString = true; + } + } + private List _RequiredNotnullableArrayOfString; + private bool _flagRequiredNotnullableArrayOfString; + + /// + /// Returns false as RequiredNotnullableArrayOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeRequiredNotnullableArrayOfString() + { + return _flagRequiredNotnullableArrayOfString; + } + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString + { + get{ return _NotrequiredNullableArrayOfString;} + set + { + _NotrequiredNullableArrayOfString = value; + _flagNotrequiredNullableArrayOfString = true; + } + } + private List _NotrequiredNullableArrayOfString; + private bool _flagNotrequiredNullableArrayOfString; + + /// + /// Returns false as NotrequiredNullableArrayOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNullableArrayOfString() + { + return _flagNotrequiredNullableArrayOfString; + } + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString + { + get{ return _NotrequiredNotnullableArrayOfString;} + set + { + _NotrequiredNotnullableArrayOfString = value; + _flagNotrequiredNotnullableArrayOfString = true; + } + } + private List _NotrequiredNotnullableArrayOfString; + private bool _flagNotrequiredNotnullableArrayOfString; + + /// + /// Returns false as NotrequiredNotnullableArrayOfString should not be serialized given that it's read-only. + /// + /// false (boolean) + public bool ShouldSerializeNotrequiredNotnullableArrayOfString() + { + return _flagNotrequiredNotnullableArrayOfString; + } + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index f15b6dbfb615..599df081178a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this._SomeProperty = someProperty; if (this.SomeProperty != null) @@ -84,7 +84,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -95,7 +94,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -128,7 +127,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -147,16 +146,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs index 7548c4dfbe2c..6efb81987a8e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -96,7 +96,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -150,7 +150,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -162,7 +161,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -195,7 +194,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -215,16 +214,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj index c040fee79765..6064f45f6dd4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-ConditionalSerialization/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj index b7165522a829..9e5f1f956bfa 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/ManualTests.Latest.UseSourceGeneration.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 enable enable @@ -10,10 +10,13 @@ - - - - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs index 4e25bc4a95cd..99a5b49e3ca6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/ManualTests.Latest.UseSourceGeneration/UnitTest1.cs @@ -22,7 +22,7 @@ public SerializationTests() IHostBuilder hostBuild = Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { string apiKeyTokenValue = context.Configuration[""] ?? "Token not found."; - ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); + ApiKeyToken apiKeyToken = new(apiKeyTokenValue, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); string bearerTokenValue = context.Configuration[""] ?? "Token not found."; @@ -64,7 +64,7 @@ public void Apple() Apple apple = new("#000000", "cultivar", "origin"); string appleJson = JsonSerializer.Serialize(apple, _jsonSerializerOptions); Apple? apple2 = JsonSerializer.Deserialize(appleJson, _jsonSerializerOptions); - Assert.IsTrue(apple2 != null && apple.Cultivar.Equals(apple2.Cultivar) && apple.Origin.Equals(apple2.Origin)); + Assert.IsTrue(apple2 != null && apple.Cultivar != null && apple.Cultivar.Equals(apple2.Cultivar) && apple.Origin != null && apple.Origin.Equals(apple2.Origin)); } [TestMethod] @@ -106,12 +106,12 @@ public void GmFruit() gmFruit2 != null && gmFruit2.Apple != null && gmFruit2.Banana != null && + gmFruit2.Apple.Cultivar != null && gmFruit2.Apple.Cultivar.Equals(gmFruit.Apple.Cultivar) && + gmFruit2.Apple.Origin != null && gmFruit2.Apple.Origin.Equals(gmFruit.Apple.Origin) && gmFruit2.Banana.LengthCm.Equals(gmFruit.Banana.LengthCm)); - Apple? apple2 = JsonSerializer.Deserialize(gmFruitJson); - Assert.IsTrue(apple2 != null && apple.Cultivar == apple2.Cultivar && apple.Origin == apple2.Origin); // TODO: assert the the properties from Banana and GmFruit are in additionalProperties } @@ -146,16 +146,16 @@ public void ChildCatTest() ChildCat childCat = new("some name", ChildCat.PetTypeEnum.ChildCat); string childCatJson = JsonSerializer.Serialize(childCat, _jsonSerializerOptions); ChildCat? childCat2 = JsonSerializer.Deserialize(childCatJson, _jsonSerializerOptions); - Assert.IsTrue(childCat2 != null && childCat.PetType.Equals(childCat2.PetType) && childCat.Name.Equals(childCat2.Name)); + Assert.IsTrue(childCat2 != null && childCat.PetType.Equals(childCat2.PetType) && childCat.Name != null && childCat.Name.Equals(childCat2.Name)); } [TestMethod] public void Cat() { - Cat cat = new("cat", false, "black"); // TODO: where is the address property? + Cat cat = new("cat", "black", false); // TODO: where is the address property? string catJson = JsonSerializer.Serialize(cat, _jsonSerializerOptions); Cat? cat2 = JsonSerializer.Deserialize(catJson, _jsonSerializerOptions); - Assert.IsTrue(cat2 != null && cat.Declawed.Equals(cat2.Declawed) && cat.ClassName.Equals(cat2.ClassName) && cat.Color.Equals(cat2.Color)); // TODO: add the address property + Assert.IsTrue(cat2 != null && cat.Declawed.Equals(cat2.Declawed) && cat.ClassName.Equals(cat2.ClassName) && cat.Color != null && cat.Color.Equals(cat2.Color)); // TODO: add the address property } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests.csproj index b1f2fbeee07c..d87af4c4d16b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests.csproj @@ -1,7 +1,7 @@ - net7.0 + net8.0 OpenAPIClient_generichost_manual_tests enable enable @@ -11,10 +11,13 @@ - - - - + + + + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/UnitTest1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/UnitTest1.cs index 1dc4e1bcbd06..430e380c102f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/UnitTest1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-manual-tests/OpenAPIClient-generichost-manual-tests/UnitTest1.cs @@ -18,7 +18,7 @@ public SerializationTests() IHostBuilder hostBuild = Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { string apiKeyTokenValue = context.Configuration[""] ?? "Token not found."; - ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); + ApiKeyToken apiKeyToken = new(apiKeyTokenValue, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); options.AddTokens(apiKeyToken); string bearerTokenValue = context.Configuration[""] ?? "Token not found."; @@ -50,7 +50,7 @@ public void Apple() Apple apple = new("#000000", "cultivar", "origin"); string appleJson = JsonSerializer.Serialize(apple, _jsonSerializerOptions); Apple? apple2 = JsonSerializer.Deserialize(appleJson, _jsonSerializerOptions); - Assert.IsTrue(apple2 != null && apple.Cultivar.Equals(apple2.Cultivar) && apple.Origin.Equals(apple2.Origin)); + Assert.IsTrue(apple2 != null && apple.Cultivar != null && apple.Cultivar.Equals(apple2.Cultivar) && apple.Origin != null && apple.Origin.Equals(apple2.Origin)); } [TestMethod] @@ -92,12 +92,12 @@ public void GmFruit() gmFruit2 != null && gmFruit2.Apple != null && gmFruit2.Banana != null && + gmFruit2.Apple.Cultivar != null && gmFruit2.Apple.Cultivar.Equals(gmFruit.Apple.Cultivar) && + gmFruit2.Apple.Origin != null && gmFruit2.Apple.Origin.Equals(gmFruit.Apple.Origin) && gmFruit2.Banana.LengthCm.Equals(gmFruit.Banana.LengthCm)); - Apple? apple2 = JsonSerializer.Deserialize(gmFruitJson); - Assert.IsTrue(apple2 != null && apple.Cultivar == apple2.Cultivar && apple.Origin == apple2.Origin); // TODO: assert the the properties from Banana and GmFruit are in additionalProperties } @@ -132,16 +132,16 @@ public void ChildCat() ChildCat childCat = new("some name", Org.OpenAPITools.Model.ChildCat.PetTypeEnum.ChildCat); string childCatJson = JsonSerializer.Serialize(childCat, _jsonSerializerOptions); ChildCat? childCat2 = JsonSerializer.Deserialize(childCatJson, _jsonSerializerOptions); - Assert.IsTrue(childCat2 != null && childCat.PetType.Equals(childCat2.PetType) && childCat.Name.Equals(childCat2.Name)); + Assert.IsTrue(childCat2 != null && childCat.PetType.Equals(childCat2.PetType) && childCat.Name != null && childCat.Name.Equals(childCat2.Name)); } [TestMethod] public void Cat() { - Cat cat = new("cat", false, "black"); // TODO: where is the address property? + Cat cat = new("cat", "black", false); // TODO: where is the address property? string catJson = JsonSerializer.Serialize(cat, _jsonSerializerOptions); Cat? cat2 = JsonSerializer.Deserialize(catJson, _jsonSerializerOptions); - Assert.IsTrue(cat2 != null && cat.Declawed.Equals(cat2.Declawed) && cat.ClassName.Equals(cat2.ClassName) && cat.Color.Equals(cat2.Color)); // TODO: add the address property + Assert.IsTrue(cat2 != null && cat.Declawed.Equals(cat2.Declawed) && cat.ClassName.Equals(cat2.ClassName) && cat.Color != null && cat.Color.Equals(cat2.Color)); // TODO: add the address property } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES index 03f61d173609..f26dd3d19b88 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/FILES @@ -79,6 +79,7 @@ docs/models/PolymorphicProperty.md docs/models/Quadrilateral.md docs/models/QuadrilateralInterface.md docs/models/ReadOnlyFirst.md +docs/models/RequiredClass.md docs/models/Return.md docs/models/RolesReportsHash.md docs/models/RolesReportsHashRole.md @@ -121,6 +122,8 @@ src/UseSourceGeneration/Client/BasicToken.cs src/UseSourceGeneration/Client/BearerToken.cs src/UseSourceGeneration/Client/ClientUtils.cs src/UseSourceGeneration/Client/CookieContainer.cs +src/UseSourceGeneration/Client/DateOnlyJsonConverter.cs +src/UseSourceGeneration/Client/DateOnlyNullableJsonConverter.cs src/UseSourceGeneration/Client/DateTimeJsonConverter.cs src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs src/UseSourceGeneration/Client/ExceptionEventArgs.cs @@ -206,6 +209,7 @@ src/UseSourceGeneration/Model/PolymorphicProperty.cs src/UseSourceGeneration/Model/Quadrilateral.cs src/UseSourceGeneration/Model/QuadrilateralInterface.cs src/UseSourceGeneration/Model/ReadOnlyFirst.cs +src/UseSourceGeneration/Model/RequiredClass.cs src/UseSourceGeneration/Model/Return.cs src/UseSourceGeneration/Model/RolesReportsHash.cs src/UseSourceGeneration/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md index 54e9f37c6deb..2549af1e9846 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using UseSourceGeneration.Api; +using UseSourceGeneration.Client; +using UseSourceGeneration.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) @@ -810,7 +896,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateTime date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) +> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateOnly date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -841,7 +927,7 @@ namespace Example var number = 8.14D; // decimal | None var varDouble = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var date = DateTime.Parse("2013-10-20"); // DateTime | None (optional) + var date = DateOnly.Parse("2013-10-20"); // DateOnly | None (optional) var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) var varFloat = 3.4F; // float | None (optional) var integer = 56; // int | None (optional) @@ -893,7 +979,7 @@ catch (ApiException e) | **number** | **decimal** | None | | | **varDouble** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **date** | **DateTime** | None | [optional] | +| **date** | **DateOnly** | None | [optional] | | **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | | **varFloat** | **float** | None | [optional] | | **integer** | **int** | None | [optional] | diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md index 760ad613c360..d4d942039923 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md index b9a2ee71fe64..0374ce69c377 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/apis/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md index 0cd0716de5f8..60851b8b7ba8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/AdditionalPropertiesClass.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Anytype1** | **Object** | | [optional] **EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] **MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] **MapProperty** | **Dictionary<string, string>** | | [optional] @@ -11,7 +12,6 @@ Name | Type | Description | Notes **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] **MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] -**Anytype1** | **Object** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md index 670272cc2025..26fa8551f364 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md index 6a98ffe33b9b..1efce906ea2a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/DateOnlyClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**DateOnlyProperty** | **DateTime** | | [optional] +**DateOnlyProperty** | **DateOnly** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md index a9a319fd6bba..00ab29d641dc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Drawing.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] -**Shapes** | [**List<Shape>**](Shape.md) | | [optional] **NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md index 49836874e08f..b1e5ad4bc428 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**EnumStringRequired** | **string** | | **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] **EnumString** | **string** | | [optional] -**EnumStringRequired** | **string** | | +**OuterEnum** | **OuterEnum** | | [optional] **OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] **OuterEnumInteger** | **OuterEnumInteger** | | [optional] **OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md index 33be89a5331b..3540ad007d2a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/FormatTest.md @@ -4,9 +4,11 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Binary** | **System.IO.Stream** | | [optional] **VarByte** | **byte[]** | | -**Date** | **DateTime** | | +**Date** | **DateOnly** | | +**Number** | **decimal** | | +**Password** | **string** | | +**Binary** | **System.IO.Stream** | | [optional] **DateTime** | **DateTime** | | [optional] **VarDecimal** | **decimal** | | [optional] **VarDouble** | **double** | | [optional] @@ -14,8 +16,6 @@ Name | Type | Description | Notes **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] **Integer** | **int** | | [optional] -**Number** | **decimal** | | -**Password** | **string** | | **PatternWithBackslash** | **string** | None | [optional] **PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] **PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md index 3bc480afe036..9c5ff428a981 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/NullableClass.md @@ -4,16 +4,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool** | | [optional] -**DateProp** | **DateTime** | | [optional] +**DateProp** | **DateOnly** | | [optional] **DatetimeProp** | **DateTime** | | [optional] **IntegerProp** | **int** | | [optional] **NumberProp** | **decimal** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] **StringProp** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md index 3ec4ab0e9adf..e1399706ef96 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Order.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Complete** | **bool** | | [optional] [default to false] **Id** | **long** | | [optional] **PetId** | **long** | | [optional] **Quantity** | **int** | | [optional] **ShipDate** | **DateTime** | | [optional] **Status** | **string** | Order Status | [optional] -**Complete** | **bool** | | [optional] [default to false] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md index 0c5ac31d7992..ea37536068af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Category** | [**Category**](Category.md) | | [optional] -**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Status** | **string** | pet status in the store | [optional] **Tags** | [**List<Tag>**](Tag.md) | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RequiredClass.md new file mode 100644 index 000000000000..27f01c16af1a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/RequiredClass.md @@ -0,0 +1,53 @@ +# UseSourceGeneration.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNotNullableDateProp** | **DateOnly** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNotnullableEnumInteger** | **int** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**RequiredNotnullableEnumString** | **string** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableStringProp** | **string** | | +**RequiredNotnullableUuid** | **Guid** | | +**RequiredNotnullableintegerProp** | **int** | | +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNullableBooleanProp** | **bool** | | +**RequiredNullableDateProp** | **DateOnly** | | +**RequiredNullableDatetimeProp** | **DateTime** | | +**RequiredNullableEnumInteger** | **int** | | +**RequiredNullableEnumIntegerOnly** | **int** | | +**RequiredNullableEnumString** | **string** | | +**RequiredNullableIntegerProp** | **int** | | +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNullableStringProp** | **string** | | +**RequiredNullableUuid** | **Guid** | | +**NotRequiredNotnullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**NotRequiredNullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNullableIntegerProp** | **int** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNullableBooleanProp** | **bool** | | [optional] +**NotrequiredNullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNullableEnumInteger** | **int** | | [optional] +**NotrequiredNullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNullableUuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md index 9c3095927a69..4b5d0d81b718 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] **Email** | **string** | | [optional] **FirstName** | **string** | | [optional] **Id** | **long** | | [optional] **LastName** | **string** | | [optional] **ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] **Password** | **string** | | [optional] **Phone** | **string** | | [optional] **UserStatus** | **int** | User Status | [optional] **Username** | **string** | | [optional] -**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs index db85f0288e93..872947234ba4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/ApiTestsBase.cs @@ -52,26 +52,30 @@ public ApiTestsBase(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureApi((context, services, options) => { - string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); + string apiKeyTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken1 = new(apiKeyTokenValue1, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); - string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - BearerToken bearerToken = new(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); + string apiKeyTokenValue2 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken2 = new(apiKeyTokenValue2, ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); - string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); - string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); - BasicToken basicToken = new(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); + string bearerTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken1 = new(bearerTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); - HttpSigningConfiguration config = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); + string basicTokenUsername1 = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword1 = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken1 = new(basicTokenUsername1, basicTokenPassword1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); - string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - OAuthToken oauthToken = new(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + HttpSigningConfiguration config1 = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + string oauthTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken1 = new(oauthTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs index 6ddf22ddedde..9d9ccbe47528 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/DependencyInjectionTests.cs @@ -24,93 +24,105 @@ namespace UseSourceGeneration.Test.Api /// public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken = new("token", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(oauthToken); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) @@ -124,22 +136,22 @@ public void ConfigureApiWithAClientTest() { var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -152,22 +164,22 @@ public void ConfigureApiWithoutAClientTest() { var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -208,22 +220,22 @@ public void AddApiWithoutAClientTest() { var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs index e36737349b7b..aff5eb0b28de 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Api/FakeApiTests.cs @@ -219,6 +219,16 @@ public async Task TestInlineAdditionalPropertiesAsyncTest() await _instance.TestInlineAdditionalPropertiesAsync(requestBody); } + /// + /// Test TestInlineFreeformAdditionalProperties + /// + [Fact (Skip = "not implemented")] + public async Task TestInlineFreeformAdditionalPropertiesAsyncTest() + { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = default!; + await _instance.TestInlineFreeformAdditionalPropertiesAsync(testInlineFreeformAdditionalPropertiesRequest); + } + /// /// Test TestJsonFormData /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs index e8f1ddf5e8c4..a4118c3dd5df 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/AdditionalPropertiesClassTests.cs @@ -53,6 +53,15 @@ public void AdditionalPropertiesClassInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// /// Test the property 'EmptyMap' /// @@ -115,14 +124,5 @@ public void MapWithUndeclaredPropertiesStringTest() { // TODO unit test for the property 'MapWithUndeclaredPropertiesString' } - - /// - /// Test the property 'Anytype1' - /// - [Fact] - public void Anytype1Test() - { - // TODO unit test for the property 'Anytype1' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs index cb15054ec7dc..4e060e7fe151 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/DrawingTests.cs @@ -62,15 +62,6 @@ public void MainShapeTest() // TODO unit test for the property 'MainShape' } - /// - /// Test the property 'Shapes' - /// - [Fact] - public void ShapesTest() - { - // TODO unit test for the property 'Shapes' - } - /// /// Test the property 'NullableShape' /// @@ -88,5 +79,14 @@ public void ShapeOrNullTest() { // TODO unit test for the property 'ShapeOrNull' } + + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs index 4935820c78d8..7afbb7d97103 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/EnumTestTests.cs @@ -53,6 +53,15 @@ public void EnumTestInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// /// Test the property 'EnumInteger' /// @@ -90,12 +99,12 @@ public void EnumStringTest() } /// - /// Test the property 'EnumStringRequired' + /// Test the property 'OuterEnum' /// [Fact] - public void EnumStringRequiredTest() + public void OuterEnumTest() { - // TODO unit test for the property 'EnumStringRequired' + // TODO unit test for the property 'OuterEnum' } /// @@ -124,14 +133,5 @@ public void OuterEnumIntegerDefaultValueTest() { // TODO unit test for the property 'OuterEnumIntegerDefaultValue' } - - /// - /// Test the property 'OuterEnum' - /// - [Fact] - public void OuterEnumTest() - { - // TODO unit test for the property 'OuterEnum' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs index 3c21562aaf1d..dda0523439cc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/FormatTestTests.cs @@ -53,15 +53,6 @@ public void FormatTestInstanceTest() //Assert.IsType(instance); } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// /// Test the property 'VarByte' /// @@ -80,6 +71,33 @@ public void DateTest() // TODO unit test for the property 'Date' } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// /// Test the property 'DateTime' /// @@ -143,24 +161,6 @@ public void IntegerTest() // TODO unit test for the property 'Integer' } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// /// Test the property 'PatternWithBackslash' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs index 54ae0050d229..506c034789b8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/NullableClassTests.cs @@ -54,30 +54,21 @@ public void NullableClassInstanceTest() } /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - - /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ArrayAndItemsNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ArrayAndItemsNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // TODO unit test for the property 'ArrayAndItemsNullableProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// @@ -143,6 +134,15 @@ public void ObjectAndItemsNullablePropTest() // TODO unit test for the property 'ObjectAndItemsNullableProp' } + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + /// /// Test the property 'ObjectNullableProp' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs index cab96781726c..f2de35feaff7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/OrderTests.cs @@ -53,6 +53,15 @@ public void OrderInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + /// /// Test the property 'Id' /// @@ -97,14 +106,5 @@ public void StatusTest() { // TODO unit test for the property 'Status' } - - /// - /// Test the property 'Complete' - /// - [Fact] - public void CompleteTest() - { - // TODO unit test for the property 'Complete' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs index 750f806d61d1..24f0472ce352 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/PetTests.cs @@ -54,39 +54,39 @@ public void PetInstanceTest() } /// - /// Test the property 'Category' + /// Test the property 'Name' /// [Fact] - public void CategoryTest() + public void NameTest() { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Name' } /// - /// Test the property 'Id' + /// Test the property 'PhotoUrls' /// [Fact] - public void IdTest() + public void PhotoUrlsTest() { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Name' + /// Test the property 'Category' /// [Fact] - public void NameTest() + public void CategoryTest() { - // TODO unit test for the property 'Name' + // TODO unit test for the property 'Category' } /// - /// Test the property 'PhotoUrls' + /// Test the property 'Id' /// [Fact] - public void PhotoUrlsTest() + public void IdTest() { - // TODO unit test for the property 'PhotoUrls' + // TODO unit test for the property 'Id' } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..92025e7499cc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/RequiredClassTests.cs @@ -0,0 +1,452 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using UseSourceGeneration.Model; +using UseSourceGeneration.Client; +using System.Reflection; + +namespace UseSourceGeneration.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs index d2e4d27334d5..eb551ea71c7b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/Model/UserTests.cs @@ -53,6 +53,24 @@ public void UserInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + /// /// Test the property 'Email' /// @@ -98,6 +116,15 @@ public void ObjectWithNoDeclaredPropsTest() // TODO unit test for the property 'ObjectWithNoDeclaredProps' } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// /// Test the property 'Password' /// @@ -133,32 +160,5 @@ public void UsernameTest() { // TODO unit test for the property 'Username' } - - /// - /// Test the property 'AnyTypeProp' - /// - [Fact] - public void AnyTypePropTest() - { - // TODO unit test for the property 'AnyTypeProp' - } - - /// - /// Test the property 'AnyTypePropNullable' - /// - [Fact] - public void AnyTypePropNullableTest() - { - // TODO unit test for the property 'AnyTypePropNullable' - } - - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj index eb88d9d320fc..59d5db6798dd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration.Test/UseSourceGeneration.Test.csproj @@ -3,15 +3,15 @@ UseSourceGeneration.Test UseSourceGeneration.Test - net7.0 + net8.0 false enable - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs index d45f7ccfe0b8..3d39a5b433d6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeApi.cs @@ -171,6 +171,29 @@ public interface IFakeApi : IApi /// <?> Task GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// request body + /// Cancellation Token to cancel the request. + /// <?> + Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + /// /// /// @@ -265,7 +288,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -289,7 +312,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <?> - Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// To test enum parameters @@ -544,6 +567,18 @@ public interface IGetArrayOfEnumsApiResponse : UseSourceGeneration.Client.IApiRe bool IsOk { get; } } + /// + /// The + /// + public interface ITestAdditionalPropertiesReferenceApiResponse : UseSourceGeneration.Client.IApiResponse + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + /// /// The /// @@ -801,6 +836,26 @@ internal void ExecuteOnErrorGetArrayOfEnums(Exception exception) OnErrorGetArrayOfEnums?.Invoke(this, new ExceptionEventArgs(exception)); } + /// + /// The event raised after the server response + /// + public event EventHandler? OnTestAdditionalPropertiesReference; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestAdditionalPropertiesReference; + + internal void ExecuteOnTestAdditionalPropertiesReference(FakeApi.TestAdditionalPropertiesReferenceApiResponse apiResponse) + { + OnTestAdditionalPropertiesReference?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestAdditionalPropertiesReference(Exception exception) + { + OnErrorTestAdditionalPropertiesReference?.Invoke(this, new ExceptionEventArgs(exception)); + } + /// /// The event raised after the server response /// @@ -2375,6 +2430,195 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } + partial void FormatTestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestAdditionalPropertiesReference(Dictionary requestBody) + { + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestAdditionalPropertiesReferenceDefaultImplementation(ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody) + { + bool suppressDefaultLog = false; + AfterTestAdditionalPropertiesReference(ref suppressDefaultLog, apiResponseLocalVar, requestBody); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestAdditionalPropertiesReference(ref bool suppressDefaultLog, ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + bool suppressDefaultLog = false; + OnErrorTestAdditionalPropertiesReference(ref suppressDefaultLog, exception, pathFormat, path, requestBody); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestAdditionalPropertiesReference(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestAdditionalPropertiesReferenceAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestAdditionalPropertiesReference(requestBody); + + FormatTestAdditionalPropertiesReference(requestBody); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/additionalProperties-reference"; + + httpRequestMessageLocalVar.Content = (requestBody as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + + TestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/additionalProperties-reference", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestAdditionalPropertiesReferenceDefaultImplementation(apiResponseLocalVar, requestBody); + + Events.ExecuteOnTestAdditionalPropertiesReference(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(e, "/fake/additionalProperties-reference", uriBuilderLocalVar.Path, requestBody); + Events.ExecuteOnErrorTestAdditionalPropertiesReference(e); + throw; + } + } + + /// + /// The + /// + public partial class TestAdditionalPropertiesReferenceApiResponse : UseSourceGeneration.Client.ApiResponse, ITestAdditionalPropertiesReferenceApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public TestAdditionalPropertiesReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + partial void FormatTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); /// @@ -2999,7 +3243,7 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } - partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); + partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); /// /// Validates the request parameters @@ -3050,7 +3294,7 @@ private void ValidateTestEndpointParameters(byte[] varByte, string patternWithou /// /// /// - private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; AfterTestEndpointParameters(ref suppressDefaultLog, apiResponseLocalVar, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3077,7 +3321,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Logs exceptions that occur while retrieving the server response @@ -3099,7 +3343,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; OnErrorTestEndpointParameters(ref suppressDefaultLog, exception, pathFormat, path, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3128,7 +3372,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// /// /// - partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -3149,7 +3393,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { try { @@ -3181,7 +3425,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { UriBuilder uriBuilderLocalVar = new UriBuilder(); @@ -3245,14 +3489,13 @@ public async Task TestEndpointParametersAsyn formParameterLocalVars.Add(new KeyValuePair("dateTime", ClientUtils.ParameterToString(dateTime.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BasicToken basicTokenLocalVar1 = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(basicTokenLocalVar); + tokenBaseLocalVars.Add(basicTokenLocalVar1); - basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + basicTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -3770,14 +4013,13 @@ public async Task TestGroupParametersAsync(bool httpRequestMessageLocalVar.Headers.Add("boolean_group", ClientUtils.ParameterToString(booleanGroup.Value)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BearerToken bearerTokenLocalVar1 = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(bearerTokenLocalVar); + tokenBaseLocalVars.Add(bearerTokenLocalVar1); - bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + bearerTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs index e314342a1b71..830c72645d3d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/FakeClassnameTags123Api.cs @@ -280,14 +280,12 @@ public async Task TestClassnameAsync(ModelClient mode : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "api_key_query"); + apiKeyTokenLocalVar1.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] contentTypes = new string[] { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs index e5675191d951..49a93f8cebdf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/PetApi.cs @@ -90,7 +90,7 @@ public interface IPetApi : IApi /// Multiple status values can be provided with comma separated strings /// /// Thrown when fails to make API call - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -101,7 +101,7 @@ public interface IPetApi : IApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <?> Task FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -116,6 +116,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -127,6 +128,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <?> + [Obsolete] Task FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -768,23 +770,22 @@ public async Task AddPetAsync(Pet pet, System.Threading.Canc : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -986,14 +987,13 @@ public async Task DeletePetAsync(long petId, Option tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; @@ -1180,23 +1180,22 @@ public async Task FindPetsByStatusAsync(List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1432,23 +1431,22 @@ public async Task FindPetsByTagsAsync(List t uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1665,14 +1663,19 @@ public async Task GetPetByIdAsync(long petId, System.Thr uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokenBaseLocalVars = new List(); + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + ApiKeyToken apiKeyTokenLocalVar2 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar2); - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + apiKeyTokenLocalVar2.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] acceptLocalVars = new string[] { @@ -1912,23 +1915,22 @@ public async Task UpdatePetAsync(Pet pet, System.Threadin : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -2161,14 +2163,13 @@ public async Task UpdatePetWithFormAsync(long pet formParameterLocalVars.Add(new KeyValuePair("status", ClientUtils.ParameterToString(status.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -2387,14 +2388,13 @@ public async Task UploadFileAsync(long petId, Option("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" @@ -2653,14 +2653,13 @@ public async Task UploadFileWithRequired formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs index 8b208175e315..905e8201c5ce 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/StoreApi.cs @@ -621,12 +621,9 @@ public async Task GetInventoryAsync(System.Threading.C uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; List tokenBaseLocalVars = new List(); - - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs index 533178b71472..97d8774bf309 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Api/UserApi.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -279,7 +280,7 @@ public interface IDeleteUserApiResponse : UseSourceGeneration.Client.IApiRespons /// /// The /// - public interface IGetUserByNameApiResponse : UseSourceGeneration.Client.IApiResponse, IOk + public interface IGetUserByNameApiResponse : UseSourceGeneration.Client.IApiResponse, IOk, ICustomHttpStatusCode599 { /// /// Returns true if the response is 200 Ok @@ -298,6 +299,18 @@ public interface IGetUserByNameApiResponse : UseSourceGeneration.Client.IApiResp /// /// bool IsNotFound { get; } + + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + bool IsCustomHttpStatusCode598 { get; } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + bool IsCustomHttpStatusCode599 { get; } } /// @@ -566,6 +579,11 @@ public sealed partial class UserApi : IUserApi /// public TokenProvider OauthTokenProvider { get; } + /// + /// The token cookie container + /// + public UseSourceGeneration.Client.CookieContainer CookieContainer { get; } + /// /// Initializes a new instance of the class. /// @@ -575,7 +593,8 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient TokenProvider bearerTokenProvider, TokenProvider basicTokenProvider, TokenProvider httpSignatureTokenProvider, - TokenProvider oauthTokenProvider) + TokenProvider oauthTokenProvider, + UseSourceGeneration.Client.CookieContainer cookieContainer) { _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; LoggerFactory = loggerFactory; @@ -587,6 +606,7 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient BasicTokenProvider = basicTokenProvider; HttpSignatureTokenProvider = httpSignatureTokenProvider; OauthTokenProvider = oauthTokenProvider; + CookieContainer = cookieContainer; } partial void FormatCreateUser(User user); @@ -1559,6 +1579,50 @@ public bool TryOk([NotNullWhen(true)]out UseSourceGeneration.Model.User? result) /// public bool IsNotFound => 404 == (int)StatusCode; + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + public bool IsCustomHttpStatusCode598 => 598 == (int)StatusCode; + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + public bool IsCustomHttpStatusCode599 => 599 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 599 CustomHttpStatusCode599 + /// + /// + public UseSourceGeneration.Model.User? CustomHttpStatusCode599() + { + // This logic may be modified with the AsModel.mustache template + return IsCustomHttpStatusCode599 + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + public bool TryCustomHttpStatusCode599([NotNullWhen(true)]out UseSourceGeneration.Model.User? result) + { + result = null; + + try + { + result = CustomHttpStatusCode599(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)599); + } + + return result != null; + } + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) { bool suppressDefaultLog = false; @@ -1716,6 +1780,33 @@ public async Task LoginUserAsync(string username, string Events.ExecuteOnLoginUser(apiResponseLocalVar); + if (httpResponseMessageLocalVar.StatusCode == (HttpStatusCode) 200 && httpResponseMessageLocalVar.Headers.TryGetValues("Set-Cookie", out var cookieHeadersLocalVar)) + { + foreach(string cookieHeader in cookieHeadersLocalVar) + { + IList setCookieHeaderValuesLocalVar = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeadersLocalVar.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValueLocalVar in setCookieHeaderValuesLocalVar) + { + Cookie cookieLocalVar = new Cookie(setCookieHeaderValueLocalVar.Name.ToString(), setCookieHeaderValueLocalVar.Value.ToString()) + { + HttpOnly = setCookieHeaderValueLocalVar.HttpOnly + }; + + if (setCookieHeaderValueLocalVar.Expires.HasValue) + cookieLocalVar.Expires = setCookieHeaderValueLocalVar.Expires.Value.UtcDateTime; + + if (setCookieHeaderValueLocalVar.Path.HasValue) + cookieLocalVar.Path = setCookieHeaderValueLocalVar.Path.Value; + + if (setCookieHeaderValueLocalVar.Domain.HasValue) + cookieLocalVar.Domain = setCookieHeaderValueLocalVar.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilderLocalVar.Scheme}://{uriBuilderLocalVar.Host}"), cookieLocalVar); + } + } + } + return apiResponseLocalVar; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs index 532b5eaa2d41..a3df12abace9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiKeyToken.cs @@ -13,14 +13,21 @@ public class ApiKeyToken : TokenBase { private string _raw; + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + /// /// Constructs an ApiKeyToken object. /// /// + /// /// /// - public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { + Header = header; _raw = $"{ prefix }{ value }"; } @@ -28,22 +35,20 @@ public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = /// Places the token in the header. /// /// - /// - public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) { - request.Headers.Add(headerName, _raw); + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); } - + /// /// Places the token in the query. /// /// /// /// - /// - public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) { - parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString()!; + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString()!; } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs index 606074e5342f..ec91996c10cc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ApiResponse`1.cs @@ -150,6 +150,26 @@ public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); } + /// + /// An interface for responses of type + /// + /// + public interface ICustomHttpStatusCode599 : IApiResponse + { + /// + /// Deserializes the response if the response is CustomHttpStatusCode599 + /// + /// + TType CustomHttpStatusCode599(); + + /// + /// Returns true if the response is CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + bool TryCustomHttpStatusCode599([NotNullWhen(true)]out TType? result); + } + /// /// An interface for responses of type /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs index a4f8e6df40d4..a98df2067ee1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/ClientUtils.cs @@ -40,7 +40,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// @@ -52,6 +54,37 @@ static ClientUtils() /// public delegate void EventHandler(object sender, T e) where T : EventArgs; + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + /// + /// The api_key header + /// + Api_key, + /// + /// The api_key_query header + /// + Api_key_query + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.Api_key => "api_key", + ApiKeyHeader.Api_key_query => "api_key_query", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + /// /// Returns true when deserialization succeeds. /// @@ -141,6 +174,8 @@ public static string SanitizeFilename(string filename) return EnumArrays.JustSymbolEnumToJsonValue(enumArraysJustSymbolEnum); if (obj is EnumClass enumClass) return EnumClassValueConverter.ToJsonValue(enumClass); + if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) + return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is EnumTest.EnumIntegerEnum enumTestEnumIntegerEnum) return EnumTest.EnumIntegerEnumToJsonValue(enumTestEnumIntegerEnum).ToString(); if (obj is EnumTest.EnumIntegerOnlyEnum enumTestEnumIntegerOnlyEnum) @@ -149,8 +184,6 @@ public static string SanitizeFilename(string filename) return EnumTest.EnumNumberEnumToJsonValue(enumTestEnumNumberEnum).ToString(); if (obj is EnumTest.EnumStringEnum enumTestEnumStringEnum) return EnumTest.EnumStringEnumToJsonValue(enumTestEnumStringEnum); - if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) - return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is MapTest.InnerEnum mapTestInnerEnum) return MapTest.InnerEnumToJsonValue(mapTestInnerEnum); if (obj is Order.StatusEnum orderStatusEnum) @@ -167,6 +200,30 @@ public static string SanitizeFilename(string filename) return OuterEnumTestValueConverter.ToJsonValue(outerEnumTest); if (obj is Pet.StatusEnum petStatusEnum) return Pet.StatusEnumToJsonValue(petStatusEnum); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerEnum requiredClassRequiredNotnullableEnumIntegerEnum) + return RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum requiredClassRequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumStringEnum requiredClassRequiredNotnullableEnumStringEnum) + return RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClassRequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.RequiredNullableEnumIntegerEnum requiredClassRequiredNullableEnumIntegerEnum) + return RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClassRequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumIntegerOnlyEnum requiredClassRequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumStringEnum requiredClassRequiredNullableEnumStringEnum) + return RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClassRequiredNullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerEnum requiredClassNotrequiredNotnullableEnumIntegerEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumStringEnum requiredClassNotrequiredNotnullableEnumStringEnum) + return RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClassNotrequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerEnum requiredClassNotrequiredNullableEnumIntegerEnum) + return RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum requiredClassNotrequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumStringEnum requiredClassNotrequiredNullableEnumStringEnum) + return RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClassNotrequiredNullableEnumStringEnum); if (obj is Zebra.TypeEnum zebraTypeEnum) return Zebra.TypeEnumToJsonValue(zebraTypeEnum); if (obj is ZeroBasedEnum zeroBasedEnum) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..7bcb8ec38979 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UseSourceGeneration.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..b12272beb828 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace UseSourceGeneration.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs index 4c66712a3e3d..47944cd6613c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace UseSourceGeneration.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs index e341a77d5cdf..03e2a747e155 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace UseSourceGeneration.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs index 7a8056ab4da0..615be479166a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/HostConfiguration.cs @@ -41,6 +41,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new ActivityJsonConverter()); _jsonOptions.Converters.Add(new ActivityOutputElementRepresentationJsonConverter()); _jsonOptions.Converters.Add(new AdditionalPropertiesClassJsonConverter()); @@ -116,6 +118,7 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new QuadrilateralJsonConverter()); _jsonOptions.Converters.Add(new QuadrilateralInterfaceJsonConverter()); _jsonOptions.Converters.Add(new ReadOnlyFirstJsonConverter()); + _jsonOptions.Converters.Add(new RequiredClassJsonConverter()); _jsonOptions.Converters.Add(new ReturnJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashRoleJsonConverter()); @@ -210,6 +213,7 @@ public HostConfiguration(IServiceCollection services) new QuadrilateralSerializationContext(), new QuadrilateralInterfaceSerializationContext(), new ReadOnlyFirstSerializationContext(), + new RequiredClassSerializationContext(), new ReturnSerializationContext(), new RolesReportsHashSerializationContext(), new RolesReportsHashRoleSerializationContext(), diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs index 93f54baec74c..2c6fe01fa6e0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/Option.cs @@ -37,5 +37,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs index 0ad3cc6e6eb0..12c2e022483e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/RateLimitProvider`1.cs @@ -11,9 +11,11 @@ #nullable enable using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace UseSourceGeneration.Client +namespace UseSourceGeneration.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -21,7 +23,7 @@ namespace UseSourceGeneration.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -32,17 +34,41 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite - }; + if (container is TokenContainer apiKeyTokenContainer) + { + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); - AvailableTokens = Channel.CreateBounded(options); + foreach (string header in headers) + { + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + AvailableTokens.Add(header, Channel.CreateBounded(options)); + } + } + else + { + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + } + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs index 1044bc055fa7..ec6b4ff03562 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Client/TokenProvider`1.cs @@ -27,7 +27,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs index 21b946eba142..d86feea2f500 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Activity.cs @@ -37,19 +37,26 @@ public partial class Activity : IValidatableObject /// /// activityOutputs [JsonConstructor] - public Activity(Dictionary> activityOutputs) + public Activity(Option>?> activityOutputs = default) { - ActivityOutputs = activityOutputs; + ActivityOutputsOption = activityOutputs; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ActivityOutputs + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ActivityOutputsOption { get; private set; } + /// /// Gets or Sets ActivityOutputs /// [JsonPropertyName("activity_outputs")] - public Dictionary> ActivityOutputs { get; set; } + public Dictionary>? ActivityOutputs { get { return this. ActivityOutputsOption; } set { this.ActivityOutputsOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary>? activityOutputs = default; + Option>?> activityOutputs = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "activity_outputs": if (utf8JsonReader.TokenType != JsonTokenType.Null) - activityOutputs = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + activityOutputs = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -131,8 +138,8 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (activityOutputs == null) - throw new ArgumentNullException(nameof(activityOutputs), "Property is required for class Activity."); + if (activityOutputs.IsSet && activityOutputs.Value == null) + throw new ArgumentNullException(nameof(activityOutputs), "Property is not nullable for class Activity."); return new Activity(activityOutputs); } @@ -161,8 +168,14 @@ public override void Write(Utf8JsonWriter writer, Activity activity, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("activity_outputs"); - JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + if (activity.ActivityOutputsOption.IsSet && activity.ActivityOutputs == null) + throw new ArgumentNullException(nameof(activity.ActivityOutputs), "Property is required for class Activity."); + + if (activity.ActivityOutputsOption.IsSet) + { + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs index 7d7042c48e51..3e94618e5cfe 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ActivityOutputElementRepresentation.cs @@ -38,26 +38,40 @@ public partial class ActivityOutputElementRepresentation : IValidatableObject /// prop1 /// prop2 [JsonConstructor] - public ActivityOutputElementRepresentation(string prop1, Object prop2) + public ActivityOutputElementRepresentation(Option prop1 = default, Option prop2 = default) { - Prop1 = prop1; - Prop2 = prop2; + Prop1Option = prop1; + Prop2Option = prop2; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Prop1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop1Option { get; private set; } + /// /// Gets or Sets Prop1 /// [JsonPropertyName("prop1")] - public string Prop1 { get; set; } + public string? Prop1 { get { return this. Prop1Option; } set { this.Prop1Option = new(value); } } + + /// + /// Used to track the state of Prop2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop2Option { get; private set; } /// /// Gets or Sets Prop2 /// [JsonPropertyName("prop2")] - public Object Prop2 { get; set; } + public Object? Prop2 { get { return this. Prop2Option; } set { this.Prop2Option = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? prop1 = default; - Object? prop2 = default; + Option prop1 = default; + Option prop2 = default; while (utf8JsonReader.Read()) { @@ -132,11 +146,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 switch (localVarJsonPropertyName) { case "prop1": - prop1 = utf8JsonReader.GetString(); + prop1 = new Option(utf8JsonReader.GetString()!); break; case "prop2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - prop2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + prop2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -144,11 +158,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 } } - if (prop1 == null) - throw new ArgumentNullException(nameof(prop1), "Property is required for class ActivityOutputElementRepresentation."); + if (prop1.IsSet && prop1.Value == null) + throw new ArgumentNullException(nameof(prop1), "Property is not nullable for class ActivityOutputElementRepresentation."); - if (prop2 == null) - throw new ArgumentNullException(nameof(prop2), "Property is required for class ActivityOutputElementRepresentation."); + if (prop2.IsSet && prop2.Value == null) + throw new ArgumentNullException(nameof(prop2), "Property is not nullable for class ActivityOutputElementRepresentation."); return new ActivityOutputElementRepresentation(prop1, prop2); } @@ -177,9 +191,20 @@ public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresent /// public void WriteProperties(ref Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); - writer.WritePropertyName("prop2"); - JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + if (activityOutputElementRepresentation.Prop1Option.IsSet && activityOutputElementRepresentation.Prop1 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop1), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop2Option.IsSet && activityOutputElementRepresentation.Prop2 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop2), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop1Option.IsSet) + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + + if (activityOutputElementRepresentation.Prop2Option.IsSet) + { + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs index 09b3dd1d2611..b0310944a823 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AdditionalPropertiesClass.cs @@ -35,6 +35,7 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// /// Initializes a new instance of the class. /// + /// anytype1 /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty /// mapProperty @@ -42,71 +43,126 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 /// mapWithUndeclaredPropertiesString - /// anytype1 [JsonConstructor] - public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object? anytype1 = default) + public AdditionalPropertiesClass(Option anytype1 = default, Option emptyMap = default, Option>?> mapOfMapProperty = default, Option?> mapProperty = default, Option mapWithUndeclaredPropertiesAnytype1 = default, Option mapWithUndeclaredPropertiesAnytype2 = default, Option?> mapWithUndeclaredPropertiesAnytype3 = default, Option?> mapWithUndeclaredPropertiesString = default) { - EmptyMap = emptyMap; - MapOfMapProperty = mapOfMapProperty; - MapProperty = mapProperty; - MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - Anytype1 = anytype1; + Anytype1Option = anytype1; + EmptyMapOption = emptyMap; + MapOfMapPropertyOption = mapOfMapProperty; + MapPropertyOption = mapProperty; + MapWithUndeclaredPropertiesAnytype1Option = mapWithUndeclaredPropertiesAnytype1; + MapWithUndeclaredPropertiesAnytype2Option = mapWithUndeclaredPropertiesAnytype2; + MapWithUndeclaredPropertiesAnytype3Option = mapWithUndeclaredPropertiesAnytype3; + MapWithUndeclaredPropertiesStringOption = mapWithUndeclaredPropertiesString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Anytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Anytype1Option { get; private set; } + + /// + /// Gets or Sets Anytype1 + /// + [JsonPropertyName("anytype_1")] + public Object? Anytype1 { get { return this. Anytype1Option; } set { this.Anytype1Option = new(value); } } + + /// + /// Used to track the state of EmptyMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmptyMapOption { get; private set; } + /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. [JsonPropertyName("empty_map")] - public Object EmptyMap { get; set; } + public Object? EmptyMap { get { return this. EmptyMapOption; } set { this.EmptyMapOption = new(value); } } + + /// + /// Used to track the state of MapOfMapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> MapOfMapPropertyOption { get; private set; } /// /// Gets or Sets MapOfMapProperty /// [JsonPropertyName("map_of_map_property")] - public Dictionary> MapOfMapProperty { get; set; } + public Dictionary>? MapOfMapProperty { get { return this. MapOfMapPropertyOption; } set { this.MapOfMapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapPropertyOption { get; private set; } /// /// Gets or Sets MapProperty /// [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + public Dictionary? MapProperty { get { return this. MapPropertyOption; } set { this.MapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype1Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 /// [JsonPropertyName("map_with_undeclared_properties_anytype_1")] - public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + public Object? MapWithUndeclaredPropertiesAnytype1 { get { return this. MapWithUndeclaredPropertiesAnytype1Option; } set { this.MapWithUndeclaredPropertiesAnytype1Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype2Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 /// [JsonPropertyName("map_with_undeclared_properties_anytype_2")] - public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + public Object? MapWithUndeclaredPropertiesAnytype2 { get { return this. MapWithUndeclaredPropertiesAnytype2Option; } set { this.MapWithUndeclaredPropertiesAnytype2Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype3 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapWithUndeclaredPropertiesAnytype3Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 /// [JsonPropertyName("map_with_undeclared_properties_anytype_3")] - public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + public Dictionary? MapWithUndeclaredPropertiesAnytype3 { get { return this. MapWithUndeclaredPropertiesAnytype3Option; } set { this.MapWithUndeclaredPropertiesAnytype3Option = new(value); } } /// - /// Gets or Sets MapWithUndeclaredPropertiesString + /// Used to track the state of MapWithUndeclaredPropertiesString /// - [JsonPropertyName("map_with_undeclared_properties_string")] - public Dictionary MapWithUndeclaredPropertiesString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapWithUndeclaredPropertiesStringOption { get; private set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapWithUndeclaredPropertiesString /// - [JsonPropertyName("anytype_1")] - public Object? Anytype1 { get; set; } + [JsonPropertyName("map_with_undeclared_properties_string")] + public Dictionary? MapWithUndeclaredPropertiesString { get { return this. MapWithUndeclaredPropertiesStringOption; } set { this.MapWithUndeclaredPropertiesStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -122,6 +178,7 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); @@ -129,7 +186,6 @@ public override string ToString() sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -168,14 +224,14 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Object? emptyMap = default; - Dictionary>? mapOfMapProperty = default; - Dictionary? mapProperty = default; - Object? mapWithUndeclaredPropertiesAnytype1 = default; - Object? mapWithUndeclaredPropertiesAnytype2 = default; - Dictionary? mapWithUndeclaredPropertiesAnytype3 = default; - Dictionary? mapWithUndeclaredPropertiesString = default; - Object? anytype1 = default; + Option anytype1 = default; + Option emptyMap = default; + Option>?> mapOfMapProperty = default; + Option?> mapProperty = default; + Option mapWithUndeclaredPropertiesAnytype1 = default; + Option mapWithUndeclaredPropertiesAnytype2 = default; + Option?> mapWithUndeclaredPropertiesAnytype3 = default; + Option?> mapWithUndeclaredPropertiesString = default; while (utf8JsonReader.Read()) { @@ -192,37 +248,37 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader switch (localVarJsonPropertyName) { + case "anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "empty_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - emptyMap = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + emptyMap = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_of_map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfMapProperty = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapOfMapProperty = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapProperty = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapProperty = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_1": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_3": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype3 = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anytype_1": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -230,28 +286,28 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader } } - if (emptyMap == null) - throw new ArgumentNullException(nameof(emptyMap), "Property is required for class AdditionalPropertiesClass."); + if (emptyMap.IsSet && emptyMap.Value == null) + throw new ArgumentNullException(nameof(emptyMap), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapOfMapProperty == null) - throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapOfMapProperty.IsSet && mapOfMapProperty.Value == null) + throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapProperty == null) - throw new ArgumentNullException(nameof(mapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapProperty.IsSet && mapProperty.Value == null) + throw new ArgumentNullException(nameof(mapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype1 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype1.IsSet && mapWithUndeclaredPropertiesAnytype1.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype2 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype2.IsSet && mapWithUndeclaredPropertiesAnytype2.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype3 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype3.IsSet && mapWithUndeclaredPropertiesAnytype3.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesString == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesString.IsSet && mapWithUndeclaredPropertiesString.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is not nullable for class AdditionalPropertiesClass."); - return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + return new AdditionalPropertiesClass(anytype1, emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString); } /// @@ -278,22 +334,70 @@ public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass addi /// public void WriteProperties(ref Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("empty_map"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); - writer.WritePropertyName("map_of_map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_string"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); - writer.WritePropertyName("anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + if (additionalPropertiesClass.EmptyMapOption.IsSet && additionalPropertiesClass.EmptyMap == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.EmptyMap), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet && additionalPropertiesClass.MapOfMapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapPropertyOption.IsSet && additionalPropertiesClass.MapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.Anytype1Option.IsSet) + if (additionalPropertiesClass.Anytype1Option.Value != null) + { + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + } + else + writer.WriteNull("anytype_1"); + if (additionalPropertiesClass.EmptyMapOption.IsSet) + { + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet) + { + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapPropertyOption.IsSet) + { + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs index 6beaaf3e97ce..d07daedca7fb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Animal.cs @@ -38,10 +38,10 @@ public partial class Animal : IValidatableObject /// className /// color (default to "red") [JsonConstructor] - public Animal(string className, string color = @"red") + public Animal(string className, Option color = default) { ClassName = className; - Color = color; + ColorOption = color; OnCreated(); } @@ -53,11 +53,18 @@ public Animal(string className, string color = @"red") [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Gets or Sets additional properties @@ -123,8 +130,8 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - string? color = default; + Option className = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -142,10 +149,10 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -153,13 +160,16 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Animal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Animal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Animal."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Animal."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Animal."); - return new Animal(className, color); + return new Animal(className.Value!, color); } /// @@ -186,8 +196,16 @@ public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) { + if (animal.ClassName == null) + throw new ArgumentNullException(nameof(animal.ClassName), "Property is required for class Animal."); + + if (animal.ColorOption.IsSet && animal.Color == null) + throw new ArgumentNullException(nameof(animal.Color), "Property is required for class Animal."); + writer.WriteString("className", animal.ClassName); - writer.WriteString("color", animal.Color); + + if (animal.ColorOption.IsSet) + writer.WriteString("color", animal.Color); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs index 44f22494b301..32f43734f0ad 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ApiResponse.cs @@ -39,33 +39,54 @@ public partial class ApiResponse : IValidatableObject /// message /// type [JsonConstructor] - public ApiResponse(int code, string message, string type) + public ApiResponse(Option code = default, Option message = default, Option type = default) { - Code = code; - Message = message; - Type = type; + CodeOption = code; + MessageOption = message; + TypeOption = type; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Code + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CodeOption { get; private set; } + /// /// Gets or Sets Code /// [JsonPropertyName("code")] - public int Code { get; set; } + public int? Code { get { return this. CodeOption; } set { this.CodeOption = new(value); } } + + /// + /// Used to track the state of Message + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MessageOption { get; private set; } /// /// Gets or Sets Message /// [JsonPropertyName("message")] - public string Message { get; set; } + public string? Message { get { return this. MessageOption; } set { this.MessageOption = new(value); } } + + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public string Type { get; set; } + public string? Type { get { return this. TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets additional properties @@ -122,9 +143,9 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? code = default; - string? message = default; - string? type = default; + Option code = default; + Option message = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -143,13 +164,13 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC { case "code": if (utf8JsonReader.TokenType != JsonTokenType.Null) - code = utf8JsonReader.GetInt32(); + code = new Option(utf8JsonReader.GetInt32()); break; case "message": - message = utf8JsonReader.GetString(); + message = new Option(utf8JsonReader.GetString()!); break; case "type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -157,16 +178,16 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (code == null) - throw new ArgumentNullException(nameof(code), "Property is required for class ApiResponse."); + if (code.IsSet && code.Value == null) + throw new ArgumentNullException(nameof(code), "Property is not nullable for class ApiResponse."); - if (message == null) - throw new ArgumentNullException(nameof(message), "Property is required for class ApiResponse."); + if (message.IsSet && message.Value == null) + throw new ArgumentNullException(nameof(message), "Property is not nullable for class ApiResponse."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class ApiResponse."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ApiResponse."); - return new ApiResponse(code.Value, message, type); + return new ApiResponse(code, message, type); } /// @@ -193,9 +214,20 @@ public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("code", apiResponse.Code); - writer.WriteString("message", apiResponse.Message); - writer.WriteString("type", apiResponse.Type); + if (apiResponse.MessageOption.IsSet && apiResponse.Message == null) + throw new ArgumentNullException(nameof(apiResponse.Message), "Property is required for class ApiResponse."); + + if (apiResponse.TypeOption.IsSet && apiResponse.Type == null) + throw new ArgumentNullException(nameof(apiResponse.Type), "Property is required for class ApiResponse."); + + if (apiResponse.CodeOption.IsSet) + writer.WriteNumber("code", apiResponse.CodeOption.Value!.Value); + + if (apiResponse.MessageOption.IsSet) + writer.WriteString("message", apiResponse.Message); + + if (apiResponse.TypeOption.IsSet) + writer.WriteString("type", apiResponse.Type); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs index f163ab1d0ba5..83db95beaff9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Apple.cs @@ -39,33 +39,54 @@ public partial class Apple : IValidatableObject /// cultivar /// origin [JsonConstructor] - public Apple(string colorCode, string cultivar, string origin) + public Apple(Option colorCode = default, Option cultivar = default, Option origin = default) { - ColorCode = colorCode; - Cultivar = cultivar; - Origin = origin; + ColorCodeOption = colorCode; + CultivarOption = cultivar; + OriginOption = origin; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ColorCode + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorCodeOption { get; private set; } + /// /// Gets or Sets ColorCode /// [JsonPropertyName("color_code")] - public string ColorCode { get; set; } + public string? ColorCode { get { return this. ColorCodeOption; } set { this.ColorCodeOption = new(value); } } + + /// + /// Used to track the state of Cultivar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CultivarOption { get; private set; } /// /// Gets or Sets Cultivar /// [JsonPropertyName("cultivar")] - public string Cultivar { get; set; } + public string? Cultivar { get { return this. CultivarOption; } set { this.CultivarOption = new(value); } } + + /// + /// Used to track the state of Origin + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OriginOption { get; private set; } /// /// Gets or Sets Origin /// [JsonPropertyName("origin")] - public string Origin { get; set; } + public string? Origin { get { return this. OriginOption; } set { this.OriginOption = new(value); } } /// /// Gets or Sets additional properties @@ -96,28 +117,31 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { - if (this.ColorCode != null) { + if (this.ColorCodeOption.Value != null) { // ColorCode (string) pattern Regex regexColorCode = new Regex(@"^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$", RegexOptions.CultureInvariant); - if (!regexColorCode.Match(this.ColorCode).Success) + + if (this.ColorCodeOption.Value != null &&!regexColorCode.Match(this.ColorCodeOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ColorCode, must match a pattern of " + regexColorCode, new [] { "ColorCode" }); } } - if (this.Cultivar != null) { + if (this.CultivarOption.Value != null) { // Cultivar (string) pattern Regex regexCultivar = new Regex(@"^[a-zA-Z\s]*$", RegexOptions.CultureInvariant); - if (!regexCultivar.Match(this.Cultivar).Success) + + if (this.CultivarOption.Value != null &&!regexCultivar.Match(this.CultivarOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); } } - if (this.Origin != null) { + if (this.OriginOption.Value != null) { // Origin (string) pattern Regex regexOrigin = new Regex(@"^[A-Z\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexOrigin.Match(this.Origin).Success) + + if (this.OriginOption.Value != null &&!regexOrigin.Match(this.OriginOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); } @@ -149,9 +173,9 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? colorCode = default; - string? cultivar = default; - string? origin = default; + Option colorCode = default; + Option cultivar = default; + Option origin = default; while (utf8JsonReader.Read()) { @@ -169,13 +193,13 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color_code": - colorCode = utf8JsonReader.GetString(); + colorCode = new Option(utf8JsonReader.GetString()!); break; case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()!); break; case "origin": - origin = utf8JsonReader.GetString(); + origin = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -183,14 +207,14 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (colorCode == null) - throw new ArgumentNullException(nameof(colorCode), "Property is required for class Apple."); + if (colorCode.IsSet && colorCode.Value == null) + throw new ArgumentNullException(nameof(colorCode), "Property is not nullable for class Apple."); - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class Apple."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class Apple."); - if (origin == null) - throw new ArgumentNullException(nameof(origin), "Property is required for class Apple."); + if (origin.IsSet && origin.Value == null) + throw new ArgumentNullException(nameof(origin), "Property is not nullable for class Apple."); return new Apple(colorCode, cultivar, origin); } @@ -219,9 +243,23 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color_code", apple.ColorCode); - writer.WriteString("cultivar", apple.Cultivar); - writer.WriteString("origin", apple.Origin); + if (apple.ColorCodeOption.IsSet && apple.ColorCode == null) + throw new ArgumentNullException(nameof(apple.ColorCode), "Property is required for class Apple."); + + if (apple.CultivarOption.IsSet && apple.Cultivar == null) + throw new ArgumentNullException(nameof(apple.Cultivar), "Property is required for class Apple."); + + if (apple.OriginOption.IsSet && apple.Origin == null) + throw new ArgumentNullException(nameof(apple.Origin), "Property is required for class Apple."); + + if (apple.ColorCodeOption.IsSet) + writer.WriteString("color_code", apple.ColorCode); + + if (apple.CultivarOption.IsSet) + writer.WriteString("cultivar", apple.Cultivar); + + if (apple.OriginOption.IsSet) + writer.WriteString("origin", apple.Origin); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs index 52d9af2f3611..33a606d744a9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/AppleReq.cs @@ -38,10 +38,10 @@ public partial class AppleReq : IValidatableObject /// cultivar /// mealy [JsonConstructor] - public AppleReq(string cultivar, bool mealy) + public AppleReq(string cultivar, Option mealy = default) { Cultivar = cultivar; - Mealy = mealy; + MealyOption = mealy; OnCreated(); } @@ -53,11 +53,18 @@ public AppleReq(string cultivar, bool mealy) [JsonPropertyName("cultivar")] public string Cultivar { get; set; } + /// + /// Used to track the state of Mealy + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MealyOption { get; private set; } + /// /// Gets or Sets Mealy /// [JsonPropertyName("mealy")] - public bool Mealy { get; set; } + public bool? Mealy { get { return this. MealyOption; } set { this.MealyOption = new(value); } } /// /// Returns the string presentation of the object @@ -106,8 +113,8 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? cultivar = default; - bool? mealy = default; + Option cultivar = default; + Option mealy = default; while (utf8JsonReader.Read()) { @@ -125,11 +132,11 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()!); break; case "mealy": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mealy = utf8JsonReader.GetBoolean(); + mealy = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -137,13 +144,16 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class AppleReq."); + if (!cultivar.IsSet) + throw new ArgumentException("Property is required for class AppleReq.", nameof(cultivar)); - if (mealy == null) - throw new ArgumentNullException(nameof(mealy), "Property is required for class AppleReq."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class AppleReq."); - return new AppleReq(cultivar, mealy.Value); + if (mealy.IsSet && mealy.Value == null) + throw new ArgumentNullException(nameof(mealy), "Property is not nullable for class AppleReq."); + + return new AppleReq(cultivar.Value!, mealy); } /// @@ -170,8 +180,13 @@ public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) { + if (appleReq.Cultivar == null) + throw new ArgumentNullException(nameof(appleReq.Cultivar), "Property is required for class AppleReq."); + writer.WriteString("cultivar", appleReq.Cultivar); - writer.WriteBoolean("mealy", appleReq.Mealy); + + if (appleReq.MealyOption.IsSet) + writer.WriteBoolean("mealy", appleReq.MealyOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs index 96905a9ad00d..852333df6a5c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfArrayOfNumberOnly.cs @@ -37,19 +37,26 @@ public partial class ArrayOfArrayOfNumberOnly : IValidatableObject /// /// arrayArrayNumber [JsonConstructor] - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) + public ArrayOfArrayOfNumberOnly(Option>?> arrayArrayNumber = default) { - ArrayArrayNumber = arrayArrayNumber; + ArrayArrayNumberOption = arrayArrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayArrayNumber /// [JsonPropertyName("ArrayArrayNumber")] - public List> ArrayArrayNumber { get; set; } + public List>? ArrayArrayNumber { get { return this. ArrayArrayNumberOption; } set { this.ArrayArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? arrayArrayNumber = default; + Option>?> arrayArrayNumber = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, { case "ArrayArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayNumber = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayNumber = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -131,8 +138,8 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, } } - if (arrayArrayNumber == null) - throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + if (arrayArrayNumber.IsSet && arrayArrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is not nullable for class ArrayOfArrayOfNumberOnly."); return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); } @@ -161,8 +168,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly array /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet && arrayOfArrayOfNumberOnly.ArrayArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfArrayOfNumberOnly.ArrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs index 2fc3f9aa15b3..3366dbdb1a5a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayOfNumberOnly.cs @@ -37,19 +37,26 @@ public partial class ArrayOfNumberOnly : IValidatableObject /// /// arrayNumber [JsonConstructor] - public ArrayOfNumberOnly(List arrayNumber) + public ArrayOfNumberOnly(Option?> arrayNumber = default) { - ArrayNumber = arrayNumber; + ArrayNumberOption = arrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayNumber /// [JsonPropertyName("ArrayNumber")] - public List ArrayNumber { get; set; } + public List? ArrayNumber { get { return this. ArrayNumberOption; } set { this.ArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayNumber = default; + Option?> arrayNumber = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t { case "ArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNumber = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNumber = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -131,8 +138,8 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (arrayNumber == null) - throw new ArgumentNullException(nameof(arrayNumber), "Property is required for class ArrayOfNumberOnly."); + if (arrayNumber.IsSet && arrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayNumber), "Property is not nullable for class ArrayOfNumberOnly."); return new ArrayOfNumberOnly(arrayNumber); } @@ -161,8 +168,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumbe /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + if (arrayOfNumberOnly.ArrayNumberOption.IsSet && arrayOfNumberOnly.ArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfNumberOnly.ArrayNumber), "Property is required for class ArrayOfNumberOnly."); + + if (arrayOfNumberOnly.ArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs index 5923398e2cac..6b6ce17d389d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ArrayTest.cs @@ -39,33 +39,54 @@ public partial class ArrayTest : IValidatableObject /// arrayArrayOfModel /// arrayOfString [JsonConstructor] - public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) + public ArrayTest(Option>?> arrayArrayOfInteger = default, Option>?> arrayArrayOfModel = default, Option?> arrayOfString = default) { - ArrayArrayOfInteger = arrayArrayOfInteger; - ArrayArrayOfModel = arrayArrayOfModel; - ArrayOfString = arrayOfString; + ArrayArrayOfIntegerOption = arrayArrayOfInteger; + ArrayArrayOfModelOption = arrayArrayOfModel; + ArrayOfStringOption = arrayOfString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayOfInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayOfIntegerOption { get; private set; } + /// /// Gets or Sets ArrayArrayOfInteger /// [JsonPropertyName("array_array_of_integer")] - public List> ArrayArrayOfInteger { get; set; } + public List>? ArrayArrayOfInteger { get { return this. ArrayArrayOfIntegerOption; } set { this.ArrayArrayOfIntegerOption = new(value); } } + + /// + /// Used to track the state of ArrayArrayOfModel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayOfModelOption { get; private set; } /// /// Gets or Sets ArrayArrayOfModel /// [JsonPropertyName("array_array_of_model")] - public List> ArrayArrayOfModel { get; set; } + public List>? ArrayArrayOfModel { get { return this. ArrayArrayOfModelOption; } set { this.ArrayArrayOfModelOption = new(value); } } + + /// + /// Used to track the state of ArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayOfStringOption { get; private set; } /// /// Gets or Sets ArrayOfString /// [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } + public List? ArrayOfString { get { return this. ArrayOfStringOption; } set { this.ArrayOfStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -122,9 +143,9 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? arrayArrayOfInteger = default; - List>? arrayArrayOfModel = default; - List? arrayOfString = default; + Option>?> arrayArrayOfInteger = default; + Option>?> arrayArrayOfModel = default; + Option?> arrayOfString = default; while (utf8JsonReader.Read()) { @@ -143,15 +164,15 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "array_array_of_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfInteger = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_array_of_model": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfModel = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfModel = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayOfString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -159,14 +180,14 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (arrayArrayOfInteger == null) - throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is required for class ArrayTest."); + if (arrayArrayOfInteger.IsSet && arrayArrayOfInteger.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is not nullable for class ArrayTest."); - if (arrayArrayOfModel == null) - throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is required for class ArrayTest."); + if (arrayArrayOfModel.IsSet && arrayArrayOfModel.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is not nullable for class ArrayTest."); - if (arrayOfString == null) - throw new ArgumentNullException(nameof(arrayOfString), "Property is required for class ArrayTest."); + if (arrayOfString.IsSet && arrayOfString.Value == null) + throw new ArgumentNullException(nameof(arrayOfString), "Property is not nullable for class ArrayTest."); return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); } @@ -195,12 +216,30 @@ public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_array_of_integer"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); - writer.WritePropertyName("array_array_of_model"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); - writer.WritePropertyName("array_of_string"); - JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + if (arrayTest.ArrayArrayOfIntegerOption.IsSet && arrayTest.ArrayArrayOfInteger == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfInteger), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfModelOption.IsSet && arrayTest.ArrayArrayOfModel == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfModel), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayOfStringOption.IsSet && arrayTest.ArrayOfString == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayOfString), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfIntegerOption.IsSet) + { + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); + } + if (arrayTest.ArrayArrayOfModelOption.IsSet) + { + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); + } + if (arrayTest.ArrayOfStringOption.IsSet) + { + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs index 5528e531ea89..3daafe3df5bf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Banana.cs @@ -37,19 +37,26 @@ public partial class Banana : IValidatableObject /// /// lengthCm [JsonConstructor] - public Banana(decimal lengthCm) + public Banana(Option lengthCm = default) { - LengthCm = lengthCm; + LengthCmOption = lengthCm; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of LengthCm + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LengthCmOption { get; private set; } + /// /// Gets or Sets LengthCm /// [JsonPropertyName("lengthCm")] - public decimal LengthCm { get; set; } + public decimal? LengthCm { get { return this. LengthCmOption; } set { this.LengthCmOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; + Option lengthCm = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -131,10 +138,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class Banana."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class Banana."); - return new Banana(lengthCm.Value); + return new Banana(lengthCm); } /// @@ -161,7 +168,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("lengthCm", banana.LengthCm); + if (banana.LengthCmOption.IsSet) + writer.WriteNumber("lengthCm", banana.LengthCmOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs index 7b5186114050..87bb604c63a6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BananaReq.cs @@ -38,10 +38,10 @@ public partial class BananaReq : IValidatableObject /// lengthCm /// sweet [JsonConstructor] - public BananaReq(decimal lengthCm, bool sweet) + public BananaReq(decimal lengthCm, Option sweet = default) { LengthCm = lengthCm; - Sweet = sweet; + SweetOption = sweet; OnCreated(); } @@ -53,11 +53,18 @@ public BananaReq(decimal lengthCm, bool sweet) [JsonPropertyName("lengthCm")] public decimal LengthCm { get; set; } + /// + /// Used to track the state of Sweet + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SweetOption { get; private set; } + /// /// Gets or Sets Sweet /// [JsonPropertyName("sweet")] - public bool Sweet { get; set; } + public bool? Sweet { get { return this. SweetOption; } set { this.SweetOption = new(value); } } /// /// Returns the string presentation of the object @@ -106,8 +113,8 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; - bool? sweet = default; + Option lengthCm = default; + Option sweet = default; while (utf8JsonReader.Read()) { @@ -126,11 +133,11 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; case "sweet": if (utf8JsonReader.TokenType != JsonTokenType.Null) - sweet = utf8JsonReader.GetBoolean(); + sweet = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -138,13 +145,16 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class BananaReq."); + if (!lengthCm.IsSet) + throw new ArgumentException("Property is required for class BananaReq.", nameof(lengthCm)); - if (sweet == null) - throw new ArgumentNullException(nameof(sweet), "Property is required for class BananaReq."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class BananaReq."); - return new BananaReq(lengthCm.Value, sweet.Value); + if (sweet.IsSet && sweet.Value == null) + throw new ArgumentNullException(nameof(sweet), "Property is not nullable for class BananaReq."); + + return new BananaReq(lengthCm.Value!.Value!, sweet); } /// @@ -172,7 +182,9 @@ public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSeria public void WriteProperties(ref Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) { writer.WriteNumber("lengthCm", bananaReq.LengthCm); - writer.WriteBoolean("sweet", bananaReq.Sweet); + + if (bananaReq.SweetOption.IsSet) + writer.WriteBoolean("sweet", bananaReq.SweetOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs index 4721383c8969..f97e58808850 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/BasquePig.cs @@ -104,7 +104,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -122,7 +122,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,10 +130,13 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class BasquePig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class BasquePig.", nameof(className)); - return new BasquePig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class BasquePig."); + + return new BasquePig(className.Value!); } /// @@ -160,6 +163,9 @@ public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) { + if (basquePig.ClassName == null) + throw new ArgumentNullException(nameof(basquePig.ClassName), "Property is required for class BasquePig."); + writer.WriteString("className", basquePig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs index b0cc3ec0d597..9394170cc39e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Capitalization.cs @@ -42,55 +42,97 @@ public partial class Capitalization : IValidatableObject /// smallCamel /// smallSnake [JsonConstructor] - public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) + public Capitalization(Option aTTNAME = default, Option capitalCamel = default, Option capitalSnake = default, Option sCAETHFlowPoints = default, Option smallCamel = default, Option smallSnake = default) { - ATT_NAME = aTTNAME; - CapitalCamel = capitalCamel; - CapitalSnake = capitalSnake; - SCAETHFlowPoints = sCAETHFlowPoints; - SmallCamel = smallCamel; - SmallSnake = smallSnake; + ATT_NAMEOption = aTTNAME; + CapitalCamelOption = capitalCamel; + CapitalSnakeOption = capitalSnake; + SCAETHFlowPointsOption = sCAETHFlowPoints; + SmallCamelOption = smallCamel; + SmallSnakeOption = smallSnake; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ATT_NAME + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ATT_NAMEOption { get; private set; } + /// /// Name of the pet /// /// Name of the pet [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + public string? ATT_NAME { get { return this. ATT_NAMEOption; } set { this.ATT_NAMEOption = new(value); } } + + /// + /// Used to track the state of CapitalCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalCamelOption { get; private set; } /// /// Gets or Sets CapitalCamel /// [JsonPropertyName("CapitalCamel")] - public string CapitalCamel { get; set; } + public string? CapitalCamel { get { return this. CapitalCamelOption; } set { this.CapitalCamelOption = new(value); } } + + /// + /// Used to track the state of CapitalSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalSnakeOption { get; private set; } /// /// Gets or Sets CapitalSnake /// [JsonPropertyName("Capital_Snake")] - public string CapitalSnake { get; set; } + public string? CapitalSnake { get { return this. CapitalSnakeOption; } set { this.CapitalSnakeOption = new(value); } } + + /// + /// Used to track the state of SCAETHFlowPoints + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SCAETHFlowPointsOption { get; private set; } /// /// Gets or Sets SCAETHFlowPoints /// [JsonPropertyName("SCA_ETH_Flow_Points")] - public string SCAETHFlowPoints { get; set; } + public string? SCAETHFlowPoints { get { return this. SCAETHFlowPointsOption; } set { this.SCAETHFlowPointsOption = new(value); } } + + /// + /// Used to track the state of SmallCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallCamelOption { get; private set; } /// /// Gets or Sets SmallCamel /// [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + public string? SmallCamel { get { return this. SmallCamelOption; } set { this.SmallCamelOption = new(value); } } + + /// + /// Used to track the state of SmallSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallSnakeOption { get; private set; } /// /// Gets or Sets SmallSnake /// [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } + public string? SmallSnake { get { return this. SmallSnakeOption; } set { this.SmallSnakeOption = new(value); } } /// /// Gets or Sets additional properties @@ -150,12 +192,12 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? aTTNAME = default; - string? capitalCamel = default; - string? capitalSnake = default; - string? sCAETHFlowPoints = default; - string? smallCamel = default; - string? smallSnake = default; + Option aTTNAME = default; + Option capitalCamel = default; + Option capitalSnake = default; + Option sCAETHFlowPoints = default; + Option smallCamel = default; + Option smallSnake = default; while (utf8JsonReader.Read()) { @@ -173,22 +215,22 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "ATT_NAME": - aTTNAME = utf8JsonReader.GetString(); + aTTNAME = new Option(utf8JsonReader.GetString()!); break; case "CapitalCamel": - capitalCamel = utf8JsonReader.GetString(); + capitalCamel = new Option(utf8JsonReader.GetString()!); break; case "Capital_Snake": - capitalSnake = utf8JsonReader.GetString(); + capitalSnake = new Option(utf8JsonReader.GetString()!); break; case "SCA_ETH_Flow_Points": - sCAETHFlowPoints = utf8JsonReader.GetString(); + sCAETHFlowPoints = new Option(utf8JsonReader.GetString()!); break; case "smallCamel": - smallCamel = utf8JsonReader.GetString(); + smallCamel = new Option(utf8JsonReader.GetString()!); break; case "small_Snake": - smallSnake = utf8JsonReader.GetString(); + smallSnake = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,23 +238,23 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (aTTNAME == null) - throw new ArgumentNullException(nameof(aTTNAME), "Property is required for class Capitalization."); + if (aTTNAME.IsSet && aTTNAME.Value == null) + throw new ArgumentNullException(nameof(aTTNAME), "Property is not nullable for class Capitalization."); - if (capitalCamel == null) - throw new ArgumentNullException(nameof(capitalCamel), "Property is required for class Capitalization."); + if (capitalCamel.IsSet && capitalCamel.Value == null) + throw new ArgumentNullException(nameof(capitalCamel), "Property is not nullable for class Capitalization."); - if (capitalSnake == null) - throw new ArgumentNullException(nameof(capitalSnake), "Property is required for class Capitalization."); + if (capitalSnake.IsSet && capitalSnake.Value == null) + throw new ArgumentNullException(nameof(capitalSnake), "Property is not nullable for class Capitalization."); - if (sCAETHFlowPoints == null) - throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is required for class Capitalization."); + if (sCAETHFlowPoints.IsSet && sCAETHFlowPoints.Value == null) + throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is not nullable for class Capitalization."); - if (smallCamel == null) - throw new ArgumentNullException(nameof(smallCamel), "Property is required for class Capitalization."); + if (smallCamel.IsSet && smallCamel.Value == null) + throw new ArgumentNullException(nameof(smallCamel), "Property is not nullable for class Capitalization."); - if (smallSnake == null) - throw new ArgumentNullException(nameof(smallSnake), "Property is required for class Capitalization."); + if (smallSnake.IsSet && smallSnake.Value == null) + throw new ArgumentNullException(nameof(smallSnake), "Property is not nullable for class Capitalization."); return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); } @@ -241,12 +283,41 @@ public override void Write(Utf8JsonWriter writer, Capitalization capitalization, /// public void WriteProperties(ref Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("ATT_NAME", capitalization.ATT_NAME); - writer.WriteString("CapitalCamel", capitalization.CapitalCamel); - writer.WriteString("Capital_Snake", capitalization.CapitalSnake); - writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); - writer.WriteString("smallCamel", capitalization.SmallCamel); - writer.WriteString("small_Snake", capitalization.SmallSnake); + if (capitalization.ATT_NAMEOption.IsSet && capitalization.ATT_NAME == null) + throw new ArgumentNullException(nameof(capitalization.ATT_NAME), "Property is required for class Capitalization."); + + if (capitalization.CapitalCamelOption.IsSet && capitalization.CapitalCamel == null) + throw new ArgumentNullException(nameof(capitalization.CapitalCamel), "Property is required for class Capitalization."); + + if (capitalization.CapitalSnakeOption.IsSet && capitalization.CapitalSnake == null) + throw new ArgumentNullException(nameof(capitalization.CapitalSnake), "Property is required for class Capitalization."); + + if (capitalization.SCAETHFlowPointsOption.IsSet && capitalization.SCAETHFlowPoints == null) + throw new ArgumentNullException(nameof(capitalization.SCAETHFlowPoints), "Property is required for class Capitalization."); + + if (capitalization.SmallCamelOption.IsSet && capitalization.SmallCamel == null) + throw new ArgumentNullException(nameof(capitalization.SmallCamel), "Property is required for class Capitalization."); + + if (capitalization.SmallSnakeOption.IsSet && capitalization.SmallSnake == null) + throw new ArgumentNullException(nameof(capitalization.SmallSnake), "Property is required for class Capitalization."); + + if (capitalization.ATT_NAMEOption.IsSet) + writer.WriteString("ATT_NAME", capitalization.ATT_NAME); + + if (capitalization.CapitalCamelOption.IsSet) + writer.WriteString("CapitalCamel", capitalization.CapitalCamel); + + if (capitalization.CapitalSnakeOption.IsSet) + writer.WriteString("Capital_Snake", capitalization.CapitalSnake); + + if (capitalization.SCAETHFlowPointsOption.IsSet) + writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); + + if (capitalization.SmallCamelOption.IsSet) + writer.WriteString("smallCamel", capitalization.SmallCamel); + + if (capitalization.SmallSnakeOption.IsSet) + writer.WriteString("small_Snake", capitalization.SmallSnake); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs index 9535772c5069..dd9ac1cb6a3e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Cat.cs @@ -36,22 +36,29 @@ public partial class Cat : Animal, IValidatableObject /// Initializes a new instance of the class. /// /// className - /// declawed /// color (default to "red") + /// declawed [JsonConstructor] - public Cat(string className, bool declawed, string color = @"red") : base(className, color) + public Cat(string className, Option color = default, Option declawed = default) : base(className, color) { - Declawed = declawed; + DeclawedOption = declawed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Declawed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeclawedOption { get; private set; } + /// /// Gets or Sets Declawed /// [JsonPropertyName("declawed")] - public bool Declawed { get; set; } + public bool? Declawed { get { return this. DeclawedOption; } set { this.DeclawedOption = new(value); } } /// /// Returns the string presentation of the object @@ -90,9 +97,9 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - bool? declawed = default; - string? color = default; + Option className = default; + Option color = default; + Option declawed = default; while (utf8JsonReader.Read()) { @@ -110,14 +117,14 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); + break; + case "color": + color = new Option(utf8JsonReader.GetString()!); break; case "declawed": if (utf8JsonReader.TokenType != JsonTokenType.Null) - declawed = utf8JsonReader.GetBoolean(); - break; - case "color": - color = utf8JsonReader.GetString(); + declawed = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -125,16 +132,19 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Cat."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Cat.", nameof(className)); - if (declawed == null) - throw new ArgumentNullException(nameof(declawed), "Property is required for class Cat."); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Cat."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Cat."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Cat."); - return new Cat(className, declawed.Value, color); + if (declawed.IsSet && declawed.Value == null) + throw new ArgumentNullException(nameof(declawed), "Property is not nullable for class Cat."); + + return new Cat(className.Value!, color, declawed); } /// @@ -161,9 +171,19 @@ public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) { + if (cat.ClassName == null) + throw new ArgumentNullException(nameof(cat.ClassName), "Property is required for class Cat."); + + if (cat.ColorOption.IsSet && cat.Color == null) + throw new ArgumentNullException(nameof(cat.Color), "Property is required for class Cat."); + writer.WriteString("className", cat.ClassName); - writer.WriteBoolean("declawed", cat.Declawed); - writer.WriteString("color", cat.Color); + + if (cat.ColorOption.IsSet) + writer.WriteString("color", cat.Color); + + if (cat.DeclawedOption.IsSet) + writer.WriteBoolean("declawed", cat.DeclawedOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs index 1c1133055c7c..b2ecc92d82a5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Category.cs @@ -38,20 +38,27 @@ public partial class Category : IValidatableObject /// id /// name (default to "default-name") [JsonConstructor] - public Category(long id, string name = @"default-name") + public Category(Option id = default, string name = @"default-name") { - Id = id; + IdOption = id; Name = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// /// Gets or Sets Name @@ -113,8 +120,8 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string? name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -133,10 +140,10 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -144,13 +151,16 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Category."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Category.", nameof(name)); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Category."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Category."); - return new Category(id.Value, name); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Category."); + + return new Category(id, name.Value!); } /// @@ -177,7 +187,12 @@ public override void Write(Utf8JsonWriter writer, Category category, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", category.Id); + if (category.Name == null) + throw new ArgumentNullException(nameof(category.Name), "Property is required for class Category."); + + if (category.IdOption.IsSet) + writer.WriteNumber("id", category.IdOption.Value!.Value); + writer.WriteString("name", category.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs index 7ef472d82939..9d695969cc4d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ChildCat.cs @@ -38,9 +38,9 @@ public partial class ChildCat : ParentPet, IValidatableObject /// name /// petType (default to PetTypeEnum.ChildCat) [JsonConstructor] - public ChildCat(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) + public ChildCat(Option name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) { - Name = name; + NameOption = name; PetType = petType; OnCreated(); } @@ -105,11 +105,18 @@ public static string PetTypeEnumToJsonValue(PetTypeEnum value) [JsonPropertyName("pet_type")] public new PetTypeEnum PetType { get; set; } + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Returns the string presentation of the object @@ -149,8 +156,8 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; - ChildCat.PetTypeEnum? petType = default; + Option name = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -168,13 +175,12 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; case "pet_type": string? petTypeRawValue = utf8JsonReader.GetString(); - petType = petTypeRawValue == null - ? null - : ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue); + if (petTypeRawValue != null) + petType = new Option(ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue)); break; default: break; @@ -182,13 +188,16 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class ChildCat."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ChildCat.", nameof(petType)); - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ChildCat."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class ChildCat."); - return new ChildCat(name, petType.Value); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ChildCat."); + + return new ChildCat(name, petType.Value!.Value!); } /// @@ -215,13 +224,14 @@ public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", childCat.Name); + if (childCat.NameOption.IsSet && childCat.Name == null) + throw new ArgumentNullException(nameof(childCat.Name), "Property is required for class ChildCat."); + + if (childCat.NameOption.IsSet) + writer.WriteString("name", childCat.Name); var petTypeRawValue = ChildCat.PetTypeEnumToJsonValue(childCat.PetType); - if (petTypeRawValue != null) - writer.WriteString("pet_type", petTypeRawValue); - else - writer.WriteNull("pet_type"); + writer.WriteString("pet_type", petTypeRawValue); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs index af9e0c3d1c52..3577fc7c3ecd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ClassModel.cs @@ -37,19 +37,26 @@ public partial class ClassModel : IValidatableObject /// /// varClass [JsonConstructor] - public ClassModel(string varClass) + public ClassModel(Option varClass = default) { - VarClass = varClass; + VarClassOption = varClass; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("_class")] - public string VarClass { get; set; } + public string? VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClass = default; + Option varClass = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { case "_class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class ClassModel."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class ClassModel."); return new ClassModel(varClass); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_class", classModel.VarClass); + if (classModel.VarClassOption.IsSet && classModel.VarClass == null) + throw new ArgumentNullException(nameof(classModel.VarClass), "Property is required for class ClassModel."); + + if (classModel.VarClassOption.IsSet) + writer.WriteString("_class", classModel.VarClass); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs index 3d57316efa89..7aac7ba92408 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ComplexQuadrilateral.cs @@ -113,8 +113,8 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; - string? shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -132,10 +132,10 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -143,13 +143,19 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class ComplexQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ComplexQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(shapeType)); - return new ComplexQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class ComplexQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ComplexQuadrilateral."); + + return new ComplexQuadrilateral(quadrilateralType.Value!, shapeType.Value!); } /// @@ -176,7 +182,14 @@ public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQu /// public void WriteProperties(ref Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (complexQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.QuadrilateralType), "Property is required for class ComplexQuadrilateral."); + + if (complexQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.ShapeType), "Property is required for class ComplexQuadrilateral."); + writer.WriteString("quadrilateralType", complexQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", complexQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs index 8734f04bad7e..312da5259bf0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DanishPig.cs @@ -104,7 +104,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -122,7 +122,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,10 +130,13 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class DanishPig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class DanishPig.", nameof(className)); - return new DanishPig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class DanishPig."); + + return new DanishPig(className.Value!); } /// @@ -160,6 +163,9 @@ public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) { + if (danishPig.ClassName == null) + throw new ArgumentNullException(nameof(danishPig.ClassName), "Property is required for class DanishPig."); + writer.WriteString("className", danishPig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs index bd4801d771cb..d5cd3f8c0745 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DateOnlyClass.cs @@ -37,20 +37,27 @@ public partial class DateOnlyClass : IValidatableObject /// /// dateOnlyProperty [JsonConstructor] - public DateOnlyClass(DateTime dateOnlyProperty) + public DateOnlyClass(Option dateOnlyProperty = default) { - DateOnlyProperty = dateOnlyProperty; + DateOnlyPropertyOption = dateOnlyProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateOnlyProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateOnlyPropertyOption { get; private set; } + /// /// Gets or Sets DateOnlyProperty /// /// Fri Jul 21 00:00:00 UTC 2017 [JsonPropertyName("dateOnlyProperty")] - public DateTime DateOnlyProperty { get; set; } + public DateOnly? DateOnlyProperty { get { return this. DateOnlyPropertyOption; } set { this.DateOnlyPropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -110,7 +117,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateOnlyProperty = default; + Option dateOnlyProperty = default; while (utf8JsonReader.Read()) { @@ -129,7 +136,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT { case "dateOnlyProperty": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateOnlyProperty = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateOnlyProperty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -137,10 +144,10 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (dateOnlyProperty == null) - throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is required for class DateOnlyClass."); + if (dateOnlyProperty.IsSet && dateOnlyProperty.Value == null) + throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is not nullable for class DateOnlyClass."); - return new DateOnlyClass(dateOnlyProperty.Value); + return new DateOnlyClass(dateOnlyProperty); } /// @@ -167,7 +174,8 @@ public override void Write(Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyProperty.ToString(DateOnlyPropertyFormat)); + if (dateOnlyClass.DateOnlyPropertyOption.IsSet) + writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyPropertyOption.Value!.Value.ToString(DateOnlyPropertyFormat)); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs index 1783c3add71c..20f34678e8af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/DeprecatedObject.cs @@ -37,19 +37,26 @@ public partial class DeprecatedObject : IValidatableObject /// /// name [JsonConstructor] - public DeprecatedObject(string name) + public DeprecatedObject(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class DeprecatedObject."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DeprecatedObject."); return new DeprecatedObject(name); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObj /// public void WriteProperties(ref Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", deprecatedObject.Name); + if (deprecatedObject.NameOption.IsSet && deprecatedObject.Name == null) + throw new ArgumentNullException(nameof(deprecatedObject.Name), "Property is required for class DeprecatedObject."); + + if (deprecatedObject.NameOption.IsSet) + writer.WriteString("name", deprecatedObject.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs index 70beb60686ba..3b5881a47119 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Dog.cs @@ -35,23 +35,30 @@ public partial class Dog : Animal, IValidatableObject /// /// Initializes a new instance of the class. /// - /// breed /// className + /// breed /// color (default to "red") [JsonConstructor] - public Dog(string breed, string className, string color = @"red") : base(className, color) + public Dog(string className, Option breed = default, Option color = default) : base(className, color) { - Breed = breed; + BreedOption = breed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Breed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BreedOption { get; private set; } + /// /// Gets or Sets Breed /// [JsonPropertyName("breed")] - public string Breed { get; set; } + public string? Breed { get { return this. BreedOption; } set { this.BreedOption = new(value); } } /// /// Returns the string presentation of the object @@ -90,9 +97,9 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? breed = default; - string? className = default; - string? color = default; + Option className = default; + Option breed = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -109,14 +116,14 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "breed": - breed = utf8JsonReader.GetString(); - break; case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); + break; + case "breed": + breed = new Option(utf8JsonReader.GetString()!); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -124,16 +131,19 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (breed == null) - throw new ArgumentNullException(nameof(breed), "Property is required for class Dog."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Dog.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Dog."); - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Dog."); + if (breed.IsSet && breed.Value == null) + throw new ArgumentNullException(nameof(breed), "Property is not nullable for class Dog."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Dog."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Dog."); - return new Dog(breed, className, color); + return new Dog(className.Value!, breed, color); } /// @@ -160,9 +170,22 @@ public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("breed", dog.Breed); + if (dog.ClassName == null) + throw new ArgumentNullException(nameof(dog.ClassName), "Property is required for class Dog."); + + if (dog.BreedOption.IsSet && dog.Breed == null) + throw new ArgumentNullException(nameof(dog.Breed), "Property is required for class Dog."); + + if (dog.ColorOption.IsSet && dog.Color == null) + throw new ArgumentNullException(nameof(dog.Color), "Property is required for class Dog."); + writer.WriteString("className", dog.ClassName); - writer.WriteString("color", dog.Color); + + if (dog.BreedOption.IsSet) + writer.WriteString("breed", dog.Breed); + + if (dog.ColorOption.IsSet) + writer.WriteString("color", dog.Color); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs index 955f0571e1d9..281477df4ae6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Drawing.cs @@ -30,50 +30,78 @@ namespace UseSourceGeneration.Model /// /// Drawing /// - public partial class Drawing : Dictionary, IValidatableObject + public partial class Drawing : IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape - /// shapes /// nullableShape /// shapeOrNull + /// shapes [JsonConstructor] - public Drawing(Shape mainShape, List shapes, NullableShape? nullableShape = default, ShapeOrNull? shapeOrNull = default) : base() + public Drawing(Option mainShape = default, Option nullableShape = default, Option shapeOrNull = default, Option?> shapes = default) { - MainShape = mainShape; - Shapes = shapes; - NullableShape = nullableShape; - ShapeOrNull = shapeOrNull; + MainShapeOption = mainShape; + NullableShapeOption = nullableShape; + ShapeOrNullOption = shapeOrNull; + ShapesOption = shapes; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MainShape + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MainShapeOption { get; private set; } + /// /// Gets or Sets MainShape /// [JsonPropertyName("mainShape")] - public Shape MainShape { get; set; } + public Shape? MainShape { get { return this. MainShapeOption; } set { this.MainShapeOption = new(value); } } /// - /// Gets or Sets Shapes + /// Used to track the state of NullableShape /// - [JsonPropertyName("shapes")] - public List Shapes { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableShapeOption { get; private set; } /// /// Gets or Sets NullableShape /// [JsonPropertyName("nullableShape")] - public NullableShape? NullableShape { get; set; } + public NullableShape? NullableShape { get { return this. NullableShapeOption; } set { this.NullableShapeOption = new(value); } } + + /// + /// Used to track the state of ShapeOrNull + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShapeOrNullOption { get; private set; } /// /// Gets or Sets ShapeOrNull /// [JsonPropertyName("shapeOrNull")] - public ShapeOrNull? ShapeOrNull { get; set; } + public ShapeOrNull? ShapeOrNull { get { return this. ShapeOrNullOption; } set { this.ShapeOrNullOption = new(value); } } + + /// + /// Used to track the state of Shapes + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ShapesOption { get; private set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List? Shapes { get { return this. ShapesOption; } set { this.ShapesOption = new(value); } } /// /// Gets or Sets additional properties @@ -89,11 +117,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); - sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -105,16 +132,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -142,10 +159,10 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Shape? mainShape = default; - List? shapes = default; - NullableShape? nullableShape = default; - ShapeOrNull? shapeOrNull = default; + Option mainShape = default; + Option nullableShape = default; + Option shapeOrNull = default; + Option?> shapes = default; while (utf8JsonReader.Read()) { @@ -164,19 +181,19 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "mainShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mainShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "shapes": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapes = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mainShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "nullableShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - nullableShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + nullableShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "shapeOrNull": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapeOrNull = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shapeOrNull = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "shapes": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -184,13 +201,13 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (mainShape == null) - throw new ArgumentNullException(nameof(mainShape), "Property is required for class Drawing."); + if (mainShape.IsSet && mainShape.Value == null) + throw new ArgumentNullException(nameof(mainShape), "Property is not nullable for class Drawing."); - if (shapes == null) - throw new ArgumentNullException(nameof(shapes), "Property is required for class Drawing."); + if (shapes.IsSet && shapes.Value == null) + throw new ArgumentNullException(nameof(shapes), "Property is not nullable for class Drawing."); - return new Drawing(mainShape, shapes, nullableShape, shapeOrNull); + return new Drawing(mainShape, nullableShape, shapeOrNull, shapes); } /// @@ -217,14 +234,38 @@ public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("mainShape"); - JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); - writer.WritePropertyName("shapes"); - JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); - writer.WritePropertyName("nullableShape"); - JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); - writer.WritePropertyName("shapeOrNull"); - JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + if (drawing.MainShapeOption.IsSet && drawing.MainShape == null) + throw new ArgumentNullException(nameof(drawing.MainShape), "Property is required for class Drawing."); + + if (drawing.ShapesOption.IsSet && drawing.Shapes == null) + throw new ArgumentNullException(nameof(drawing.Shapes), "Property is required for class Drawing."); + + if (drawing.MainShapeOption.IsSet) + { + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); + } + if (drawing.NullableShapeOption.IsSet) + if (drawing.NullableShapeOption.Value != null) + { + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); + } + else + writer.WriteNull("nullableShape"); + if (drawing.ShapeOrNullOption.IsSet) + if (drawing.ShapeOrNullOption.Value != null) + { + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + } + else + writer.WriteNull("shapeOrNull"); + if (drawing.ShapesOption.IsSet) + { + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs index b450ddadfb17..be92abbdce12 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumArrays.cs @@ -38,10 +38,10 @@ public partial class EnumArrays : IValidatableObject /// arrayEnum /// justSymbol [JsonConstructor] - public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) + public EnumArrays(Option?> arrayEnum = default, Option justSymbol = default) { - ArrayEnum = arrayEnum; - JustSymbol = justSymbol; + ArrayEnumOption = arrayEnum; + JustSymbolOption = justSymbol; OnCreated(); } @@ -102,7 +102,7 @@ public static ArrayEnumEnum ArrayEnumEnumFromString(string value) /// /// /// - public static string ArrayEnumEnumToJsonValue(ArrayEnumEnum value) + public static string ArrayEnumEnumToJsonValue(ArrayEnumEnum? value) { if (value == ArrayEnumEnum.Fish) return "fish"; @@ -168,7 +168,7 @@ public static JustSymbolEnum JustSymbolEnumFromString(string value) /// /// /// - public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) + public static string JustSymbolEnumToJsonValue(JustSymbolEnum? value) { if (value == JustSymbolEnum.GreaterThanOrEqualTo) return ">="; @@ -179,17 +179,31 @@ public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of JustSymbol + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustSymbolOption { get; private set; } + /// /// Gets or Sets JustSymbol /// [JsonPropertyName("just_symbol")] - public JustSymbolEnum JustSymbol { get; set; } + public JustSymbolEnum? JustSymbol { get { return this.JustSymbolOption; } set { this.JustSymbolOption = new(value); } } + + /// + /// Used to track the state of ArrayEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayEnumOption { get; private set; } /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List? ArrayEnum { get { return this. ArrayEnumOption; } set { this.ArrayEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -245,8 +259,8 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayEnum = default; - EnumArrays.JustSymbolEnum? justSymbol = default; + Option?> arrayEnum = default; + Option justSymbol = default; while (utf8JsonReader.Read()) { @@ -265,13 +279,12 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "array_enum": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayEnum = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayEnum = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "just_symbol": string? justSymbolRawValue = utf8JsonReader.GetString(); - justSymbol = justSymbolRawValue == null - ? null - : EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue); + if (justSymbolRawValue != null) + justSymbol = new Option(EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue)); break; default: break; @@ -279,13 +292,13 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (arrayEnum == null) - throw new ArgumentNullException(nameof(arrayEnum), "Property is required for class EnumArrays."); + if (arrayEnum.IsSet && arrayEnum.Value == null) + throw new ArgumentNullException(nameof(arrayEnum), "Property is not nullable for class EnumArrays."); - if (justSymbol == null) - throw new ArgumentNullException(nameof(justSymbol), "Property is required for class EnumArrays."); + if (justSymbol.IsSet && justSymbol.Value == null) + throw new ArgumentNullException(nameof(justSymbol), "Property is not nullable for class EnumArrays."); - return new EnumArrays(arrayEnum, justSymbol.Value); + return new EnumArrays(arrayEnum, justSymbol); } /// @@ -312,14 +325,16 @@ public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_enum"); - JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); - - var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); - if (justSymbolRawValue != null) - writer.WriteString("just_symbol", justSymbolRawValue); - else - writer.WriteNull("just_symbol"); + if (enumArrays.ArrayEnumOption.IsSet && enumArrays.ArrayEnum == null) + throw new ArgumentNullException(nameof(enumArrays.ArrayEnum), "Property is required for class EnumArrays."); + + if (enumArrays.ArrayEnumOption.IsSet) + { + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); + } + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbolOption.Value!.Value); + writer.WriteString("just_symbol", justSymbolRawValue); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs index 88fa5ff18a16..10c51ed3600b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EnumTest.cs @@ -35,32 +35,188 @@ public partial class EnumTest : IValidatableObject /// /// Initializes a new instance of the class. /// + /// enumStringRequired /// enumInteger /// enumIntegerOnly /// enumNumber /// enumString - /// enumStringRequired + /// outerEnum /// outerEnumDefaultValue /// outerEnumInteger /// outerEnumIntegerDefaultValue - /// outerEnum [JsonConstructor] - public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) + public EnumTest(EnumStringRequiredEnum enumStringRequired, Option enumInteger = default, Option enumIntegerOnly = default, Option enumNumber = default, Option enumString = default, Option outerEnum = default, Option outerEnumDefaultValue = default, Option outerEnumInteger = default, Option outerEnumIntegerDefaultValue = default) { - EnumInteger = enumInteger; - EnumIntegerOnly = enumIntegerOnly; - EnumNumber = enumNumber; - EnumString = enumString; EnumStringRequired = enumStringRequired; - OuterEnumDefaultValue = outerEnumDefaultValue; - OuterEnumInteger = outerEnumInteger; - OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - OuterEnum = outerEnum; + EnumIntegerOption = enumInteger; + EnumIntegerOnlyOption = enumIntegerOnly; + EnumNumberOption = enumNumber; + EnumStringOption = enumString; + OuterEnumOption = outerEnum; + OuterEnumDefaultValueOption = outerEnumDefaultValue; + OuterEnumIntegerOption = outerEnumInteger; + OuterEnumIntegerDefaultValueOption = outerEnumIntegerDefaultValue; OnCreated(); } partial void OnCreated(); + /// + /// Defines EnumStringRequired + /// + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) + { + if (value == EnumStringRequiredEnum.UPPER) + return "UPPER"; + + if (value == EnumStringRequiredEnum.Lower) + return "lower"; + + if (value == EnumStringRequiredEnum.Empty) + return ""; + + if (value == EnumStringRequiredEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringRequiredEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringRequiredEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringRequiredEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumStringRequired + /// + [JsonPropertyName("enum_string_required")] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + /// /// Defines EnumInteger /// @@ -120,11 +276,18 @@ public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) return (int) value; } + /// + /// Used to track the state of EnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOption { get; private set; } + /// /// Gets or Sets EnumInteger /// [JsonPropertyName("enum_integer")] - public EnumIntegerEnum EnumInteger { get; set; } + public EnumIntegerEnum? EnumInteger { get { return this.EnumIntegerOption; } set { this.EnumIntegerOption = new(value); } } /// /// Defines EnumIntegerOnly @@ -185,11 +348,18 @@ public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) return (int) value; } + /// + /// Used to track the state of EnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOnlyOption { get; private set; } + /// /// Gets or Sets EnumIntegerOnly /// [JsonPropertyName("enum_integer_only")] - public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } + public EnumIntegerOnlyEnum? EnumIntegerOnly { get { return this.EnumIntegerOnlyOption; } set { this.EnumIntegerOnlyOption = new(value); } } /// /// Defines EnumNumber @@ -246,7 +416,7 @@ public static EnumNumberEnum EnumNumberEnumFromString(string value) /// /// /// - public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) + public static double EnumNumberEnumToJsonValue(EnumNumberEnum? value) { if (value == EnumNumberEnum.NUMBER_1_DOT_1) return 1.1; @@ -257,11 +427,18 @@ public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of EnumNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumNumberOption { get; private set; } + /// /// Gets or Sets EnumNumber /// [JsonPropertyName("enum_number")] - public EnumNumberEnum EnumNumber { get; set; } + public EnumNumberEnum? EnumNumber { get { return this.EnumNumberOption; } set { this.EnumNumberOption = new(value); } } /// /// Defines EnumString @@ -384,7 +561,7 @@ public static EnumStringEnum EnumStringEnumFromString(string value) /// /// /// - public static string EnumStringEnumToJsonValue(EnumStringEnum value) + public static string EnumStringEnumToJsonValue(EnumStringEnum? value) { if (value == EnumStringEnum.UPPER) return "UPPER"; @@ -414,190 +591,69 @@ public static string EnumStringEnumToJsonValue(EnumStringEnum value) } /// - /// Gets or Sets EnumString + /// Used to track the state of EnumString /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumStringOption { get; private set; } /// - /// Defines EnumStringRequired + /// Gets or Sets EnumString /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - Lower = 2, - - /// - /// Enum Empty for value: - /// - Empty = 3, - - /// - /// Enum ValuewithTab for value: Value\twith tab - /// - ValuewithTab = 4, - - /// - /// Enum ValueWithQuote for value: Value with \" quote - /// - ValueWithQuote = 5, - - /// - /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote - /// - ValueWithEscapedQuote = 6, - - /// - /// Enum Duplicatevalue for value: Duplicate\nvalue - /// - Duplicatevalue = 7, - - /// - /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue - /// - Duplicatevalue2 = 8 - } + [JsonPropertyName("enum_string")] + public EnumStringEnum? EnumString { get { return this.EnumStringOption; } set { this.EnumStringOption = new(value); } } /// - /// Returns a + /// Used to track the state of OuterEnum /// - /// - /// - /// - public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumOption { get; private set; } /// - /// Returns a + /// Gets or Sets OuterEnum /// - /// - /// - public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - return null; - } + [JsonPropertyName("outerEnum")] + public OuterEnum? OuterEnum { get { return this.OuterEnumOption; } set { this.OuterEnumOption = new(value); } } /// - /// Converts the to the json value + /// Used to track the state of OuterEnumDefaultValue /// - /// - /// - /// - public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) - { - if (value == EnumStringRequiredEnum.UPPER) - return "UPPER"; - - if (value == EnumStringRequiredEnum.Lower) - return "lower"; - - if (value == EnumStringRequiredEnum.Empty) - return ""; - - if (value == EnumStringRequiredEnum.ValuewithTab) - return "Value\twith tab"; - - if (value == EnumStringRequiredEnum.ValueWithQuote) - return "Value with \" quote"; - - if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) - return "Value with escaped \" quote"; - - if (value == EnumStringRequiredEnum.Duplicatevalue) - return "Duplicate\nvalue"; - - if (value == EnumStringRequiredEnum.Duplicatevalue2) - return "Duplicate\r\nvalue"; - - throw new NotImplementedException($"Value could not be handled: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumDefaultValueOption { get; private set; } /// - /// Gets or Sets EnumStringRequired + /// Gets or Sets OuterEnumDefaultValue /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } + [JsonPropertyName("outerEnumDefaultValue")] + public OuterEnumDefaultValue? OuterEnumDefaultValue { get { return this.OuterEnumDefaultValueOption; } set { this.OuterEnumDefaultValueOption = new(value); } } /// - /// Gets or Sets OuterEnumDefaultValue + /// Used to track the state of OuterEnumInteger /// - [JsonPropertyName("outerEnumDefaultValue")] - public OuterEnumDefaultValue OuterEnumDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerOption { get; private set; } /// /// Gets or Sets OuterEnumInteger /// [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + public OuterEnumInteger? OuterEnumInteger { get { return this.OuterEnumIntegerOption; } set { this.OuterEnumIntegerOption = new(value); } } /// - /// Gets or Sets OuterEnumIntegerDefaultValue + /// Used to track the state of OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnumIntegerDefaultValue")] - public OuterEnumIntegerDefaultValue OuterEnumIntegerDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerDefaultValueOption { get; private set; } /// - /// Gets or Sets OuterEnum + /// Gets or Sets OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnum")] - public OuterEnum? OuterEnum { get; set; } + [JsonPropertyName("outerEnumIntegerDefaultValue")] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get { return this.OuterEnumIntegerDefaultValueOption; } set { this.OuterEnumIntegerDefaultValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -613,15 +669,15 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -660,15 +716,15 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - EnumTest.EnumIntegerEnum? enumInteger = default; - EnumTest.EnumIntegerOnlyEnum? enumIntegerOnly = default; - EnumTest.EnumNumberEnum? enumNumber = default; - EnumTest.EnumStringEnum? enumString = default; - EnumTest.EnumStringRequiredEnum? enumStringRequired = default; - OuterEnumDefaultValue? outerEnumDefaultValue = default; - OuterEnumInteger? outerEnumInteger = default; - OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default; - OuterEnum? outerEnum = default; + Option enumStringRequired = default; + Option enumInteger = default; + Option enumIntegerOnly = default; + Option enumNumber = default; + Option enumString = default; + Option outerEnum = default; + Option outerEnumDefaultValue = default; + Option outerEnumInteger = default; + Option outerEnumIntegerDefaultValue = default; while (utf8JsonReader.Read()) { @@ -685,53 +741,47 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { + case "enum_string_required": + string? enumStringRequiredRawValue = utf8JsonReader.GetString(); + if (enumStringRequiredRawValue != null) + enumStringRequired = new Option(EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue)); + break; case "enum_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumInteger = (EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32(); + enumInteger = new Option((EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32()); break; case "enum_integer_only": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32(); + enumIntegerOnly = new Option((EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); break; case "enum_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumNumber = (EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32(); + enumNumber = new Option((EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32()); break; case "enum_string": string? enumStringRawValue = utf8JsonReader.GetString(); - enumString = enumStringRawValue == null - ? null - : EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue); + if (enumStringRawValue != null) + enumString = new Option(EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue)); break; - case "enum_string_required": - string? enumStringRequiredRawValue = utf8JsonReader.GetString(); - enumStringRequired = enumStringRequiredRawValue == null - ? null - : EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue); + case "outerEnum": + string? outerEnumRawValue = utf8JsonReader.GetString(); + if (outerEnumRawValue != null) + outerEnum = new Option(OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue)); break; case "outerEnumDefaultValue": string? outerEnumDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumDefaultValue = outerEnumDefaultValueRawValue == null - ? null - : OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue); + if (outerEnumDefaultValueRawValue != null) + outerEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue)); break; case "outerEnumInteger": string? outerEnumIntegerRawValue = utf8JsonReader.GetString(); - outerEnumInteger = outerEnumIntegerRawValue == null - ? null - : OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue); + if (outerEnumIntegerRawValue != null) + outerEnumInteger = new Option(OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue)); break; case "outerEnumIntegerDefaultValue": string? outerEnumIntegerDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValueRawValue == null - ? null - : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue); - break; - case "outerEnum": - string? outerEnumRawValue = utf8JsonReader.GetString(); - outerEnum = outerEnumRawValue == null - ? null - : OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue); + if (outerEnumIntegerDefaultValueRawValue != null) + outerEnumIntegerDefaultValue = new Option(OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue)); break; default: break; @@ -739,31 +789,34 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (enumInteger == null) - throw new ArgumentNullException(nameof(enumInteger), "Property is required for class EnumTest."); + if (!enumStringRequired.IsSet) + throw new ArgumentException("Property is required for class EnumTest.", nameof(enumStringRequired)); + + if (enumStringRequired.IsSet && enumStringRequired.Value == null) + throw new ArgumentNullException(nameof(enumStringRequired), "Property is not nullable for class EnumTest."); - if (enumIntegerOnly == null) - throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is required for class EnumTest."); + if (enumInteger.IsSet && enumInteger.Value == null) + throw new ArgumentNullException(nameof(enumInteger), "Property is not nullable for class EnumTest."); - if (enumNumber == null) - throw new ArgumentNullException(nameof(enumNumber), "Property is required for class EnumTest."); + if (enumIntegerOnly.IsSet && enumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is not nullable for class EnumTest."); - if (enumString == null) - throw new ArgumentNullException(nameof(enumString), "Property is required for class EnumTest."); + if (enumNumber.IsSet && enumNumber.Value == null) + throw new ArgumentNullException(nameof(enumNumber), "Property is not nullable for class EnumTest."); - if (enumStringRequired == null) - throw new ArgumentNullException(nameof(enumStringRequired), "Property is required for class EnumTest."); + if (enumString.IsSet && enumString.Value == null) + throw new ArgumentNullException(nameof(enumString), "Property is not nullable for class EnumTest."); - if (outerEnumDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is required for class EnumTest."); + if (outerEnumDefaultValue.IsSet && outerEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is not nullable for class EnumTest."); - if (outerEnumInteger == null) - throw new ArgumentNullException(nameof(outerEnumInteger), "Property is required for class EnumTest."); + if (outerEnumInteger.IsSet && outerEnumInteger.Value == null) + throw new ArgumentNullException(nameof(outerEnumInteger), "Property is not nullable for class EnumTest."); - if (outerEnumIntegerDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is required for class EnumTest."); + if (outerEnumIntegerDefaultValue.IsSet && outerEnumIntegerDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is not nullable for class EnumTest."); - return new EnumTest(enumInteger.Value, enumIntegerOnly.Value, enumNumber.Value, enumString.Value, enumStringRequired.Value, outerEnumDefaultValue.Value, outerEnumInteger.Value, outerEnumIntegerDefaultValue.Value, outerEnum); + return new EnumTest(enumStringRequired.Value!.Value!, enumInteger, enumIntegerOnly, enumNumber, enumString, outerEnum, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue); } /// @@ -790,43 +843,41 @@ public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumInteger)); - writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnly)); - writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumber)); - - var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumString); - if (enumStringRawValue != null) - writer.WriteString("enum_string", enumStringRawValue); - else - writer.WriteNull("enum_string"); - var enumStringRequiredRawValue = EnumTest.EnumStringRequiredEnumToJsonValue(enumTest.EnumStringRequired); - if (enumStringRequiredRawValue != null) - writer.WriteString("enum_string_required", enumStringRequiredRawValue); - else - writer.WriteNull("enum_string_required"); + writer.WriteString("enum_string_required", enumStringRequiredRawValue); + if (enumTest.EnumIntegerOption.IsSet) + writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumIntegerOption.Value!.Value)); - var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (enumTest.EnumIntegerOnlyOption.IsSet) + writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnlyOption.Value!.Value)); - if (outerEnumDefaultValueRawValue != null) - writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); - else - writer.WriteNull("outerEnumDefaultValue"); - - var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger); - writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); - var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); - writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + if (enumTest.EnumNumberOption.IsSet) + writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumberOption.Value!.Value)); - if (enumTest.OuterEnum == null) - writer.WriteNull("outerEnum"); - else - { - var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnum.Value); - if (outerEnumRawValue != null) + var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumStringOption.Value!.Value); + writer.WriteString("enum_string", enumStringRawValue); + if (enumTest.OuterEnumOption.IsSet) + if (enumTest.OuterEnumOption!.Value != null) + { + var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnumOption.Value!.Value); writer.WriteString("outerEnum", outerEnumRawValue); + } else writer.WriteNull("outerEnum"); + if (enumTest.OuterEnumDefaultValueOption.IsSet) + { + var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue!.Value); + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + } + if (enumTest.OuterEnumIntegerOption.IsSet) + { + var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger!.Value); + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + } + if (enumTest.OuterEnumIntegerDefaultValueOption.IsSet) + { + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue!.Value); + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs index b161cd58e182..ef87cf48dfdd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/EquilateralTriangle.cs @@ -113,8 +113,8 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -132,10 +132,10 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -143,13 +143,19 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class EquilateralTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class EquilateralTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(triangleType)); - return new EquilateralTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class EquilateralTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class EquilateralTriangle."); + + return new EquilateralTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -176,7 +182,14 @@ public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilatera /// public void WriteProperties(ref Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (equilateralTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.ShapeType), "Property is required for class EquilateralTriangle."); + + if (equilateralTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.TriangleType), "Property is required for class EquilateralTriangle."); + writer.WriteString("shapeType", equilateralTriangle.ShapeType); + writer.WriteString("triangleType", equilateralTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs index bc7f05fae9e0..7a650ad95b0f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/File.cs @@ -37,20 +37,27 @@ public partial class File : IValidatableObject /// /// Test capitalization [JsonConstructor] - public File(string sourceURI) + public File(Option sourceURI = default) { - SourceURI = sourceURI; + SourceURIOption = sourceURI; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SourceURI + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SourceURIOption { get; private set; } + /// /// Test capitalization /// /// Test capitalization [JsonPropertyName("sourceURI")] - public string SourceURI { get; set; } + public string? SourceURI { get { return this. SourceURIOption; } set { this.SourceURIOption = new(value); } } /// /// Gets or Sets additional properties @@ -105,7 +112,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? sourceURI = default; + Option sourceURI = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "sourceURI": - sourceURI = utf8JsonReader.GetString(); + sourceURI = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -131,8 +138,8 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (sourceURI == null) - throw new ArgumentNullException(nameof(sourceURI), "Property is required for class File."); + if (sourceURI.IsSet && sourceURI.Value == null) + throw new ArgumentNullException(nameof(sourceURI), "Property is not nullable for class File."); return new File(sourceURI); } @@ -161,7 +168,11 @@ public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("sourceURI", file.SourceURI); + if (file.SourceURIOption.IsSet && file.SourceURI == null) + throw new ArgumentNullException(nameof(file.SourceURI), "Property is required for class File."); + + if (file.SourceURIOption.IsSet) + writer.WriteString("sourceURI", file.SourceURI); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs index 68d2af61dbc1..b061b4c87faa 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FileSchemaTestClass.cs @@ -38,26 +38,40 @@ public partial class FileSchemaTestClass : IValidatableObject /// file /// files [JsonConstructor] - public FileSchemaTestClass(File file, List files) + public FileSchemaTestClass(Option file = default, Option?> files = default) { - File = file; - Files = files; + FileOption = file; + FilesOption = files; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of File + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FileOption { get; private set; } + /// /// Gets or Sets File /// [JsonPropertyName("file")] - public File File { get; set; } + public File? File { get { return this. FileOption; } set { this.FileOption = new(value); } } + + /// + /// Used to track the state of Files + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> FilesOption { get; private set; } /// /// Gets or Sets Files /// [JsonPropertyName("files")] - public List Files { get; set; } + public List? Files { get { return this. FilesOption; } set { this.FilesOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - File? file = default; - List? files = default; + Option file = default; + Option?> files = default; while (utf8JsonReader.Read()) { @@ -133,11 +147,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "file": if (utf8JsonReader.TokenType != JsonTokenType.Null) - file = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + file = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "files": if (utf8JsonReader.TokenType != JsonTokenType.Null) - files = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + files = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -145,11 +159,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (file == null) - throw new ArgumentNullException(nameof(file), "Property is required for class FileSchemaTestClass."); + if (file.IsSet && file.Value == null) + throw new ArgumentNullException(nameof(file), "Property is not nullable for class FileSchemaTestClass."); - if (files == null) - throw new ArgumentNullException(nameof(files), "Property is required for class FileSchemaTestClass."); + if (files.IsSet && files.Value == null) + throw new ArgumentNullException(nameof(files), "Property is not nullable for class FileSchemaTestClass."); return new FileSchemaTestClass(file, files); } @@ -178,10 +192,22 @@ public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchema /// public void WriteProperties(ref Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("file"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); - writer.WritePropertyName("files"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + if (fileSchemaTestClass.FileOption.IsSet && fileSchemaTestClass.File == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.File), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FilesOption.IsSet && fileSchemaTestClass.Files == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.Files), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FileOption.IsSet) + { + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); + } + if (fileSchemaTestClass.FilesOption.IsSet) + { + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs index dbedd34f861d..39566c13eaf5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Foo.cs @@ -37,19 +37,26 @@ public partial class Foo : IValidatableObject /// /// bar (default to "bar") [JsonConstructor] - public Foo(string bar = @"bar") + public Foo(Option bar = default) { - Bar = bar; + BarOption = bar; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; private set; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; set; } + public string? Bar { get { return this. BarOption; } set { this.BarOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; + Option bar = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class Foo."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class Foo."); return new Foo(bar); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", foo.Bar); + if (foo.BarOption.IsSet && foo.Bar == null) + throw new ArgumentNullException(nameof(foo.Bar), "Property is required for class Foo."); + + if (foo.BarOption.IsSet) + writer.WriteString("bar", foo.Bar); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs index dabc1bd83dbf..1bbe0ddf0fe8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FooGetDefaultResponse.cs @@ -37,19 +37,26 @@ public partial class FooGetDefaultResponse : IValidatableObject /// /// varString [JsonConstructor] - public FooGetDefaultResponse(Foo varString) + public FooGetDefaultResponse(Option varString = default) { - VarString = varString; + VarStringOption = varString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } + /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public Foo VarString { get; set; } + public Foo? VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Foo? varString = default; + Option varString = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty { case "string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varString = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varString = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -131,8 +138,8 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty } } - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FooGetDefaultResponse."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FooGetDefaultResponse."); return new FooGetDefaultResponse(varString); } @@ -161,8 +168,14 @@ public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDe /// public void WriteProperties(ref Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("string"); - JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + if (fooGetDefaultResponse.VarStringOption.IsSet && fooGetDefaultResponse.VarString == null) + throw new ArgumentNullException(nameof(fooGetDefaultResponse.VarString), "Property is required for class FooGetDefaultResponse."); + + if (fooGetDefaultResponse.VarStringOption.IsSet) + { + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs index d45a83b0f1d7..254504ca937c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/FormatTest.cs @@ -35,9 +35,11 @@ public partial class FormatTest : IValidatableObject /// /// Initializes a new instance of the class. /// - /// binary /// varByte /// date + /// number + /// password + /// binary /// dateTime /// varDecimal /// varDouble @@ -45,8 +47,6 @@ public partial class FormatTest : IValidatableObject /// int32 /// int64 /// integer - /// number - /// password /// None /// A string that is a 10 digit number. Can have leading zeros. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. @@ -55,38 +55,32 @@ public partial class FormatTest : IValidatableObject /// unsignedLong /// uuid [JsonConstructor] - public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTime dateTime, decimal varDecimal, double varDouble, float varFloat, int int32, long int64, int integer, decimal number, string password, string patternWithBackslash, string patternWithDigits, string patternWithDigitsAndDelimiter, string varString, uint unsignedInteger, ulong unsignedLong, Guid uuid) + public FormatTest(byte[] varByte, DateOnly date, decimal number, string password, Option binary = default, Option dateTime = default, Option varDecimal = default, Option varDouble = default, Option varFloat = default, Option int32 = default, Option int64 = default, Option integer = default, Option patternWithBackslash = default, Option patternWithDigits = default, Option patternWithDigitsAndDelimiter = default, Option varString = default, Option unsignedInteger = default, Option unsignedLong = default, Option uuid = default) { - Binary = binary; VarByte = varByte; Date = date; - DateTime = dateTime; - VarDecimal = varDecimal; - VarDouble = varDouble; - VarFloat = varFloat; - Int32 = int32; - Int64 = int64; - Integer = integer; Number = number; Password = password; - PatternWithBackslash = patternWithBackslash; - PatternWithDigits = patternWithDigits; - PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - VarString = varString; - UnsignedInteger = unsignedInteger; - UnsignedLong = unsignedLong; - Uuid = uuid; + BinaryOption = binary; + DateTimeOption = dateTime; + VarDecimalOption = varDecimal; + VarDoubleOption = varDouble; + VarFloatOption = varFloat; + Int32Option = int32; + Int64Option = int64; + IntegerOption = integer; + PatternWithBackslashOption = patternWithBackslash; + PatternWithDigitsOption = patternWithDigits; + PatternWithDigitsAndDelimiterOption = patternWithDigitsAndDelimiter; + VarStringOption = varString; + UnsignedIntegerOption = unsignedInteger; + UnsignedLongOption = unsignedLong; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - /// /// Gets or Sets VarByte /// @@ -98,108 +92,219 @@ public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTi /// /// Sun Feb 02 00:00:00 UTC 2020 [JsonPropertyName("date")] - public DateTime Date { get; set; } + public DateOnly Date { get; set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public decimal Number { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Used to track the state of Binary + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BinaryOption { get; private set; } + + /// + /// Gets or Sets Binary + /// + [JsonPropertyName("binary")] + public System.IO.Stream? Binary { get { return this. BinaryOption; } set { this.BinaryOption = new(value); } } + + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } /// /// Gets or Sets DateTime /// /// 2007-12-03T10:15:30+01:00 [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of VarDecimal + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDecimalOption { get; private set; } /// /// Gets or Sets VarDecimal /// [JsonPropertyName("decimal")] - public decimal VarDecimal { get; set; } + public decimal? VarDecimal { get { return this. VarDecimalOption; } set { this.VarDecimalOption = new(value); } } + + /// + /// Used to track the state of VarDouble + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDoubleOption { get; private set; } /// /// Gets or Sets VarDouble /// [JsonPropertyName("double")] - public double VarDouble { get; set; } + public double? VarDouble { get { return this. VarDoubleOption; } set { this.VarDoubleOption = new(value); } } + + /// + /// Used to track the state of VarFloat + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarFloatOption { get; private set; } /// /// Gets or Sets VarFloat /// [JsonPropertyName("float")] - public float VarFloat { get; set; } + public float? VarFloat { get { return this. VarFloatOption; } set { this.VarFloatOption = new(value); } } + + /// + /// Used to track the state of Int32 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int32Option { get; private set; } /// /// Gets or Sets Int32 /// [JsonPropertyName("int32")] - public int Int32 { get; set; } + public int? Int32 { get { return this. Int32Option; } set { this.Int32Option = new(value); } } + + /// + /// Used to track the state of Int64 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int64Option { get; private set; } /// /// Gets or Sets Int64 /// [JsonPropertyName("int64")] - public long Int64 { get; set; } + public long? Int64 { get { return this. Int64Option; } set { this.Int64Option = new(value); } } /// - /// Gets or Sets Integer + /// Used to track the state of Integer /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerOption { get; private set; } /// - /// Gets or Sets Number + /// Gets or Sets Integer /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("integer")] + public int? Integer { get { return this. IntegerOption; } set { this.IntegerOption = new(value); } } /// - /// Gets or Sets Password + /// Used to track the state of PatternWithBackslash /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithBackslashOption { get; private set; } /// /// None /// /// None [JsonPropertyName("pattern_with_backslash")] - public string PatternWithBackslash { get; set; } + public string? PatternWithBackslash { get { return this. PatternWithBackslashOption; } set { this.PatternWithBackslashOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigits + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsOption { get; private set; } /// /// A string that is a 10 digit number. Can have leading zeros. /// /// A string that is a 10 digit number. Can have leading zeros. [JsonPropertyName("pattern_with_digits")] - public string PatternWithDigits { get; set; } + public string? PatternWithDigits { get { return this. PatternWithDigitsOption; } set { this.PatternWithDigitsOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigitsAndDelimiter + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsAndDelimiterOption { get; private set; } /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. [JsonPropertyName("pattern_with_digits_and_delimiter")] - public string PatternWithDigitsAndDelimiter { get; set; } + public string? PatternWithDigitsAndDelimiter { get { return this. PatternWithDigitsAndDelimiterOption; } set { this.PatternWithDigitsAndDelimiterOption = new(value); } } + + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public string VarString { get; set; } + public string? VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } + + /// + /// Used to track the state of UnsignedInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedIntegerOption { get; private set; } /// /// Gets or Sets UnsignedInteger /// [JsonPropertyName("unsigned_integer")] - public uint UnsignedInteger { get; set; } + public uint? UnsignedInteger { get { return this. UnsignedIntegerOption; } set { this.UnsignedIntegerOption = new(value); } } + + /// + /// Used to track the state of UnsignedLong + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedLongOption { get; private set; } /// /// Gets or Sets UnsignedLong /// [JsonPropertyName("unsigned_long")] - public ulong UnsignedLong { get; set; } + public ulong? UnsignedLong { get { return this. UnsignedLongOption; } set { this.UnsignedLongOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -215,9 +320,11 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" VarByte: ").Append(VarByte).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" VarDecimal: ").Append(VarDecimal).Append("\n"); sb.Append(" VarDouble: ").Append(VarDouble).Append("\n"); @@ -225,8 +332,6 @@ public override string ToString() sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" PatternWithBackslash: ").Append(PatternWithBackslash).Append("\n"); sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); @@ -246,122 +351,126 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + // VarDouble (double) maximum - if (this.VarDouble > (double)123.4) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value less than or equal to 123.4.", new [] { "VarDouble" }); } // VarDouble (double) minimum - if (this.VarDouble < (double)67.8) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value greater than or equal to 67.8.", new [] { "VarDouble" }); } // VarFloat (float) maximum - if (this.VarFloat > (float)987.6) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value less than or equal to 987.6.", new [] { "VarFloat" }); } // VarFloat (float) minimum - if (this.VarFloat < (float)54.3) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value greater than or equal to 54.3.", new [] { "VarFloat" }); } // Int32 (int) maximum - if (this.Int32 > (int)200) + if (this.Int32Option.IsSet && this.Int32Option.Value > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if (this.Int32 < (int)20) + if (this.Int32Option.IsSet && this.Int32Option.Value < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Integer (int) maximum - if (this.Integer > (int)100) + if (this.IntegerOption.IsSet && this.IntegerOption.Value > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if (this.Integer < (int)10) + if (this.IntegerOption.IsSet && this.IntegerOption.Value < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } - // Number (decimal) maximum - if (this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if (this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Password (string) maxLength - if (this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if (this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - if (this.PatternWithBackslash != null) { + if (this.PatternWithBackslashOption.Value != null) { // PatternWithBackslash (string) pattern Regex regexPatternWithBackslash = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$", RegexOptions.CultureInvariant); - if (!regexPatternWithBackslash.Match(this.PatternWithBackslash).Success) + + if (this.PatternWithBackslashOption.Value != null &&!regexPatternWithBackslash.Match(this.PatternWithBackslashOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithBackslash, must match a pattern of " + regexPatternWithBackslash, new [] { "PatternWithBackslash" }); } } - if (this.PatternWithDigits != null) { + if (this.PatternWithDigitsOption.Value != null) { // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\d{10}$", RegexOptions.CultureInvariant); - if (!regexPatternWithDigits.Match(this.PatternWithDigits).Success) + + if (this.PatternWithDigitsOption.Value != null &&!regexPatternWithDigits.Match(this.PatternWithDigitsOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); } } - if (this.PatternWithDigitsAndDelimiter != null) { + if (this.PatternWithDigitsAndDelimiterOption.Value != null) { // PatternWithDigitsAndDelimiter (string) pattern Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + + if (this.PatternWithDigitsAndDelimiterOption.Value != null &&!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiterOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } } - if (this.VarString != null) { + if (this.VarStringOption.Value != null) { // VarString (string) pattern Regex regexVarString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexVarString.Match(this.VarString).Success) + + if (this.VarStringOption.Value != null &&!regexVarString.Match(this.VarStringOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarString, must match a pattern of " + regexVarString, new [] { "VarString" }); } } // UnsignedInteger (uint) maximum - if (this.UnsignedInteger > (uint)200) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value > (uint)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value less than or equal to 200.", new [] { "UnsignedInteger" }); } // UnsignedInteger (uint) minimum - if (this.UnsignedInteger < (uint)20) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value < (uint)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value greater than or equal to 20.", new [] { "UnsignedInteger" }); } @@ -402,25 +511,25 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - System.IO.Stream? binary = default; - byte[]? varByte = default; - DateTime? date = default; - DateTime? dateTime = default; - decimal? varDecimal = default; - double? varDouble = default; - float? varFloat = default; - int? int32 = default; - long? int64 = default; - int? integer = default; - decimal? number = default; - string? password = default; - string? patternWithBackslash = default; - string? patternWithDigits = default; - string? patternWithDigitsAndDelimiter = default; - string? varString = default; - uint? unsignedInteger = default; - ulong? unsignedLong = default; - Guid? uuid = default; + Option varByte = default; + Option date = default; + Option number = default; + Option password = default; + Option binary = default; + Option dateTime = default; + Option varDecimal = default; + Option varDouble = default; + Option varFloat = default; + Option int32 = default; + Option int64 = default; + Option integer = default; + Option patternWithBackslash = default; + Option patternWithDigits = default; + Option patternWithDigitsAndDelimiter = default; + Option varString = default; + Option unsignedInteger = default; + Option unsignedLong = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -437,76 +546,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { - case "binary": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - binary = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; case "byte": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varByte = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varByte = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "date": if (utf8JsonReader.TokenType != JsonTokenType.Null) - date = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + number = new Option(utf8JsonReader.GetDecimal()); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "binary": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + binary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "decimal": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDecimal = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varDecimal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "double": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDouble = utf8JsonReader.GetDouble(); + varDouble = new Option(utf8JsonReader.GetDouble()); break; case "float": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varFloat = (float)utf8JsonReader.GetDouble(); + varFloat = new Option((float)utf8JsonReader.GetDouble()); break; case "int32": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int32 = utf8JsonReader.GetInt32(); + int32 = new Option(utf8JsonReader.GetInt32()); break; case "int64": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int64 = utf8JsonReader.GetInt64(); + int64 = new Option(utf8JsonReader.GetInt64()); break; case "integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integer = utf8JsonReader.GetInt32(); - break; - case "number": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - number = utf8JsonReader.GetDecimal(); - break; - case "password": - password = utf8JsonReader.GetString(); + integer = new Option(utf8JsonReader.GetInt32()); break; case "pattern_with_backslash": - patternWithBackslash = utf8JsonReader.GetString(); + patternWithBackslash = new Option(utf8JsonReader.GetString()!); break; case "pattern_with_digits": - patternWithDigits = utf8JsonReader.GetString(); + patternWithDigits = new Option(utf8JsonReader.GetString()!); break; case "pattern_with_digits_and_delimiter": - patternWithDigitsAndDelimiter = utf8JsonReader.GetString(); + patternWithDigitsAndDelimiter = new Option(utf8JsonReader.GetString()!); break; case "string": - varString = utf8JsonReader.GetString(); + varString = new Option(utf8JsonReader.GetString()!); break; case "unsigned_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedInteger = utf8JsonReader.GetUInt32(); + unsignedInteger = new Option(utf8JsonReader.GetUInt32()); break; case "unsigned_long": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedLong = utf8JsonReader.GetUInt64(); + unsignedLong = new Option(utf8JsonReader.GetUInt64()); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -514,64 +623,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (binary == null) - throw new ArgumentNullException(nameof(binary), "Property is required for class FormatTest."); + if (!varByte.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(varByte)); + + if (!date.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(date)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(number)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(password)); - if (varByte == null) - throw new ArgumentNullException(nameof(varByte), "Property is required for class FormatTest."); + if (varByte.IsSet && varByte.Value == null) + throw new ArgumentNullException(nameof(varByte), "Property is not nullable for class FormatTest."); - if (date == null) - throw new ArgumentNullException(nameof(date), "Property is required for class FormatTest."); + if (date.IsSet && date.Value == null) + throw new ArgumentNullException(nameof(date), "Property is not nullable for class FormatTest."); - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class FormatTest."); + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class FormatTest."); - if (varDecimal == null) - throw new ArgumentNullException(nameof(varDecimal), "Property is required for class FormatTest."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class FormatTest."); - if (varDouble == null) - throw new ArgumentNullException(nameof(varDouble), "Property is required for class FormatTest."); + if (binary.IsSet && binary.Value == null) + throw new ArgumentNullException(nameof(binary), "Property is not nullable for class FormatTest."); - if (varFloat == null) - throw new ArgumentNullException(nameof(varFloat), "Property is required for class FormatTest."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class FormatTest."); - if (int32 == null) - throw new ArgumentNullException(nameof(int32), "Property is required for class FormatTest."); + if (varDecimal.IsSet && varDecimal.Value == null) + throw new ArgumentNullException(nameof(varDecimal), "Property is not nullable for class FormatTest."); - if (int64 == null) - throw new ArgumentNullException(nameof(int64), "Property is required for class FormatTest."); + if (varDouble.IsSet && varDouble.Value == null) + throw new ArgumentNullException(nameof(varDouble), "Property is not nullable for class FormatTest."); - if (integer == null) - throw new ArgumentNullException(nameof(integer), "Property is required for class FormatTest."); + if (varFloat.IsSet && varFloat.Value == null) + throw new ArgumentNullException(nameof(varFloat), "Property is not nullable for class FormatTest."); - if (number == null) - throw new ArgumentNullException(nameof(number), "Property is required for class FormatTest."); + if (int32.IsSet && int32.Value == null) + throw new ArgumentNullException(nameof(int32), "Property is not nullable for class FormatTest."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class FormatTest."); + if (int64.IsSet && int64.Value == null) + throw new ArgumentNullException(nameof(int64), "Property is not nullable for class FormatTest."); - if (patternWithBackslash == null) - throw new ArgumentNullException(nameof(patternWithBackslash), "Property is required for class FormatTest."); + if (integer.IsSet && integer.Value == null) + throw new ArgumentNullException(nameof(integer), "Property is not nullable for class FormatTest."); - if (patternWithDigits == null) - throw new ArgumentNullException(nameof(patternWithDigits), "Property is required for class FormatTest."); + if (patternWithBackslash.IsSet && patternWithBackslash.Value == null) + throw new ArgumentNullException(nameof(patternWithBackslash), "Property is not nullable for class FormatTest."); - if (patternWithDigitsAndDelimiter == null) - throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + if (patternWithDigits.IsSet && patternWithDigits.Value == null) + throw new ArgumentNullException(nameof(patternWithDigits), "Property is not nullable for class FormatTest."); - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FormatTest."); + if (patternWithDigitsAndDelimiter.IsSet && patternWithDigitsAndDelimiter.Value == null) + throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is not nullable for class FormatTest."); - if (unsignedInteger == null) - throw new ArgumentNullException(nameof(unsignedInteger), "Property is required for class FormatTest."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FormatTest."); - if (unsignedLong == null) - throw new ArgumentNullException(nameof(unsignedLong), "Property is required for class FormatTest."); + if (unsignedInteger.IsSet && unsignedInteger.Value == null) + throw new ArgumentNullException(nameof(unsignedInteger), "Property is not nullable for class FormatTest."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class FormatTest."); + if (unsignedLong.IsSet && unsignedLong.Value == null) + throw new ArgumentNullException(nameof(unsignedLong), "Property is not nullable for class FormatTest."); - return new FormatTest(binary, varByte, date.Value, dateTime.Value, varDecimal.Value, varDouble.Value, varFloat.Value, int32.Value, int64.Value, integer.Value, number.Value, password, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger.Value, unsignedLong.Value, uuid.Value); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class FormatTest."); + + return new FormatTest(varByte.Value!, date.Value!.Value!, number.Value!.Value!, password.Value!, binary, dateTime, varDecimal, varDouble, varFloat, int32, int64, integer, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger, unsignedLong, uuid); } /// @@ -598,28 +719,83 @@ public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("binary"); - JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + if (formatTest.VarByte == null) + throw new ArgumentNullException(nameof(formatTest.VarByte), "Property is required for class FormatTest."); + + if (formatTest.Password == null) + throw new ArgumentNullException(nameof(formatTest.Password), "Property is required for class FormatTest."); + + if (formatTest.BinaryOption.IsSet && formatTest.Binary == null) + throw new ArgumentNullException(nameof(formatTest.Binary), "Property is required for class FormatTest."); + + if (formatTest.PatternWithBackslashOption.IsSet && formatTest.PatternWithBackslash == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithBackslash), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsOption.IsSet && formatTest.PatternWithDigits == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigits), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet && formatTest.PatternWithDigitsAndDelimiter == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + + if (formatTest.VarStringOption.IsSet && formatTest.VarString == null) + throw new ArgumentNullException(nameof(formatTest.VarString), "Property is required for class FormatTest."); + writer.WritePropertyName("byte"); JsonSerializer.Serialize(writer, formatTest.VarByte, jsonSerializerOptions); writer.WriteString("date", formatTest.Date.ToString(DateFormat)); - writer.WriteString("dateTime", formatTest.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("decimal"); - JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); - writer.WriteNumber("double", formatTest.VarDouble); - writer.WriteNumber("float", formatTest.VarFloat); - writer.WriteNumber("int32", formatTest.Int32); - writer.WriteNumber("int64", formatTest.Int64); - writer.WriteNumber("integer", formatTest.Integer); + writer.WriteNumber("number", formatTest.Number); + writer.WriteString("password", formatTest.Password); - writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); - writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); - writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); - writer.WriteString("string", formatTest.VarString); - writer.WriteNumber("unsigned_integer", formatTest.UnsignedInteger); - writer.WriteNumber("unsigned_long", formatTest.UnsignedLong); - writer.WriteString("uuid", formatTest.Uuid); + + if (formatTest.BinaryOption.IsSet) + { + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + } + if (formatTest.DateTimeOption.IsSet) + writer.WriteString("dateTime", formatTest.DateTimeOption.Value!.Value.ToString(DateTimeFormat)); + + if (formatTest.VarDecimalOption.IsSet) + { + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); + } + if (formatTest.VarDoubleOption.IsSet) + writer.WriteNumber("double", formatTest.VarDoubleOption.Value!.Value); + + if (formatTest.VarFloatOption.IsSet) + writer.WriteNumber("float", formatTest.VarFloatOption.Value!.Value); + + if (formatTest.Int32Option.IsSet) + writer.WriteNumber("int32", formatTest.Int32Option.Value!.Value); + + if (formatTest.Int64Option.IsSet) + writer.WriteNumber("int64", formatTest.Int64Option.Value!.Value); + + if (formatTest.IntegerOption.IsSet) + writer.WriteNumber("integer", formatTest.IntegerOption.Value!.Value); + + if (formatTest.PatternWithBackslashOption.IsSet) + writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); + + if (formatTest.PatternWithDigitsOption.IsSet) + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet) + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + + if (formatTest.VarStringOption.IsSet) + writer.WriteString("string", formatTest.VarString); + + if (formatTest.UnsignedIntegerOption.IsSet) + writer.WriteNumber("unsigned_integer", formatTest.UnsignedIntegerOption.Value!.Value); + + if (formatTest.UnsignedLongOption.IsSet) + writer.WriteNumber("unsigned_long", formatTest.UnsignedLongOption.Value!.Value); + + if (formatTest.UuidOption.IsSet) + writer.WriteString("uuid", formatTest.UuidOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs index be945563eba9..066324fd8ac0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Fruit.cs @@ -37,10 +37,10 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple apple, string color) + public Fruit(Apple apple, Option color = default) { Apple = apple; - Color = color; + ColorOption = color; OnCreated(); } @@ -49,10 +49,10 @@ public Fruit(Apple apple, string color) /// /// /// color - public Fruit(Banana banana, string color) + public Fruit(Banana banana, Option color = default) { Banana = banana; - Color = color; + ColorOption = color; OnCreated(); } @@ -68,11 +68,18 @@ public Fruit(Banana banana, string color) /// public Banana? Banana { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -120,7 +127,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -160,7 +167,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -168,8 +175,8 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); if (apple != null) return new Fruit(apple, color); @@ -204,7 +211,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs index fea0b966137f..ce3104ed3261 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GmFruit.cs @@ -38,31 +38,52 @@ public partial class GmFruit : IValidatableObject /// /// /// color - public GmFruit(Apple? apple, Banana? banana, string color) + public GmFruit(Option apple, Option banana, Option color = default) { - Apple = apple; - Banana = banana; - Color = color; + AppleOption = apple; + BananaOption = banana; + ColorOption = color; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Apple + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AppleOption { get; private set; } + /// /// Gets or Sets Apple /// - public Apple? Apple { get; set; } + public Apple? Apple { get { return this.AppleOption; } set { this.AppleOption = new(value); } } + + /// + /// Used to track the state of Banana + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BananaOption { get; private set; } /// /// Gets or Sets Banana /// - public Banana? Banana { get; set; } + public Banana? Banana { get { return this.BananaOption; } set { this.BananaOption = new(value); } } + + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -110,7 +131,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -150,7 +171,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -158,10 +179,17 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class GmFruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class GmFruit."); - return new GmFruit(apple, banana, color); + Option appleParsedValue = apple == null + ? default + : new Option(apple); + Option bananaParsedValue = banana == null + ? default + : new Option(banana); + + return new GmFruit(appleParsedValue, bananaParsedValue, color); } /// @@ -175,16 +203,16 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize { writer.WriteStartObject(); - if (gmFruit.Apple != null) + if (gmFruit.AppleOption.IsSet && gmFruit.AppleOption.Value != null) { - AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Apple.GetType())); - AppleJsonConverter.WriteProperties(ref writer, gmFruit.Apple, jsonSerializerOptions); + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.AppleOption.Value.GetType())); + AppleJsonConverter.WriteProperties(ref writer, gmFruit.AppleOption.Value, jsonSerializerOptions); } - if (gmFruit.Banana != null) + if (gmFruit.BananaOption.IsSet && gmFruit.BananaOption.Value != null) { - BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Banana.GetType())); - BananaJsonConverter.WriteProperties(ref writer, gmFruit.Banana, jsonSerializerOptions); + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.BananaOption.Value.GetType())); + BananaJsonConverter.WriteProperties(ref writer, gmFruit.BananaOption.Value, jsonSerializerOptions); } WriteProperties(ref writer, gmFruit, jsonSerializerOptions); @@ -200,7 +228,11 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", gmFruit.Color); + if (gmFruit.ColorOption.IsSet && gmFruit.Color == null) + throw new ArgumentNullException(nameof(gmFruit.Color), "Property is required for class GmFruit."); + + if (gmFruit.ColorOption.IsSet) + writer.WriteString("color", gmFruit.Color); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs index d4a0752699b2..ff6399cd2fed 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/GrandparentAnimal.cs @@ -114,7 +114,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -132,7 +132,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -140,10 +140,13 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class GrandparentAnimal."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class GrandparentAnimal.", nameof(petType)); - return new GrandparentAnimal(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class GrandparentAnimal."); + + return new GrandparentAnimal(petType.Value!); } /// @@ -170,6 +173,9 @@ public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentA /// public void WriteProperties(ref Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) { + if (grandparentAnimal.PetType == null) + throw new ArgumentNullException(nameof(grandparentAnimal.PetType), "Property is required for class GrandparentAnimal."); + writer.WriteString("pet_type", grandparentAnimal.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs index 0ba58633d833..75e57fcf4fec 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HasOnlyReadOnly.cs @@ -38,26 +38,40 @@ public partial class HasOnlyReadOnly : IEquatable, IValidatabl /// bar /// foo [JsonConstructor] - internal HasOnlyReadOnly(string bar, string foo) + internal HasOnlyReadOnly(Option bar = default, Option foo = default) { - Bar = bar; - Foo = foo; + BarOption = bar; + FooOption = foo; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string? Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Foo + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FooOption { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; } + public string? Foo { get { return this. FooOption; } } /// /// Gets or Sets additional properties @@ -109,8 +123,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); - hashCode = (hashCode * 59) + Foo.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + + if (Foo != null) + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -150,8 +168,8 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; - string? foo = default; + Option bar = default; + Option foo = default; while (utf8JsonReader.Read()) { @@ -169,10 +187,10 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; case "foo": - foo = utf8JsonReader.GetString(); + foo = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -180,11 +198,11 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class HasOnlyReadOnly."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class HasOnlyReadOnly."); - if (foo == null) - throw new ArgumentNullException(nameof(foo), "Property is required for class HasOnlyReadOnly."); + if (foo.IsSet && foo.Value == null) + throw new ArgumentNullException(nameof(foo), "Property is not nullable for class HasOnlyReadOnly."); return new HasOnlyReadOnly(bar, foo); } @@ -213,8 +231,17 @@ public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnl /// public void WriteProperties(ref Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", hasOnlyReadOnly.Bar); - writer.WriteString("foo", hasOnlyReadOnly.Foo); + if (hasOnlyReadOnly.BarOption.IsSet && hasOnlyReadOnly.Bar == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Bar), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.FooOption.IsSet && hasOnlyReadOnly.Foo == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Foo), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.BarOption.IsSet) + writer.WriteString("bar", hasOnlyReadOnly.Bar); + + if (hasOnlyReadOnly.FooOption.IsSet) + writer.WriteString("foo", hasOnlyReadOnly.Foo); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs index b0753cea2a42..44988806cfb7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/HealthCheckResult.cs @@ -37,19 +37,26 @@ public partial class HealthCheckResult : IValidatableObject /// /// nullableMessage [JsonConstructor] - public HealthCheckResult(string? nullableMessage = default) + public HealthCheckResult(Option nullableMessage = default) { - NullableMessage = nullableMessage; + NullableMessageOption = nullableMessage; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of NullableMessage + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableMessageOption { get; private set; } + /// /// Gets or Sets NullableMessage /// [JsonPropertyName("NullableMessage")] - public string? NullableMessage { get; set; } + public string? NullableMessage { get { return this. NullableMessageOption; } set { this.NullableMessageOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? nullableMessage = default; + Option nullableMessage = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "NullableMessage": - nullableMessage = utf8JsonReader.GetString(); + nullableMessage = new Option(utf8JsonReader.GetString()); break; default: break; @@ -157,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckR /// public void WriteProperties(ref Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + if (healthCheckResult.NullableMessageOption.IsSet) + if (healthCheckResult.NullableMessageOption.Value != null) + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + else + writer.WriteNull("NullableMessage"); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs index e54fa76f0663..90f931a85c55 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/IsoscelesTriangle.cs @@ -106,8 +106,8 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -125,10 +125,10 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -136,13 +136,19 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class IsoscelesTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class IsoscelesTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(triangleType)); - return new IsoscelesTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class IsoscelesTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class IsoscelesTriangle."); + + return new IsoscelesTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -169,7 +175,14 @@ public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTri /// public void WriteProperties(ref Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (isoscelesTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.ShapeType), "Property is required for class IsoscelesTriangle."); + + if (isoscelesTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.TriangleType), "Property is required for class IsoscelesTriangle."); + writer.WriteString("shapeType", isoscelesTriangle.ShapeType); + writer.WriteString("triangleType", isoscelesTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs index 031e16c39a57..2f75d0bb148a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/List.cs @@ -37,19 +37,26 @@ public partial class List : IValidatableObject /// /// var123List [JsonConstructor] - public List(string var123List) + public List(Option var123List = default) { - Var123List = var123List; + Var123ListOption = var123List; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Var123List + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123ListOption { get; private set; } + /// /// Gets or Sets Var123List /// [JsonPropertyName("123-list")] - public string Var123List { get; set; } + public string? Var123List { get { return this. Var123ListOption; } set { this.Var123ListOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? var123List = default; + Option var123List = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "123-list": - var123List = utf8JsonReader.GetString(); + var123List = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (var123List == null) - throw new ArgumentNullException(nameof(var123List), "Property is required for class List."); + if (var123List.IsSet && var123List.Value == null) + throw new ArgumentNullException(nameof(var123List), "Property is not nullable for class List."); return new List(var123List); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("123-list", list.Var123List); + if (list.Var123ListOption.IsSet && list.Var123List == null) + throw new ArgumentNullException(nameof(list.Var123List), "Property is required for class List."); + + if (list.Var123ListOption.IsSet) + writer.WriteString("123-list", list.Var123List); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs index 46ae1dc05ae3..67cd536b7ba7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/LiteralStringClass.cs @@ -38,26 +38,40 @@ public partial class LiteralStringClass : IValidatableObject /// escapedLiteralString (default to "C:\\Users\\username") /// unescapedLiteralString (default to "C:\Users\username") [JsonConstructor] - public LiteralStringClass(string escapedLiteralString = @"C:\\Users\\username", string unescapedLiteralString = @"C:\Users\username") + public LiteralStringClass(Option escapedLiteralString = default, Option unescapedLiteralString = default) { - EscapedLiteralString = escapedLiteralString; - UnescapedLiteralString = unescapedLiteralString; + EscapedLiteralStringOption = escapedLiteralString; + UnescapedLiteralStringOption = unescapedLiteralString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of EscapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EscapedLiteralStringOption { get; private set; } + /// /// Gets or Sets EscapedLiteralString /// [JsonPropertyName("escapedLiteralString")] - public string EscapedLiteralString { get; set; } + public string? EscapedLiteralString { get { return this. EscapedLiteralStringOption; } set { this.EscapedLiteralStringOption = new(value); } } + + /// + /// Used to track the state of UnescapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnescapedLiteralStringOption { get; private set; } /// /// Gets or Sets UnescapedLiteralString /// [JsonPropertyName("unescapedLiteralString")] - public string UnescapedLiteralString { get; set; } + public string? UnescapedLiteralString { get { return this. UnescapedLiteralStringOption; } set { this.UnescapedLiteralStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? escapedLiteralString = default; - string? unescapedLiteralString = default; + Option escapedLiteralString = default; + Option unescapedLiteralString = default; while (utf8JsonReader.Read()) { @@ -132,10 +146,10 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "escapedLiteralString": - escapedLiteralString = utf8JsonReader.GetString(); + escapedLiteralString = new Option(utf8JsonReader.GetString()!); break; case "unescapedLiteralString": - unescapedLiteralString = utf8JsonReader.GetString(); + unescapedLiteralString = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -143,11 +157,11 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (escapedLiteralString == null) - throw new ArgumentNullException(nameof(escapedLiteralString), "Property is required for class LiteralStringClass."); + if (escapedLiteralString.IsSet && escapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(escapedLiteralString), "Property is not nullable for class LiteralStringClass."); - if (unescapedLiteralString == null) - throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is required for class LiteralStringClass."); + if (unescapedLiteralString.IsSet && unescapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is not nullable for class LiteralStringClass."); return new LiteralStringClass(escapedLiteralString, unescapedLiteralString); } @@ -176,8 +190,17 @@ public override void Write(Utf8JsonWriter writer, LiteralStringClass literalStri /// public void WriteProperties(ref Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); - writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); + if (literalStringClass.EscapedLiteralStringOption.IsSet && literalStringClass.EscapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.EscapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet && literalStringClass.UnescapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.UnescapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.EscapedLiteralStringOption.IsSet) + writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet) + writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs index fcc1424f2c19..676b1d08c139 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Mammal.cs @@ -154,7 +154,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; Pig? pig = null; Whale? whale = null; @@ -211,7 +211,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -219,17 +219,20 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Mammal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Mammal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Mammal."); if (pig != null) - return new Mammal(pig, className); + return new Mammal(pig, className.Value!); if (whale != null) - return new Mammal(whale, className); + return new Mammal(whale, className.Value!); if (zebra != null) - return new Mammal(zebra, className); + return new Mammal(zebra, className.Value!); throw new JsonException(); } @@ -273,6 +276,9 @@ public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) { + if (mammal.ClassName == null) + throw new ArgumentNullException(nameof(mammal.ClassName), "Property is required for class Mammal."); + writer.WriteString("className", mammal.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs index 6ed69e85cf4a..9e9b2b725f53 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MapTest.cs @@ -40,12 +40,12 @@ public partial class MapTest : IValidatableObject /// mapMapOfString /// mapOfEnumString [JsonConstructor] - public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) + public MapTest(Option?> directMap = default, Option?> indirectMap = default, Option>?> mapMapOfString = default, Option?> mapOfEnumString = default) { - DirectMap = directMap; - IndirectMap = indirectMap; - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; + DirectMapOption = directMap; + IndirectMapOption = indirectMap; + MapMapOfStringOption = mapMapOfString; + MapOfEnumStringOption = mapOfEnumString; OnCreated(); } @@ -106,7 +106,7 @@ public static InnerEnum InnerEnumFromString(string value) /// /// /// - public static string InnerEnumToJsonValue(InnerEnum value) + public static string InnerEnumToJsonValue(InnerEnum? value) { if (value == InnerEnum.UPPER) return "UPPER"; @@ -117,29 +117,57 @@ public static string InnerEnumToJsonValue(InnerEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of DirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> DirectMapOption { get; private set; } + /// /// Gets or Sets DirectMap /// [JsonPropertyName("direct_map")] - public Dictionary DirectMap { get; set; } + public Dictionary? DirectMap { get { return this. DirectMapOption; } set { this.DirectMapOption = new(value); } } + + /// + /// Used to track the state of IndirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> IndirectMapOption { get; private set; } /// /// Gets or Sets IndirectMap /// [JsonPropertyName("indirect_map")] - public Dictionary IndirectMap { get; set; } + public Dictionary? IndirectMap { get { return this. IndirectMapOption; } set { this.IndirectMapOption = new(value); } } + + /// + /// Used to track the state of MapMapOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> MapMapOfStringOption { get; private set; } /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + public Dictionary>? MapMapOfString { get { return this. MapMapOfStringOption; } set { this.MapMapOfStringOption = new(value); } } + + /// + /// Used to track the state of MapOfEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapOfEnumStringOption { get; private set; } /// /// Gets or Sets MapOfEnumString /// [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + public Dictionary? MapOfEnumString { get { return this. MapOfEnumStringOption; } set { this.MapOfEnumStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -197,10 +225,10 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary? directMap = default; - Dictionary? indirectMap = default; - Dictionary>? mapMapOfString = default; - Dictionary? mapOfEnumString = default; + Option?> directMap = default; + Option?> indirectMap = default; + Option>?> mapMapOfString = default; + Option?> mapOfEnumString = default; while (utf8JsonReader.Read()) { @@ -219,19 +247,19 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "direct_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - directMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + directMap = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "indirect_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - indirectMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + indirectMap = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_map_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapMapOfString = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapMapOfString = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_of_enum_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfEnumString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapOfEnumString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -239,17 +267,17 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (directMap == null) - throw new ArgumentNullException(nameof(directMap), "Property is required for class MapTest."); + if (directMap.IsSet && directMap.Value == null) + throw new ArgumentNullException(nameof(directMap), "Property is not nullable for class MapTest."); - if (indirectMap == null) - throw new ArgumentNullException(nameof(indirectMap), "Property is required for class MapTest."); + if (indirectMap.IsSet && indirectMap.Value == null) + throw new ArgumentNullException(nameof(indirectMap), "Property is not nullable for class MapTest."); - if (mapMapOfString == null) - throw new ArgumentNullException(nameof(mapMapOfString), "Property is required for class MapTest."); + if (mapMapOfString.IsSet && mapMapOfString.Value == null) + throw new ArgumentNullException(nameof(mapMapOfString), "Property is not nullable for class MapTest."); - if (mapOfEnumString == null) - throw new ArgumentNullException(nameof(mapOfEnumString), "Property is required for class MapTest."); + if (mapOfEnumString.IsSet && mapOfEnumString.Value == null) + throw new ArgumentNullException(nameof(mapOfEnumString), "Property is not nullable for class MapTest."); return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); } @@ -278,14 +306,38 @@ public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("direct_map"); - JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); - writer.WritePropertyName("indirect_map"); - JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); - writer.WritePropertyName("map_map_of_string"); - JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); - writer.WritePropertyName("map_of_enum_string"); - JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + if (mapTest.DirectMapOption.IsSet && mapTest.DirectMap == null) + throw new ArgumentNullException(nameof(mapTest.DirectMap), "Property is required for class MapTest."); + + if (mapTest.IndirectMapOption.IsSet && mapTest.IndirectMap == null) + throw new ArgumentNullException(nameof(mapTest.IndirectMap), "Property is required for class MapTest."); + + if (mapTest.MapMapOfStringOption.IsSet && mapTest.MapMapOfString == null) + throw new ArgumentNullException(nameof(mapTest.MapMapOfString), "Property is required for class MapTest."); + + if (mapTest.MapOfEnumStringOption.IsSet && mapTest.MapOfEnumString == null) + throw new ArgumentNullException(nameof(mapTest.MapOfEnumString), "Property is required for class MapTest."); + + if (mapTest.DirectMapOption.IsSet) + { + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); + } + if (mapTest.IndirectMapOption.IsSet) + { + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); + } + if (mapTest.MapMapOfStringOption.IsSet) + { + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); + } + if (mapTest.MapOfEnumStringOption.IsSet) + { + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 25ea1076cd59..0bc78f42edec 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -40,40 +40,68 @@ public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableO /// uuid /// uuidWithPattern [JsonConstructor] - public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid, Guid uuidWithPattern) + public MixedPropertiesAndAdditionalPropertiesClass(Option dateTime = default, Option?> map = default, Option uuid = default, Option uuidWithPattern = default) { - DateTime = dateTime; - Map = map; - Uuid = uuid; - UuidWithPattern = uuidWithPattern; + DateTimeOption = dateTime; + MapOption = map; + UuidOption = uuid; + UuidWithPatternOption = uuidWithPattern; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } + /// /// Gets or Sets DateTime /// [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of Map + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapOption { get; private set; } /// /// Gets or Sets Map /// [JsonPropertyName("map")] - public Dictionary Map { get; set; } + public Dictionary? Map { get { return this. MapOption; } set { this.MapOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } + + /// + /// Used to track the state of UuidWithPattern + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidWithPatternOption { get; private set; } /// /// Gets or Sets UuidWithPattern /// [JsonPropertyName("uuid_with_pattern")] - public Guid UuidWithPattern { get; set; } + public Guid? UuidWithPattern { get { return this. UuidWithPatternOption; } set { this.UuidWithPatternOption = new(value); } } /// /// Gets or Sets additional properties @@ -107,7 +135,8 @@ public override string ToString() { // UuidWithPattern (Guid) pattern Regex regexUuidWithPattern = new Regex(@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOptions.CultureInvariant); - if (!regexUuidWithPattern.Match(this.UuidWithPattern.ToString()).Success) + + if (this.UuidWithPatternOption.Value != null &&!regexUuidWithPattern.Match(this.UuidWithPatternOption.Value.ToString()!).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UuidWithPattern, must match a pattern of " + regexUuidWithPattern, new [] { "UuidWithPattern" }); } @@ -142,10 +171,10 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateTime = default; - Dictionary? map = default; - Guid? uuid = default; - Guid? uuidWithPattern = default; + Option dateTime = default; + Option?> map = default; + Option uuid = default; + Option uuidWithPattern = default; while (utf8JsonReader.Read()) { @@ -164,19 +193,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea { case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - map = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + map = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; case "uuid_with_pattern": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuidWithPattern = utf8JsonReader.GetGuid(); + uuidWithPattern = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -184,19 +213,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea } } - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (map == null) - throw new ArgumentNullException(nameof(map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (map.IsSet && map.Value == null) + throw new ArgumentNullException(nameof(map), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuidWithPattern == null) - throw new ArgumentNullException(nameof(uuidWithPattern), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuidWithPattern.IsSet && uuidWithPattern.Value == null) + throw new ArgumentNullException(nameof(uuidWithPattern), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - return new MixedPropertiesAndAdditionalPropertiesClass(dateTime.Value, map, uuid.Value, uuidWithPattern.Value); + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid, uuidWithPattern); } /// @@ -223,11 +252,22 @@ public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("map"); - JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); - writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); - writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPattern); + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet && mixedPropertiesAndAdditionalPropertiesClass.Map == null) + throw new ArgumentNullException(nameof(mixedPropertiesAndAdditionalPropertiesClass.Map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.IsSet) + writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.Value!.Value.ToString(DateTimeFormat)); + + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet) + { + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); + } + if (mixedPropertiesAndAdditionalPropertiesClass.UuidOption.IsSet) + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.UuidOption.Value!.Value); + + if (mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.IsSet) + writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs index 74f7acb1e828..6d738cf1d6a5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Model200Response.cs @@ -38,26 +38,40 @@ public partial class Model200Response : IValidatableObject /// varClass /// name [JsonConstructor] - public Model200Response(string varClass, int name) + public Model200Response(Option varClass = default, Option name = default) { - VarClass = varClass; - Name = name; + VarClassOption = varClass; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("class")] - public string VarClass { get; set; } + public string? VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public int Name { get; set; } + public int? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClass = default; - int? name = default; + Option varClass = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -132,11 +146,11 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()!); break; case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - name = utf8JsonReader.GetInt32(); + name = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -144,13 +158,13 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class Model200Response."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class Model200Response."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Model200Response."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Model200Response."); - return new Model200Response(varClass, name.Value); + return new Model200Response(varClass, name); } /// @@ -177,8 +191,14 @@ public override void Write(Utf8JsonWriter writer, Model200Response model200Respo /// public void WriteProperties(ref Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("class", model200Response.VarClass); - writer.WriteNumber("name", model200Response.Name); + if (model200Response.VarClassOption.IsSet && model200Response.VarClass == null) + throw new ArgumentNullException(nameof(model200Response.VarClass), "Property is required for class Model200Response."); + + if (model200Response.VarClassOption.IsSet) + writer.WriteString("class", model200Response.VarClass); + + if (model200Response.NameOption.IsSet) + writer.WriteNumber("name", model200Response.NameOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs index 5bc60589f350..08959d3204cc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ModelClient.cs @@ -37,19 +37,26 @@ public partial class ModelClient : IValidatableObject /// /// varClient [JsonConstructor] - public ModelClient(string varClient) + public ModelClient(Option varClient = default) { - VarClient = varClient; + VarClientOption = varClient; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClient + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClientOption { get; private set; } + /// /// Gets or Sets VarClient /// [JsonPropertyName("client")] - public string VarClient { get; set; } + public string? VarClient { get { return this. VarClientOption; } set { this.VarClientOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClient = default; + Option varClient = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "client": - varClient = utf8JsonReader.GetString(); + varClient = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (varClient == null) - throw new ArgumentNullException(nameof(varClient), "Property is required for class ModelClient."); + if (varClient.IsSet && varClient.Value == null) + throw new ArgumentNullException(nameof(varClient), "Property is not nullable for class ModelClient."); return new ModelClient(varClient); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("client", modelClient.VarClient); + if (modelClient.VarClientOption.IsSet && modelClient.VarClient == null) + throw new ArgumentNullException(nameof(modelClient.VarClient), "Property is required for class ModelClient."); + + if (modelClient.VarClientOption.IsSet) + writer.WriteString("client", modelClient.VarClient); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs index 4648cf04f7d2..464ad8d4f38d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Name.cs @@ -40,12 +40,12 @@ public partial class Name : IEquatable, IValidatableObject /// snakeCase /// var123Number [JsonConstructor] - public Name(int varName, string property, int snakeCase, int var123Number) + public Name(int varName, Option property = default, Option snakeCase = default, Option var123Number = default) { VarName = varName; - Property = property; - SnakeCase = snakeCase; - Var123Number = var123Number; + PropertyOption = property; + SnakeCaseOption = snakeCase; + Var123NumberOption = var123Number; OnCreated(); } @@ -57,23 +57,44 @@ public Name(int varName, string property, int snakeCase, int var123Number) [JsonPropertyName("name")] public int VarName { get; set; } + /// + /// Used to track the state of Property + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PropertyOption { get; private set; } + /// /// Gets or Sets Property /// [JsonPropertyName("property")] - public string Property { get; set; } + public string? Property { get { return this. PropertyOption; } set { this.PropertyOption = new(value); } } + + /// + /// Used to track the state of SnakeCase + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SnakeCaseOption { get; } /// /// Gets or Sets SnakeCase /// [JsonPropertyName("snake_case")] - public int SnakeCase { get; } + public int? SnakeCase { get { return this. SnakeCaseOption; } } + + /// + /// Used to track the state of Var123Number + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123NumberOption { get; } /// /// Gets or Sets Var123Number /// [JsonPropertyName("123Number")] - public int Var123Number { get; } + public int? Var123Number { get { return this. Var123NumberOption; } } /// /// Gets or Sets additional properties @@ -127,8 +148,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); - hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + if (SnakeCase != null) + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + + if (Var123Number != null) + hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -168,10 +193,10 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varName = default; - string? property = default; - int? snakeCase = default; - int? var123Number = default; + Option varName = default; + Option property = default; + Option snakeCase = default; + Option var123Number = default; while (utf8JsonReader.Read()) { @@ -190,18 +215,18 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varName = utf8JsonReader.GetInt32(); + varName = new Option(utf8JsonReader.GetInt32()); break; case "property": - property = utf8JsonReader.GetString(); + property = new Option(utf8JsonReader.GetString()!); break; case "snake_case": if (utf8JsonReader.TokenType != JsonTokenType.Null) - snakeCase = utf8JsonReader.GetInt32(); + snakeCase = new Option(utf8JsonReader.GetInt32()); break; case "123Number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - var123Number = utf8JsonReader.GetInt32(); + var123Number = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -209,19 +234,22 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (varName == null) - throw new ArgumentNullException(nameof(varName), "Property is required for class Name."); + if (!varName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(varName)); + + if (varName.IsSet && varName.Value == null) + throw new ArgumentNullException(nameof(varName), "Property is not nullable for class Name."); - if (property == null) - throw new ArgumentNullException(nameof(property), "Property is required for class Name."); + if (property.IsSet && property.Value == null) + throw new ArgumentNullException(nameof(property), "Property is not nullable for class Name."); - if (snakeCase == null) - throw new ArgumentNullException(nameof(snakeCase), "Property is required for class Name."); + if (snakeCase.IsSet && snakeCase.Value == null) + throw new ArgumentNullException(nameof(snakeCase), "Property is not nullable for class Name."); - if (var123Number == null) - throw new ArgumentNullException(nameof(var123Number), "Property is required for class Name."); + if (var123Number.IsSet && var123Number.Value == null) + throw new ArgumentNullException(nameof(var123Number), "Property is not nullable for class Name."); - return new Name(varName.Value, property, snakeCase.Value, var123Number.Value); + return new Name(varName.Value!.Value!, property, snakeCase, var123Number); } /// @@ -248,10 +276,19 @@ public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) { + if (name.PropertyOption.IsSet && name.Property == null) + throw new ArgumentNullException(nameof(name.Property), "Property is required for class Name."); + writer.WriteNumber("name", name.VarName); - writer.WriteString("property", name.Property); - writer.WriteNumber("snake_case", name.SnakeCase); - writer.WriteNumber("123Number", name.Var123Number); + + if (name.PropertyOption.IsSet) + writer.WriteString("property", name.Property); + + if (name.SnakeCaseOption.IsSet) + writer.WriteNumber("snake_case", name.SnakeCaseOption.Value!.Value); + + if (name.Var123NumberOption.IsSet) + writer.WriteNumber("123Number", name.Var123NumberOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs index ed43ab9fcd27..d453934498af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NotificationtestGetElementsV1ResponseMPayload.cs @@ -113,8 +113,8 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? aObjVariableobject = default; - int? pkiNotificationtestID = default; + Option>?> aObjVariableobject = default; + Option pkiNotificationtestID = default; while (utf8JsonReader.Read()) { @@ -133,11 +133,11 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR { case "a_objVariableobject": if (utf8JsonReader.TokenType != JsonTokenType.Null) - aObjVariableobject = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + aObjVariableobject = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "pkiNotificationtestID": if (utf8JsonReader.TokenType != JsonTokenType.Null) - pkiNotificationtestID = utf8JsonReader.GetInt32(); + pkiNotificationtestID = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -145,13 +145,19 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR } } - if (aObjVariableobject == null) - throw new ArgumentNullException(nameof(aObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!aObjVariableobject.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(aObjVariableobject)); - if (pkiNotificationtestID == null) - throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!pkiNotificationtestID.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(pkiNotificationtestID)); - return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject, pkiNotificationtestID.Value); + if (aObjVariableobject.IsSet && aObjVariableobject.Value == null) + throw new ArgumentNullException(nameof(aObjVariableobject), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + if (pkiNotificationtestID.IsSet && pkiNotificationtestID.Value == null) + throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject.Value!, pkiNotificationtestID.Value!.Value!); } /// @@ -178,6 +184,9 @@ public override void Write(Utf8JsonWriter writer, NotificationtestGetElementsV1R /// public void WriteProperties(ref Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) { + if (notificationtestGetElementsV1ResponseMPayload.AObjVariableobject == null) + throw new ArgumentNullException(nameof(notificationtestGetElementsV1ResponseMPayload.AObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + writer.WritePropertyName("a_objVariableobject"); JsonSerializer.Serialize(writer, notificationtestGetElementsV1ResponseMPayload.AObjVariableobject, jsonSerializerOptions); writer.WriteNumber("pkiNotificationtestID", notificationtestGetElementsV1ResponseMPayload.PkiNotificationtestID); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs index 5374e7a890e8..1b496faaa43e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableClass.cs @@ -30,14 +30,13 @@ namespace UseSourceGeneration.Model /// /// NullableClass /// - public partial class NullableClass : Dictionary, IValidatableObject + public partial class NullableClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayItemsNullable - /// objectItemsNullable /// arrayAndItemsNullableProp + /// arrayItemsNullable /// arrayNullableProp /// booleanProp /// dateProp @@ -45,99 +44,184 @@ public partial class NullableClass : Dictionary, IValidatableObj /// integerProp /// numberProp /// objectAndItemsNullableProp + /// objectItemsNullable /// objectNullableProp /// stringProp [JsonConstructor] - public NullableClass(List arrayItemsNullable, Dictionary objectItemsNullable, List? arrayAndItemsNullableProp = default, List? arrayNullableProp = default, bool? booleanProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, int? integerProp = default, decimal? numberProp = default, Dictionary? objectAndItemsNullableProp = default, Dictionary? objectNullableProp = default, string? stringProp = default) : base() + public NullableClass(Option?> arrayAndItemsNullableProp = default, Option?> arrayItemsNullable = default, Option?> arrayNullableProp = default, Option booleanProp = default, Option dateProp = default, Option datetimeProp = default, Option integerProp = default, Option numberProp = default, Option?> objectAndItemsNullableProp = default, Option?> objectItemsNullable = default, Option?> objectNullableProp = default, Option stringProp = default) { - ArrayItemsNullable = arrayItemsNullable; - ObjectItemsNullable = objectItemsNullable; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayNullableProp = arrayNullableProp; - BooleanProp = booleanProp; - DateProp = dateProp; - DatetimeProp = datetimeProp; - IntegerProp = integerProp; - NumberProp = numberProp; - ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectNullableProp = objectNullableProp; - StringProp = stringProp; + ArrayAndItemsNullablePropOption = arrayAndItemsNullableProp; + ArrayItemsNullableOption = arrayItemsNullable; + ArrayNullablePropOption = arrayNullableProp; + BooleanPropOption = booleanProp; + DatePropOption = dateProp; + DatetimePropOption = datetimeProp; + IntegerPropOption = integerProp; + NumberPropOption = numberProp; + ObjectAndItemsNullablePropOption = objectAndItemsNullableProp; + ObjectItemsNullableOption = objectItemsNullable; + ObjectNullablePropOption = objectNullableProp; + StringPropOption = stringProp; OnCreated(); } partial void OnCreated(); /// - /// Gets or Sets ArrayItemsNullable + /// Used to track the state of ArrayAndItemsNullableProp /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayAndItemsNullablePropOption { get; private set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ArrayAndItemsNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("array_and_items_nullable_prop")] + public List? ArrayAndItemsNullableProp { get { return this. ArrayAndItemsNullablePropOption; } set { this.ArrayAndItemsNullablePropOption = new(value); } } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Used to track the state of ArrayItemsNullable /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List? ArrayAndItemsNullableProp { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ArrayItemsNullable + /// + [JsonPropertyName("array_items_nullable")] + public List? ArrayItemsNullable { get { return this. ArrayItemsNullableOption; } set { this.ArrayItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ArrayNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayNullablePropOption { get; private set; } /// /// Gets or Sets ArrayNullableProp /// [JsonPropertyName("array_nullable_prop")] - public List? ArrayNullableProp { get; set; } + public List? ArrayNullableProp { get { return this. ArrayNullablePropOption; } set { this.ArrayNullablePropOption = new(value); } } + + /// + /// Used to track the state of BooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BooleanPropOption { get; private set; } /// /// Gets or Sets BooleanProp /// [JsonPropertyName("boolean_prop")] - public bool? BooleanProp { get; set; } + public bool? BooleanProp { get { return this. BooleanPropOption; } set { this.BooleanPropOption = new(value); } } + + /// + /// Used to track the state of DateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatePropOption { get; private set; } /// /// Gets or Sets DateProp /// [JsonPropertyName("date_prop")] - public DateTime? DateProp { get; set; } + public DateOnly? DateProp { get { return this. DatePropOption; } set { this.DatePropOption = new(value); } } + + /// + /// Used to track the state of DatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatetimePropOption { get; private set; } /// /// Gets or Sets DatetimeProp /// [JsonPropertyName("datetime_prop")] - public DateTime? DatetimeProp { get; set; } + public DateTime? DatetimeProp { get { return this. DatetimePropOption; } set { this.DatetimePropOption = new(value); } } + + /// + /// Used to track the state of IntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerPropOption { get; private set; } /// /// Gets or Sets IntegerProp /// [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + public int? IntegerProp { get { return this. IntegerPropOption; } set { this.IntegerPropOption = new(value); } } + + /// + /// Used to track the state of NumberProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberPropOption { get; private set; } /// /// Gets or Sets NumberProp /// [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + public decimal? NumberProp { get { return this. NumberPropOption; } set { this.NumberPropOption = new(value); } } + + /// + /// Used to track the state of ObjectAndItemsNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectAndItemsNullablePropOption { get; private set; } /// /// Gets or Sets ObjectAndItemsNullableProp /// [JsonPropertyName("object_and_items_nullable_prop")] - public Dictionary? ObjectAndItemsNullableProp { get; set; } + public Dictionary? ObjectAndItemsNullableProp { get { return this. ObjectAndItemsNullablePropOption; } set { this.ObjectAndItemsNullablePropOption = new(value); } } + + /// + /// Used to track the state of ObjectItemsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [JsonPropertyName("object_items_nullable")] + public Dictionary? ObjectItemsNullable { get { return this. ObjectItemsNullableOption; } set { this.ObjectItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ObjectNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectNullablePropOption { get; private set; } /// /// Gets or Sets ObjectNullableProp /// [JsonPropertyName("object_nullable_prop")] - public Dictionary? ObjectNullableProp { get; set; } + public Dictionary? ObjectNullableProp { get { return this. ObjectNullablePropOption; } set { this.ObjectNullablePropOption = new(value); } } + + /// + /// Used to track the state of StringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StringPropOption { get; private set; } /// /// Gets or Sets StringProp /// [JsonPropertyName("string_prop")] - public string? StringProp { get; set; } + public string? StringProp { get { return this. StringPropOption; } set { this.StringPropOption = new(value); } } /// /// Gets or Sets additional properties @@ -153,10 +237,8 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); @@ -164,6 +246,7 @@ public override string ToString() sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -177,16 +260,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -224,18 +297,18 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayItemsNullable = default; - Dictionary? objectItemsNullable = default; - List? arrayAndItemsNullableProp = default; - List? arrayNullableProp = default; - bool? booleanProp = default; - DateTime? dateProp = default; - DateTime? datetimeProp = default; - int? integerProp = default; - decimal? numberProp = default; - Dictionary? objectAndItemsNullableProp = default; - Dictionary? objectNullableProp = default; - string? stringProp = default; + Option?> arrayAndItemsNullableProp = default; + Option?> arrayItemsNullable = default; + Option?> arrayNullableProp = default; + Option booleanProp = default; + Option dateProp = default; + Option datetimeProp = default; + Option integerProp = default; + Option numberProp = default; + Option?> objectAndItemsNullableProp = default; + Option?> objectItemsNullable = default; + Option?> objectNullableProp = default; + Option stringProp = default; while (utf8JsonReader.Read()) { @@ -252,52 +325,52 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { - case "array_items_nullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "object_items_nullable": + case "array_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayAndItemsNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "array_and_items_nullable_prop": + case "array_items_nullable": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayItemsNullable = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "boolean_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - booleanProp = utf8JsonReader.GetBoolean(); + booleanProp = new Option(utf8JsonReader.GetBoolean()); break; case "date_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "datetime_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - datetimeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + datetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "integer_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integerProp = utf8JsonReader.GetInt32(); + integerProp = new Option(utf8JsonReader.GetInt32()); break; case "number_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - numberProp = utf8JsonReader.GetDecimal(); + numberProp = new Option(utf8JsonReader.GetDecimal()); break; case "object_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectAndItemsNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "object_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectItemsNullable = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "object_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "string_prop": - stringProp = utf8JsonReader.GetString(); + stringProp = new Option(utf8JsonReader.GetString()); break; default: break; @@ -305,13 +378,13 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (arrayItemsNullable == null) - throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is required for class NullableClass."); + if (arrayItemsNullable.IsSet && arrayItemsNullable.Value == null) + throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is not nullable for class NullableClass."); - if (objectItemsNullable == null) - throw new ArgumentNullException(nameof(objectItemsNullable), "Property is required for class NullableClass."); + if (objectItemsNullable.IsSet && objectItemsNullable.Value == null) + throw new ArgumentNullException(nameof(objectItemsNullable), "Property is not nullable for class NullableClass."); - return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + return new NullableClass(arrayAndItemsNullableProp, arrayItemsNullable, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectItemsNullable, objectNullableProp, stringProp); } /// @@ -338,45 +411,89 @@ public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("object_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("array_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("array_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); - - if (nullableClass.BooleanProp != null) - writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); - else - writer.WriteNull("boolean_prop"); - - if (nullableClass.DateProp != null) - writer.WriteString("date_prop", nullableClass.DateProp.Value.ToString(DatePropFormat)); - else - writer.WriteNull("date_prop"); - - if (nullableClass.DatetimeProp != null) - writer.WriteString("datetime_prop", nullableClass.DatetimeProp.Value.ToString(DatetimePropFormat)); - else - writer.WriteNull("datetime_prop"); - - if (nullableClass.IntegerProp != null) - writer.WriteNumber("integer_prop", nullableClass.IntegerProp.Value); - else - writer.WriteNull("integer_prop"); - - if (nullableClass.NumberProp != null) - writer.WriteNumber("number_prop", nullableClass.NumberProp.Value); - else - writer.WriteNull("number_prop"); - - writer.WritePropertyName("object_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("object_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); - writer.WriteString("string_prop", nullableClass.StringProp); + if (nullableClass.ArrayItemsNullableOption.IsSet && nullableClass.ArrayItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ArrayItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ObjectItemsNullableOption.IsSet && nullableClass.ObjectItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ObjectItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ArrayAndItemsNullablePropOption.IsSet) + if (nullableClass.ArrayAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_and_items_nullable_prop"); + if (nullableClass.ArrayItemsNullableOption.IsSet) + { + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ArrayNullablePropOption.IsSet) + if (nullableClass.ArrayNullablePropOption.Value != null) + { + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_nullable_prop"); + if (nullableClass.BooleanPropOption.IsSet) + if (nullableClass.BooleanPropOption.Value != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanPropOption.Value!.Value); + else + writer.WriteNull("boolean_prop"); + + if (nullableClass.DatePropOption.IsSet) + if (nullableClass.DatePropOption.Value != null) + writer.WriteString("date_prop", nullableClass.DatePropOption.Value!.Value.ToString(DatePropFormat)); + else + writer.WriteNull("date_prop"); + + if (nullableClass.DatetimePropOption.IsSet) + if (nullableClass.DatetimePropOption.Value != null) + writer.WriteString("datetime_prop", nullableClass.DatetimePropOption.Value!.Value.ToString(DatetimePropFormat)); + else + writer.WriteNull("datetime_prop"); + + if (nullableClass.IntegerPropOption.IsSet) + if (nullableClass.IntegerPropOption.Value != null) + writer.WriteNumber("integer_prop", nullableClass.IntegerPropOption.Value!.Value); + else + writer.WriteNull("integer_prop"); + + if (nullableClass.NumberPropOption.IsSet) + if (nullableClass.NumberPropOption.Value != null) + writer.WriteNumber("number_prop", nullableClass.NumberPropOption.Value!.Value); + else + writer.WriteNull("number_prop"); + + if (nullableClass.ObjectAndItemsNullablePropOption.IsSet) + if (nullableClass.ObjectAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_and_items_nullable_prop"); + if (nullableClass.ObjectItemsNullableOption.IsSet) + { + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ObjectNullablePropOption.IsSet) + if (nullableClass.ObjectNullablePropOption.Value != null) + { + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_nullable_prop"); + if (nullableClass.StringPropOption.IsSet) + if (nullableClass.StringPropOption.Value != null) + writer.WriteString("string_prop", nullableClass.StringProp); + else + writer.WriteNull("string_prop"); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs index eb5434dc5ba1..4bb7bbfc88c0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableGuidClass.cs @@ -37,20 +37,27 @@ public partial class NullableGuidClass : IValidatableObject /// /// uuid [JsonConstructor] - public NullableGuidClass(Guid? uuid = default) + public NullableGuidClass(Option uuid = default) { - Uuid = uuid; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } + /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid? Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -105,7 +112,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Guid? uuid = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -124,7 +131,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t { case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -159,11 +166,11 @@ public override void Write(Utf8JsonWriter writer, NullableGuidClass nullableGuid /// public void WriteProperties(ref Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) { - - if (nullableGuidClass.Uuid == null) - writer.WriteNull("uuid"); - else - writer.WriteString("uuid", nullableGuidClass.Uuid.Value); + if (nullableGuidClass.UuidOption.IsSet) + if (nullableGuidClass.UuidOption.Value != null) + writer.WriteString("uuid", nullableGuidClass.UuidOption.Value!.Value); + else + writer.WriteNull("uuid"); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs index 8a1f0995af65..5e07a4b642a9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NullableShape.cs @@ -137,7 +137,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -188,7 +188,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,14 +196,17 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class NullableShape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class NullableShape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class NullableShape."); if (quadrilateral != null) - return new NullableShape(quadrilateral, shapeType); + return new NullableShape(quadrilateral, shapeType.Value!); if (triangle != null) - return new NullableShape(triangle, shapeType); + return new NullableShape(triangle, shapeType.Value!); throw new JsonException(); } @@ -242,6 +245,9 @@ public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) { + if (nullableShape.ShapeType == null) + throw new ArgumentNullException(nameof(nullableShape.ShapeType), "Property is required for class NullableShape."); + writer.WriteString("shapeType", nullableShape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs index 740f496eb9d7..6362c24186d0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/NumberOnly.cs @@ -37,19 +37,26 @@ public partial class NumberOnly : IValidatableObject /// /// justNumber [JsonConstructor] - public NumberOnly(decimal justNumber) + public NumberOnly(Option justNumber = default) { - JustNumber = justNumber; + JustNumberOption = justNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of JustNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustNumberOption { get; private set; } + /// /// Gets or Sets JustNumber /// [JsonPropertyName("JustNumber")] - public decimal JustNumber { get; set; } + public decimal? JustNumber { get { return this. JustNumberOption; } set { this.JustNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? justNumber = default; + Option justNumber = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "JustNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - justNumber = utf8JsonReader.GetDecimal(); + justNumber = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -131,10 +138,10 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (justNumber == null) - throw new ArgumentNullException(nameof(justNumber), "Property is required for class NumberOnly."); + if (justNumber.IsSet && justNumber.Value == null) + throw new ArgumentNullException(nameof(justNumber), "Property is not nullable for class NumberOnly."); - return new NumberOnly(justNumber.Value); + return new NumberOnly(justNumber); } /// @@ -161,7 +168,8 @@ public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("JustNumber", numberOnly.JustNumber); + if (numberOnly.JustNumberOption.IsSet) + writer.WriteNumber("JustNumber", numberOnly.JustNumberOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs index 729b057bdb4e..506fddc846e4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ObjectWithDeprecatedFields.cs @@ -40,43 +40,71 @@ public partial class ObjectWithDeprecatedFields : IValidatableObject /// id /// uuid [JsonConstructor] - public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) + public ObjectWithDeprecatedFields(Option?> bars = default, Option deprecatedRef = default, Option id = default, Option uuid = default) { - Bars = bars; - DeprecatedRef = deprecatedRef; - Id = id; - Uuid = uuid; + BarsOption = bars; + DeprecatedRefOption = deprecatedRef; + IdOption = id; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bars + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BarsOption { get; private set; } + /// /// Gets or Sets Bars /// [JsonPropertyName("bars")] [Obsolete] - public List Bars { get; set; } + public List? Bars { get { return this. BarsOption; } set { this.BarsOption = new(value); } } + + /// + /// Used to track the state of DeprecatedRef + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeprecatedRefOption { get; private set; } /// /// Gets or Sets DeprecatedRef /// [JsonPropertyName("deprecatedRef")] [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } + public DeprecatedObject? DeprecatedRef { get { return this. DeprecatedRefOption; } set { this.DeprecatedRefOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] [Obsolete] - public decimal Id { get; set; } + public decimal? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public string Uuid { get; set; } + public string? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -134,10 +162,10 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? bars = default; - DeprecatedObject? deprecatedRef = default; - decimal? id = default; - string? uuid = default; + Option?> bars = default; + Option deprecatedRef = default; + Option id = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -156,18 +184,18 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade { case "bars": if (utf8JsonReader.TokenType != JsonTokenType.Null) - bars = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + bars = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "deprecatedRef": if (utf8JsonReader.TokenType != JsonTokenType.Null) - deprecatedRef = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + deprecatedRef = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetDecimal(); + id = new Option(utf8JsonReader.GetDecimal()); break; case "uuid": - uuid = utf8JsonReader.GetString(); + uuid = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -175,19 +203,19 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade } } - if (bars == null) - throw new ArgumentNullException(nameof(bars), "Property is required for class ObjectWithDeprecatedFields."); + if (bars.IsSet && bars.Value == null) + throw new ArgumentNullException(nameof(bars), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (deprecatedRef == null) - throw new ArgumentNullException(nameof(deprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + if (deprecatedRef.IsSet && deprecatedRef.Value == null) + throw new ArgumentNullException(nameof(deprecatedRef), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class ObjectWithDeprecatedFields."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class ObjectWithDeprecatedFields."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class ObjectWithDeprecatedFields."); - return new ObjectWithDeprecatedFields(bars, deprecatedRef, id.Value, uuid); + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); } /// @@ -214,12 +242,30 @@ public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields obj /// public void WriteProperties(ref Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("bars"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); - writer.WritePropertyName("deprecatedRef"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); - writer.WriteNumber("id", objectWithDeprecatedFields.Id); - writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + if (objectWithDeprecatedFields.BarsOption.IsSet && objectWithDeprecatedFields.Bars == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Bars), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet && objectWithDeprecatedFields.DeprecatedRef == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.DeprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.UuidOption.IsSet && objectWithDeprecatedFields.Uuid == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Uuid), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.BarsOption.IsSet) + { + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet) + { + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.IdOption.IsSet) + writer.WriteNumber("id", objectWithDeprecatedFields.IdOption.Value!.Value); + + if (objectWithDeprecatedFields.UuidOption.IsSet) + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs index add01056906b..43322b5b87e7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Order.cs @@ -35,21 +35,21 @@ public partial class Order : IValidatableObject /// /// Initializes a new instance of the class. /// + /// complete (default to false) /// id /// petId /// quantity /// shipDate /// Order Status - /// complete (default to false) [JsonConstructor] - public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) + public Order(Option complete = default, Option id = default, Option petId = default, Option quantity = default, Option shipDate = default, Option status = default) { - Id = id; - PetId = petId; - Quantity = quantity; - ShipDate = shipDate; - Status = status; - Complete = complete; + CompleteOption = complete; + IdOption = id; + PetIdOption = petId; + QuantityOption = quantity; + ShipDateOption = shipDate; + StatusOption = status; OnCreated(); } @@ -122,7 +122,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Placed) return "placed"; @@ -136,43 +136,85 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// Order Status /// /// Order Status [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Complete + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CompleteOption { get; private set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool? Complete { get { return this. CompleteOption; } set { this.CompleteOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of PetId + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PetIdOption { get; private set; } /// /// Gets or Sets PetId /// [JsonPropertyName("petId")] - public long PetId { get; set; } + public long? PetId { get { return this. PetIdOption; } set { this.PetIdOption = new(value); } } + + /// + /// Used to track the state of Quantity + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option QuantityOption { get; private set; } /// /// Gets or Sets Quantity /// [JsonPropertyName("quantity")] - public int Quantity { get; set; } + public int? Quantity { get { return this. QuantityOption; } set { this.QuantityOption = new(value); } } /// - /// Gets or Sets ShipDate + /// Used to track the state of ShipDate /// - /// 2020-02-02T20:20:20.000222Z - [JsonPropertyName("shipDate")] - public DateTime ShipDate { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShipDateOption { get; private set; } /// - /// Gets or Sets Complete + /// Gets or Sets ShipDate /// - [JsonPropertyName("complete")] - public bool Complete { get; set; } + /// 2020-02-02T20:20:20.000222Z + [JsonPropertyName("shipDate")] + public DateTime? ShipDate { get { return this. ShipDateOption; } set { this.ShipDateOption = new(value); } } /// /// Gets or Sets additional properties @@ -188,12 +230,12 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -237,12 +279,12 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - long? petId = default; - int? quantity = default; - DateTime? shipDate = default; - Order.StatusEnum? status = default; - bool? complete = default; + Option complete = default; + Option id = default; + Option petId = default; + Option quantity = default; + Option shipDate = default; + Option status = default; while (utf8JsonReader.Read()) { @@ -259,31 +301,30 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { + case "complete": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + complete = new Option(utf8JsonReader.GetBoolean()); + break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "petId": if (utf8JsonReader.TokenType != JsonTokenType.Null) - petId = utf8JsonReader.GetInt64(); + petId = new Option(utf8JsonReader.GetInt64()); break; case "quantity": if (utf8JsonReader.TokenType != JsonTokenType.Null) - quantity = utf8JsonReader.GetInt32(); + quantity = new Option(utf8JsonReader.GetInt32()); break; case "shipDate": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shipDate = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shipDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "status": string? statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Order.StatusEnumFromStringOrDefault(statusRawValue); - break; - case "complete": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - complete = utf8JsonReader.GetBoolean(); + if (statusRawValue != null) + status = new Option(Order.StatusEnumFromStringOrDefault(statusRawValue)); break; default: break; @@ -291,25 +332,25 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Order."); + if (complete.IsSet && complete.Value == null) + throw new ArgumentNullException(nameof(complete), "Property is not nullable for class Order."); - if (petId == null) - throw new ArgumentNullException(nameof(petId), "Property is required for class Order."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Order."); - if (quantity == null) - throw new ArgumentNullException(nameof(quantity), "Property is required for class Order."); + if (petId.IsSet && petId.Value == null) + throw new ArgumentNullException(nameof(petId), "Property is not nullable for class Order."); - if (shipDate == null) - throw new ArgumentNullException(nameof(shipDate), "Property is required for class Order."); + if (quantity.IsSet && quantity.Value == null) + throw new ArgumentNullException(nameof(quantity), "Property is not nullable for class Order."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Order."); + if (shipDate.IsSet && shipDate.Value == null) + throw new ArgumentNullException(nameof(shipDate), "Property is not nullable for class Order."); - if (complete == null) - throw new ArgumentNullException(nameof(complete), "Property is required for class Order."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Order."); - return new Order(id.Value, petId.Value, quantity.Value, shipDate.Value, status.Value, complete.Value); + return new Order(complete, id, petId, quantity, shipDate, status); } /// @@ -336,18 +377,23 @@ public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", order.Id); - writer.WriteNumber("petId", order.PetId); - writer.WriteNumber("quantity", order.Quantity); - writer.WriteString("shipDate", order.ShipDate.ToString(ShipDateFormat)); - - var statusRawValue = Order.StatusEnumToJsonValue(order.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WriteBoolean("complete", order.Complete); + if (order.CompleteOption.IsSet) + writer.WriteBoolean("complete", order.CompleteOption.Value!.Value); + + if (order.IdOption.IsSet) + writer.WriteNumber("id", order.IdOption.Value!.Value); + + if (order.PetIdOption.IsSet) + writer.WriteNumber("petId", order.PetIdOption.Value!.Value); + + if (order.QuantityOption.IsSet) + writer.WriteNumber("quantity", order.QuantityOption.Value!.Value); + + if (order.ShipDateOption.IsSet) + writer.WriteString("shipDate", order.ShipDateOption.Value!.Value.ToString(ShipDateFormat)); + + var statusRawValue = Order.StatusEnumToJsonValue(order.StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs index 87526afade06..929cfede69a8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/OuterComposite.cs @@ -39,33 +39,54 @@ public partial class OuterComposite : IValidatableObject /// myNumber /// myString [JsonConstructor] - public OuterComposite(bool myBoolean, decimal myNumber, string myString) + public OuterComposite(Option myBoolean = default, Option myNumber = default, Option myString = default) { - MyBoolean = myBoolean; - MyNumber = myNumber; - MyString = myString; + MyBooleanOption = myBoolean; + MyNumberOption = myNumber; + MyStringOption = myString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MyBoolean + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyBooleanOption { get; private set; } + /// /// Gets or Sets MyBoolean /// [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } + public bool? MyBoolean { get { return this. MyBooleanOption; } set { this.MyBooleanOption = new(value); } } + + /// + /// Used to track the state of MyNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyNumberOption { get; private set; } /// /// Gets or Sets MyNumber /// [JsonPropertyName("my_number")] - public decimal MyNumber { get; set; } + public decimal? MyNumber { get { return this. MyNumberOption; } set { this.MyNumberOption = new(value); } } + + /// + /// Used to track the state of MyString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyStringOption { get; private set; } /// /// Gets or Sets MyString /// [JsonPropertyName("my_string")] - public string MyString { get; set; } + public string? MyString { get { return this. MyStringOption; } set { this.MyStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -122,9 +143,9 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - bool? myBoolean = default; - decimal? myNumber = default; - string? myString = default; + Option myBoolean = default; + Option myNumber = default; + Option myString = default; while (utf8JsonReader.Read()) { @@ -143,14 +164,14 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type { case "my_boolean": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myBoolean = utf8JsonReader.GetBoolean(); + myBoolean = new Option(utf8JsonReader.GetBoolean()); break; case "my_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myNumber = utf8JsonReader.GetDecimal(); + myNumber = new Option(utf8JsonReader.GetDecimal()); break; case "my_string": - myString = utf8JsonReader.GetString(); + myString = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -158,16 +179,16 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (myBoolean == null) - throw new ArgumentNullException(nameof(myBoolean), "Property is required for class OuterComposite."); + if (myBoolean.IsSet && myBoolean.Value == null) + throw new ArgumentNullException(nameof(myBoolean), "Property is not nullable for class OuterComposite."); - if (myNumber == null) - throw new ArgumentNullException(nameof(myNumber), "Property is required for class OuterComposite."); + if (myNumber.IsSet && myNumber.Value == null) + throw new ArgumentNullException(nameof(myNumber), "Property is not nullable for class OuterComposite."); - if (myString == null) - throw new ArgumentNullException(nameof(myString), "Property is required for class OuterComposite."); + if (myString.IsSet && myString.Value == null) + throw new ArgumentNullException(nameof(myString), "Property is not nullable for class OuterComposite."); - return new OuterComposite(myBoolean.Value, myNumber.Value, myString); + return new OuterComposite(myBoolean, myNumber, myString); } /// @@ -194,9 +215,17 @@ public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, /// public void WriteProperties(ref Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); - writer.WriteNumber("my_number", outerComposite.MyNumber); - writer.WriteString("my_string", outerComposite.MyString); + if (outerComposite.MyStringOption.IsSet && outerComposite.MyString == null) + throw new ArgumentNullException(nameof(outerComposite.MyString), "Property is required for class OuterComposite."); + + if (outerComposite.MyBooleanOption.IsSet) + writer.WriteBoolean("my_boolean", outerComposite.MyBooleanOption.Value!.Value); + + if (outerComposite.MyNumberOption.IsSet) + writer.WriteNumber("my_number", outerComposite.MyNumberOption.Value!.Value); + + if (outerComposite.MyStringOption.IsSet) + writer.WriteString("my_string", outerComposite.MyString); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs index 1162f9a2a32d..5244fe8b0eff 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ParentPet.cs @@ -80,7 +80,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -98,7 +98,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -106,10 +106,13 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ParentPet."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ParentPet.", nameof(petType)); - return new ParentPet(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ParentPet."); + + return new ParentPet(petType.Value!); } /// @@ -136,6 +139,9 @@ public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) { + if (parentPet.PetType == null) + throw new ArgumentNullException(nameof(parentPet.PetType), "Property is required for class ParentPet."); + writer.WriteString("pet_type", parentPet.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs index e012ef64c9cb..10a27080916f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pet.cs @@ -35,21 +35,21 @@ public partial class Pet : IValidatableObject /// /// Initializes a new instance of the class. /// - /// category - /// id /// name /// photoUrls + /// category + /// id /// pet status in the store /// tags [JsonConstructor] - public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) + public Pet(string name, List photoUrls, Option category = default, Option id = default, Option status = default, Option?> tags = default) { - Category = category; - Id = id; Name = name; PhotoUrls = photoUrls; - Status = status; - Tags = tags; + CategoryOption = category; + IdOption = id; + StatusOption = status; + TagsOption = tags; OnCreated(); } @@ -122,7 +122,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Available) return "available"; @@ -136,43 +136,71 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// pet status in the store /// /// pet status in the store [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Gets or Sets Name + /// + /// doggie + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Used to track the state of Category + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CategoryOption { get; private set; } /// /// Gets or Sets Category /// [JsonPropertyName("category")] - public Category Category { get; set; } + public Category? Category { get { return this. CategoryOption; } set { this.CategoryOption = new(value); } } /// - /// Gets or Sets Id + /// Used to track the state of Id /// - [JsonPropertyName("id")] - public long Id { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// - /// Gets or Sets Name + /// Gets or Sets Id /// - /// doggie - [JsonPropertyName("name")] - public string Name { get; set; } + [JsonPropertyName("id")] + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// - /// Gets or Sets PhotoUrls + /// Used to track the state of Tags /// - [JsonPropertyName("photoUrls")] - public List PhotoUrls { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> TagsOption { get; private set; } /// /// Gets or Sets Tags /// [JsonPropertyName("tags")] - public List Tags { get; set; } + public List? Tags { get { return this. TagsOption; } set { this.TagsOption = new(value); } } /// /// Gets or Sets additional properties @@ -188,10 +216,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -232,12 +260,12 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Category? category = default; - long? id = default; - string? name = default; - List? photoUrls = default; - Pet.StatusEnum? status = default; - List? tags = default; + Option name = default; + Option?> photoUrls = default; + Option category = default; + Option id = default; + Option status = default; + Option?> tags = default; while (utf8JsonReader.Read()) { @@ -254,30 +282,29 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "category": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - category = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + case "name": + name = new Option(utf8JsonReader.GetString()!); break; - case "id": + case "photoUrls": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + photoUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; - case "name": - name = utf8JsonReader.GetString(); + case "category": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + category = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; - case "photoUrls": + case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - photoUrls = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + id = new Option(utf8JsonReader.GetInt64()); break; case "status": string? statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Pet.StatusEnumFromStringOrDefault(statusRawValue); + if (statusRawValue != null) + status = new Option(Pet.StatusEnumFromStringOrDefault(statusRawValue)); break; case "tags": if (utf8JsonReader.TokenType != JsonTokenType.Null) - tags = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + tags = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -285,25 +312,31 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (category == null) - throw new ArgumentNullException(nameof(category), "Property is required for class Pet."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(name)); + + if (!photoUrls.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(photoUrls)); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Pet."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Pet."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Pet."); + if (photoUrls.IsSet && photoUrls.Value == null) + throw new ArgumentNullException(nameof(photoUrls), "Property is not nullable for class Pet."); - if (photoUrls == null) - throw new ArgumentNullException(nameof(photoUrls), "Property is required for class Pet."); + if (category.IsSet && category.Value == null) + throw new ArgumentNullException(nameof(category), "Property is not nullable for class Pet."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Pet."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Pet."); - if (tags == null) - throw new ArgumentNullException(nameof(tags), "Property is required for class Pet."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Pet."); - return new Pet(category, id.Value, name, photoUrls, status.Value, tags); + if (tags.IsSet && tags.Value == null) + throw new ArgumentNullException(nameof(tags), "Property is not nullable for class Pet."); + + return new Pet(name.Value!, photoUrls.Value!, category, id, status, tags); } /// @@ -330,21 +363,37 @@ public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("category"); - JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); - writer.WriteNumber("id", pet.Id); + if (pet.Name == null) + throw new ArgumentNullException(nameof(pet.Name), "Property is required for class Pet."); + + if (pet.PhotoUrls == null) + throw new ArgumentNullException(nameof(pet.PhotoUrls), "Property is required for class Pet."); + + if (pet.CategoryOption.IsSet && pet.Category == null) + throw new ArgumentNullException(nameof(pet.Category), "Property is required for class Pet."); + + if (pet.TagsOption.IsSet && pet.Tags == null) + throw new ArgumentNullException(nameof(pet.Tags), "Property is required for class Pet."); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); JsonSerializer.Serialize(writer, pet.PhotoUrls, jsonSerializerOptions); + if (pet.CategoryOption.IsSet) + { + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); + } + if (pet.IdOption.IsSet) + writer.WriteNumber("id", pet.IdOption.Value!.Value); - var statusRawValue = Pet.StatusEnumToJsonValue(pet.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WritePropertyName("tags"); - JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + var statusRawValue = Pet.StatusEnumToJsonValue(pet.StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + if (pet.TagsOption.IsSet) + { + writer.WritePropertyName("tags"); + JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs index 3f9fdf20cd85..09e650c7df0a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Pig.cs @@ -137,7 +137,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; BasquePig? basquePig = null; DanishPig? danishPig = null; @@ -188,7 +188,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,14 +196,17 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Pig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Pig.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Pig."); if (basquePig != null) - return new Pig(basquePig, className); + return new Pig(basquePig, className.Value!); if (danishPig != null) - return new Pig(danishPig, className); + return new Pig(danishPig, className.Value!); throw new JsonException(); } @@ -242,6 +245,9 @@ public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) { + if (pig.ClassName == null) + throw new ArgumentNullException(nameof(pig.ClassName), "Property is required for class Pig."); + writer.WriteString("className", pig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs index 8b6c244ab73d..dfb4799a35eb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Quadrilateral.cs @@ -137,7 +137,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; + Option quadrilateralType = default; ComplexQuadrilateral? complexQuadrilateral = null; SimpleQuadrilateral? simpleQuadrilateral = null; @@ -188,7 +188,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,14 +196,17 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class Quadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class Quadrilateral.", nameof(quadrilateralType)); + + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class Quadrilateral."); if (complexQuadrilateral != null) - return new Quadrilateral(complexQuadrilateral, quadrilateralType); + return new Quadrilateral(complexQuadrilateral, quadrilateralType.Value!); if (simpleQuadrilateral != null) - return new Quadrilateral(simpleQuadrilateral, quadrilateralType); + return new Quadrilateral(simpleQuadrilateral, quadrilateralType.Value!); throw new JsonException(); } @@ -242,6 +245,9 @@ public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, J /// public void WriteProperties(ref Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateral.QuadrilateralType), "Property is required for class Quadrilateral."); + writer.WriteString("quadrilateralType", quadrilateral.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs index 91f6a55eb207..671d8dac199c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/QuadrilateralInterface.cs @@ -104,7 +104,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; + Option quadrilateralType = default; while (utf8JsonReader.Read()) { @@ -122,7 +122,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,10 +130,13 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class QuadrilateralInterface."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class QuadrilateralInterface.", nameof(quadrilateralType)); - return new QuadrilateralInterface(quadrilateralType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class QuadrilateralInterface."); + + return new QuadrilateralInterface(quadrilateralType.Value!); } /// @@ -160,6 +163,9 @@ public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadril /// public void WriteProperties(ref Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateralInterface.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralInterface.QuadrilateralType), "Property is required for class QuadrilateralInterface."); + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs index 5ecf54003200..b63c0cbc81e8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ReadOnlyFirst.cs @@ -38,26 +38,40 @@ public partial class ReadOnlyFirst : IEquatable, IValidatableObj /// bar /// baz [JsonConstructor] - public ReadOnlyFirst(string bar, string baz) + public ReadOnlyFirst(Option bar = default, Option baz = default) { - Bar = bar; - Baz = baz; + BarOption = bar; + BazOption = baz; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string? Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Baz + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BazOption { get; private set; } /// /// Gets or Sets Baz /// [JsonPropertyName("baz")] - public string Baz { get; set; } + public string? Baz { get { return this. BazOption; } set { this.BazOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,7 +123,9 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -149,8 +165,8 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; - string? baz = default; + Option bar = default; + Option baz = default; while (utf8JsonReader.Read()) { @@ -168,10 +184,10 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; case "baz": - baz = utf8JsonReader.GetString(); + baz = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -179,11 +195,11 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class ReadOnlyFirst."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class ReadOnlyFirst."); - if (baz == null) - throw new ArgumentNullException(nameof(baz), "Property is required for class ReadOnlyFirst."); + if (baz.IsSet && baz.Value == null) + throw new ArgumentNullException(nameof(baz), "Property is not nullable for class ReadOnlyFirst."); return new ReadOnlyFirst(bar, baz); } @@ -212,8 +228,17 @@ public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, J /// public void WriteProperties(ref Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", readOnlyFirst.Bar); - writer.WriteString("baz", readOnlyFirst.Baz); + if (readOnlyFirst.BarOption.IsSet && readOnlyFirst.Bar == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Bar), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BazOption.IsSet && readOnlyFirst.Baz == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Baz), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BarOption.IsSet) + writer.WriteString("bar", readOnlyFirst.Bar); + + if (readOnlyFirst.BazOption.IsSet) + writer.WriteString("baz", readOnlyFirst.Baz); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RequiredClass.cs new file mode 100644 index 000000000000..aa44204c380c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RequiredClass.cs @@ -0,0 +1,2388 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = UseSourceGeneration.Client.ClientUtils; +using System.Text.Json.Serialization.Metadata; +using UseSourceGeneration.Client; + +namespace UseSourceGeneration.Model +{ + /// + /// RequiredClass + /// + public partial class RequiredClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// requiredNotNullableDateProp + /// requiredNotnullableArrayOfString + /// requiredNotnullableBooleanProp + /// requiredNotnullableDatetimeProp + /// requiredNotnullableEnumInteger + /// requiredNotnullableEnumIntegerOnly + /// requiredNotnullableEnumString + /// requiredNotnullableOuterEnumDefaultValue + /// requiredNotnullableStringProp + /// requiredNotnullableUuid + /// requiredNotnullableintegerProp + /// requiredNullableArrayOfString + /// requiredNullableBooleanProp + /// requiredNullableDateProp + /// requiredNullableDatetimeProp + /// requiredNullableEnumInteger + /// requiredNullableEnumIntegerOnly + /// requiredNullableEnumString + /// requiredNullableIntegerProp + /// requiredNullableOuterEnumDefaultValue + /// requiredNullableStringProp + /// requiredNullableUuid + /// notRequiredNotnullableDateProp + /// notRequiredNotnullableintegerProp + /// notRequiredNullableDateProp + /// notRequiredNullableIntegerProp + /// notrequiredNotnullableArrayOfString + /// notrequiredNotnullableBooleanProp + /// notrequiredNotnullableDatetimeProp + /// notrequiredNotnullableEnumInteger + /// notrequiredNotnullableEnumIntegerOnly + /// notrequiredNotnullableEnumString + /// notrequiredNotnullableOuterEnumDefaultValue + /// notrequiredNotnullableStringProp + /// notrequiredNotnullableUuid + /// notrequiredNullableArrayOfString + /// notrequiredNullableBooleanProp + /// notrequiredNullableDatetimeProp + /// notrequiredNullableEnumInteger + /// notrequiredNullableEnumIntegerOnly + /// notrequiredNullableEnumString + /// notrequiredNullableOuterEnumDefaultValue + /// notrequiredNullableStringProp + /// notrequiredNullableUuid + [JsonConstructor] + public RequiredClass(DateOnly requiredNotNullableDateProp, List requiredNotnullableArrayOfString, bool requiredNotnullableBooleanProp, DateTime requiredNotnullableDatetimeProp, RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger, RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly, RequiredNotnullableEnumStringEnum requiredNotnullableEnumString, OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue, string requiredNotnullableStringProp, Guid requiredNotnullableUuid, int requiredNotnullableintegerProp, List? requiredNullableArrayOfString = default, bool? requiredNullableBooleanProp = default, DateOnly? requiredNullableDateProp = default, DateTime? requiredNullableDatetimeProp = default, RequiredNullableEnumIntegerEnum? requiredNullableEnumInteger = default, RequiredNullableEnumIntegerOnlyEnum? requiredNullableEnumIntegerOnly = default, RequiredNullableEnumStringEnum? requiredNullableEnumString = default, int? requiredNullableIntegerProp = default, OuterEnumDefaultValue? requiredNullableOuterEnumDefaultValue = default, string? requiredNullableStringProp = default, Guid? requiredNullableUuid = default, Option notRequiredNotnullableDateProp = default, Option notRequiredNotnullableintegerProp = default, Option notRequiredNullableDateProp = default, Option notRequiredNullableIntegerProp = default, Option?> notrequiredNotnullableArrayOfString = default, Option notrequiredNotnullableBooleanProp = default, Option notrequiredNotnullableDatetimeProp = default, Option notrequiredNotnullableEnumInteger = default, Option notrequiredNotnullableEnumIntegerOnly = default, Option notrequiredNotnullableEnumString = default, Option notrequiredNotnullableOuterEnumDefaultValue = default, Option notrequiredNotnullableStringProp = default, Option notrequiredNotnullableUuid = default, Option?> notrequiredNullableArrayOfString = default, Option notrequiredNullableBooleanProp = default, Option notrequiredNullableDatetimeProp = default, Option notrequiredNullableEnumInteger = default, Option notrequiredNullableEnumIntegerOnly = default, Option notrequiredNullableEnumString = default, Option notrequiredNullableOuterEnumDefaultValue = default, Option notrequiredNullableStringProp = default, Option notrequiredNullableUuid = default) + { + RequiredNotNullableDateProp = requiredNotNullableDateProp; + RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + RequiredNotnullableEnumString = requiredNotnullableEnumString; + RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + RequiredNotnullableStringProp = requiredNotnullableStringProp; + RequiredNotnullableUuid = requiredNotnullableUuid; + RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + RequiredNullableArrayOfString = requiredNullableArrayOfString; + RequiredNullableBooleanProp = requiredNullableBooleanProp; + RequiredNullableDateProp = requiredNullableDateProp; + RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + RequiredNullableEnumInteger = requiredNullableEnumInteger; + RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + RequiredNullableEnumString = requiredNullableEnumString; + RequiredNullableIntegerProp = requiredNullableIntegerProp; + RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + RequiredNullableStringProp = requiredNullableStringProp; + RequiredNullableUuid = requiredNullableUuid; + NotRequiredNotnullableDatePropOption = notRequiredNotnullableDateProp; + NotRequiredNotnullableintegerPropOption = notRequiredNotnullableintegerProp; + NotRequiredNullableDatePropOption = notRequiredNullableDateProp; + NotRequiredNullableIntegerPropOption = notRequiredNullableIntegerProp; + NotrequiredNotnullableArrayOfStringOption = notrequiredNotnullableArrayOfString; + NotrequiredNotnullableBooleanPropOption = notrequiredNotnullableBooleanProp; + NotrequiredNotnullableDatetimePropOption = notrequiredNotnullableDatetimeProp; + NotrequiredNotnullableEnumIntegerOption = notrequiredNotnullableEnumInteger; + NotrequiredNotnullableEnumIntegerOnlyOption = notrequiredNotnullableEnumIntegerOnly; + NotrequiredNotnullableEnumStringOption = notrequiredNotnullableEnumString; + NotrequiredNotnullableOuterEnumDefaultValueOption = notrequiredNotnullableOuterEnumDefaultValue; + NotrequiredNotnullableStringPropOption = notrequiredNotnullableStringProp; + NotrequiredNotnullableUuidOption = notrequiredNotnullableUuid; + NotrequiredNullableArrayOfStringOption = notrequiredNullableArrayOfString; + NotrequiredNullableBooleanPropOption = notrequiredNullableBooleanProp; + NotrequiredNullableDatetimePropOption = notrequiredNullableDatetimeProp; + NotrequiredNullableEnumIntegerOption = notrequiredNullableEnumInteger; + NotrequiredNullableEnumIntegerOnlyOption = notrequiredNullableEnumIntegerOnly; + NotrequiredNullableEnumStringOption = notrequiredNullableEnumString; + NotrequiredNullableOuterEnumDefaultValueOption = notrequiredNullableOuterEnumDefaultValue; + NotrequiredNullableStringPropOption = notrequiredNullableStringProp; + NotrequiredNullableUuidOption = notrequiredNullableUuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum? RequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerEnumToJsonValue(RequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [JsonPropertyName("required_notnullable_enum_integer")] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum? RequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(RequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("required_notnullable_enum_integer_only")] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNotnullableEnumString + /// + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumStringEnum RequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumStringEnum? RequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNotnullableEnumStringEnumToJsonValue(RequiredNotnullableEnumStringEnum value) + { + if (value == RequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [JsonPropertyName("required_notnullable_enum_string")] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerEnum RequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerEnum? RequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerEnumToJsonValue(RequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [JsonPropertyName("required_nullable_enum_integer")] + public RequiredNullableEnumIntegerEnum? RequiredNullableEnumInteger { get; set; } + + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerOnlyEnumToJsonValue(RequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("required_nullable_enum_integer_only")] + public RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNullableEnumString + /// + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumStringEnum RequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumStringEnum? RequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string? RequiredNullableEnumStringEnumToJsonValue(RequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == RequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [JsonPropertyName("required_nullable_enum_string")] + public RequiredNullableEnumStringEnum? RequiredNullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum NotrequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerEnumToJsonValue(NotrequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [JsonPropertyName("notrequired_notnullable_enum_integer")] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get { return this.NotrequiredNotnullableEnumIntegerOption; } set { this.NotrequiredNotnullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum NotrequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_notnullable_enum_integer_only")] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get { return this.NotrequiredNotnullableEnumIntegerOnlyOption; } set { this.NotrequiredNotnullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumString + /// + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum NotrequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNotnullableEnumStringEnumToJsonValue(NotrequiredNotnullableEnumStringEnum? value) + { + if (value == NotrequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [JsonPropertyName("notrequired_notnullable_enum_string")] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get { return this.NotrequiredNotnullableEnumStringOption; } set { this.NotrequiredNotnullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get { return this.NotrequiredNotnullableOuterEnumDefaultValueOption; } set { this.NotrequiredNotnullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum NotrequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerEnumToJsonValue(NotrequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [JsonPropertyName("notrequired_nullable_enum_integer")] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get { return this.NotrequiredNullableEnumIntegerOption; } set { this.NotrequiredNullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum NotrequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_nullable_enum_integer_only")] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get { return this.NotrequiredNullableEnumIntegerOnlyOption; } set { this.NotrequiredNullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumString + /// + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumStringEnum NotrequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string? NotrequiredNullableEnumStringEnumToJsonValue(NotrequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == NotrequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [JsonPropertyName("notrequired_nullable_enum_string")] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get { return this.NotrequiredNullableEnumStringOption; } set { this.NotrequiredNullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get { return this.NotrequiredNullableOuterEnumDefaultValueOption; } set { this.NotrequiredNullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [JsonPropertyName("required_not_nullable_date_prop")] + public DateOnly RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [JsonPropertyName("required_notnullable_array_of_string")] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [JsonPropertyName("required_notnullable_boolean_prop")] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [JsonPropertyName("required_notnullable_datetime_prop")] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [JsonPropertyName("required_notnullable_string_prop")] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_notnullable_uuid")] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [JsonPropertyName("required_notnullableinteger_prop")] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [JsonPropertyName("required_nullable_array_of_string")] + public List? RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [JsonPropertyName("required_nullable_boolean_prop")] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [JsonPropertyName("required_nullable_date_prop")] + public DateOnly? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [JsonPropertyName("required_nullable_datetime_prop")] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [JsonPropertyName("required_nullable_integer_prop")] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [JsonPropertyName("required_nullable_string_prop")] + public string? RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_nullable_uuid")] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Used to track the state of NotRequiredNotnullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [JsonPropertyName("not_required_notnullable_date_prop")] + public DateOnly? NotRequiredNotnullableDateProp { get { return this. NotRequiredNotnullableDatePropOption; } set { this.NotRequiredNotnullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNotnullableintegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableintegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [JsonPropertyName("not_required_notnullableinteger_prop")] + public int? NotRequiredNotnullableintegerProp { get { return this. NotRequiredNotnullableintegerPropOption; } set { this.NotRequiredNotnullableintegerPropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [JsonPropertyName("not_required_nullable_date_prop")] + public DateOnly? NotRequiredNullableDateProp { get { return this. NotRequiredNullableDatePropOption; } set { this.NotRequiredNullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableIntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableIntegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [JsonPropertyName("not_required_nullable_integer_prop")] + public int? NotRequiredNullableIntegerProp { get { return this. NotRequiredNullableIntegerPropOption; } set { this.NotRequiredNullableIntegerPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> NotrequiredNotnullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [JsonPropertyName("notrequired_notnullable_array_of_string")] + public List? NotrequiredNotnullableArrayOfString { get { return this. NotrequiredNotnullableArrayOfStringOption; } set { this.NotrequiredNotnullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [JsonPropertyName("notrequired_notnullable_boolean_prop")] + public bool? NotrequiredNotnullableBooleanProp { get { return this. NotrequiredNotnullableBooleanPropOption; } set { this.NotrequiredNotnullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [JsonPropertyName("notrequired_notnullable_datetime_prop")] + public DateTime? NotrequiredNotnullableDatetimeProp { get { return this. NotrequiredNotnullableDatetimePropOption; } set { this.NotrequiredNotnullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [JsonPropertyName("notrequired_notnullable_string_prop")] + public string? NotrequiredNotnullableStringProp { get { return this. NotrequiredNotnullableStringPropOption; } set { this.NotrequiredNotnullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_notnullable_uuid")] + public Guid? NotrequiredNotnullableUuid { get { return this. NotrequiredNotnullableUuidOption; } set { this.NotrequiredNotnullableUuidOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> NotrequiredNullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [JsonPropertyName("notrequired_nullable_array_of_string")] + public List? NotrequiredNullableArrayOfString { get { return this. NotrequiredNullableArrayOfStringOption; } set { this.NotrequiredNullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [JsonPropertyName("notrequired_nullable_boolean_prop")] + public bool? NotrequiredNullableBooleanProp { get { return this. NotrequiredNullableBooleanPropOption; } set { this.NotrequiredNullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [JsonPropertyName("notrequired_nullable_datetime_prop")] + public DateTime? NotrequiredNullableDatetimeProp { get { return this. NotrequiredNullableDatetimePropOption; } set { this.NotrequiredNullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [JsonPropertyName("notrequired_nullable_string_prop")] + public string? NotrequiredNullableStringProp { get { return this. NotrequiredNullableStringPropOption; } set { this.NotrequiredNullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_nullable_uuid")] + public Guid? NotrequiredNullableUuid { get { return this. NotrequiredNullableUuidOption; } set { this.NotrequiredNullableUuidOption = new(value); } } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RequiredClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RequiredNotNullableDateProp + /// + public static string RequiredNotNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNotnullableDatetimeProp + /// + public static string RequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize RequiredNullableDateProp + /// + public static string RequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNullableDatetimeProp + /// + public static string RequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotRequiredNotnullableDateProp + /// + public static string NotRequiredNotnullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotRequiredNullableDateProp + /// + public static string NotRequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotrequiredNotnullableDatetimeProp + /// + public static string NotrequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotrequiredNullableDatetimeProp + /// + public static string NotrequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RequiredClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requiredNotNullableDateProp = default; + Option?> requiredNotnullableArrayOfString = default; + Option requiredNotnullableBooleanProp = default; + Option requiredNotnullableDatetimeProp = default; + Option requiredNotnullableEnumInteger = default; + Option requiredNotnullableEnumIntegerOnly = default; + Option requiredNotnullableEnumString = default; + Option requiredNotnullableOuterEnumDefaultValue = default; + Option requiredNotnullableStringProp = default; + Option requiredNotnullableUuid = default; + Option requiredNotnullableintegerProp = default; + Option?> requiredNullableArrayOfString = default; + Option requiredNullableBooleanProp = default; + Option requiredNullableDateProp = default; + Option requiredNullableDatetimeProp = default; + Option requiredNullableEnumInteger = default; + Option requiredNullableEnumIntegerOnly = default; + Option requiredNullableEnumString = default; + Option requiredNullableIntegerProp = default; + Option requiredNullableOuterEnumDefaultValue = default; + Option requiredNullableStringProp = default; + Option requiredNullableUuid = default; + Option notRequiredNotnullableDateProp = default; + Option notRequiredNotnullableintegerProp = default; + Option notRequiredNullableDateProp = default; + Option notRequiredNullableIntegerProp = default; + Option?> notrequiredNotnullableArrayOfString = default; + Option notrequiredNotnullableBooleanProp = default; + Option notrequiredNotnullableDatetimeProp = default; + Option notrequiredNotnullableEnumInteger = default; + Option notrequiredNotnullableEnumIntegerOnly = default; + Option notrequiredNotnullableEnumString = default; + Option notrequiredNotnullableOuterEnumDefaultValue = default; + Option notrequiredNotnullableStringProp = default; + Option notrequiredNotnullableUuid = default; + Option?> notrequiredNullableArrayOfString = default; + Option notrequiredNullableBooleanProp = default; + Option notrequiredNullableDatetimeProp = default; + Option notrequiredNullableEnumInteger = default; + Option notrequiredNullableEnumIntegerOnly = default; + Option notrequiredNullableEnumString = default; + Option notrequiredNullableOuterEnumDefaultValue = default; + Option notrequiredNullableStringProp = default; + Option notrequiredNullableUuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "required_not_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "required_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumInteger = new Option((RequiredClass.RequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumIntegerOnly = new Option((RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_string": + string? requiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableEnumStringRawValue != null) + requiredNotnullableEnumString = new Option(RequiredClass.RequiredNotnullableEnumStringEnumFromStringOrDefault(requiredNotnullableEnumStringRawValue)); + break; + case "required_notnullable_outerEnumDefaultValue": + string? requiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableOuterEnumDefaultValueRawValue != null) + requiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "required_notnullable_string_prop": + requiredNotnullableStringProp = new Option(utf8JsonReader.GetString()!); + break; + case "required_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumInteger = new Option((RequiredClass.RequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumIntegerOnly = new Option((RequiredClass.RequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_string": + string? requiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNullableEnumStringRawValue != null) + requiredNullableEnumString = new Option(RequiredClass.RequiredNullableEnumStringEnumFromStringOrDefault(requiredNullableEnumStringRawValue)); + break; + case "required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_outerEnumDefaultValue": + string? requiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + requiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNullableOuterEnumDefaultValueRawValue)); + break; + case "required_nullable_string_prop": + requiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "not_required_notnullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "not_required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notrequired_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumInteger = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_string": + string? notrequiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableEnumStringRawValue != null) + notrequiredNotnullableEnumString = new Option(RequiredClass.NotrequiredNotnullableEnumStringEnumFromStringOrDefault(notrequiredNotnullableEnumStringRawValue)); + break; + case "notrequired_notnullable_outerEnumDefaultValue": + string? notrequiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableOuterEnumDefaultValueRawValue != null) + notrequiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_notnullable_string_prop": + notrequiredNotnullableStringProp = new Option(utf8JsonReader.GetString()!); + break; + case "notrequired_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "notrequired_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumInteger = new Option((RequiredClass.NotrequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_string": + string? notrequiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableEnumStringRawValue != null) + notrequiredNullableEnumString = new Option(RequiredClass.NotrequiredNullableEnumStringEnumFromStringOrDefault(notrequiredNullableEnumStringRawValue)); + break; + case "notrequired_nullable_outerEnumDefaultValue": + string? notrequiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableOuterEnumDefaultValueRawValue != null) + notrequiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_nullable_string_prop": + notrequiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + default: + break; + } + } + } + + if (!requiredNotNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotNullableDateProp)); + + if (!requiredNotnullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableArrayOfString)); + + if (!requiredNotnullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableBooleanProp)); + + if (!requiredNotnullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableDatetimeProp)); + + if (!requiredNotnullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumInteger)); + + if (!requiredNotnullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumIntegerOnly)); + + if (!requiredNotnullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumString)); + + if (!requiredNotnullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableOuterEnumDefaultValue)); + + if (!requiredNotnullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableStringProp)); + + if (!requiredNotnullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableUuid)); + + if (!requiredNotnullableintegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableintegerProp)); + + if (!requiredNullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableArrayOfString)); + + if (!requiredNullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableBooleanProp)); + + if (!requiredNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDateProp)); + + if (!requiredNullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDatetimeProp)); + + if (!requiredNullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumInteger)); + + if (!requiredNullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumIntegerOnly)); + + if (!requiredNullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumString)); + + if (!requiredNullableIntegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableIntegerProp)); + + if (!requiredNullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableOuterEnumDefaultValue)); + + if (!requiredNullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableStringProp)); + + if (!requiredNullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableUuid)); + + if (requiredNotNullableDateProp.IsSet && requiredNotNullableDateProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotNullableDateProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableArrayOfString.IsSet && requiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableBooleanProp.IsSet && requiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableDatetimeProp.IsSet && requiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumInteger.IsSet && requiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumIntegerOnly.IsSet && requiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumString.IsSet && requiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableOuterEnumDefaultValue.IsSet && requiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableStringProp.IsSet && requiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableUuid.IsSet && requiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableintegerProp.IsSet && requiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableDateProp.IsSet && notRequiredNotnullableDateProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableDateProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableintegerProp.IsSet && notRequiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableArrayOfString.IsSet && notrequiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableBooleanProp.IsSet && notrequiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableDatetimeProp.IsSet && notrequiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumInteger.IsSet && notrequiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumIntegerOnly.IsSet && notrequiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumString.IsSet && notrequiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableOuterEnumDefaultValue.IsSet && notrequiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableStringProp.IsSet && notrequiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableUuid.IsSet && notrequiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + return new RequiredClass(requiredNotNullableDateProp.Value!.Value!, requiredNotnullableArrayOfString.Value!, requiredNotnullableBooleanProp.Value!.Value!, requiredNotnullableDatetimeProp.Value!.Value!, requiredNotnullableEnumInteger.Value!.Value!, requiredNotnullableEnumIntegerOnly.Value!.Value!, requiredNotnullableEnumString.Value!.Value!, requiredNotnullableOuterEnumDefaultValue.Value!.Value!, requiredNotnullableStringProp.Value!, requiredNotnullableUuid.Value!.Value!, requiredNotnullableintegerProp.Value!.Value!, requiredNullableArrayOfString.Value!, requiredNullableBooleanProp.Value!, requiredNullableDateProp.Value!, requiredNullableDatetimeProp.Value!, requiredNullableEnumInteger.Value!, requiredNullableEnumIntegerOnly.Value!, requiredNullableEnumString.Value!, requiredNullableIntegerProp.Value!, requiredNullableOuterEnumDefaultValue.Value!, requiredNullableStringProp.Value!, requiredNullableUuid.Value!, notRequiredNotnullableDateProp, notRequiredNotnullableintegerProp, notRequiredNullableDateProp, notRequiredNullableIntegerProp, notrequiredNotnullableArrayOfString, notrequiredNotnullableBooleanProp, notrequiredNotnullableDatetimeProp, notrequiredNotnullableEnumInteger, notrequiredNotnullableEnumIntegerOnly, notrequiredNotnullableEnumString, notrequiredNotnullableOuterEnumDefaultValue, notrequiredNotnullableStringProp, notrequiredNotnullableUuid, notrequiredNullableArrayOfString, notrequiredNullableBooleanProp, notrequiredNullableDatetimeProp, notrequiredNullableEnumInteger, notrequiredNullableEnumIntegerOnly, notrequiredNullableEnumString, notrequiredNullableOuterEnumDefaultValue, notrequiredNullableStringProp, notrequiredNullableUuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, requiredClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + if (requiredClass.RequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.RequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet && requiredClass.NotrequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet && requiredClass.NotrequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + writer.WriteString("required_not_nullable_date_prop", requiredClass.RequiredNotNullableDateProp.ToString(RequiredNotNullableDatePropFormat)); + + writer.WritePropertyName("required_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNotnullableArrayOfString, jsonSerializerOptions); + writer.WriteBoolean("required_notnullable_boolean_prop", requiredClass.RequiredNotnullableBooleanProp); + + writer.WriteString("required_notnullable_datetime_prop", requiredClass.RequiredNotnullableDatetimeProp.ToString(RequiredNotnullableDatetimePropFormat)); + + writer.WriteNumber("required_notnullable_enum_integer", RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNotnullableEnumInteger)); + + writer.WriteNumber("required_notnullable_enum_integer_only", RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNotnullableEnumIntegerOnly)); + + var requiredNotnullableEnumStringRawValue = RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClass.RequiredNotnullableEnumString); + writer.WriteString("required_notnullable_enum_string", requiredNotnullableEnumStringRawValue); + var requiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNotnullableOuterEnumDefaultValue); + writer.WriteString("required_notnullable_outerEnumDefaultValue", requiredNotnullableOuterEnumDefaultValueRawValue); + + writer.WriteString("required_notnullable_string_prop", requiredClass.RequiredNotnullableStringProp); + + writer.WriteString("required_notnullable_uuid", requiredClass.RequiredNotnullableUuid); + + writer.WriteNumber("required_notnullableinteger_prop", requiredClass.RequiredNotnullableintegerProp); + + if (requiredClass.RequiredNullableArrayOfString != null) + { + writer.WritePropertyName("required_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("required_nullable_array_of_string"); + if (requiredClass.RequiredNullableBooleanProp != null) + writer.WriteBoolean("required_nullable_boolean_prop", requiredClass.RequiredNullableBooleanProp.Value); + else + writer.WriteNull("required_nullable_boolean_prop"); + + if (requiredClass.RequiredNullableDateProp != null) + writer.WriteString("required_nullable_date_prop", requiredClass.RequiredNullableDateProp.Value.ToString(RequiredNullableDatePropFormat)); + else + writer.WriteNull("required_nullable_date_prop"); + + if (requiredClass.RequiredNullableDatetimeProp != null) + writer.WriteString("required_nullable_datetime_prop", requiredClass.RequiredNullableDatetimeProp.Value.ToString(RequiredNullableDatetimePropFormat)); + else + writer.WriteNull("required_nullable_datetime_prop"); + + if (requiredClass.RequiredNullableEnumInteger != null) + writer.WriteNumber("required_nullable_enum_integer", RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNullableEnumInteger.Value)); + else + writer.WriteNull("required_nullable_enum_integer"); + + if (requiredClass.RequiredNullableEnumIntegerOnly != null) + writer.WriteNumber("required_nullable_enum_integer_only", RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNullableEnumIntegerOnly.Value)); + else + writer.WriteNull("required_nullable_enum_integer_only"); + + var requiredNullableEnumStringRawValue = RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClass.RequiredNullableEnumString!.Value); + if (requiredNullableEnumStringRawValue != null) + writer.WriteString("required_nullable_enum_string", requiredNullableEnumStringRawValue); + else + writer.WriteNull("required_nullable_enum_string"); + + if (requiredClass.RequiredNullableIntegerProp != null) + writer.WriteNumber("required_nullable_integer_prop", requiredClass.RequiredNullableIntegerProp.Value); + else + writer.WriteNull("required_nullable_integer_prop"); + + if (requiredClass.RequiredNullableOuterEnumDefaultValue == null) + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + else + { + var requiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNullableOuterEnumDefaultValue.Value); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + writer.WriteString("required_nullable_outerEnumDefaultValue", requiredNullableOuterEnumDefaultValueRawValue); + else + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + } + + if (requiredClass.RequiredNullableStringProp != null) + writer.WriteString("required_nullable_string_prop", requiredClass.RequiredNullableStringProp); + else + writer.WriteNull("required_nullable_string_prop"); + + if (requiredClass.RequiredNullableUuid != null) + writer.WriteString("required_nullable_uuid", requiredClass.RequiredNullableUuid.Value); + else + writer.WriteNull("required_nullable_uuid"); + + if (requiredClass.NotRequiredNotnullableDatePropOption.IsSet) + writer.WriteString("not_required_notnullable_date_prop", requiredClass.NotRequiredNotnullableDatePropOption.Value!.Value.ToString(NotRequiredNotnullableDatePropFormat)); + + if (requiredClass.NotRequiredNotnullableintegerPropOption.IsSet) + writer.WriteNumber("not_required_notnullableinteger_prop", requiredClass.NotRequiredNotnullableintegerPropOption.Value!.Value); + + if (requiredClass.NotRequiredNullableDatePropOption.IsSet) + if (requiredClass.NotRequiredNullableDatePropOption.Value != null) + writer.WriteString("not_required_nullable_date_prop", requiredClass.NotRequiredNullableDatePropOption.Value!.Value.ToString(NotRequiredNullableDatePropFormat)); + else + writer.WriteNull("not_required_nullable_date_prop"); + + if (requiredClass.NotRequiredNullableIntegerPropOption.IsSet) + if (requiredClass.NotRequiredNullableIntegerPropOption.Value != null) + writer.WriteNumber("not_required_nullable_integer_prop", requiredClass.NotRequiredNullableIntegerPropOption.Value!.Value); + else + writer.WriteNull("not_required_nullable_integer_prop"); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet) + { + writer.WritePropertyName("notrequired_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNotnullableArrayOfString, jsonSerializerOptions); + } + if (requiredClass.NotrequiredNotnullableBooleanPropOption.IsSet) + writer.WriteBoolean("notrequired_notnullable_boolean_prop", requiredClass.NotrequiredNotnullableBooleanPropOption.Value!.Value); + + if (requiredClass.NotrequiredNotnullableDatetimePropOption.IsSet) + writer.WriteString("notrequired_notnullable_datetime_prop", requiredClass.NotrequiredNotnullableDatetimePropOption.Value!.Value.ToString(NotrequiredNotnullableDatetimePropFormat)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer", RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOption.Value!.Value)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer_only", RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.Value!.Value)); + + var notrequiredNotnullableEnumStringRawValue = RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumStringOption.Value!.Value); + writer.WriteString("notrequired_notnullable_enum_string", notrequiredNotnullableEnumStringRawValue); + if (requiredClass.NotrequiredNotnullableOuterEnumDefaultValueOption.IsSet) + { + var notrequiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNotnullableOuterEnumDefaultValue!.Value); + writer.WriteString("notrequired_notnullable_outerEnumDefaultValue", notrequiredNotnullableOuterEnumDefaultValueRawValue); + } + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet) + writer.WriteString("notrequired_notnullable_string_prop", requiredClass.NotrequiredNotnullableStringProp); + + if (requiredClass.NotrequiredNotnullableUuidOption.IsSet) + writer.WriteString("notrequired_notnullable_uuid", requiredClass.NotrequiredNotnullableUuidOption.Value!.Value); + + if (requiredClass.NotrequiredNullableArrayOfStringOption.IsSet) + if (requiredClass.NotrequiredNullableArrayOfStringOption.Value != null) + { + writer.WritePropertyName("notrequired_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("notrequired_nullable_array_of_string"); + if (requiredClass.NotrequiredNullableBooleanPropOption.IsSet) + if (requiredClass.NotrequiredNullableBooleanPropOption.Value != null) + writer.WriteBoolean("notrequired_nullable_boolean_prop", requiredClass.NotrequiredNullableBooleanPropOption.Value!.Value); + else + writer.WriteNull("notrequired_nullable_boolean_prop"); + + if (requiredClass.NotrequiredNullableDatetimePropOption.IsSet) + if (requiredClass.NotrequiredNullableDatetimePropOption.Value != null) + writer.WriteString("notrequired_nullable_datetime_prop", requiredClass.NotrequiredNullableDatetimePropOption.Value!.Value.ToString(NotrequiredNullableDatetimePropFormat)); + else + writer.WriteNull("notrequired_nullable_datetime_prop"); + + if (requiredClass.NotrequiredNullableEnumIntegerOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer", RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOption.Value!.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer"); + + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer_only", RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value!.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer_only"); + + var notrequiredNullableEnumStringRawValue = RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNullableEnumStringOption.Value!.Value); + if (notrequiredNullableEnumStringRawValue != null) + writer.WriteString("notrequired_nullable_enum_string", notrequiredNullableEnumStringRawValue); + else + writer.WriteNull("notrequired_nullable_enum_string"); + + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.IsSet) + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption!.Value != null) + { + var notrequiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value!.Value); + writer.WriteString("notrequired_nullable_outerEnumDefaultValue", notrequiredNullableOuterEnumDefaultValueRawValue); + } + else + writer.WriteNull("notrequired_nullable_outerEnumDefaultValue"); + if (requiredClass.NotrequiredNullableStringPropOption.IsSet) + if (requiredClass.NotrequiredNullableStringPropOption.Value != null) + writer.WriteString("notrequired_nullable_string_prop", requiredClass.NotrequiredNullableStringProp); + else + writer.WriteNull("notrequired_nullable_string_prop"); + + if (requiredClass.NotrequiredNullableUuidOption.IsSet) + if (requiredClass.NotrequiredNullableUuidOption.Value != null) + writer.WriteString("notrequired_nullable_uuid", requiredClass.NotrequiredNullableUuidOption.Value!.Value); + else + writer.WriteNull("notrequired_nullable_uuid"); + } + } + + /// + /// The RequiredClassSerializationContext + /// + [JsonSourceGenerationOptions(WriteIndented = true, GenerationMode = JsonSourceGenerationMode.Metadata | JsonSourceGenerationMode.Serialization)] + [JsonSerializable(typeof(RequiredClass))] + public partial class RequiredClassSerializationContext : JsonSerializerContext { } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs index 454e16dd0f52..3a3bf398ebc6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Return.cs @@ -37,19 +37,26 @@ public partial class Return : IValidatableObject /// /// varReturn [JsonConstructor] - public Return(int varReturn) + public Return(Option varReturn = default) { - VarReturn = varReturn; + VarReturnOption = varReturn; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarReturn + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarReturnOption { get; private set; } + /// /// Gets or Sets VarReturn /// [JsonPropertyName("return")] - public int VarReturn { get; set; } + public int? VarReturn { get { return this. VarReturnOption; } set { this.VarReturnOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varReturn = default; + Option varReturn = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "return": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varReturn = utf8JsonReader.GetInt32(); + varReturn = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -131,10 +138,10 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (varReturn == null) - throw new ArgumentNullException(nameof(varReturn), "Property is required for class Return."); + if (varReturn.IsSet && varReturn.Value == null) + throw new ArgumentNullException(nameof(varReturn), "Property is not nullable for class Return."); - return new Return(varReturn.Value); + return new Return(varReturn); } /// @@ -161,7 +168,8 @@ public override void Write(Utf8JsonWriter writer, Return varReturn, JsonSerializ /// public void WriteProperties(ref Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("return", varReturn.VarReturn); + if (varReturn.VarReturnOption.IsSet) + writer.WriteNumber("return", varReturn.VarReturnOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs index 3485ce95577c..7597e889587e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHash.cs @@ -38,26 +38,40 @@ public partial class RolesReportsHash : IValidatableObject /// role /// roleUuid [JsonConstructor] - public RolesReportsHash(RolesReportsHashRole role, Guid roleUuid) + public RolesReportsHash(Option role = default, Option roleUuid = default) { - Role = role; - RoleUuid = roleUuid; + RoleOption = role; + RoleUuidOption = roleUuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Role + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleOption { get; private set; } + /// /// Gets or Sets Role /// [JsonPropertyName("role")] - public RolesReportsHashRole Role { get; set; } + public RolesReportsHashRole? Role { get { return this. RoleOption; } set { this.RoleOption = new(value); } } + + /// + /// Used to track the state of RoleUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleUuidOption { get; private set; } /// /// Gets or Sets RoleUuid /// [JsonPropertyName("role_uuid")] - public Guid RoleUuid { get; set; } + public Guid? RoleUuid { get { return this. RoleUuidOption; } set { this.RoleUuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - RolesReportsHashRole? role = default; - Guid? roleUuid = default; + Option role = default; + Option roleUuid = default; while (utf8JsonReader.Read()) { @@ -133,11 +147,11 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty { case "role": if (utf8JsonReader.TokenType != JsonTokenType.Null) - role = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + role = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "role_uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - roleUuid = utf8JsonReader.GetGuid(); + roleUuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -145,13 +159,13 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (role == null) - throw new ArgumentNullException(nameof(role), "Property is required for class RolesReportsHash."); + if (role.IsSet && role.Value == null) + throw new ArgumentNullException(nameof(role), "Property is not nullable for class RolesReportsHash."); - if (roleUuid == null) - throw new ArgumentNullException(nameof(roleUuid), "Property is required for class RolesReportsHash."); + if (roleUuid.IsSet && roleUuid.Value == null) + throw new ArgumentNullException(nameof(roleUuid), "Property is not nullable for class RolesReportsHash."); - return new RolesReportsHash(role, roleUuid.Value); + return new RolesReportsHash(role, roleUuid); } /// @@ -178,9 +192,16 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHash rolesReportsH /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("role"); - JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); - writer.WriteString("role_uuid", rolesReportsHash.RoleUuid); + if (rolesReportsHash.RoleOption.IsSet && rolesReportsHash.Role == null) + throw new ArgumentNullException(nameof(rolesReportsHash.Role), "Property is required for class RolesReportsHash."); + + if (rolesReportsHash.RoleOption.IsSet) + { + writer.WritePropertyName("role"); + JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); + } + if (rolesReportsHash.RoleUuidOption.IsSet) + writer.WriteString("role_uuid", rolesReportsHash.RoleUuidOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs index 9c20ab46bad7..d74e74a0cdbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/RolesReportsHashRole.cs @@ -37,19 +37,26 @@ public partial class RolesReportsHashRole : IValidatableObject /// /// name [JsonConstructor] - public RolesReportsHashRole(string name) + public RolesReportsHashRole(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class RolesReportsHashRole."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class RolesReportsHashRole."); return new RolesReportsHashRole(name); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHashRole rolesRepo /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", rolesReportsHashRole.Name); + if (rolesReportsHashRole.NameOption.IsSet && rolesReportsHashRole.Name == null) + throw new ArgumentNullException(nameof(rolesReportsHashRole.Name), "Property is required for class RolesReportsHashRole."); + + if (rolesReportsHashRole.NameOption.IsSet) + writer.WriteString("name", rolesReportsHashRole.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs index 39f7d8cc72f2..df238cd6fb8d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ScaleneTriangle.cs @@ -113,8 +113,8 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -132,10 +132,10 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -143,13 +143,19 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ScaleneTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class ScaleneTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(triangleType)); - return new ScaleneTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ScaleneTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class ScaleneTriangle."); + + return new ScaleneTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -176,7 +182,14 @@ public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangl /// public void WriteProperties(ref Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (scaleneTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.ShapeType), "Property is required for class ScaleneTriangle."); + + if (scaleneTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.TriangleType), "Property is required for class ScaleneTriangle."); + writer.WriteString("shapeType", scaleneTriangle.ShapeType); + writer.WriteString("triangleType", scaleneTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs index 7100b878d3bd..d7f628a58c9a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Shape.cs @@ -137,7 +137,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -188,7 +188,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,14 +196,17 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class Shape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class Shape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class Shape."); if (quadrilateral != null) - return new Shape(quadrilateral, shapeType); + return new Shape(quadrilateral, shapeType.Value!); if (triangle != null) - return new Shape(triangle, shapeType); + return new Shape(triangle, shapeType.Value!); throw new JsonException(); } @@ -242,6 +245,9 @@ public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) { + if (shape.ShapeType == null) + throw new ArgumentNullException(nameof(shape.ShapeType), "Property is required for class Shape."); + writer.WriteString("shapeType", shape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs index 0a994154af08..bd75259c1192 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeInterface.cs @@ -104,7 +104,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -122,7 +122,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,10 +130,13 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeInterface."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeInterface.", nameof(shapeType)); - return new ShapeInterface(shapeType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeInterface."); + + return new ShapeInterface(shapeType.Value!); } /// @@ -160,6 +163,9 @@ public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) { + if (shapeInterface.ShapeType == null) + throw new ArgumentNullException(nameof(shapeInterface.ShapeType), "Property is required for class ShapeInterface."); + writer.WriteString("shapeType", shapeInterface.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs index c0b313a2f362..b7063afd9a1c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ShapeOrNull.cs @@ -137,7 +137,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -188,7 +188,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -196,14 +196,17 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeOrNull."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeOrNull.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeOrNull."); if (quadrilateral != null) - return new ShapeOrNull(quadrilateral, shapeType); + return new ShapeOrNull(quadrilateral, shapeType.Value!); if (triangle != null) - return new ShapeOrNull(triangle, shapeType); + return new ShapeOrNull(triangle, shapeType.Value!); throw new JsonException(); } @@ -242,6 +245,9 @@ public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) { + if (shapeOrNull.ShapeType == null) + throw new ArgumentNullException(nameof(shapeOrNull.ShapeType), "Property is required for class ShapeOrNull."); + writer.WriteString("shapeType", shapeOrNull.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs index c41dcdc9dcf6..9e2ecd14d85e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SimpleQuadrilateral.cs @@ -113,8 +113,8 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; - string? shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -132,10 +132,10 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -143,13 +143,19 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class SimpleQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class SimpleQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(shapeType)); - return new SimpleQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class SimpleQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class SimpleQuadrilateral."); + + return new SimpleQuadrilateral(quadrilateralType.Value!, shapeType.Value!); } /// @@ -176,7 +182,14 @@ public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuad /// public void WriteProperties(ref Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (simpleQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.QuadrilateralType), "Property is required for class SimpleQuadrilateral."); + + if (simpleQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.ShapeType), "Property is required for class SimpleQuadrilateral."); + writer.WriteString("quadrilateralType", simpleQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", simpleQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs index 06b9d48e4696..4ce1e685dc69 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/SpecialModelName.cs @@ -38,26 +38,40 @@ public partial class SpecialModelName : IValidatableObject /// varSpecialModelName /// specialPropertyName [JsonConstructor] - public SpecialModelName(string varSpecialModelName, long specialPropertyName) + public SpecialModelName(Option varSpecialModelName = default, Option specialPropertyName = default) { - VarSpecialModelName = varSpecialModelName; - SpecialPropertyName = specialPropertyName; + VarSpecialModelNameOption = varSpecialModelName; + SpecialPropertyNameOption = specialPropertyName; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarSpecialModelName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarSpecialModelNameOption { get; private set; } + /// /// Gets or Sets VarSpecialModelName /// [JsonPropertyName("_special_model.name_")] - public string VarSpecialModelName { get; set; } + public string? VarSpecialModelName { get { return this. VarSpecialModelNameOption; } set { this.VarSpecialModelNameOption = new(value); } } + + /// + /// Used to track the state of SpecialPropertyName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SpecialPropertyNameOption { get; private set; } /// /// Gets or Sets SpecialPropertyName /// [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + public long? SpecialPropertyName { get { return this. SpecialPropertyNameOption; } set { this.SpecialPropertyNameOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varSpecialModelName = default; - long? specialPropertyName = default; + Option varSpecialModelName = default; + Option specialPropertyName = default; while (utf8JsonReader.Read()) { @@ -132,11 +146,11 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "_special_model.name_": - varSpecialModelName = utf8JsonReader.GetString(); + varSpecialModelName = new Option(utf8JsonReader.GetString()!); break; case "$special[property.name]": if (utf8JsonReader.TokenType != JsonTokenType.Null) - specialPropertyName = utf8JsonReader.GetInt64(); + specialPropertyName = new Option(utf8JsonReader.GetInt64()); break; default: break; @@ -144,13 +158,13 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varSpecialModelName == null) - throw new ArgumentNullException(nameof(varSpecialModelName), "Property is required for class SpecialModelName."); + if (varSpecialModelName.IsSet && varSpecialModelName.Value == null) + throw new ArgumentNullException(nameof(varSpecialModelName), "Property is not nullable for class SpecialModelName."); - if (specialPropertyName == null) - throw new ArgumentNullException(nameof(specialPropertyName), "Property is required for class SpecialModelName."); + if (specialPropertyName.IsSet && specialPropertyName.Value == null) + throw new ArgumentNullException(nameof(specialPropertyName), "Property is not nullable for class SpecialModelName."); - return new SpecialModelName(varSpecialModelName, specialPropertyName.Value); + return new SpecialModelName(varSpecialModelName, specialPropertyName); } /// @@ -177,8 +191,14 @@ public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelN /// public void WriteProperties(ref Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); - writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyName); + if (specialModelName.VarSpecialModelNameOption.IsSet && specialModelName.VarSpecialModelName == null) + throw new ArgumentNullException(nameof(specialModelName.VarSpecialModelName), "Property is required for class SpecialModelName."); + + if (specialModelName.VarSpecialModelNameOption.IsSet) + writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); + + if (specialModelName.SpecialPropertyNameOption.IsSet) + writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyNameOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs index 1bf8c4ad9a0b..a29366ecfa79 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Tag.cs @@ -38,26 +38,40 @@ public partial class Tag : IValidatableObject /// id /// name [JsonConstructor] - public Tag(long id, string name) + public Tag(Option id = default, Option name = default) { - Id = id; - Name = name; + IdOption = id; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -113,8 +127,8 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string? name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -133,10 +147,10 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -144,13 +158,13 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Tag."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Tag."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Tag."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Tag."); - return new Tag(id.Value, name); + return new Tag(id, name); } /// @@ -177,8 +191,14 @@ public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", tag.Id); - writer.WriteString("name", tag.Name); + if (tag.NameOption.IsSet && tag.Name == null) + throw new ArgumentNullException(nameof(tag.Name), "Property is required for class Tag."); + + if (tag.IdOption.IsSet) + writer.WriteNumber("id", tag.IdOption.Value!.Value); + + if (tag.NameOption.IsSet) + writer.WriteString("name", tag.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs index 4249ff2fb47b..c253c134a3ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordList.cs @@ -37,19 +37,26 @@ public partial class TestCollectionEndingWithWordList : IValidatableObject /// /// value [JsonConstructor] - public TestCollectionEndingWithWordList(string value) + public TestCollectionEndingWithWordList(Option value = default) { - Value = value; + ValueOption = value; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Value + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ValueOption { get; private set; } + /// /// Gets or Sets Value /// [JsonPropertyName("value")] - public string Value { get; set; } + public string? Value { get { return this. ValueOption; } set { this.ValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? value = default; + Option value = default; while (utf8JsonReader.Read()) { @@ -122,7 +129,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso switch (localVarJsonPropertyName) { case "value": - value = utf8JsonReader.GetString(); + value = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,8 +137,8 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso } } - if (value == null) - throw new ArgumentNullException(nameof(value), "Property is required for class TestCollectionEndingWithWordList."); + if (value.IsSet && value.Value == null) + throw new ArgumentNullException(nameof(value), "Property is not nullable for class TestCollectionEndingWithWordList."); return new TestCollectionEndingWithWordList(value); } @@ -160,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("value", testCollectionEndingWithWordList.Value); + if (testCollectionEndingWithWordList.ValueOption.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList.Value), "Property is required for class TestCollectionEndingWithWordList."); + + if (testCollectionEndingWithWordList.ValueOption.IsSet) + writer.WriteString("value", testCollectionEndingWithWordList.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs index ed130760a758..fe73bc2ded6e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestCollectionEndingWithWordListObject.cs @@ -37,19 +37,26 @@ public partial class TestCollectionEndingWithWordListObject : IValidatableObject /// /// testCollectionEndingWithWordList [JsonConstructor] - public TestCollectionEndingWithWordListObject(List testCollectionEndingWithWordList) + public TestCollectionEndingWithWordListObject(Option?> testCollectionEndingWithWordList = default) { - TestCollectionEndingWithWordList = testCollectionEndingWithWordList; + TestCollectionEndingWithWordListOption = testCollectionEndingWithWordList; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of TestCollectionEndingWithWordList + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> TestCollectionEndingWithWordListOption { get; private set; } + /// /// Gets or Sets TestCollectionEndingWithWordList /// [JsonPropertyName("TestCollectionEndingWithWordList")] - public List TestCollectionEndingWithWordList { get; set; } + public List? TestCollectionEndingWithWordList { get { return this. TestCollectionEndingWithWordListOption; } set { this.TestCollectionEndingWithWordListOption = new(value); } } /// /// Gets or Sets additional properties @@ -104,7 +111,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? testCollectionEndingWithWordList = default; + Option?> testCollectionEndingWithWordList = default; while (utf8JsonReader.Read()) { @@ -123,7 +130,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u { case "TestCollectionEndingWithWordList": if (utf8JsonReader.TokenType != JsonTokenType.Null) - testCollectionEndingWithWordList = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + testCollectionEndingWithWordList = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -131,8 +138,8 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u } } - if (testCollectionEndingWithWordList == null) - throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + if (testCollectionEndingWithWordList.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is not nullable for class TestCollectionEndingWithWordListObject."); return new TestCollectionEndingWithWordListObject(testCollectionEndingWithWordList); } @@ -161,8 +168,14 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("TestCollectionEndingWithWordList"); - JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet && testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet) + { + writer.WritePropertyName("TestCollectionEndingWithWordList"); + JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index dd3c3ec026a0..7c0d25ba730e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,26 +30,33 @@ namespace UseSourceGeneration.Model /// /// TestInlineFreeformAdditionalPropertiesRequest /// - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty [JsonConstructor] - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty) : base() + public TestInlineFreeformAdditionalPropertiesRequest(Option someProperty = default) { - SomeProperty = someProperty; + SomePropertyOption = someProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SomeProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SomePropertyOption { get; private set; } + /// /// Gets or Sets SomeProperty /// [JsonPropertyName("someProperty")] - public string SomeProperty { get; set; } + public string? SomeProperty { get { return this. SomePropertyOption; } set { this.SomePropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -65,7 +72,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -78,16 +84,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -115,7 +111,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? someProperty = default; + Option someProperty = default; while (utf8JsonReader.Read()) { @@ -133,7 +129,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR switch (localVarJsonPropertyName) { case "someProperty": - someProperty = utf8JsonReader.GetString(); + someProperty = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,8 +137,8 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR } } - if (someProperty == null) - throw new ArgumentNullException(nameof(someProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + if (someProperty.IsSet && someProperty.Value == null) + throw new ArgumentNullException(nameof(someProperty), "Property is not nullable for class TestInlineFreeformAdditionalPropertiesRequest."); return new TestInlineFreeformAdditionalPropertiesRequest(someProperty); } @@ -171,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, TestInlineFreeformAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet && testInlineFreeformAdditionalPropertiesRequest.SomeProperty == null) + throw new ArgumentNullException(nameof(testInlineFreeformAdditionalPropertiesRequest.SomeProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet) + writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs index bddcf663a293..932095793874 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Triangle.cs @@ -154,7 +154,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? triangleType = default; + Option triangleType = default; EquilateralTriangle? equilateralTriangle = null; IsoscelesTriangle? isoscelesTriangle = null; @@ -211,7 +211,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -219,17 +219,20 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class Triangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class Triangle.", nameof(triangleType)); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class Triangle."); if (equilateralTriangle != null) - return new Triangle(equilateralTriangle, triangleType); + return new Triangle(equilateralTriangle, triangleType.Value!); if (isoscelesTriangle != null) - return new Triangle(isoscelesTriangle, triangleType); + return new Triangle(isoscelesTriangle, triangleType.Value!); if (scaleneTriangle != null) - return new Triangle(scaleneTriangle, triangleType); + return new Triangle(scaleneTriangle, triangleType.Value!); throw new JsonException(); } @@ -273,6 +276,9 @@ public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) { + if (triangle.TriangleType == null) + throw new ArgumentNullException(nameof(triangle.TriangleType), "Property is required for class Triangle."); + writer.WriteString("triangleType", triangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs index adc70c646cb9..3e50cd4e3263 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/TriangleInterface.cs @@ -104,7 +104,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? triangleType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -122,7 +122,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -130,10 +130,13 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class TriangleInterface."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class TriangleInterface.", nameof(triangleType)); - return new TriangleInterface(triangleType); + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class TriangleInterface."); + + return new TriangleInterface(triangleType.Value!); } /// @@ -160,6 +163,9 @@ public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInte /// public void WriteProperties(ref Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) { + if (triangleInterface.TriangleType == null) + throw new ArgumentNullException(nameof(triangleInterface.TriangleType), "Property is required for class TriangleInterface."); + writer.WriteString("triangleType", triangleInterface.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs index 684c3ff5a2e0..c36799b77ed7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/User.cs @@ -35,114 +35,198 @@ public partial class User : IValidatableObject /// /// Initializes a new instance of the class. /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. /// email /// firstName /// id /// lastName /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. /// password /// phone /// User Status /// username - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. [JsonConstructor] - public User(string email, string firstName, long id, string lastName, Object objectWithNoDeclaredProps, string password, string phone, int userStatus, string username, Object? anyTypeProp = default, Object? anyTypePropNullable = default, Object? objectWithNoDeclaredPropsNullable = default) + public User(Option anyTypeProp = default, Option anyTypePropNullable = default, Option email = default, Option firstName = default, Option id = default, Option lastName = default, Option objectWithNoDeclaredProps = default, Option objectWithNoDeclaredPropsNullable = default, Option password = default, Option phone = default, Option userStatus = default, Option username = default) { - Email = email; - FirstName = firstName; - Id = id; - LastName = lastName; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - Password = password; - Phone = phone; - UserStatus = userStatus; - Username = username; - AnyTypeProp = anyTypeProp; - AnyTypePropNullable = anyTypePropNullable; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + AnyTypePropOption = anyTypeProp; + AnyTypePropNullableOption = anyTypePropNullable; + EmailOption = email; + FirstNameOption = firstName; + IdOption = id; + LastNameOption = lastName; + ObjectWithNoDeclaredPropsOption = objectWithNoDeclaredProps; + ObjectWithNoDeclaredPropsNullableOption = objectWithNoDeclaredPropsNullable; + PasswordOption = password; + PhoneOption = phone; + UserStatusOption = userStatus; + UsernameOption = username; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of AnyTypeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [JsonPropertyName("anyTypeProp")] + public Object? AnyTypeProp { get { return this. AnyTypePropOption; } set { this.AnyTypePropOption = new(value); } } + + /// + /// Used to track the state of AnyTypePropNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropNullableOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [JsonPropertyName("anyTypePropNullable")] + public Object? AnyTypePropNullable { get { return this. AnyTypePropNullableOption; } set { this.AnyTypePropNullableOption = new(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + /// /// Gets or Sets Email /// [JsonPropertyName("email")] - public string Email { get; set; } + public string? Email { get { return this. EmailOption; } set { this.EmailOption = new(value); } } + + /// + /// Used to track the state of FirstName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstNameOption { get; private set; } /// /// Gets or Sets FirstName /// [JsonPropertyName("firstName")] - public string FirstName { get; set; } + public string? FirstName { get { return this. FirstNameOption; } set { this.FirstNameOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of LastName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LastNameOption { get; private set; } /// /// Gets or Sets LastName /// [JsonPropertyName("lastName")] - public string LastName { get; set; } + public string? LastName { get { return this. LastNameOption; } set { this.LastNameOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredProps + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsOption { get; private set; } /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. [JsonPropertyName("objectWithNoDeclaredProps")] - public Object ObjectWithNoDeclaredProps { get; set; } + public Object? ObjectWithNoDeclaredProps { get { return this. ObjectWithNoDeclaredPropsOption; } set { this.ObjectWithNoDeclaredPropsOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredPropsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsNullableOption { get; private set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonPropertyName("objectWithNoDeclaredPropsNullable")] + public Object? ObjectWithNoDeclaredPropsNullable { get { return this. ObjectWithNoDeclaredPropsNullableOption; } set { this.ObjectWithNoDeclaredPropsNullableOption = new(value); } } + + /// + /// Used to track the state of Password + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PasswordOption { get; private set; } /// /// Gets or Sets Password /// [JsonPropertyName("password")] - public string Password { get; set; } + public string? Password { get { return this. PasswordOption; } set { this.PasswordOption = new(value); } } /// - /// Gets or Sets Phone + /// Used to track the state of Phone /// - [JsonPropertyName("phone")] - public string Phone { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PhoneOption { get; private set; } /// - /// User Status + /// Gets or Sets Phone /// - /// User Status - [JsonPropertyName("userStatus")] - public int UserStatus { get; set; } + [JsonPropertyName("phone")] + public string? Phone { get { return this. PhoneOption; } set { this.PhoneOption = new(value); } } /// - /// Gets or Sets Username + /// Used to track the state of UserStatus /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UserStatusOption { get; private set; } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// User Status /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - [JsonPropertyName("anyTypeProp")] - public Object? AnyTypeProp { get; set; } + /// User Status + [JsonPropertyName("userStatus")] + public int? UserStatus { get { return this. UserStatusOption; } set { this.UserStatusOption = new(value); } } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// Used to track the state of Username /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - [JsonPropertyName("anyTypePropNullable")] - public Object? AnyTypePropNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UsernameOption { get; private set; } /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// Gets or Sets Username /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. - [JsonPropertyName("objectWithNoDeclaredPropsNullable")] - public Object? ObjectWithNoDeclaredPropsNullable { get; set; } + [JsonPropertyName("username")] + public string? Username { get { return this. UsernameOption; } set { this.UsernameOption = new(value); } } /// /// Gets or Sets additional properties @@ -158,18 +242,18 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); - sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -208,18 +292,18 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? email = default; - string? firstName = default; - long? id = default; - string? lastName = default; - Object? objectWithNoDeclaredProps = default; - string? password = default; - string? phone = default; - int? userStatus = default; - string? username = default; - Object? anyTypeProp = default; - Object? anyTypePropNullable = default; - Object? objectWithNoDeclaredPropsNullable = default; + Option anyTypeProp = default; + Option anyTypePropNullable = default; + Option email = default; + Option firstName = default; + Option id = default; + Option lastName = default; + Option objectWithNoDeclaredProps = default; + Option objectWithNoDeclaredPropsNullable = default; + Option password = default; + Option phone = default; + Option userStatus = default; + Option username = default; while (utf8JsonReader.Read()) { @@ -236,47 +320,47 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { + case "anyTypeProp": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "anyTypePropNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypePropNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "email": - email = utf8JsonReader.GetString(); + email = new Option(utf8JsonReader.GetString()!); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()!); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()!); break; case "objectWithNoDeclaredProps": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + objectWithNoDeclaredProps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "objectWithNoDeclaredPropsNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredPropsNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "password": - password = utf8JsonReader.GetString(); + password = new Option(utf8JsonReader.GetString()!); break; case "phone": - phone = utf8JsonReader.GetString(); + phone = new Option(utf8JsonReader.GetString()!); break; case "userStatus": if (utf8JsonReader.TokenType != JsonTokenType.Null) - userStatus = utf8JsonReader.GetInt32(); + userStatus = new Option(utf8JsonReader.GetInt32()); break; case "username": - username = utf8JsonReader.GetString(); - break; - case "anyTypeProp": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anyTypePropNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypePropNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "objectWithNoDeclaredPropsNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + username = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -284,34 +368,34 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (email == null) - throw new ArgumentNullException(nameof(email), "Property is required for class User."); + if (email.IsSet && email.Value == null) + throw new ArgumentNullException(nameof(email), "Property is not nullable for class User."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class User."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class User."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class User."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class User."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class User."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class User."); - if (objectWithNoDeclaredProps == null) - throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is required for class User."); + if (objectWithNoDeclaredProps.IsSet && objectWithNoDeclaredProps.Value == null) + throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is not nullable for class User."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class User."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class User."); - if (phone == null) - throw new ArgumentNullException(nameof(phone), "Property is required for class User."); + if (phone.IsSet && phone.Value == null) + throw new ArgumentNullException(nameof(phone), "Property is not nullable for class User."); - if (userStatus == null) - throw new ArgumentNullException(nameof(userStatus), "Property is required for class User."); + if (userStatus.IsSet && userStatus.Value == null) + throw new ArgumentNullException(nameof(userStatus), "Property is not nullable for class User."); - if (username == null) - throw new ArgumentNullException(nameof(username), "Property is required for class User."); + if (username.IsSet && username.Value == null) + throw new ArgumentNullException(nameof(username), "Property is not nullable for class User."); - return new User(email, firstName, id.Value, lastName, objectWithNoDeclaredProps, password, phone, userStatus.Value, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + return new User(anyTypeProp, anyTypePropNullable, email, firstName, id, lastName, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, password, phone, userStatus, username); } /// @@ -338,22 +422,79 @@ public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("email", user.Email); - writer.WriteString("firstName", user.FirstName); - writer.WriteNumber("id", user.Id); - writer.WriteString("lastName", user.LastName); - writer.WritePropertyName("objectWithNoDeclaredProps"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); - writer.WriteString("password", user.Password); - writer.WriteString("phone", user.Phone); - writer.WriteNumber("userStatus", user.UserStatus); - writer.WriteString("username", user.Username); - writer.WritePropertyName("anyTypeProp"); - JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); - writer.WritePropertyName("anyTypePropNullable"); - JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); - writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + if (user.EmailOption.IsSet && user.Email == null) + throw new ArgumentNullException(nameof(user.Email), "Property is required for class User."); + + if (user.FirstNameOption.IsSet && user.FirstName == null) + throw new ArgumentNullException(nameof(user.FirstName), "Property is required for class User."); + + if (user.LastNameOption.IsSet && user.LastName == null) + throw new ArgumentNullException(nameof(user.LastName), "Property is required for class User."); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet && user.ObjectWithNoDeclaredProps == null) + throw new ArgumentNullException(nameof(user.ObjectWithNoDeclaredProps), "Property is required for class User."); + + if (user.PasswordOption.IsSet && user.Password == null) + throw new ArgumentNullException(nameof(user.Password), "Property is required for class User."); + + if (user.PhoneOption.IsSet && user.Phone == null) + throw new ArgumentNullException(nameof(user.Phone), "Property is required for class User."); + + if (user.UsernameOption.IsSet && user.Username == null) + throw new ArgumentNullException(nameof(user.Username), "Property is required for class User."); + + if (user.AnyTypePropOption.IsSet) + if (user.AnyTypePropOption.Value != null) + { + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypeProp"); + if (user.AnyTypePropNullableOption.IsSet) + if (user.AnyTypePropNullableOption.Value != null) + { + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypePropNullable"); + if (user.EmailOption.IsSet) + writer.WriteString("email", user.Email); + + if (user.FirstNameOption.IsSet) + writer.WriteString("firstName", user.FirstName); + + if (user.IdOption.IsSet) + writer.WriteNumber("id", user.IdOption.Value!.Value); + + if (user.LastNameOption.IsSet) + writer.WriteString("lastName", user.LastName); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet) + { + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); + } + if (user.ObjectWithNoDeclaredPropsNullableOption.IsSet) + if (user.ObjectWithNoDeclaredPropsNullableOption.Value != null) + { + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + } + else + writer.WriteNull("objectWithNoDeclaredPropsNullable"); + if (user.PasswordOption.IsSet) + writer.WriteString("password", user.Password); + + if (user.PhoneOption.IsSet) + writer.WriteString("phone", user.Phone); + + if (user.UserStatusOption.IsSet) + writer.WriteNumber("userStatus", user.UserStatusOption.Value!.Value); + + if (user.UsernameOption.IsSet) + writer.WriteString("username", user.Username); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs index 7d320ced8bb2..40f40250f504 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Whale.cs @@ -39,11 +39,11 @@ public partial class Whale : IValidatableObject /// hasBaleen /// hasTeeth [JsonConstructor] - public Whale(string className, bool hasBaleen, bool hasTeeth) + public Whale(string className, Option hasBaleen = default, Option hasTeeth = default) { ClassName = className; - HasBaleen = hasBaleen; - HasTeeth = hasTeeth; + HasBaleenOption = hasBaleen; + HasTeethOption = hasTeeth; OnCreated(); } @@ -55,17 +55,31 @@ public Whale(string className, bool hasBaleen, bool hasTeeth) [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of HasBaleen + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasBaleenOption { get; private set; } + /// /// Gets or Sets HasBaleen /// [JsonPropertyName("hasBaleen")] - public bool HasBaleen { get; set; } + public bool? HasBaleen { get { return this. HasBaleenOption; } set { this.HasBaleenOption = new(value); } } + + /// + /// Used to track the state of HasTeeth + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasTeethOption { get; private set; } /// /// Gets or Sets HasTeeth /// [JsonPropertyName("hasTeeth")] - public bool HasTeeth { get; set; } + public bool? HasTeeth { get { return this. HasTeethOption; } set { this.HasTeethOption = new(value); } } /// /// Gets or Sets additional properties @@ -122,9 +136,9 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - bool? hasBaleen = default; - bool? hasTeeth = default; + Option className = default; + Option hasBaleen = default; + Option hasTeeth = default; while (utf8JsonReader.Read()) { @@ -142,15 +156,15 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "hasBaleen": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasBaleen = utf8JsonReader.GetBoolean(); + hasBaleen = new Option(utf8JsonReader.GetBoolean()); break; case "hasTeeth": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasTeeth = utf8JsonReader.GetBoolean(); + hasTeeth = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -158,16 +172,19 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Whale."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Whale.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Whale."); - if (hasBaleen == null) - throw new ArgumentNullException(nameof(hasBaleen), "Property is required for class Whale."); + if (hasBaleen.IsSet && hasBaleen.Value == null) + throw new ArgumentNullException(nameof(hasBaleen), "Property is not nullable for class Whale."); - if (hasTeeth == null) - throw new ArgumentNullException(nameof(hasTeeth), "Property is required for class Whale."); + if (hasTeeth.IsSet && hasTeeth.Value == null) + throw new ArgumentNullException(nameof(hasTeeth), "Property is not nullable for class Whale."); - return new Whale(className, hasBaleen.Value, hasTeeth.Value); + return new Whale(className.Value!, hasBaleen, hasTeeth); } /// @@ -194,9 +211,16 @@ public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) { + if (whale.ClassName == null) + throw new ArgumentNullException(nameof(whale.ClassName), "Property is required for class Whale."); + writer.WriteString("className", whale.ClassName); - writer.WriteBoolean("hasBaleen", whale.HasBaleen); - writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + if (whale.HasBaleenOption.IsSet) + writer.WriteBoolean("hasBaleen", whale.HasBaleenOption.Value!.Value); + + if (whale.HasTeethOption.IsSet) + writer.WriteBoolean("hasTeeth", whale.HasTeethOption.Value!.Value); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs index 6e1c25bb5df0..834465542ba8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace UseSourceGeneration.Model /// /// Zebra /// - public partial class Zebra : Dictionary, IValidatableObject + public partial class Zebra : IValidatableObject { /// /// Initializes a new instance of the class. @@ -38,10 +38,10 @@ public partial class Zebra : Dictionary, IValidatableObject /// className /// type [JsonConstructor] - public Zebra(string className, TypeEnum type) : base() + public Zebra(string className, Option type = default) { ClassName = className; - Type = type; + TypeOption = type; OnCreated(); } @@ -113,7 +113,7 @@ public static TypeEnum TypeEnumFromString(string value) /// /// /// - public static string TypeEnumToJsonValue(TypeEnum value) + public static string TypeEnumToJsonValue(TypeEnum? value) { if (value == TypeEnum.Plains) return "plains"; @@ -127,11 +127,18 @@ public static string TypeEnumToJsonValue(TypeEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } + /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public TypeEnum Type { get; set; } + public TypeEnum? Type { get { return this.TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets ClassName @@ -153,7 +160,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -167,16 +173,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -204,8 +200,8 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - Zebra.TypeEnum? type = default; + Option className = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -223,13 +219,12 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "type": string? typeRawValue = utf8JsonReader.GetString(); - type = typeRawValue == null - ? null - : Zebra.TypeEnumFromStringOrDefault(typeRawValue); + if (typeRawValue != null) + type = new Option(Zebra.TypeEnumFromStringOrDefault(typeRawValue)); break; default: break; @@ -237,13 +232,16 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Zebra."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Zebra.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Zebra."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Zebra."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Zebra."); - return new Zebra(className, type.Value); + return new Zebra(className.Value!, type); } /// @@ -270,13 +268,13 @@ public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) { + if (zebra.ClassName == null) + throw new ArgumentNullException(nameof(zebra.ClassName), "Property is required for class Zebra."); + writer.WriteString("className", zebra.ClassName); - var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); - if (typeRawValue != null) - writer.WriteString("type", typeRawValue); - else - writer.WriteNull("type"); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs index e8e474a4a69f..ba9599e0717b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/Model/ZeroBasedEnumClass.cs @@ -37,9 +37,9 @@ public partial class ZeroBasedEnumClass : IValidatableObject /// /// zeroBasedEnum [JsonConstructor] - public ZeroBasedEnumClass(ZeroBasedEnumEnum zeroBasedEnum) + public ZeroBasedEnumClass(Option zeroBasedEnum = default) { - ZeroBasedEnum = zeroBasedEnum; + ZeroBasedEnumOption = zeroBasedEnum; OnCreated(); } @@ -100,7 +100,7 @@ public static ZeroBasedEnumEnum ZeroBasedEnumEnumFromString(string value) /// /// /// - public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) + public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum? value) { if (value == ZeroBasedEnumEnum.Unknown) return "unknown"; @@ -111,11 +111,18 @@ public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of ZeroBasedEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ZeroBasedEnumOption { get; private set; } + /// /// Gets or Sets ZeroBasedEnum /// [JsonPropertyName("ZeroBasedEnum")] - public ZeroBasedEnumEnum ZeroBasedEnum { get; set; } + public ZeroBasedEnumEnum? ZeroBasedEnum { get { return this.ZeroBasedEnumOption; } set { this.ZeroBasedEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -170,7 +177,7 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - ZeroBasedEnumClass.ZeroBasedEnumEnum? zeroBasedEnum = default; + Option zeroBasedEnum = default; while (utf8JsonReader.Read()) { @@ -189,9 +196,8 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "ZeroBasedEnum": string? zeroBasedEnumRawValue = utf8JsonReader.GetString(); - zeroBasedEnum = zeroBasedEnumRawValue == null - ? null - : ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue); + if (zeroBasedEnumRawValue != null) + zeroBasedEnum = new Option(ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue)); break; default: break; @@ -199,10 +205,10 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (zeroBasedEnum == null) - throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is required for class ZeroBasedEnumClass."); + if (zeroBasedEnum.IsSet && zeroBasedEnum.Value == null) + throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is not nullable for class ZeroBasedEnumClass."); - return new ZeroBasedEnumClass(zeroBasedEnum.Value); + return new ZeroBasedEnumClass(zeroBasedEnum); } /// @@ -229,12 +235,8 @@ public override void Write(Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEn /// public void WriteProperties(ref Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) { - - var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnum); - if (zeroBasedEnumRawValue != null) - writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); - else - writer.WriteNull("ZeroBasedEnum"); + var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnumOption.Value!.Value); + writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md index b6e75fbf4990..fd8e8c0c374e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=true', 'hideGenerationTimestamp=true', @@ -69,42 +69,7 @@ namespace YourProject .ConfigureApi((context, options) => { // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); options.AddTokens(token); // optionally choose the method the tokens will be provided with, default is RateLimitProvider @@ -249,7 +214,7 @@ Authentication schemes defined for the API: - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj index 60dd69fbf95c..29de00f0098f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt-useSourceGeneration/src/UseSourceGeneration/UseSourceGeneration.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 UseSourceGeneration UseSourceGeneration Library @@ -21,10 +21,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES index 1179de6767be..0c900b9c260e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/FILES @@ -79,6 +79,7 @@ docs/models/PolymorphicProperty.md docs/models/Quadrilateral.md docs/models/QuadrilateralInterface.md docs/models/ReadOnlyFirst.md +docs/models/RequiredClass.md docs/models/Return.md docs/models/RolesReportsHash.md docs/models/RolesReportsHashRole.md @@ -121,6 +122,8 @@ src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/ExceptionEventArgs.cs @@ -206,6 +209,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md index 76873f715c8e..a89b1cda5acd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) @@ -810,7 +896,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateTime date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) +> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateOnly date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -841,7 +927,7 @@ namespace Example var number = 8.14D; // decimal | None var varDouble = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var date = DateTime.Parse("2013-10-20"); // DateTime | None (optional) + var date = DateOnly.Parse("2013-10-20"); // DateOnly | None (optional) var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) var varFloat = 3.4F; // float | None (optional) var integer = 56; // int | None (optional) @@ -893,7 +979,7 @@ catch (ApiException e) | **number** | **decimal** | None | | | **varDouble** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **date** | **DateTime** | None | [optional] | +| **date** | **DateOnly** | None | [optional] | | **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | | **varFloat** | **float** | None | [optional] | | **integer** | **int** | None | [optional] | diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md index 44c9eeac76b9..407fb30dccb4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md index 56c1acb79285..ee189c866ec5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/apis/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md index f79869f95a71..2bbe882fcfcc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/AdditionalPropertiesClass.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Anytype1** | **Object** | | [optional] **EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] **MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] **MapProperty** | **Dictionary<string, string>** | | [optional] @@ -11,7 +12,6 @@ Name | Type | Description | Notes **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] **MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] -**Anytype1** | **Object** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/ChildCat.md index b8f7d81fbbee..88fe8f7a7fdd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/DateOnlyClass.md index 5dd63b313ccf..4fc3775ed87d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/DateOnlyClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/DateOnlyClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**DateOnlyProperty** | **DateTime** | | [optional] +**DateOnlyProperty** | **DateOnly** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md index 215793515f64..95f49b2ed600 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Drawing.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] -**Shapes** | [**List<Shape>**](Shape.md) | | [optional] **NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md index 53bbfe31e77c..ebd7ccf2c864 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**EnumStringRequired** | **string** | | **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] **EnumString** | **string** | | [optional] -**EnumStringRequired** | **string** | | +**OuterEnum** | **OuterEnum** | | [optional] **OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] **OuterEnumInteger** | **OuterEnumInteger** | | [optional] **OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md index 28f1a8093581..849cd26c0b6f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/FormatTest.md @@ -4,9 +4,11 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Binary** | **System.IO.Stream** | | [optional] **VarByte** | **byte[]** | | -**Date** | **DateTime** | | +**Date** | **DateOnly** | | +**Number** | **decimal** | | +**Password** | **string** | | +**Binary** | **System.IO.Stream** | | [optional] **DateTime** | **DateTime** | | [optional] **VarDecimal** | **decimal** | | [optional] **VarDouble** | **double** | | [optional] @@ -14,8 +16,6 @@ Name | Type | Description | Notes **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] **Integer** | **int** | | [optional] -**Number** | **decimal** | | -**Password** | **string** | | **PatternWithBackslash** | **string** | None | [optional] **PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] **PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md index 394feef77dbb..c9afe86510da 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/NullableClass.md @@ -4,16 +4,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool** | | [optional] -**DateProp** | **DateTime** | | [optional] +**DateProp** | **DateOnly** | | [optional] **DatetimeProp** | **DateTime** | | [optional] **IntegerProp** | **int** | | [optional] **NumberProp** | **decimal** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] **StringProp** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Order.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Order.md index ca5d8992a513..f7d6827ed5c9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Order.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Order.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Complete** | **bool** | | [optional] [default to false] **Id** | **long** | | [optional] **PetId** | **long** | | [optional] **Quantity** | **int** | | [optional] **ShipDate** | **DateTime** | | [optional] **Status** | **string** | Order Status | [optional] -**Complete** | **bool** | | [optional] [default to false] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md index b13bb576b450..4f019b613bd7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Category** | [**Category**](Category.md) | | [optional] -**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Status** | **string** | pet status in the store | [optional] **Tags** | [**List<Tag>**](Tag.md) | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/RequiredClass.md new file mode 100644 index 000000000000..bbdf6d8407b1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNotNullableDateProp** | **DateOnly** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNotnullableEnumInteger** | **int** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**RequiredNotnullableEnumString** | **string** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableStringProp** | **string** | | +**RequiredNotnullableUuid** | **Guid** | | +**RequiredNotnullableintegerProp** | **int** | | +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNullableBooleanProp** | **bool** | | +**RequiredNullableDateProp** | **DateOnly** | | +**RequiredNullableDatetimeProp** | **DateTime** | | +**RequiredNullableEnumInteger** | **int** | | +**RequiredNullableEnumIntegerOnly** | **int** | | +**RequiredNullableEnumString** | **string** | | +**RequiredNullableIntegerProp** | **int** | | +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNullableStringProp** | **string** | | +**RequiredNullableUuid** | **Guid** | | +**NotRequiredNotnullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**NotRequiredNullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNullableIntegerProp** | **int** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNullableBooleanProp** | **bool** | | [optional] +**NotrequiredNullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNullableEnumInteger** | **int** | | [optional] +**NotrequiredNullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNullableUuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md index 455f031674d5..b5700f1c75d9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] **Email** | **string** | | [optional] **FirstName** | **string** | | [optional] **Id** | **long** | | [optional] **LastName** | **string** | | [optional] **ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] **Password** | **string** | | [optional] **Phone** | **string** | | [optional] **UserStatus** | **int** | User Status | [optional] **Username** | **string** | | [optional] -**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index 09680ae4cedd..03ad026fa146 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -52,26 +52,30 @@ public ApiTestsBase(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureApi((context, services, options) => { - string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); + string apiKeyTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken1 = new(apiKeyTokenValue1, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); - string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - BearerToken bearerToken = new(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); + string apiKeyTokenValue2 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken2 = new(apiKeyTokenValue2, ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); - string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); - string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); - BasicToken basicToken = new(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); + string bearerTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken1 = new(bearerTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); - HttpSigningConfiguration config = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); + string basicTokenUsername1 = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword1 = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken1 = new(basicTokenUsername1, basicTokenPassword1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); - string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - OAuthToken oauthToken = new(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + HttpSigningConfiguration config1 = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + string oauthTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken1 = new(oauthTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 5ad1cd420f95..028d71f43359 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,93 +24,105 @@ namespace Org.OpenAPITools.Test.Api ///
              public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken = new("token", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(oauthToken); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) @@ -124,22 +136,22 @@ public void ConfigureApiWithAClientTest() { var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -152,22 +164,22 @@ public void ConfigureApiWithoutAClientTest() { var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -208,22 +220,22 @@ public void AddApiWithoutAClientTest() { var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index 758fb96ce8b8..19d536890f17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -164,7 +164,7 @@ public async Task TestEndpointParametersAsyncTest() decimal number = default!; double varDouble = default!; string patternWithoutDelimiter = default!; - Client.Option date = default!; + Client.Option date = default!; Client.Option binary = default!; Client.Option varFloat = default!; Client.Option integer = default!; @@ -219,6 +219,16 @@ public async Task TestInlineAdditionalPropertiesAsyncTest() await _instance.TestInlineAdditionalPropertiesAsync(requestBody); } + /// + /// Test TestInlineFreeformAdditionalProperties + /// + [Fact (Skip = "not implemented")] + public async Task TestInlineFreeformAdditionalPropertiesAsyncTest() + { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = default!; + await _instance.TestInlineFreeformAdditionalPropertiesAsync(testInlineFreeformAdditionalPropertiesRequest); + } + /// /// Test TestJsonFormData /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index b6bff036a466..e157b477193e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -53,6 +53,15 @@ public void AdditionalPropertiesClassInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// /// Test the property 'EmptyMap' /// @@ -115,14 +124,5 @@ public void MapWithUndeclaredPropertiesStringTest() { // TODO unit test for the property 'MapWithUndeclaredPropertiesString' } - - /// - /// Test the property 'Anytype1' - /// - [Fact] - public void Anytype1Test() - { - // TODO unit test for the property 'Anytype1' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0ed2f54aab54..a2de4a1b97b1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -62,15 +62,6 @@ public void MainShapeTest() // TODO unit test for the property 'MainShape' } - /// - /// Test the property 'Shapes' - /// - [Fact] - public void ShapesTest() - { - // TODO unit test for the property 'Shapes' - } - /// /// Test the property 'NullableShape' /// @@ -88,5 +79,14 @@ public void ShapeOrNullTest() { // TODO unit test for the property 'ShapeOrNull' } + + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e5a97f428662..3781eebbfcf2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -53,6 +53,15 @@ public void EnumTestInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// /// Test the property 'EnumInteger' /// @@ -90,12 +99,12 @@ public void EnumStringTest() } /// - /// Test the property 'EnumStringRequired' + /// Test the property 'OuterEnum' /// [Fact] - public void EnumStringRequiredTest() + public void OuterEnumTest() { - // TODO unit test for the property 'EnumStringRequired' + // TODO unit test for the property 'OuterEnum' } /// @@ -124,14 +133,5 @@ public void OuterEnumIntegerDefaultValueTest() { // TODO unit test for the property 'OuterEnumIntegerDefaultValue' } - - /// - /// Test the property 'OuterEnum' - /// - [Fact] - public void OuterEnumTest() - { - // TODO unit test for the property 'OuterEnum' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index fbffe502af78..164baa8862be 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -53,15 +53,6 @@ public void FormatTestInstanceTest() //Assert.IsType(instance); } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// /// Test the property 'VarByte' /// @@ -80,6 +71,33 @@ public void DateTest() // TODO unit test for the property 'Date' } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// /// Test the property 'DateTime' /// @@ -143,24 +161,6 @@ public void IntegerTest() // TODO unit test for the property 'Integer' } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// /// Test the property 'PatternWithBackslash' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 47901aeb2f4c..1e19aa6b8231 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -54,30 +54,21 @@ public void NullableClassInstanceTest() } /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - - /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ArrayAndItemsNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ArrayAndItemsNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // TODO unit test for the property 'ArrayAndItemsNullableProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// @@ -143,6 +134,15 @@ public void ObjectAndItemsNullablePropTest() // TODO unit test for the property 'ObjectAndItemsNullableProp' } + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + /// /// Test the property 'ObjectNullableProp' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs index afab7d23a20e..e7187bbdc92c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -53,6 +53,15 @@ public void OrderInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + /// /// Test the property 'Id' /// @@ -97,14 +106,5 @@ public void StatusTest() { // TODO unit test for the property 'Status' } - - /// - /// Test the property 'Complete' - /// - [Fact] - public void CompleteTest() - { - // TODO unit test for the property 'Complete' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs index fff8db45faad..8485d1213ce6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -54,39 +54,39 @@ public void PetInstanceTest() } /// - /// Test the property 'Category' + /// Test the property 'Name' /// [Fact] - public void CategoryTest() + public void NameTest() { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Name' } /// - /// Test the property 'Id' + /// Test the property 'PhotoUrls' /// [Fact] - public void IdTest() + public void PhotoUrlsTest() { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Name' + /// Test the property 'Category' /// [Fact] - public void NameTest() + public void CategoryTest() { - // TODO unit test for the property 'Name' + // TODO unit test for the property 'Category' } /// - /// Test the property 'PhotoUrls' + /// Test the property 'Id' /// [Fact] - public void PhotoUrlsTest() + public void IdTest() { - // TODO unit test for the property 'PhotoUrls' + // TODO unit test for the property 'Id' } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..e51863915927 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,452 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs index cc4d133818ac..6415f8561f1f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -53,6 +53,24 @@ public void UserInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + /// /// Test the property 'Email' /// @@ -98,6 +116,15 @@ public void ObjectWithNoDeclaredPropsTest() // TODO unit test for the property 'ObjectWithNoDeclaredProps' } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// /// Test the property 'Password' /// @@ -133,32 +160,5 @@ public void UsernameTest() { // TODO unit test for the property 'Username' } - - /// - /// Test the property 'AnyTypeProp' - /// - [Fact] - public void AnyTypePropTest() - { - // TODO unit test for the property 'AnyTypeProp' - } - - /// - /// Test the property 'AnyTypePropNullable' - /// - [Fact] - public void AnyTypePropNullableTest() - { - // TODO unit test for the property 'AnyTypePropNullable' - } - - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f7c0eaf370cb..872d1687aa20 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,15 +3,15 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net8.0 false enable - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs index 90ec5f067f36..baaa01776963 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeApi.cs @@ -171,6 +171,29 @@ public interface IFakeApi : IApi /// <?> Task GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// request body + /// Cancellation Token to cancel the request. + /// <?> + Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + /// /// /// @@ -265,7 +288,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -289,7 +312,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <?> - Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// To test enum parameters @@ -544,6 +567,18 @@ public interface IGetArrayOfEnumsApiResponse : Org.OpenAPITools.Client.IApiRespo bool IsOk { get; } } + /// + /// The + /// + public interface ITestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.IApiResponse + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + /// /// The /// @@ -801,6 +836,26 @@ internal void ExecuteOnErrorGetArrayOfEnums(Exception exception) OnErrorGetArrayOfEnums?.Invoke(this, new ExceptionEventArgs(exception)); } + /// + /// The event raised after the server response + /// + public event EventHandler? OnTestAdditionalPropertiesReference; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorTestAdditionalPropertiesReference; + + internal void ExecuteOnTestAdditionalPropertiesReference(FakeApi.TestAdditionalPropertiesReferenceApiResponse apiResponse) + { + OnTestAdditionalPropertiesReference?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestAdditionalPropertiesReference(Exception exception) + { + OnErrorTestAdditionalPropertiesReference?.Invoke(this, new ExceptionEventArgs(exception)); + } + /// /// The event raised after the server response /// @@ -2375,6 +2430,195 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } + partial void FormatTestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestAdditionalPropertiesReference(Dictionary requestBody) + { + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestAdditionalPropertiesReferenceDefaultImplementation(ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody) + { + bool suppressDefaultLog = false; + AfterTestAdditionalPropertiesReference(ref suppressDefaultLog, apiResponseLocalVar, requestBody); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestAdditionalPropertiesReference(ref bool suppressDefaultLog, ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + bool suppressDefaultLog = false; + OnErrorTestAdditionalPropertiesReference(ref suppressDefaultLog, exception, pathFormat, path, requestBody); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestAdditionalPropertiesReference(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestAdditionalPropertiesReferenceAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestAdditionalPropertiesReference(requestBody); + + FormatTestAdditionalPropertiesReference(requestBody); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/additionalProperties-reference"; + + httpRequestMessageLocalVar.Content = (requestBody as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string? contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + + TestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/additionalProperties-reference", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestAdditionalPropertiesReferenceDefaultImplementation(apiResponseLocalVar, requestBody); + + Events.ExecuteOnTestAdditionalPropertiesReference(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(e, "/fake/additionalProperties-reference", uriBuilderLocalVar.Path, requestBody); + Events.ExecuteOnErrorTestAdditionalPropertiesReference(e); + throw; + } + } + + /// + /// The + /// + public partial class TestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.ApiResponse, ITestAdditionalPropertiesReferenceApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public TestAdditionalPropertiesReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + partial void FormatTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); /// @@ -2999,7 +3243,7 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } - partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); + partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); /// /// Validates the request parameters @@ -3050,7 +3294,7 @@ private void ValidateTestEndpointParameters(byte[] varByte, string patternWithou /// /// /// - private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; AfterTestEndpointParameters(ref suppressDefaultLog, apiResponseLocalVar, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3077,7 +3321,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Logs exceptions that occur while retrieving the server response @@ -3099,7 +3343,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; OnErrorTestEndpointParameters(ref suppressDefaultLog, exception, pathFormat, path, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3128,7 +3372,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// /// /// - partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -3149,7 +3393,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { try { @@ -3181,7 +3425,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { UriBuilder uriBuilderLocalVar = new UriBuilder(); @@ -3245,14 +3489,13 @@ public async Task TestEndpointParametersAsyn formParameterLocalVars.Add(new KeyValuePair("dateTime", ClientUtils.ParameterToString(dateTime.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BasicToken basicTokenLocalVar1 = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(basicTokenLocalVar); + tokenBaseLocalVars.Add(basicTokenLocalVar1); - basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + basicTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -3770,14 +4013,13 @@ public async Task TestGroupParametersAsync(bool httpRequestMessageLocalVar.Headers.Add("boolean_group", ClientUtils.ParameterToString(booleanGroup.Value)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BearerToken bearerTokenLocalVar1 = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(bearerTokenLocalVar); + tokenBaseLocalVars.Add(bearerTokenLocalVar1); - bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + bearerTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 08d34ad36723..d7264a7338c9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -280,14 +280,12 @@ public async Task TestClassnameAsync(ModelClient mode : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "api_key_query"); + apiKeyTokenLocalVar1.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] contentTypes = new string[] { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs index 0dfc6c7d534a..b302ea0482b1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/PetApi.cs @@ -90,7 +90,7 @@ public interface IPetApi : IApi /// Multiple status values can be provided with comma separated strings /// /// Thrown when fails to make API call - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -101,7 +101,7 @@ public interface IPetApi : IApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <?> Task FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -116,6 +116,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -127,6 +128,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <?> + [Obsolete] Task FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -768,23 +770,22 @@ public async Task AddPetAsync(Pet pet, System.Threading.Canc : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -986,14 +987,13 @@ public async Task DeletePetAsync(long petId, Option tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; @@ -1180,23 +1180,22 @@ public async Task FindPetsByStatusAsync(List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1432,23 +1431,22 @@ public async Task FindPetsByTagsAsync(List t uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1665,14 +1663,19 @@ public async Task GetPetByIdAsync(long petId, System.Thr uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokenBaseLocalVars = new List(); + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + ApiKeyToken apiKeyTokenLocalVar2 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar2); - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + apiKeyTokenLocalVar2.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] acceptLocalVars = new string[] { @@ -1912,23 +1915,22 @@ public async Task UpdatePetAsync(Pet pet, System.Threadin : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -2161,14 +2163,13 @@ public async Task UpdatePetWithFormAsync(long pet formParameterLocalVars.Add(new KeyValuePair("status", ClientUtils.ParameterToString(status.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -2387,14 +2388,13 @@ public async Task UploadFileAsync(long petId, Option("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" @@ -2653,14 +2653,13 @@ public async Task UploadFileWithRequired formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs index f9081e66f708..2757e12618b3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/StoreApi.cs @@ -621,12 +621,9 @@ public async Task GetInventoryAsync(System.Threading.C uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; List tokenBaseLocalVars = new List(); - - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs index 2f06f13a9f6e..ebe235bc9d7d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Api/UserApi.cs @@ -12,6 +12,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -279,7 +280,7 @@ public interface IDeleteUserApiResponse : Org.OpenAPITools.Client.IApiResponse /// /// The /// - public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk + public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk, ICustomHttpStatusCode599 { /// /// Returns true if the response is 200 Ok @@ -298,6 +299,18 @@ public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiRespons /// /// bool IsNotFound { get; } + + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + bool IsCustomHttpStatusCode598 { get; } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + bool IsCustomHttpStatusCode599 { get; } } /// @@ -566,6 +579,11 @@ public sealed partial class UserApi : IUserApi /// public TokenProvider OauthTokenProvider { get; } + /// + /// The token cookie container + /// + public Org.OpenAPITools.Client.CookieContainer CookieContainer { get; } + /// /// Initializes a new instance of the class. /// @@ -575,7 +593,8 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient TokenProvider bearerTokenProvider, TokenProvider basicTokenProvider, TokenProvider httpSignatureTokenProvider, - TokenProvider oauthTokenProvider) + TokenProvider oauthTokenProvider, + Org.OpenAPITools.Client.CookieContainer cookieContainer) { _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; LoggerFactory = loggerFactory; @@ -587,6 +606,7 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient BasicTokenProvider = basicTokenProvider; HttpSignatureTokenProvider = httpSignatureTokenProvider; OauthTokenProvider = oauthTokenProvider; + CookieContainer = cookieContainer; } partial void FormatCreateUser(User user); @@ -1559,6 +1579,50 @@ public bool TryOk([NotNullWhen(true)]out Org.OpenAPITools.Model.User? result) /// public bool IsNotFound => 404 == (int)StatusCode; + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + public bool IsCustomHttpStatusCode598 => 598 == (int)StatusCode; + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + public bool IsCustomHttpStatusCode599 => 599 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 599 CustomHttpStatusCode599 + /// + /// + public Org.OpenAPITools.Model.User? CustomHttpStatusCode599() + { + // This logic may be modified with the AsModel.mustache template + return IsCustomHttpStatusCode599 + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + public bool TryCustomHttpStatusCode599([NotNullWhen(true)]out Org.OpenAPITools.Model.User? result) + { + result = null; + + try + { + result = CustomHttpStatusCode599(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)599); + } + + return result != null; + } + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) { bool suppressDefaultLog = false; @@ -1716,6 +1780,33 @@ public async Task LoginUserAsync(string username, string Events.ExecuteOnLoginUser(apiResponseLocalVar); + if (httpResponseMessageLocalVar.StatusCode == (HttpStatusCode) 200 && httpResponseMessageLocalVar.Headers.TryGetValues("Set-Cookie", out var cookieHeadersLocalVar)) + { + foreach(string cookieHeader in cookieHeadersLocalVar) + { + IList setCookieHeaderValuesLocalVar = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeadersLocalVar.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValueLocalVar in setCookieHeaderValuesLocalVar) + { + Cookie cookieLocalVar = new Cookie(setCookieHeaderValueLocalVar.Name.ToString(), setCookieHeaderValueLocalVar.Value.ToString()) + { + HttpOnly = setCookieHeaderValueLocalVar.HttpOnly + }; + + if (setCookieHeaderValueLocalVar.Expires.HasValue) + cookieLocalVar.Expires = setCookieHeaderValueLocalVar.Expires.Value.UtcDateTime; + + if (setCookieHeaderValueLocalVar.Path.HasValue) + cookieLocalVar.Path = setCookieHeaderValueLocalVar.Path.Value; + + if (setCookieHeaderValueLocalVar.Domain.HasValue) + cookieLocalVar.Domain = setCookieHeaderValueLocalVar.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilderLocalVar.Scheme}://{uriBuilderLocalVar.Host}"), cookieLocalVar); + } + } + } + return apiResponseLocalVar; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs index a421f4e53e6b..ed3b8de44dfb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -13,14 +13,21 @@ public class ApiKeyToken : TokenBase { private string _raw; + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + /// /// Constructs an ApiKeyToken object. /// /// + /// /// /// - public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { + Header = header; _raw = $"{ prefix }{ value }"; } @@ -28,22 +35,20 @@ public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = /// Places the token in the header. /// /// - /// - public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) { - request.Headers.Add(headerName, _raw); + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); } - + /// /// Places the token in the query. /// /// /// /// - /// - public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) { - parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString()!; + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString()!; } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs index 1e59205d73aa..b3045d2ab092 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -150,6 +150,26 @@ public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); } + /// + /// An interface for responses of type + /// + /// + public interface ICustomHttpStatusCode599 : IApiResponse + { + /// + /// Deserializes the response if the response is CustomHttpStatusCode599 + /// + /// + TType CustomHttpStatusCode599(); + + /// + /// Returns true if the response is CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + bool TryCustomHttpStatusCode599([NotNullWhen(true)]out TType? result); + } + /// /// An interface for responses of type /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs index e4ccc2b4d239..caafbfef6e56 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -40,7 +40,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// @@ -52,6 +54,37 @@ static ClientUtils() /// public delegate void EventHandler(object sender, T e) where T : EventArgs; + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + /// + /// The api_key header + /// + Api_key, + /// + /// The api_key_query header + /// + Api_key_query + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.Api_key => "api_key", + ApiKeyHeader.Api_key_query => "api_key_query", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + /// /// Returns true when deserialization succeeds. /// @@ -141,6 +174,8 @@ public static string SanitizeFilename(string filename) return EnumArrays.JustSymbolEnumToJsonValue(enumArraysJustSymbolEnum); if (obj is EnumClass enumClass) return EnumClassValueConverter.ToJsonValue(enumClass); + if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) + return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is EnumTest.EnumIntegerEnum enumTestEnumIntegerEnum) return EnumTest.EnumIntegerEnumToJsonValue(enumTestEnumIntegerEnum).ToString(); if (obj is EnumTest.EnumIntegerOnlyEnum enumTestEnumIntegerOnlyEnum) @@ -149,8 +184,6 @@ public static string SanitizeFilename(string filename) return EnumTest.EnumNumberEnumToJsonValue(enumTestEnumNumberEnum).ToString(); if (obj is EnumTest.EnumStringEnum enumTestEnumStringEnum) return EnumTest.EnumStringEnumToJsonValue(enumTestEnumStringEnum); - if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) - return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is MapTest.InnerEnum mapTestInnerEnum) return MapTest.InnerEnumToJsonValue(mapTestInnerEnum); if (obj is Order.StatusEnum orderStatusEnum) @@ -167,6 +200,30 @@ public static string SanitizeFilename(string filename) return OuterEnumTestValueConverter.ToJsonValue(outerEnumTest); if (obj is Pet.StatusEnum petStatusEnum) return Pet.StatusEnumToJsonValue(petStatusEnum); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerEnum requiredClassRequiredNotnullableEnumIntegerEnum) + return RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum requiredClassRequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumStringEnum requiredClassRequiredNotnullableEnumStringEnum) + return RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClassRequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.RequiredNullableEnumIntegerEnum requiredClassRequiredNullableEnumIntegerEnum) + return RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClassRequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumIntegerOnlyEnum requiredClassRequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumStringEnum requiredClassRequiredNullableEnumStringEnum) + return RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClassRequiredNullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerEnum requiredClassNotrequiredNotnullableEnumIntegerEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumStringEnum requiredClassNotrequiredNotnullableEnumStringEnum) + return RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClassNotrequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerEnum requiredClassNotrequiredNullableEnumIntegerEnum) + return RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum requiredClassNotrequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumStringEnum requiredClassNotrequiredNullableEnumStringEnum) + return RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClassNotrequiredNullableEnumStringEnum); if (obj is Zebra.TypeEnum zebraTypeEnum) return Zebra.TypeEnumToJsonValue(zebraTypeEnum); if (obj is ZeroBasedEnum zeroBasedEnum) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..c9dc766e4639 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..5e42c9efb856 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index 71992dc8d86c..de6a37a17df7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index 90d2174e4a36..02b767330d0a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs index 968417a9e748..6ab2ad09bbda 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -41,6 +41,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new ActivityJsonConverter()); _jsonOptions.Converters.Add(new ActivityOutputElementRepresentationJsonConverter()); _jsonOptions.Converters.Add(new AdditionalPropertiesClassJsonConverter()); @@ -116,6 +118,7 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new QuadrilateralJsonConverter()); _jsonOptions.Converters.Add(new QuadrilateralInterfaceJsonConverter()); _jsonOptions.Converters.Add(new ReadOnlyFirstJsonConverter()); + _jsonOptions.Converters.Add(new RequiredClassJsonConverter()); _jsonOptions.Converters.Add(new ReturnJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashRoleJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/Option.cs index 7aa655c9b813..e6fd1c26872d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/Option.cs @@ -37,5 +37,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index 49269df7f913..d5510735d390 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -11,9 +11,11 @@ #nullable enable using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -21,7 +23,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -32,17 +34,41 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite - }; + if (container is TokenContainer apiKeyTokenContainer) + { + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); - AvailableTokens = Channel.CreateBounded(options); + foreach (string header in headers) + { + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + AvailableTokens.Add(header, Channel.CreateBounded(options)); + } + } + else + { + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + } + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/TokenProvider`1.cs index a629474b6a10..b873d5323e7a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -27,7 +27,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs index 22464eec75fe..c96ec917c52b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Activity.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Activity : IValidatableObject /// /// activityOutputs [JsonConstructor] - public Activity(Dictionary> activityOutputs) + public Activity(Option>?> activityOutputs = default) { - ActivityOutputs = activityOutputs; + ActivityOutputsOption = activityOutputs; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ActivityOutputs + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ActivityOutputsOption { get; private set; } + /// /// Gets or Sets ActivityOutputs /// [JsonPropertyName("activity_outputs")] - public Dictionary> ActivityOutputs { get; set; } + public Dictionary>? ActivityOutputs { get { return this. ActivityOutputsOption; } set { this.ActivityOutputsOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary>? activityOutputs = default; + Option>?> activityOutputs = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "activity_outputs": if (utf8JsonReader.TokenType != JsonTokenType.Null) - activityOutputs = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + activityOutputs = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -129,8 +137,8 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (activityOutputs == null) - throw new ArgumentNullException(nameof(activityOutputs), "Property is required for class Activity."); + if (activityOutputs.IsSet && activityOutputs.Value == null) + throw new ArgumentNullException(nameof(activityOutputs), "Property is not nullable for class Activity."); return new Activity(activityOutputs); } @@ -159,8 +167,14 @@ public override void Write(Utf8JsonWriter writer, Activity activity, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("activity_outputs"); - JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + if (activity.ActivityOutputsOption.IsSet && activity.ActivityOutputs == null) + throw new ArgumentNullException(nameof(activity.ActivityOutputs), "Property is required for class Activity."); + + if (activity.ActivityOutputsOption.IsSet) + { + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index 39c2e8b05e60..78bdf9d3abaf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class ActivityOutputElementRepresentation : IValidatableObject /// prop1 /// prop2 [JsonConstructor] - public ActivityOutputElementRepresentation(string prop1, Object prop2) + public ActivityOutputElementRepresentation(Option prop1 = default, Option prop2 = default) { - Prop1 = prop1; - Prop2 = prop2; + Prop1Option = prop1; + Prop2Option = prop2; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Prop1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop1Option { get; private set; } + /// /// Gets or Sets Prop1 /// [JsonPropertyName("prop1")] - public string Prop1 { get; set; } + public string? Prop1 { get { return this. Prop1Option; } set { this.Prop1Option = new(value); } } + + /// + /// Used to track the state of Prop2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop2Option { get; private set; } /// /// Gets or Sets Prop2 /// [JsonPropertyName("prop2")] - public Object Prop2 { get; set; } + public Object? Prop2 { get { return this. Prop2Option; } set { this.Prop2Option = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? prop1 = default; - Object? prop2 = default; + Option prop1 = default; + Option prop2 = default; while (utf8JsonReader.Read()) { @@ -130,11 +145,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 switch (localVarJsonPropertyName) { case "prop1": - prop1 = utf8JsonReader.GetString(); + prop1 = new Option(utf8JsonReader.GetString()!); break; case "prop2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - prop2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + prop2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -142,11 +157,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 } } - if (prop1 == null) - throw new ArgumentNullException(nameof(prop1), "Property is required for class ActivityOutputElementRepresentation."); + if (prop1.IsSet && prop1.Value == null) + throw new ArgumentNullException(nameof(prop1), "Property is not nullable for class ActivityOutputElementRepresentation."); - if (prop2 == null) - throw new ArgumentNullException(nameof(prop2), "Property is required for class ActivityOutputElementRepresentation."); + if (prop2.IsSet && prop2.Value == null) + throw new ArgumentNullException(nameof(prop2), "Property is not nullable for class ActivityOutputElementRepresentation."); return new ActivityOutputElementRepresentation(prop1, prop2); } @@ -175,9 +190,20 @@ public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresent /// public void WriteProperties(ref Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); - writer.WritePropertyName("prop2"); - JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + if (activityOutputElementRepresentation.Prop1Option.IsSet && activityOutputElementRepresentation.Prop1 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop1), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop2Option.IsSet && activityOutputElementRepresentation.Prop2 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop2), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop1Option.IsSet) + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + + if (activityOutputElementRepresentation.Prop2Option.IsSet) + { + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index 37ab8b4f3b4a..d373bc67722e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,6 +34,7 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// /// Initializes a new instance of the class. /// + /// anytype1 /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty /// mapProperty @@ -40,71 +42,126 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 /// mapWithUndeclaredPropertiesString - /// anytype1 [JsonConstructor] - public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object? anytype1 = default) + public AdditionalPropertiesClass(Option anytype1 = default, Option emptyMap = default, Option>?> mapOfMapProperty = default, Option?> mapProperty = default, Option mapWithUndeclaredPropertiesAnytype1 = default, Option mapWithUndeclaredPropertiesAnytype2 = default, Option?> mapWithUndeclaredPropertiesAnytype3 = default, Option?> mapWithUndeclaredPropertiesString = default) { - EmptyMap = emptyMap; - MapOfMapProperty = mapOfMapProperty; - MapProperty = mapProperty; - MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - Anytype1 = anytype1; + Anytype1Option = anytype1; + EmptyMapOption = emptyMap; + MapOfMapPropertyOption = mapOfMapProperty; + MapPropertyOption = mapProperty; + MapWithUndeclaredPropertiesAnytype1Option = mapWithUndeclaredPropertiesAnytype1; + MapWithUndeclaredPropertiesAnytype2Option = mapWithUndeclaredPropertiesAnytype2; + MapWithUndeclaredPropertiesAnytype3Option = mapWithUndeclaredPropertiesAnytype3; + MapWithUndeclaredPropertiesStringOption = mapWithUndeclaredPropertiesString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Anytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Anytype1Option { get; private set; } + + /// + /// Gets or Sets Anytype1 + /// + [JsonPropertyName("anytype_1")] + public Object? Anytype1 { get { return this. Anytype1Option; } set { this.Anytype1Option = new(value); } } + + /// + /// Used to track the state of EmptyMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmptyMapOption { get; private set; } + /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. [JsonPropertyName("empty_map")] - public Object EmptyMap { get; set; } + public Object? EmptyMap { get { return this. EmptyMapOption; } set { this.EmptyMapOption = new(value); } } + + /// + /// Used to track the state of MapOfMapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> MapOfMapPropertyOption { get; private set; } /// /// Gets or Sets MapOfMapProperty /// [JsonPropertyName("map_of_map_property")] - public Dictionary> MapOfMapProperty { get; set; } + public Dictionary>? MapOfMapProperty { get { return this. MapOfMapPropertyOption; } set { this.MapOfMapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapPropertyOption { get; private set; } /// /// Gets or Sets MapProperty /// [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + public Dictionary? MapProperty { get { return this. MapPropertyOption; } set { this.MapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype1Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 /// [JsonPropertyName("map_with_undeclared_properties_anytype_1")] - public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + public Object? MapWithUndeclaredPropertiesAnytype1 { get { return this. MapWithUndeclaredPropertiesAnytype1Option; } set { this.MapWithUndeclaredPropertiesAnytype1Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype2Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 /// [JsonPropertyName("map_with_undeclared_properties_anytype_2")] - public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + public Object? MapWithUndeclaredPropertiesAnytype2 { get { return this. MapWithUndeclaredPropertiesAnytype2Option; } set { this.MapWithUndeclaredPropertiesAnytype2Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype3 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapWithUndeclaredPropertiesAnytype3Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 /// [JsonPropertyName("map_with_undeclared_properties_anytype_3")] - public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + public Dictionary? MapWithUndeclaredPropertiesAnytype3 { get { return this. MapWithUndeclaredPropertiesAnytype3Option; } set { this.MapWithUndeclaredPropertiesAnytype3Option = new(value); } } /// - /// Gets or Sets MapWithUndeclaredPropertiesString + /// Used to track the state of MapWithUndeclaredPropertiesString /// - [JsonPropertyName("map_with_undeclared_properties_string")] - public Dictionary MapWithUndeclaredPropertiesString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapWithUndeclaredPropertiesStringOption { get; private set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapWithUndeclaredPropertiesString /// - [JsonPropertyName("anytype_1")] - public Object? Anytype1 { get; set; } + [JsonPropertyName("map_with_undeclared_properties_string")] + public Dictionary? MapWithUndeclaredPropertiesString { get { return this. MapWithUndeclaredPropertiesStringOption; } set { this.MapWithUndeclaredPropertiesStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -120,6 +177,7 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); @@ -127,7 +185,6 @@ public override string ToString() sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -166,14 +223,14 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Object? emptyMap = default; - Dictionary>? mapOfMapProperty = default; - Dictionary? mapProperty = default; - Object? mapWithUndeclaredPropertiesAnytype1 = default; - Object? mapWithUndeclaredPropertiesAnytype2 = default; - Dictionary? mapWithUndeclaredPropertiesAnytype3 = default; - Dictionary? mapWithUndeclaredPropertiesString = default; - Object? anytype1 = default; + Option anytype1 = default; + Option emptyMap = default; + Option>?> mapOfMapProperty = default; + Option?> mapProperty = default; + Option mapWithUndeclaredPropertiesAnytype1 = default; + Option mapWithUndeclaredPropertiesAnytype2 = default; + Option?> mapWithUndeclaredPropertiesAnytype3 = default; + Option?> mapWithUndeclaredPropertiesString = default; while (utf8JsonReader.Read()) { @@ -190,37 +247,37 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader switch (localVarJsonPropertyName) { + case "anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "empty_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - emptyMap = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + emptyMap = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_of_map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfMapProperty = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapOfMapProperty = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapProperty = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapProperty = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_1": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_anytype_3": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype3 = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_with_undeclared_properties_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anytype_1": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -228,28 +285,28 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader } } - if (emptyMap == null) - throw new ArgumentNullException(nameof(emptyMap), "Property is required for class AdditionalPropertiesClass."); + if (emptyMap.IsSet && emptyMap.Value == null) + throw new ArgumentNullException(nameof(emptyMap), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapOfMapProperty == null) - throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapOfMapProperty.IsSet && mapOfMapProperty.Value == null) + throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapProperty == null) - throw new ArgumentNullException(nameof(mapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapProperty.IsSet && mapProperty.Value == null) + throw new ArgumentNullException(nameof(mapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype1 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype1.IsSet && mapWithUndeclaredPropertiesAnytype1.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype2 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype2.IsSet && mapWithUndeclaredPropertiesAnytype2.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype3 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype3.IsSet && mapWithUndeclaredPropertiesAnytype3.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesString == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesString.IsSet && mapWithUndeclaredPropertiesString.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is not nullable for class AdditionalPropertiesClass."); - return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + return new AdditionalPropertiesClass(anytype1, emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString); } /// @@ -276,22 +333,70 @@ public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass addi /// public void WriteProperties(ref Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("empty_map"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); - writer.WritePropertyName("map_of_map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_string"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); - writer.WritePropertyName("anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + if (additionalPropertiesClass.EmptyMapOption.IsSet && additionalPropertiesClass.EmptyMap == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.EmptyMap), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet && additionalPropertiesClass.MapOfMapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapPropertyOption.IsSet && additionalPropertiesClass.MapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.Anytype1Option.IsSet) + if (additionalPropertiesClass.Anytype1Option.Value != null) + { + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + } + else + writer.WriteNull("anytype_1"); + if (additionalPropertiesClass.EmptyMapOption.IsSet) + { + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet) + { + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapPropertyOption.IsSet) + { + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs index dd36cad83283..10b1c44a8c08 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Animal.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,10 +37,10 @@ public partial class Animal : IValidatableObject /// className /// color (default to "red") [JsonConstructor] - public Animal(string className, string color = @"red") + public Animal(string className, Option color = default) { ClassName = className; - Color = color; + ColorOption = color; OnCreated(); } @@ -51,11 +52,18 @@ public Animal(string className, string color = @"red") [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Gets or Sets additional properties @@ -121,8 +129,8 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - string? color = default; + Option className = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -140,10 +148,10 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -151,13 +159,16 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Animal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Animal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Animal."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Animal."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Animal."); - return new Animal(className, color); + return new Animal(className.Value!, color); } /// @@ -184,8 +195,16 @@ public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) { + if (animal.ClassName == null) + throw new ArgumentNullException(nameof(animal.ClassName), "Property is required for class Animal."); + + if (animal.ColorOption.IsSet && animal.Color == null) + throw new ArgumentNullException(nameof(animal.Color), "Property is required for class Animal."); + writer.WriteString("className", animal.ClassName); - writer.WriteString("color", animal.Color); + + if (animal.ColorOption.IsSet) + writer.WriteString("color", animal.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs index a9e4c983c629..844d79e43e18 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,33 +38,54 @@ public partial class ApiResponse : IValidatableObject /// message /// type [JsonConstructor] - public ApiResponse(int code, string message, string type) + public ApiResponse(Option code = default, Option message = default, Option type = default) { - Code = code; - Message = message; - Type = type; + CodeOption = code; + MessageOption = message; + TypeOption = type; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Code + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CodeOption { get; private set; } + /// /// Gets or Sets Code /// [JsonPropertyName("code")] - public int Code { get; set; } + public int? Code { get { return this. CodeOption; } set { this.CodeOption = new(value); } } + + /// + /// Used to track the state of Message + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MessageOption { get; private set; } /// /// Gets or Sets Message /// [JsonPropertyName("message")] - public string Message { get; set; } + public string? Message { get { return this. MessageOption; } set { this.MessageOption = new(value); } } + + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public string Type { get; set; } + public string? Type { get { return this. TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets additional properties @@ -120,9 +142,9 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? code = default; - string? message = default; - string? type = default; + Option code = default; + Option message = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -141,13 +163,13 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC { case "code": if (utf8JsonReader.TokenType != JsonTokenType.Null) - code = utf8JsonReader.GetInt32(); + code = new Option(utf8JsonReader.GetInt32()); break; case "message": - message = utf8JsonReader.GetString(); + message = new Option(utf8JsonReader.GetString()!); break; case "type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -155,16 +177,16 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (code == null) - throw new ArgumentNullException(nameof(code), "Property is required for class ApiResponse."); + if (code.IsSet && code.Value == null) + throw new ArgumentNullException(nameof(code), "Property is not nullable for class ApiResponse."); - if (message == null) - throw new ArgumentNullException(nameof(message), "Property is required for class ApiResponse."); + if (message.IsSet && message.Value == null) + throw new ArgumentNullException(nameof(message), "Property is not nullable for class ApiResponse."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class ApiResponse."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ApiResponse."); - return new ApiResponse(code.Value, message, type); + return new ApiResponse(code, message, type); } /// @@ -191,9 +213,20 @@ public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("code", apiResponse.Code); - writer.WriteString("message", apiResponse.Message); - writer.WriteString("type", apiResponse.Type); + if (apiResponse.MessageOption.IsSet && apiResponse.Message == null) + throw new ArgumentNullException(nameof(apiResponse.Message), "Property is required for class ApiResponse."); + + if (apiResponse.TypeOption.IsSet && apiResponse.Type == null) + throw new ArgumentNullException(nameof(apiResponse.Type), "Property is required for class ApiResponse."); + + if (apiResponse.CodeOption.IsSet) + writer.WriteNumber("code", apiResponse.CodeOption.Value!.Value); + + if (apiResponse.MessageOption.IsSet) + writer.WriteString("message", apiResponse.Message); + + if (apiResponse.TypeOption.IsSet) + writer.WriteString("type", apiResponse.Type); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs index 39c4ddd6c25b..d50ea4406a00 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Apple.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,33 +38,54 @@ public partial class Apple : IValidatableObject /// cultivar /// origin [JsonConstructor] - public Apple(string colorCode, string cultivar, string origin) + public Apple(Option colorCode = default, Option cultivar = default, Option origin = default) { - ColorCode = colorCode; - Cultivar = cultivar; - Origin = origin; + ColorCodeOption = colorCode; + CultivarOption = cultivar; + OriginOption = origin; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ColorCode + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorCodeOption { get; private set; } + /// /// Gets or Sets ColorCode /// [JsonPropertyName("color_code")] - public string ColorCode { get; set; } + public string? ColorCode { get { return this. ColorCodeOption; } set { this.ColorCodeOption = new(value); } } + + /// + /// Used to track the state of Cultivar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CultivarOption { get; private set; } /// /// Gets or Sets Cultivar /// [JsonPropertyName("cultivar")] - public string Cultivar { get; set; } + public string? Cultivar { get { return this. CultivarOption; } set { this.CultivarOption = new(value); } } + + /// + /// Used to track the state of Origin + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OriginOption { get; private set; } /// /// Gets or Sets Origin /// [JsonPropertyName("origin")] - public string Origin { get; set; } + public string? Origin { get { return this. OriginOption; } set { this.OriginOption = new(value); } } /// /// Gets or Sets additional properties @@ -94,28 +116,31 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { - if (this.ColorCode != null) { + if (this.ColorCodeOption.Value != null) { // ColorCode (string) pattern Regex regexColorCode = new Regex(@"^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$", RegexOptions.CultureInvariant); - if (!regexColorCode.Match(this.ColorCode).Success) + + if (this.ColorCodeOption.Value != null &&!regexColorCode.Match(this.ColorCodeOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ColorCode, must match a pattern of " + regexColorCode, new [] { "ColorCode" }); } } - if (this.Cultivar != null) { + if (this.CultivarOption.Value != null) { // Cultivar (string) pattern Regex regexCultivar = new Regex(@"^[a-zA-Z\s]*$", RegexOptions.CultureInvariant); - if (!regexCultivar.Match(this.Cultivar).Success) + + if (this.CultivarOption.Value != null &&!regexCultivar.Match(this.CultivarOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); } } - if (this.Origin != null) { + if (this.OriginOption.Value != null) { // Origin (string) pattern Regex regexOrigin = new Regex(@"^[A-Z\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexOrigin.Match(this.Origin).Success) + + if (this.OriginOption.Value != null &&!regexOrigin.Match(this.OriginOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); } @@ -147,9 +172,9 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? colorCode = default; - string? cultivar = default; - string? origin = default; + Option colorCode = default; + Option cultivar = default; + Option origin = default; while (utf8JsonReader.Read()) { @@ -167,13 +192,13 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color_code": - colorCode = utf8JsonReader.GetString(); + colorCode = new Option(utf8JsonReader.GetString()!); break; case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()!); break; case "origin": - origin = utf8JsonReader.GetString(); + origin = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -181,14 +206,14 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (colorCode == null) - throw new ArgumentNullException(nameof(colorCode), "Property is required for class Apple."); + if (colorCode.IsSet && colorCode.Value == null) + throw new ArgumentNullException(nameof(colorCode), "Property is not nullable for class Apple."); - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class Apple."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class Apple."); - if (origin == null) - throw new ArgumentNullException(nameof(origin), "Property is required for class Apple."); + if (origin.IsSet && origin.Value == null) + throw new ArgumentNullException(nameof(origin), "Property is not nullable for class Apple."); return new Apple(colorCode, cultivar, origin); } @@ -217,9 +242,23 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color_code", apple.ColorCode); - writer.WriteString("cultivar", apple.Cultivar); - writer.WriteString("origin", apple.Origin); + if (apple.ColorCodeOption.IsSet && apple.ColorCode == null) + throw new ArgumentNullException(nameof(apple.ColorCode), "Property is required for class Apple."); + + if (apple.CultivarOption.IsSet && apple.Cultivar == null) + throw new ArgumentNullException(nameof(apple.Cultivar), "Property is required for class Apple."); + + if (apple.OriginOption.IsSet && apple.Origin == null) + throw new ArgumentNullException(nameof(apple.Origin), "Property is required for class Apple."); + + if (apple.ColorCodeOption.IsSet) + writer.WriteString("color_code", apple.ColorCode); + + if (apple.CultivarOption.IsSet) + writer.WriteString("cultivar", apple.Cultivar); + + if (apple.OriginOption.IsSet) + writer.WriteString("origin", apple.Origin); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs index ca139374d181..0fb31ae31859 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/AppleReq.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,10 +37,10 @@ public partial class AppleReq : IValidatableObject /// cultivar /// mealy [JsonConstructor] - public AppleReq(string cultivar, bool mealy) + public AppleReq(string cultivar, Option mealy = default) { Cultivar = cultivar; - Mealy = mealy; + MealyOption = mealy; OnCreated(); } @@ -51,11 +52,18 @@ public AppleReq(string cultivar, bool mealy) [JsonPropertyName("cultivar")] public string Cultivar { get; set; } + /// + /// Used to track the state of Mealy + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MealyOption { get; private set; } + /// /// Gets or Sets Mealy /// [JsonPropertyName("mealy")] - public bool Mealy { get; set; } + public bool? Mealy { get { return this. MealyOption; } set { this.MealyOption = new(value); } } /// /// Returns the string presentation of the object @@ -104,8 +112,8 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? cultivar = default; - bool? mealy = default; + Option cultivar = default; + Option mealy = default; while (utf8JsonReader.Read()) { @@ -123,11 +131,11 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()!); break; case "mealy": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mealy = utf8JsonReader.GetBoolean(); + mealy = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -135,13 +143,16 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class AppleReq."); + if (!cultivar.IsSet) + throw new ArgumentException("Property is required for class AppleReq.", nameof(cultivar)); - if (mealy == null) - throw new ArgumentNullException(nameof(mealy), "Property is required for class AppleReq."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class AppleReq."); - return new AppleReq(cultivar, mealy.Value); + if (mealy.IsSet && mealy.Value == null) + throw new ArgumentNullException(nameof(mealy), "Property is not nullable for class AppleReq."); + + return new AppleReq(cultivar.Value!, mealy); } /// @@ -168,8 +179,13 @@ public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) { + if (appleReq.Cultivar == null) + throw new ArgumentNullException(nameof(appleReq.Cultivar), "Property is required for class AppleReq."); + writer.WriteString("cultivar", appleReq.Cultivar); - writer.WriteBoolean("mealy", appleReq.Mealy); + + if (appleReq.MealyOption.IsSet) + writer.WriteBoolean("mealy", appleReq.MealyOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 78ae23d63d61..c723d43d16c8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class ArrayOfArrayOfNumberOnly : IValidatableObject /// /// arrayArrayNumber [JsonConstructor] - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) + public ArrayOfArrayOfNumberOnly(Option>?> arrayArrayNumber = default) { - ArrayArrayNumber = arrayArrayNumber; + ArrayArrayNumberOption = arrayArrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayArrayNumber /// [JsonPropertyName("ArrayArrayNumber")] - public List> ArrayArrayNumber { get; set; } + public List>? ArrayArrayNumber { get { return this. ArrayArrayNumberOption; } set { this.ArrayArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? arrayArrayNumber = default; + Option>?> arrayArrayNumber = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, { case "ArrayArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayNumber = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayNumber = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -129,8 +137,8 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, } } - if (arrayArrayNumber == null) - throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + if (arrayArrayNumber.IsSet && arrayArrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is not nullable for class ArrayOfArrayOfNumberOnly."); return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); } @@ -159,8 +167,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly array /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet && arrayOfArrayOfNumberOnly.ArrayArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfArrayOfNumberOnly.ArrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 29af43d6c8b3..f1929407e896 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class ArrayOfNumberOnly : IValidatableObject /// /// arrayNumber [JsonConstructor] - public ArrayOfNumberOnly(List arrayNumber) + public ArrayOfNumberOnly(Option?> arrayNumber = default) { - ArrayNumber = arrayNumber; + ArrayNumberOption = arrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayNumber /// [JsonPropertyName("ArrayNumber")] - public List ArrayNumber { get; set; } + public List? ArrayNumber { get { return this. ArrayNumberOption; } set { this.ArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayNumber = default; + Option?> arrayNumber = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t { case "ArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNumber = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNumber = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -129,8 +137,8 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (arrayNumber == null) - throw new ArgumentNullException(nameof(arrayNumber), "Property is required for class ArrayOfNumberOnly."); + if (arrayNumber.IsSet && arrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayNumber), "Property is not nullable for class ArrayOfNumberOnly."); return new ArrayOfNumberOnly(arrayNumber); } @@ -159,8 +167,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumbe /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + if (arrayOfNumberOnly.ArrayNumberOption.IsSet && arrayOfNumberOnly.ArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfNumberOnly.ArrayNumber), "Property is required for class ArrayOfNumberOnly."); + + if (arrayOfNumberOnly.ArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs index c021f61cca54..f6ecfbb72d66 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,33 +38,54 @@ public partial class ArrayTest : IValidatableObject /// arrayArrayOfModel /// arrayOfString [JsonConstructor] - public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) + public ArrayTest(Option>?> arrayArrayOfInteger = default, Option>?> arrayArrayOfModel = default, Option?> arrayOfString = default) { - ArrayArrayOfInteger = arrayArrayOfInteger; - ArrayArrayOfModel = arrayArrayOfModel; - ArrayOfString = arrayOfString; + ArrayArrayOfIntegerOption = arrayArrayOfInteger; + ArrayArrayOfModelOption = arrayArrayOfModel; + ArrayOfStringOption = arrayOfString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayOfInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayOfIntegerOption { get; private set; } + /// /// Gets or Sets ArrayArrayOfInteger /// [JsonPropertyName("array_array_of_integer")] - public List> ArrayArrayOfInteger { get; set; } + public List>? ArrayArrayOfInteger { get { return this. ArrayArrayOfIntegerOption; } set { this.ArrayArrayOfIntegerOption = new(value); } } + + /// + /// Used to track the state of ArrayArrayOfModel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> ArrayArrayOfModelOption { get; private set; } /// /// Gets or Sets ArrayArrayOfModel /// [JsonPropertyName("array_array_of_model")] - public List> ArrayArrayOfModel { get; set; } + public List>? ArrayArrayOfModel { get { return this. ArrayArrayOfModelOption; } set { this.ArrayArrayOfModelOption = new(value); } } + + /// + /// Used to track the state of ArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayOfStringOption { get; private set; } /// /// Gets or Sets ArrayOfString /// [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } + public List? ArrayOfString { get { return this. ArrayOfStringOption; } set { this.ArrayOfStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -120,9 +142,9 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? arrayArrayOfInteger = default; - List>? arrayArrayOfModel = default; - List? arrayOfString = default; + Option>?> arrayArrayOfInteger = default; + Option>?> arrayArrayOfModel = default; + Option?> arrayOfString = default; while (utf8JsonReader.Read()) { @@ -141,15 +163,15 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "array_array_of_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfInteger = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_array_of_model": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfModel = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfModel = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayOfString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -157,14 +179,14 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (arrayArrayOfInteger == null) - throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is required for class ArrayTest."); + if (arrayArrayOfInteger.IsSet && arrayArrayOfInteger.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is not nullable for class ArrayTest."); - if (arrayArrayOfModel == null) - throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is required for class ArrayTest."); + if (arrayArrayOfModel.IsSet && arrayArrayOfModel.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is not nullable for class ArrayTest."); - if (arrayOfString == null) - throw new ArgumentNullException(nameof(arrayOfString), "Property is required for class ArrayTest."); + if (arrayOfString.IsSet && arrayOfString.Value == null) + throw new ArgumentNullException(nameof(arrayOfString), "Property is not nullable for class ArrayTest."); return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); } @@ -193,12 +215,30 @@ public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_array_of_integer"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); - writer.WritePropertyName("array_array_of_model"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); - writer.WritePropertyName("array_of_string"); - JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + if (arrayTest.ArrayArrayOfIntegerOption.IsSet && arrayTest.ArrayArrayOfInteger == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfInteger), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfModelOption.IsSet && arrayTest.ArrayArrayOfModel == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfModel), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayOfStringOption.IsSet && arrayTest.ArrayOfString == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayOfString), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfIntegerOption.IsSet) + { + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); + } + if (arrayTest.ArrayArrayOfModelOption.IsSet) + { + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); + } + if (arrayTest.ArrayOfStringOption.IsSet) + { + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs index a73515d6023b..de17f0c93875 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Banana.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Banana : IValidatableObject /// /// lengthCm [JsonConstructor] - public Banana(decimal lengthCm) + public Banana(Option lengthCm = default) { - LengthCm = lengthCm; + LengthCmOption = lengthCm; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of LengthCm + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LengthCmOption { get; private set; } + /// /// Gets or Sets LengthCm /// [JsonPropertyName("lengthCm")] - public decimal LengthCm { get; set; } + public decimal? LengthCm { get { return this. LengthCmOption; } set { this.LengthCmOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; + Option lengthCm = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -129,10 +137,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class Banana."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class Banana."); - return new Banana(lengthCm.Value); + return new Banana(lengthCm); } /// @@ -159,7 +167,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("lengthCm", banana.LengthCm); + if (banana.LengthCmOption.IsSet) + writer.WriteNumber("lengthCm", banana.LengthCmOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs index 20d095383d78..399687d74f0e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BananaReq.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,10 +37,10 @@ public partial class BananaReq : IValidatableObject /// lengthCm /// sweet [JsonConstructor] - public BananaReq(decimal lengthCm, bool sweet) + public BananaReq(decimal lengthCm, Option sweet = default) { LengthCm = lengthCm; - Sweet = sweet; + SweetOption = sweet; OnCreated(); } @@ -51,11 +52,18 @@ public BananaReq(decimal lengthCm, bool sweet) [JsonPropertyName("lengthCm")] public decimal LengthCm { get; set; } + /// + /// Used to track the state of Sweet + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SweetOption { get; private set; } + /// /// Gets or Sets Sweet /// [JsonPropertyName("sweet")] - public bool Sweet { get; set; } + public bool? Sweet { get { return this. SweetOption; } set { this.SweetOption = new(value); } } /// /// Returns the string presentation of the object @@ -104,8 +112,8 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; - bool? sweet = default; + Option lengthCm = default; + Option sweet = default; while (utf8JsonReader.Read()) { @@ -124,11 +132,11 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; case "sweet": if (utf8JsonReader.TokenType != JsonTokenType.Null) - sweet = utf8JsonReader.GetBoolean(); + sweet = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -136,13 +144,16 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class BananaReq."); + if (!lengthCm.IsSet) + throw new ArgumentException("Property is required for class BananaReq.", nameof(lengthCm)); - if (sweet == null) - throw new ArgumentNullException(nameof(sweet), "Property is required for class BananaReq."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class BananaReq."); - return new BananaReq(lengthCm.Value, sweet.Value); + if (sweet.IsSet && sweet.Value == null) + throw new ArgumentNullException(nameof(sweet), "Property is not nullable for class BananaReq."); + + return new BananaReq(lengthCm.Value!.Value!, sweet); } /// @@ -170,7 +181,9 @@ public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSeria public void WriteProperties(ref Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) { writer.WriteNumber("lengthCm", bananaReq.LengthCm); - writer.WriteBoolean("sweet", bananaReq.Sweet); + + if (bananaReq.SweetOption.IsSet) + writer.WriteBoolean("sweet", bananaReq.SweetOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs index 87c83d423c17..6388a29478f7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/BasquePig.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,7 +103,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -120,7 +121,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,10 +129,13 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class BasquePig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class BasquePig.", nameof(className)); - return new BasquePig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class BasquePig."); + + return new BasquePig(className.Value!); } /// @@ -158,6 +162,9 @@ public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) { + if (basquePig.ClassName == null) + throw new ArgumentNullException(nameof(basquePig.ClassName), "Property is required for class BasquePig."); + writer.WriteString("className", basquePig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs index 53520c57a3d9..d2cbece80d4f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Capitalization.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -40,55 +41,97 @@ public partial class Capitalization : IValidatableObject /// smallCamel /// smallSnake [JsonConstructor] - public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) + public Capitalization(Option aTTNAME = default, Option capitalCamel = default, Option capitalSnake = default, Option sCAETHFlowPoints = default, Option smallCamel = default, Option smallSnake = default) { - ATT_NAME = aTTNAME; - CapitalCamel = capitalCamel; - CapitalSnake = capitalSnake; - SCAETHFlowPoints = sCAETHFlowPoints; - SmallCamel = smallCamel; - SmallSnake = smallSnake; + ATT_NAMEOption = aTTNAME; + CapitalCamelOption = capitalCamel; + CapitalSnakeOption = capitalSnake; + SCAETHFlowPointsOption = sCAETHFlowPoints; + SmallCamelOption = smallCamel; + SmallSnakeOption = smallSnake; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ATT_NAME + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ATT_NAMEOption { get; private set; } + /// /// Name of the pet /// /// Name of the pet [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + public string? ATT_NAME { get { return this. ATT_NAMEOption; } set { this.ATT_NAMEOption = new(value); } } + + /// + /// Used to track the state of CapitalCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalCamelOption { get; private set; } /// /// Gets or Sets CapitalCamel /// [JsonPropertyName("CapitalCamel")] - public string CapitalCamel { get; set; } + public string? CapitalCamel { get { return this. CapitalCamelOption; } set { this.CapitalCamelOption = new(value); } } + + /// + /// Used to track the state of CapitalSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalSnakeOption { get; private set; } /// /// Gets or Sets CapitalSnake /// [JsonPropertyName("Capital_Snake")] - public string CapitalSnake { get; set; } + public string? CapitalSnake { get { return this. CapitalSnakeOption; } set { this.CapitalSnakeOption = new(value); } } + + /// + /// Used to track the state of SCAETHFlowPoints + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SCAETHFlowPointsOption { get; private set; } /// /// Gets or Sets SCAETHFlowPoints /// [JsonPropertyName("SCA_ETH_Flow_Points")] - public string SCAETHFlowPoints { get; set; } + public string? SCAETHFlowPoints { get { return this. SCAETHFlowPointsOption; } set { this.SCAETHFlowPointsOption = new(value); } } + + /// + /// Used to track the state of SmallCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallCamelOption { get; private set; } /// /// Gets or Sets SmallCamel /// [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + public string? SmallCamel { get { return this. SmallCamelOption; } set { this.SmallCamelOption = new(value); } } + + /// + /// Used to track the state of SmallSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallSnakeOption { get; private set; } /// /// Gets or Sets SmallSnake /// [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } + public string? SmallSnake { get { return this. SmallSnakeOption; } set { this.SmallSnakeOption = new(value); } } /// /// Gets or Sets additional properties @@ -148,12 +191,12 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? aTTNAME = default; - string? capitalCamel = default; - string? capitalSnake = default; - string? sCAETHFlowPoints = default; - string? smallCamel = default; - string? smallSnake = default; + Option aTTNAME = default; + Option capitalCamel = default; + Option capitalSnake = default; + Option sCAETHFlowPoints = default; + Option smallCamel = default; + Option smallSnake = default; while (utf8JsonReader.Read()) { @@ -171,22 +214,22 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "ATT_NAME": - aTTNAME = utf8JsonReader.GetString(); + aTTNAME = new Option(utf8JsonReader.GetString()!); break; case "CapitalCamel": - capitalCamel = utf8JsonReader.GetString(); + capitalCamel = new Option(utf8JsonReader.GetString()!); break; case "Capital_Snake": - capitalSnake = utf8JsonReader.GetString(); + capitalSnake = new Option(utf8JsonReader.GetString()!); break; case "SCA_ETH_Flow_Points": - sCAETHFlowPoints = utf8JsonReader.GetString(); + sCAETHFlowPoints = new Option(utf8JsonReader.GetString()!); break; case "smallCamel": - smallCamel = utf8JsonReader.GetString(); + smallCamel = new Option(utf8JsonReader.GetString()!); break; case "small_Snake": - smallSnake = utf8JsonReader.GetString(); + smallSnake = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,23 +237,23 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (aTTNAME == null) - throw new ArgumentNullException(nameof(aTTNAME), "Property is required for class Capitalization."); + if (aTTNAME.IsSet && aTTNAME.Value == null) + throw new ArgumentNullException(nameof(aTTNAME), "Property is not nullable for class Capitalization."); - if (capitalCamel == null) - throw new ArgumentNullException(nameof(capitalCamel), "Property is required for class Capitalization."); + if (capitalCamel.IsSet && capitalCamel.Value == null) + throw new ArgumentNullException(nameof(capitalCamel), "Property is not nullable for class Capitalization."); - if (capitalSnake == null) - throw new ArgumentNullException(nameof(capitalSnake), "Property is required for class Capitalization."); + if (capitalSnake.IsSet && capitalSnake.Value == null) + throw new ArgumentNullException(nameof(capitalSnake), "Property is not nullable for class Capitalization."); - if (sCAETHFlowPoints == null) - throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is required for class Capitalization."); + if (sCAETHFlowPoints.IsSet && sCAETHFlowPoints.Value == null) + throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is not nullable for class Capitalization."); - if (smallCamel == null) - throw new ArgumentNullException(nameof(smallCamel), "Property is required for class Capitalization."); + if (smallCamel.IsSet && smallCamel.Value == null) + throw new ArgumentNullException(nameof(smallCamel), "Property is not nullable for class Capitalization."); - if (smallSnake == null) - throw new ArgumentNullException(nameof(smallSnake), "Property is required for class Capitalization."); + if (smallSnake.IsSet && smallSnake.Value == null) + throw new ArgumentNullException(nameof(smallSnake), "Property is not nullable for class Capitalization."); return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); } @@ -239,12 +282,41 @@ public override void Write(Utf8JsonWriter writer, Capitalization capitalization, /// public void WriteProperties(ref Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("ATT_NAME", capitalization.ATT_NAME); - writer.WriteString("CapitalCamel", capitalization.CapitalCamel); - writer.WriteString("Capital_Snake", capitalization.CapitalSnake); - writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); - writer.WriteString("smallCamel", capitalization.SmallCamel); - writer.WriteString("small_Snake", capitalization.SmallSnake); + if (capitalization.ATT_NAMEOption.IsSet && capitalization.ATT_NAME == null) + throw new ArgumentNullException(nameof(capitalization.ATT_NAME), "Property is required for class Capitalization."); + + if (capitalization.CapitalCamelOption.IsSet && capitalization.CapitalCamel == null) + throw new ArgumentNullException(nameof(capitalization.CapitalCamel), "Property is required for class Capitalization."); + + if (capitalization.CapitalSnakeOption.IsSet && capitalization.CapitalSnake == null) + throw new ArgumentNullException(nameof(capitalization.CapitalSnake), "Property is required for class Capitalization."); + + if (capitalization.SCAETHFlowPointsOption.IsSet && capitalization.SCAETHFlowPoints == null) + throw new ArgumentNullException(nameof(capitalization.SCAETHFlowPoints), "Property is required for class Capitalization."); + + if (capitalization.SmallCamelOption.IsSet && capitalization.SmallCamel == null) + throw new ArgumentNullException(nameof(capitalization.SmallCamel), "Property is required for class Capitalization."); + + if (capitalization.SmallSnakeOption.IsSet && capitalization.SmallSnake == null) + throw new ArgumentNullException(nameof(capitalization.SmallSnake), "Property is required for class Capitalization."); + + if (capitalization.ATT_NAMEOption.IsSet) + writer.WriteString("ATT_NAME", capitalization.ATT_NAME); + + if (capitalization.CapitalCamelOption.IsSet) + writer.WriteString("CapitalCamel", capitalization.CapitalCamel); + + if (capitalization.CapitalSnakeOption.IsSet) + writer.WriteString("Capital_Snake", capitalization.CapitalSnake); + + if (capitalization.SCAETHFlowPointsOption.IsSet) + writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); + + if (capitalization.SmallCamelOption.IsSet) + writer.WriteString("smallCamel", capitalization.SmallCamel); + + if (capitalization.SmallSnakeOption.IsSet) + writer.WriteString("small_Snake", capitalization.SmallSnake); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs index 2a0960e3a903..b914d1dd4d6e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Cat.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,22 +35,29 @@ public partial class Cat : Animal, IValidatableObject /// Initializes a new instance of the class. /// /// className - /// declawed /// color (default to "red") + /// declawed [JsonConstructor] - public Cat(string className, bool declawed, string color = @"red") : base(className, color) + public Cat(string className, Option color = default, Option declawed = default) : base(className, color) { - Declawed = declawed; + DeclawedOption = declawed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Declawed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeclawedOption { get; private set; } + /// /// Gets or Sets Declawed /// [JsonPropertyName("declawed")] - public bool Declawed { get; set; } + public bool? Declawed { get { return this. DeclawedOption; } set { this.DeclawedOption = new(value); } } /// /// Returns the string presentation of the object @@ -88,9 +96,9 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - bool? declawed = default; - string? color = default; + Option className = default; + Option color = default; + Option declawed = default; while (utf8JsonReader.Read()) { @@ -108,14 +116,14 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); + break; + case "color": + color = new Option(utf8JsonReader.GetString()!); break; case "declawed": if (utf8JsonReader.TokenType != JsonTokenType.Null) - declawed = utf8JsonReader.GetBoolean(); - break; - case "color": - color = utf8JsonReader.GetString(); + declawed = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -123,16 +131,19 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Cat."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Cat.", nameof(className)); - if (declawed == null) - throw new ArgumentNullException(nameof(declawed), "Property is required for class Cat."); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Cat."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Cat."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Cat."); - return new Cat(className, declawed.Value, color); + if (declawed.IsSet && declawed.Value == null) + throw new ArgumentNullException(nameof(declawed), "Property is not nullable for class Cat."); + + return new Cat(className.Value!, color, declawed); } /// @@ -159,9 +170,19 @@ public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) { + if (cat.ClassName == null) + throw new ArgumentNullException(nameof(cat.ClassName), "Property is required for class Cat."); + + if (cat.ColorOption.IsSet && cat.Color == null) + throw new ArgumentNullException(nameof(cat.Color), "Property is required for class Cat."); + writer.WriteString("className", cat.ClassName); - writer.WriteBoolean("declawed", cat.Declawed); - writer.WriteString("color", cat.Color); + + if (cat.ColorOption.IsSet) + writer.WriteString("color", cat.Color); + + if (cat.DeclawedOption.IsSet) + writer.WriteBoolean("declawed", cat.DeclawedOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs index 714575af8f4d..55a7984769bc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Category.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,20 +37,27 @@ public partial class Category : IValidatableObject /// id /// name (default to "default-name") [JsonConstructor] - public Category(long id, string name = @"default-name") + public Category(Option id = default, string name = @"default-name") { - Id = id; + IdOption = id; Name = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// /// Gets or Sets Name @@ -111,8 +119,8 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string? name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -131,10 +139,10 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -142,13 +150,16 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Category."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Category.", nameof(name)); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Category."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Category."); - return new Category(id.Value, name); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Category."); + + return new Category(id, name.Value!); } /// @@ -175,7 +186,12 @@ public override void Write(Utf8JsonWriter writer, Category category, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", category.Id); + if (category.Name == null) + throw new ArgumentNullException(nameof(category.Name), "Property is required for class Category."); + + if (category.IdOption.IsSet) + writer.WriteNumber("id", category.IdOption.Value!.Value); + writer.WriteString("name", category.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs index 2d39883e18b2..4a9624ad2416 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ChildCat.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,9 +37,9 @@ public partial class ChildCat : ParentPet, IValidatableObject /// name /// petType (default to PetTypeEnum.ChildCat) [JsonConstructor] - public ChildCat(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) + public ChildCat(Option name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) { - Name = name; + NameOption = name; PetType = petType; OnCreated(); } @@ -103,11 +104,18 @@ public static string PetTypeEnumToJsonValue(PetTypeEnum value) [JsonPropertyName("pet_type")] public new PetTypeEnum PetType { get; set; } + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Returns the string presentation of the object @@ -147,8 +155,8 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; - ChildCat.PetTypeEnum? petType = default; + Option name = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -166,13 +174,12 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; case "pet_type": string? petTypeRawValue = utf8JsonReader.GetString(); - petType = petTypeRawValue == null - ? null - : ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue); + if (petTypeRawValue != null) + petType = new Option(ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue)); break; default: break; @@ -180,13 +187,16 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class ChildCat."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ChildCat.", nameof(petType)); - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ChildCat."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class ChildCat."); - return new ChildCat(name, petType.Value); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ChildCat."); + + return new ChildCat(name, petType.Value!.Value!); } /// @@ -213,13 +223,14 @@ public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", childCat.Name); + if (childCat.NameOption.IsSet && childCat.Name == null) + throw new ArgumentNullException(nameof(childCat.Name), "Property is required for class ChildCat."); + + if (childCat.NameOption.IsSet) + writer.WriteString("name", childCat.Name); var petTypeRawValue = ChildCat.PetTypeEnumToJsonValue(childCat.PetType); - if (petTypeRawValue != null) - writer.WriteString("pet_type", petTypeRawValue); - else - writer.WriteNull("pet_type"); + writer.WriteString("pet_type", petTypeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs index 66a7dee91d88..995f04192dc0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ClassModel.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class ClassModel : IValidatableObject /// /// varClass [JsonConstructor] - public ClassModel(string varClass) + public ClassModel(Option varClass = default) { - VarClass = varClass; + VarClassOption = varClass; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("_class")] - public string VarClass { get; set; } + public string? VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClass = default; + Option varClass = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { case "_class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class ClassModel."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class ClassModel."); return new ClassModel(varClass); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_class", classModel.VarClass); + if (classModel.VarClassOption.IsSet && classModel.VarClass == null) + throw new ArgumentNullException(nameof(classModel.VarClass), "Property is required for class ClassModel."); + + if (classModel.VarClassOption.IsSet) + writer.WriteString("_class", classModel.VarClass); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 01f2390005d2..6e9034b20b2a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -111,8 +112,8 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; - string? shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -130,10 +131,10 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,13 +142,19 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class ComplexQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ComplexQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(shapeType)); - return new ComplexQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class ComplexQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ComplexQuadrilateral."); + + return new ComplexQuadrilateral(quadrilateralType.Value!, shapeType.Value!); } /// @@ -174,7 +181,14 @@ public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQu /// public void WriteProperties(ref Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (complexQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.QuadrilateralType), "Property is required for class ComplexQuadrilateral."); + + if (complexQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.ShapeType), "Property is required for class ComplexQuadrilateral."); + writer.WriteString("quadrilateralType", complexQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", complexQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs index fd9ee9d36830..cb41bcddcd6c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DanishPig.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,7 +103,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -120,7 +121,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,10 +129,13 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class DanishPig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class DanishPig.", nameof(className)); - return new DanishPig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class DanishPig."); + + return new DanishPig(className.Value!); } /// @@ -158,6 +162,9 @@ public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) { + if (danishPig.ClassName == null) + throw new ArgumentNullException(nameof(danishPig.ClassName), "Property is required for class DanishPig."); + writer.WriteString("className", danishPig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DateOnlyClass.cs index 6a9c5d4a7952..354931e975f4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DateOnlyClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,20 +36,27 @@ public partial class DateOnlyClass : IValidatableObject /// /// dateOnlyProperty [JsonConstructor] - public DateOnlyClass(DateTime dateOnlyProperty) + public DateOnlyClass(Option dateOnlyProperty = default) { - DateOnlyProperty = dateOnlyProperty; + DateOnlyPropertyOption = dateOnlyProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateOnlyProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateOnlyPropertyOption { get; private set; } + /// /// Gets or Sets DateOnlyProperty /// /// Fri Jul 21 00:00:00 UTC 2017 [JsonPropertyName("dateOnlyProperty")] - public DateTime DateOnlyProperty { get; set; } + public DateOnly? DateOnlyProperty { get { return this. DateOnlyPropertyOption; } set { this.DateOnlyPropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -108,7 +116,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateOnlyProperty = default; + Option dateOnlyProperty = default; while (utf8JsonReader.Read()) { @@ -127,7 +135,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT { case "dateOnlyProperty": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateOnlyProperty = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateOnlyProperty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -135,10 +143,10 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (dateOnlyProperty == null) - throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is required for class DateOnlyClass."); + if (dateOnlyProperty.IsSet && dateOnlyProperty.Value == null) + throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is not nullable for class DateOnlyClass."); - return new DateOnlyClass(dateOnlyProperty.Value); + return new DateOnlyClass(dateOnlyProperty); } /// @@ -165,7 +173,8 @@ public override void Write(Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyProperty.ToString(DateOnlyPropertyFormat)); + if (dateOnlyClass.DateOnlyPropertyOption.IsSet) + writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyPropertyOption.Value!.Value.ToString(DateOnlyPropertyFormat)); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 84ebd0792c33..77dea9cffa72 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class DeprecatedObject : IValidatableObject /// /// name [JsonConstructor] - public DeprecatedObject(string name) + public DeprecatedObject(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class DeprecatedObject."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DeprecatedObject."); return new DeprecatedObject(name); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObj /// public void WriteProperties(ref Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", deprecatedObject.Name); + if (deprecatedObject.NameOption.IsSet && deprecatedObject.Name == null) + throw new ArgumentNullException(nameof(deprecatedObject.Name), "Property is required for class DeprecatedObject."); + + if (deprecatedObject.NameOption.IsSet) + writer.WriteString("name", deprecatedObject.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs index fa2bab080244..7891f26505a3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Dog.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,23 +34,30 @@ public partial class Dog : Animal, IValidatableObject /// /// Initializes a new instance of the class. /// - /// breed /// className + /// breed /// color (default to "red") [JsonConstructor] - public Dog(string breed, string className, string color = @"red") : base(className, color) + public Dog(string className, Option breed = default, Option color = default) : base(className, color) { - Breed = breed; + BreedOption = breed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Breed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BreedOption { get; private set; } + /// /// Gets or Sets Breed /// [JsonPropertyName("breed")] - public string Breed { get; set; } + public string? Breed { get { return this. BreedOption; } set { this.BreedOption = new(value); } } /// /// Returns the string presentation of the object @@ -88,9 +96,9 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? breed = default; - string? className = default; - string? color = default; + Option className = default; + Option breed = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -107,14 +115,14 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "breed": - breed = utf8JsonReader.GetString(); - break; case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); + break; + case "breed": + breed = new Option(utf8JsonReader.GetString()!); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -122,16 +130,19 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (breed == null) - throw new ArgumentNullException(nameof(breed), "Property is required for class Dog."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Dog.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Dog."); - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Dog."); + if (breed.IsSet && breed.Value == null) + throw new ArgumentNullException(nameof(breed), "Property is not nullable for class Dog."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Dog."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Dog."); - return new Dog(breed, className, color); + return new Dog(className.Value!, breed, color); } /// @@ -158,9 +169,22 @@ public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("breed", dog.Breed); + if (dog.ClassName == null) + throw new ArgumentNullException(nameof(dog.ClassName), "Property is required for class Dog."); + + if (dog.BreedOption.IsSet && dog.Breed == null) + throw new ArgumentNullException(nameof(dog.Breed), "Property is required for class Dog."); + + if (dog.ColorOption.IsSet && dog.Color == null) + throw new ArgumentNullException(nameof(dog.Color), "Property is required for class Dog."); + writer.WriteString("className", dog.ClassName); - writer.WriteString("color", dog.Color); + + if (dog.BreedOption.IsSet) + writer.WriteString("breed", dog.Breed); + + if (dog.ColorOption.IsSet) + writer.WriteString("color", dog.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs index 8f5fff0f79a0..038d71cc8342 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Drawing.cs @@ -22,56 +22,85 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Drawing /// - public partial class Drawing : Dictionary, IValidatableObject + public partial class Drawing : IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape - /// shapes /// nullableShape /// shapeOrNull + /// shapes [JsonConstructor] - public Drawing(Shape mainShape, List shapes, NullableShape? nullableShape = default, ShapeOrNull? shapeOrNull = default) : base() + public Drawing(Option mainShape = default, Option nullableShape = default, Option shapeOrNull = default, Option?> shapes = default) { - MainShape = mainShape; - Shapes = shapes; - NullableShape = nullableShape; - ShapeOrNull = shapeOrNull; + MainShapeOption = mainShape; + NullableShapeOption = nullableShape; + ShapeOrNullOption = shapeOrNull; + ShapesOption = shapes; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MainShape + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MainShapeOption { get; private set; } + /// /// Gets or Sets MainShape /// [JsonPropertyName("mainShape")] - public Shape MainShape { get; set; } + public Shape? MainShape { get { return this. MainShapeOption; } set { this.MainShapeOption = new(value); } } /// - /// Gets or Sets Shapes + /// Used to track the state of NullableShape /// - [JsonPropertyName("shapes")] - public List Shapes { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableShapeOption { get; private set; } /// /// Gets or Sets NullableShape /// [JsonPropertyName("nullableShape")] - public NullableShape? NullableShape { get; set; } + public NullableShape? NullableShape { get { return this. NullableShapeOption; } set { this.NullableShapeOption = new(value); } } + + /// + /// Used to track the state of ShapeOrNull + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShapeOrNullOption { get; private set; } /// /// Gets or Sets ShapeOrNull /// [JsonPropertyName("shapeOrNull")] - public ShapeOrNull? ShapeOrNull { get; set; } + public ShapeOrNull? ShapeOrNull { get { return this. ShapeOrNullOption; } set { this.ShapeOrNullOption = new(value); } } + + /// + /// Used to track the state of Shapes + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ShapesOption { get; private set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List? Shapes { get { return this. ShapesOption; } set { this.ShapesOption = new(value); } } /// /// Gets or Sets additional properties @@ -87,11 +116,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); - sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -103,16 +131,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -140,10 +158,10 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Shape? mainShape = default; - List? shapes = default; - NullableShape? nullableShape = default; - ShapeOrNull? shapeOrNull = default; + Option mainShape = default; + Option nullableShape = default; + Option shapeOrNull = default; + Option?> shapes = default; while (utf8JsonReader.Read()) { @@ -162,19 +180,19 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "mainShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mainShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "shapes": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapes = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mainShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "nullableShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - nullableShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + nullableShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "shapeOrNull": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapeOrNull = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shapeOrNull = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "shapes": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapes = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -182,13 +200,13 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (mainShape == null) - throw new ArgumentNullException(nameof(mainShape), "Property is required for class Drawing."); + if (mainShape.IsSet && mainShape.Value == null) + throw new ArgumentNullException(nameof(mainShape), "Property is not nullable for class Drawing."); - if (shapes == null) - throw new ArgumentNullException(nameof(shapes), "Property is required for class Drawing."); + if (shapes.IsSet && shapes.Value == null) + throw new ArgumentNullException(nameof(shapes), "Property is not nullable for class Drawing."); - return new Drawing(mainShape, shapes, nullableShape, shapeOrNull); + return new Drawing(mainShape, nullableShape, shapeOrNull, shapes); } /// @@ -215,14 +233,38 @@ public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("mainShape"); - JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); - writer.WritePropertyName("shapes"); - JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); - writer.WritePropertyName("nullableShape"); - JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); - writer.WritePropertyName("shapeOrNull"); - JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + if (drawing.MainShapeOption.IsSet && drawing.MainShape == null) + throw new ArgumentNullException(nameof(drawing.MainShape), "Property is required for class Drawing."); + + if (drawing.ShapesOption.IsSet && drawing.Shapes == null) + throw new ArgumentNullException(nameof(drawing.Shapes), "Property is required for class Drawing."); + + if (drawing.MainShapeOption.IsSet) + { + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); + } + if (drawing.NullableShapeOption.IsSet) + if (drawing.NullableShapeOption.Value != null) + { + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); + } + else + writer.WriteNull("nullableShape"); + if (drawing.ShapeOrNullOption.IsSet) + if (drawing.ShapeOrNullOption.Value != null) + { + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + } + else + writer.WriteNull("shapeOrNull"); + if (drawing.ShapesOption.IsSet) + { + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs index 431924ef1e6c..423dffd7b64c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,10 +37,10 @@ public partial class EnumArrays : IValidatableObject /// arrayEnum /// justSymbol [JsonConstructor] - public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) + public EnumArrays(Option?> arrayEnum = default, Option justSymbol = default) { - ArrayEnum = arrayEnum; - JustSymbol = justSymbol; + ArrayEnumOption = arrayEnum; + JustSymbolOption = justSymbol; OnCreated(); } @@ -100,7 +101,7 @@ public static ArrayEnumEnum ArrayEnumEnumFromString(string value) /// /// /// - public static string ArrayEnumEnumToJsonValue(ArrayEnumEnum value) + public static string ArrayEnumEnumToJsonValue(ArrayEnumEnum? value) { if (value == ArrayEnumEnum.Fish) return "fish"; @@ -166,7 +167,7 @@ public static JustSymbolEnum JustSymbolEnumFromString(string value) /// /// /// - public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) + public static string JustSymbolEnumToJsonValue(JustSymbolEnum? value) { if (value == JustSymbolEnum.GreaterThanOrEqualTo) return ">="; @@ -177,17 +178,31 @@ public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of JustSymbol + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustSymbolOption { get; private set; } + /// /// Gets or Sets JustSymbol /// [JsonPropertyName("just_symbol")] - public JustSymbolEnum JustSymbol { get; set; } + public JustSymbolEnum? JustSymbol { get { return this.JustSymbolOption; } set { this.JustSymbolOption = new(value); } } + + /// + /// Used to track the state of ArrayEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayEnumOption { get; private set; } /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List? ArrayEnum { get { return this. ArrayEnumOption; } set { this.ArrayEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -243,8 +258,8 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayEnum = default; - EnumArrays.JustSymbolEnum? justSymbol = default; + Option?> arrayEnum = default; + Option justSymbol = default; while (utf8JsonReader.Read()) { @@ -263,13 +278,12 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "array_enum": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayEnum = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayEnum = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "just_symbol": string? justSymbolRawValue = utf8JsonReader.GetString(); - justSymbol = justSymbolRawValue == null - ? null - : EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue); + if (justSymbolRawValue != null) + justSymbol = new Option(EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue)); break; default: break; @@ -277,13 +291,13 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (arrayEnum == null) - throw new ArgumentNullException(nameof(arrayEnum), "Property is required for class EnumArrays."); + if (arrayEnum.IsSet && arrayEnum.Value == null) + throw new ArgumentNullException(nameof(arrayEnum), "Property is not nullable for class EnumArrays."); - if (justSymbol == null) - throw new ArgumentNullException(nameof(justSymbol), "Property is required for class EnumArrays."); + if (justSymbol.IsSet && justSymbol.Value == null) + throw new ArgumentNullException(nameof(justSymbol), "Property is not nullable for class EnumArrays."); - return new EnumArrays(arrayEnum, justSymbol.Value); + return new EnumArrays(arrayEnum, justSymbol); } /// @@ -310,14 +324,16 @@ public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_enum"); - JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); - - var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); - if (justSymbolRawValue != null) - writer.WriteString("just_symbol", justSymbolRawValue); - else - writer.WriteNull("just_symbol"); + if (enumArrays.ArrayEnumOption.IsSet && enumArrays.ArrayEnum == null) + throw new ArgumentNullException(nameof(enumArrays.ArrayEnum), "Property is required for class EnumArrays."); + + if (enumArrays.ArrayEnumOption.IsSet) + { + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); + } + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbolOption.Value!.Value); + writer.WriteString("just_symbol", justSymbolRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs index 76dcba15b394..03b2780c4842 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs index 6ea096d90414..4cea89ad2853 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EnumTest.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,32 +34,188 @@ public partial class EnumTest : IValidatableObject /// /// Initializes a new instance of the class. /// + /// enumStringRequired /// enumInteger /// enumIntegerOnly /// enumNumber /// enumString - /// enumStringRequired + /// outerEnum /// outerEnumDefaultValue /// outerEnumInteger /// outerEnumIntegerDefaultValue - /// outerEnum [JsonConstructor] - public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) + public EnumTest(EnumStringRequiredEnum enumStringRequired, Option enumInteger = default, Option enumIntegerOnly = default, Option enumNumber = default, Option enumString = default, Option outerEnum = default, Option outerEnumDefaultValue = default, Option outerEnumInteger = default, Option outerEnumIntegerDefaultValue = default) { - EnumInteger = enumInteger; - EnumIntegerOnly = enumIntegerOnly; - EnumNumber = enumNumber; - EnumString = enumString; EnumStringRequired = enumStringRequired; - OuterEnumDefaultValue = outerEnumDefaultValue; - OuterEnumInteger = outerEnumInteger; - OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - OuterEnum = outerEnum; + EnumIntegerOption = enumInteger; + EnumIntegerOnlyOption = enumIntegerOnly; + EnumNumberOption = enumNumber; + EnumStringOption = enumString; + OuterEnumOption = outerEnum; + OuterEnumDefaultValueOption = outerEnumDefaultValue; + OuterEnumIntegerOption = outerEnumInteger; + OuterEnumIntegerDefaultValueOption = outerEnumIntegerDefaultValue; OnCreated(); } partial void OnCreated(); + /// + /// Defines EnumStringRequired + /// + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) + { + if (value == EnumStringRequiredEnum.UPPER) + return "UPPER"; + + if (value == EnumStringRequiredEnum.Lower) + return "lower"; + + if (value == EnumStringRequiredEnum.Empty) + return ""; + + if (value == EnumStringRequiredEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringRequiredEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringRequiredEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringRequiredEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumStringRequired + /// + [JsonPropertyName("enum_string_required")] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + /// /// Defines EnumInteger /// @@ -118,11 +275,18 @@ public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) return (int) value; } + /// + /// Used to track the state of EnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOption { get; private set; } + /// /// Gets or Sets EnumInteger /// [JsonPropertyName("enum_integer")] - public EnumIntegerEnum EnumInteger { get; set; } + public EnumIntegerEnum? EnumInteger { get { return this.EnumIntegerOption; } set { this.EnumIntegerOption = new(value); } } /// /// Defines EnumIntegerOnly @@ -183,11 +347,18 @@ public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) return (int) value; } + /// + /// Used to track the state of EnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOnlyOption { get; private set; } + /// /// Gets or Sets EnumIntegerOnly /// [JsonPropertyName("enum_integer_only")] - public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } + public EnumIntegerOnlyEnum? EnumIntegerOnly { get { return this.EnumIntegerOnlyOption; } set { this.EnumIntegerOnlyOption = new(value); } } /// /// Defines EnumNumber @@ -244,7 +415,7 @@ public static EnumNumberEnum EnumNumberEnumFromString(string value) /// /// /// - public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) + public static double EnumNumberEnumToJsonValue(EnumNumberEnum? value) { if (value == EnumNumberEnum.NUMBER_1_DOT_1) return 1.1; @@ -255,11 +426,18 @@ public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of EnumNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumNumberOption { get; private set; } + /// /// Gets or Sets EnumNumber /// [JsonPropertyName("enum_number")] - public EnumNumberEnum EnumNumber { get; set; } + public EnumNumberEnum? EnumNumber { get { return this.EnumNumberOption; } set { this.EnumNumberOption = new(value); } } /// /// Defines EnumString @@ -382,7 +560,7 @@ public static EnumStringEnum EnumStringEnumFromString(string value) /// /// /// - public static string EnumStringEnumToJsonValue(EnumStringEnum value) + public static string EnumStringEnumToJsonValue(EnumStringEnum? value) { if (value == EnumStringEnum.UPPER) return "UPPER"; @@ -412,190 +590,69 @@ public static string EnumStringEnumToJsonValue(EnumStringEnum value) } /// - /// Gets or Sets EnumString + /// Used to track the state of EnumString /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumStringOption { get; private set; } /// - /// Defines EnumStringRequired + /// Gets or Sets EnumString /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - Lower = 2, - - /// - /// Enum Empty for value: - /// - Empty = 3, - - /// - /// Enum ValuewithTab for value: Value\twith tab - /// - ValuewithTab = 4, - - /// - /// Enum ValueWithQuote for value: Value with \" quote - /// - ValueWithQuote = 5, - - /// - /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote - /// - ValueWithEscapedQuote = 6, - - /// - /// Enum Duplicatevalue for value: Duplicate\nvalue - /// - Duplicatevalue = 7, - - /// - /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue - /// - Duplicatevalue2 = 8 - } + [JsonPropertyName("enum_string")] + public EnumStringEnum? EnumString { get { return this.EnumStringOption; } set { this.EnumStringOption = new(value); } } /// - /// Returns a + /// Used to track the state of OuterEnum /// - /// - /// - /// - public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumOption { get; private set; } /// - /// Returns a + /// Gets or Sets OuterEnum /// - /// - /// - public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - return null; - } + [JsonPropertyName("outerEnum")] + public OuterEnum? OuterEnum { get { return this.OuterEnumOption; } set { this.OuterEnumOption = new(value); } } /// - /// Converts the to the json value + /// Used to track the state of OuterEnumDefaultValue /// - /// - /// - /// - public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) - { - if (value == EnumStringRequiredEnum.UPPER) - return "UPPER"; - - if (value == EnumStringRequiredEnum.Lower) - return "lower"; - - if (value == EnumStringRequiredEnum.Empty) - return ""; - - if (value == EnumStringRequiredEnum.ValuewithTab) - return "Value\twith tab"; - - if (value == EnumStringRequiredEnum.ValueWithQuote) - return "Value with \" quote"; - - if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) - return "Value with escaped \" quote"; - - if (value == EnumStringRequiredEnum.Duplicatevalue) - return "Duplicate\nvalue"; - - if (value == EnumStringRequiredEnum.Duplicatevalue2) - return "Duplicate\r\nvalue"; - - throw new NotImplementedException($"Value could not be handled: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumDefaultValueOption { get; private set; } /// - /// Gets or Sets EnumStringRequired + /// Gets or Sets OuterEnumDefaultValue /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } + [JsonPropertyName("outerEnumDefaultValue")] + public OuterEnumDefaultValue? OuterEnumDefaultValue { get { return this.OuterEnumDefaultValueOption; } set { this.OuterEnumDefaultValueOption = new(value); } } /// - /// Gets or Sets OuterEnumDefaultValue + /// Used to track the state of OuterEnumInteger /// - [JsonPropertyName("outerEnumDefaultValue")] - public OuterEnumDefaultValue OuterEnumDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerOption { get; private set; } /// /// Gets or Sets OuterEnumInteger /// [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + public OuterEnumInteger? OuterEnumInteger { get { return this.OuterEnumIntegerOption; } set { this.OuterEnumIntegerOption = new(value); } } /// - /// Gets or Sets OuterEnumIntegerDefaultValue + /// Used to track the state of OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnumIntegerDefaultValue")] - public OuterEnumIntegerDefaultValue OuterEnumIntegerDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerDefaultValueOption { get; private set; } /// - /// Gets or Sets OuterEnum + /// Gets or Sets OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnum")] - public OuterEnum? OuterEnum { get; set; } + [JsonPropertyName("outerEnumIntegerDefaultValue")] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get { return this.OuterEnumIntegerDefaultValueOption; } set { this.OuterEnumIntegerDefaultValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -611,15 +668,15 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -658,15 +715,15 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - EnumTest.EnumIntegerEnum? enumInteger = default; - EnumTest.EnumIntegerOnlyEnum? enumIntegerOnly = default; - EnumTest.EnumNumberEnum? enumNumber = default; - EnumTest.EnumStringEnum? enumString = default; - EnumTest.EnumStringRequiredEnum? enumStringRequired = default; - OuterEnumDefaultValue? outerEnumDefaultValue = default; - OuterEnumInteger? outerEnumInteger = default; - OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default; - OuterEnum? outerEnum = default; + Option enumStringRequired = default; + Option enumInteger = default; + Option enumIntegerOnly = default; + Option enumNumber = default; + Option enumString = default; + Option outerEnum = default; + Option outerEnumDefaultValue = default; + Option outerEnumInteger = default; + Option outerEnumIntegerDefaultValue = default; while (utf8JsonReader.Read()) { @@ -683,53 +740,47 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { + case "enum_string_required": + string? enumStringRequiredRawValue = utf8JsonReader.GetString(); + if (enumStringRequiredRawValue != null) + enumStringRequired = new Option(EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue)); + break; case "enum_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumInteger = (EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32(); + enumInteger = new Option((EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32()); break; case "enum_integer_only": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32(); + enumIntegerOnly = new Option((EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); break; case "enum_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumNumber = (EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32(); + enumNumber = new Option((EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32()); break; case "enum_string": string? enumStringRawValue = utf8JsonReader.GetString(); - enumString = enumStringRawValue == null - ? null - : EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue); + if (enumStringRawValue != null) + enumString = new Option(EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue)); break; - case "enum_string_required": - string? enumStringRequiredRawValue = utf8JsonReader.GetString(); - enumStringRequired = enumStringRequiredRawValue == null - ? null - : EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue); + case "outerEnum": + string? outerEnumRawValue = utf8JsonReader.GetString(); + if (outerEnumRawValue != null) + outerEnum = new Option(OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue)); break; case "outerEnumDefaultValue": string? outerEnumDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumDefaultValue = outerEnumDefaultValueRawValue == null - ? null - : OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue); + if (outerEnumDefaultValueRawValue != null) + outerEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue)); break; case "outerEnumInteger": string? outerEnumIntegerRawValue = utf8JsonReader.GetString(); - outerEnumInteger = outerEnumIntegerRawValue == null - ? null - : OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue); + if (outerEnumIntegerRawValue != null) + outerEnumInteger = new Option(OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue)); break; case "outerEnumIntegerDefaultValue": string? outerEnumIntegerDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValueRawValue == null - ? null - : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue); - break; - case "outerEnum": - string? outerEnumRawValue = utf8JsonReader.GetString(); - outerEnum = outerEnumRawValue == null - ? null - : OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue); + if (outerEnumIntegerDefaultValueRawValue != null) + outerEnumIntegerDefaultValue = new Option(OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue)); break; default: break; @@ -737,31 +788,34 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (enumInteger == null) - throw new ArgumentNullException(nameof(enumInteger), "Property is required for class EnumTest."); + if (!enumStringRequired.IsSet) + throw new ArgumentException("Property is required for class EnumTest.", nameof(enumStringRequired)); + + if (enumStringRequired.IsSet && enumStringRequired.Value == null) + throw new ArgumentNullException(nameof(enumStringRequired), "Property is not nullable for class EnumTest."); - if (enumIntegerOnly == null) - throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is required for class EnumTest."); + if (enumInteger.IsSet && enumInteger.Value == null) + throw new ArgumentNullException(nameof(enumInteger), "Property is not nullable for class EnumTest."); - if (enumNumber == null) - throw new ArgumentNullException(nameof(enumNumber), "Property is required for class EnumTest."); + if (enumIntegerOnly.IsSet && enumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is not nullable for class EnumTest."); - if (enumString == null) - throw new ArgumentNullException(nameof(enumString), "Property is required for class EnumTest."); + if (enumNumber.IsSet && enumNumber.Value == null) + throw new ArgumentNullException(nameof(enumNumber), "Property is not nullable for class EnumTest."); - if (enumStringRequired == null) - throw new ArgumentNullException(nameof(enumStringRequired), "Property is required for class EnumTest."); + if (enumString.IsSet && enumString.Value == null) + throw new ArgumentNullException(nameof(enumString), "Property is not nullable for class EnumTest."); - if (outerEnumDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is required for class EnumTest."); + if (outerEnumDefaultValue.IsSet && outerEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is not nullable for class EnumTest."); - if (outerEnumInteger == null) - throw new ArgumentNullException(nameof(outerEnumInteger), "Property is required for class EnumTest."); + if (outerEnumInteger.IsSet && outerEnumInteger.Value == null) + throw new ArgumentNullException(nameof(outerEnumInteger), "Property is not nullable for class EnumTest."); - if (outerEnumIntegerDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is required for class EnumTest."); + if (outerEnumIntegerDefaultValue.IsSet && outerEnumIntegerDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is not nullable for class EnumTest."); - return new EnumTest(enumInteger.Value, enumIntegerOnly.Value, enumNumber.Value, enumString.Value, enumStringRequired.Value, outerEnumDefaultValue.Value, outerEnumInteger.Value, outerEnumIntegerDefaultValue.Value, outerEnum); + return new EnumTest(enumStringRequired.Value!.Value!, enumInteger, enumIntegerOnly, enumNumber, enumString, outerEnum, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue); } /// @@ -788,43 +842,41 @@ public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumInteger)); - writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnly)); - writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumber)); - - var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumString); - if (enumStringRawValue != null) - writer.WriteString("enum_string", enumStringRawValue); - else - writer.WriteNull("enum_string"); - var enumStringRequiredRawValue = EnumTest.EnumStringRequiredEnumToJsonValue(enumTest.EnumStringRequired); - if (enumStringRequiredRawValue != null) - writer.WriteString("enum_string_required", enumStringRequiredRawValue); - else - writer.WriteNull("enum_string_required"); + writer.WriteString("enum_string_required", enumStringRequiredRawValue); + if (enumTest.EnumIntegerOption.IsSet) + writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumIntegerOption.Value!.Value)); - var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (enumTest.EnumIntegerOnlyOption.IsSet) + writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnlyOption.Value!.Value)); - if (outerEnumDefaultValueRawValue != null) - writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); - else - writer.WriteNull("outerEnumDefaultValue"); - - var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger); - writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); - var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); - writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + if (enumTest.EnumNumberOption.IsSet) + writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumberOption.Value!.Value)); - if (enumTest.OuterEnum == null) - writer.WriteNull("outerEnum"); - else - { - var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnum.Value); - if (outerEnumRawValue != null) + var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumStringOption.Value!.Value); + writer.WriteString("enum_string", enumStringRawValue); + if (enumTest.OuterEnumOption.IsSet) + if (enumTest.OuterEnumOption!.Value != null) + { + var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnumOption.Value!.Value); writer.WriteString("outerEnum", outerEnumRawValue); + } else writer.WriteNull("outerEnum"); + if (enumTest.OuterEnumDefaultValueOption.IsSet) + { + var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue!.Value); + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + } + if (enumTest.OuterEnumIntegerOption.IsSet) + { + var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger!.Value); + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + } + if (enumTest.OuterEnumIntegerDefaultValueOption.IsSet) + { + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue!.Value); + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 717de0e356f4..67be73e69d8e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -111,8 +112,8 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -130,10 +131,10 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,13 +142,19 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class EquilateralTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class EquilateralTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(triangleType)); - return new EquilateralTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class EquilateralTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class EquilateralTriangle."); + + return new EquilateralTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -174,7 +181,14 @@ public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilatera /// public void WriteProperties(ref Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (equilateralTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.ShapeType), "Property is required for class EquilateralTriangle."); + + if (equilateralTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.TriangleType), "Property is required for class EquilateralTriangle."); + writer.WriteString("shapeType", equilateralTriangle.ShapeType); + writer.WriteString("triangleType", equilateralTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs index f0e27f10fa32..84bcc677147c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/File.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,20 +36,27 @@ public partial class File : IValidatableObject /// /// Test capitalization [JsonConstructor] - public File(string sourceURI) + public File(Option sourceURI = default) { - SourceURI = sourceURI; + SourceURIOption = sourceURI; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SourceURI + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SourceURIOption { get; private set; } + /// /// Test capitalization /// /// Test capitalization [JsonPropertyName("sourceURI")] - public string SourceURI { get; set; } + public string? SourceURI { get { return this. SourceURIOption; } set { this.SourceURIOption = new(value); } } /// /// Gets or Sets additional properties @@ -103,7 +111,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? sourceURI = default; + Option sourceURI = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "sourceURI": - sourceURI = utf8JsonReader.GetString(); + sourceURI = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -129,8 +137,8 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (sourceURI == null) - throw new ArgumentNullException(nameof(sourceURI), "Property is required for class File."); + if (sourceURI.IsSet && sourceURI.Value == null) + throw new ArgumentNullException(nameof(sourceURI), "Property is not nullable for class File."); return new File(sourceURI); } @@ -159,7 +167,11 @@ public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("sourceURI", file.SourceURI); + if (file.SourceURIOption.IsSet && file.SourceURI == null) + throw new ArgumentNullException(nameof(file.SourceURI), "Property is required for class File."); + + if (file.SourceURIOption.IsSet) + writer.WriteString("sourceURI", file.SourceURI); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index da341a59421b..8791b3498ae4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class FileSchemaTestClass : IValidatableObject /// file /// files [JsonConstructor] - public FileSchemaTestClass(File file, List files) + public FileSchemaTestClass(Option file = default, Option?> files = default) { - File = file; - Files = files; + FileOption = file; + FilesOption = files; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of File + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FileOption { get; private set; } + /// /// Gets or Sets File /// [JsonPropertyName("file")] - public File File { get; set; } + public File? File { get { return this. FileOption; } set { this.FileOption = new(value); } } + + /// + /// Used to track the state of Files + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> FilesOption { get; private set; } /// /// Gets or Sets Files /// [JsonPropertyName("files")] - public List Files { get; set; } + public List? Files { get { return this. FilesOption; } set { this.FilesOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - File? file = default; - List? files = default; + Option file = default; + Option?> files = default; while (utf8JsonReader.Read()) { @@ -131,11 +146,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "file": if (utf8JsonReader.TokenType != JsonTokenType.Null) - file = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + file = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "files": if (utf8JsonReader.TokenType != JsonTokenType.Null) - files = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + files = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -143,11 +158,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (file == null) - throw new ArgumentNullException(nameof(file), "Property is required for class FileSchemaTestClass."); + if (file.IsSet && file.Value == null) + throw new ArgumentNullException(nameof(file), "Property is not nullable for class FileSchemaTestClass."); - if (files == null) - throw new ArgumentNullException(nameof(files), "Property is required for class FileSchemaTestClass."); + if (files.IsSet && files.Value == null) + throw new ArgumentNullException(nameof(files), "Property is not nullable for class FileSchemaTestClass."); return new FileSchemaTestClass(file, files); } @@ -176,10 +191,22 @@ public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchema /// public void WriteProperties(ref Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("file"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); - writer.WritePropertyName("files"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + if (fileSchemaTestClass.FileOption.IsSet && fileSchemaTestClass.File == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.File), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FilesOption.IsSet && fileSchemaTestClass.Files == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.Files), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FileOption.IsSet) + { + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); + } + if (fileSchemaTestClass.FilesOption.IsSet) + { + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs index 3628416eb0d0..85d6ba28af34 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Foo.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Foo : IValidatableObject /// /// bar (default to "bar") [JsonConstructor] - public Foo(string bar = @"bar") + public Foo(Option bar = default) { - Bar = bar; + BarOption = bar; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; private set; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; set; } + public string? Bar { get { return this. BarOption; } set { this.BarOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; + Option bar = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class Foo."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class Foo."); return new Foo(bar); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", foo.Bar); + if (foo.BarOption.IsSet && foo.Bar == null) + throw new ArgumentNullException(nameof(foo.Bar), "Property is required for class Foo."); + + if (foo.BarOption.IsSet) + writer.WriteString("bar", foo.Bar); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index 6f2670034f24..09e11f0babbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class FooGetDefaultResponse : IValidatableObject /// /// varString [JsonConstructor] - public FooGetDefaultResponse(Foo varString) + public FooGetDefaultResponse(Option varString = default) { - VarString = varString; + VarStringOption = varString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } + /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public Foo VarString { get; set; } + public Foo? VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Foo? varString = default; + Option varString = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty { case "string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varString = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varString = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -129,8 +137,8 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty } } - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FooGetDefaultResponse."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FooGetDefaultResponse."); return new FooGetDefaultResponse(varString); } @@ -159,8 +167,14 @@ public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDe /// public void WriteProperties(ref Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("string"); - JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + if (fooGetDefaultResponse.VarStringOption.IsSet && fooGetDefaultResponse.VarString == null) + throw new ArgumentNullException(nameof(fooGetDefaultResponse.VarString), "Property is required for class FooGetDefaultResponse."); + + if (fooGetDefaultResponse.VarStringOption.IsSet) + { + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs index 9066cc903b6a..8b590db2f662 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FormatTest.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,9 +34,11 @@ public partial class FormatTest : IValidatableObject /// /// Initializes a new instance of the class. /// - /// binary /// varByte /// date + /// number + /// password + /// binary /// dateTime /// varDecimal /// varDouble @@ -43,8 +46,6 @@ public partial class FormatTest : IValidatableObject /// int32 /// int64 /// integer - /// number - /// password /// None /// A string that is a 10 digit number. Can have leading zeros. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. @@ -53,38 +54,32 @@ public partial class FormatTest : IValidatableObject /// unsignedLong /// uuid [JsonConstructor] - public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTime dateTime, decimal varDecimal, double varDouble, float varFloat, int int32, long int64, int integer, decimal number, string password, string patternWithBackslash, string patternWithDigits, string patternWithDigitsAndDelimiter, string varString, uint unsignedInteger, ulong unsignedLong, Guid uuid) + public FormatTest(byte[] varByte, DateOnly date, decimal number, string password, Option binary = default, Option dateTime = default, Option varDecimal = default, Option varDouble = default, Option varFloat = default, Option int32 = default, Option int64 = default, Option integer = default, Option patternWithBackslash = default, Option patternWithDigits = default, Option patternWithDigitsAndDelimiter = default, Option varString = default, Option unsignedInteger = default, Option unsignedLong = default, Option uuid = default) { - Binary = binary; VarByte = varByte; Date = date; - DateTime = dateTime; - VarDecimal = varDecimal; - VarDouble = varDouble; - VarFloat = varFloat; - Int32 = int32; - Int64 = int64; - Integer = integer; Number = number; Password = password; - PatternWithBackslash = patternWithBackslash; - PatternWithDigits = patternWithDigits; - PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - VarString = varString; - UnsignedInteger = unsignedInteger; - UnsignedLong = unsignedLong; - Uuid = uuid; + BinaryOption = binary; + DateTimeOption = dateTime; + VarDecimalOption = varDecimal; + VarDoubleOption = varDouble; + VarFloatOption = varFloat; + Int32Option = int32; + Int64Option = int64; + IntegerOption = integer; + PatternWithBackslashOption = patternWithBackslash; + PatternWithDigitsOption = patternWithDigits; + PatternWithDigitsAndDelimiterOption = patternWithDigitsAndDelimiter; + VarStringOption = varString; + UnsignedIntegerOption = unsignedInteger; + UnsignedLongOption = unsignedLong; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - /// /// Gets or Sets VarByte /// @@ -96,108 +91,219 @@ public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTi /// /// Sun Feb 02 00:00:00 UTC 2020 [JsonPropertyName("date")] - public DateTime Date { get; set; } + public DateOnly Date { get; set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public decimal Number { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Used to track the state of Binary + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BinaryOption { get; private set; } + + /// + /// Gets or Sets Binary + /// + [JsonPropertyName("binary")] + public System.IO.Stream? Binary { get { return this. BinaryOption; } set { this.BinaryOption = new(value); } } + + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } /// /// Gets or Sets DateTime /// /// 2007-12-03T10:15:30+01:00 [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of VarDecimal + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDecimalOption { get; private set; } /// /// Gets or Sets VarDecimal /// [JsonPropertyName("decimal")] - public decimal VarDecimal { get; set; } + public decimal? VarDecimal { get { return this. VarDecimalOption; } set { this.VarDecimalOption = new(value); } } + + /// + /// Used to track the state of VarDouble + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDoubleOption { get; private set; } /// /// Gets or Sets VarDouble /// [JsonPropertyName("double")] - public double VarDouble { get; set; } + public double? VarDouble { get { return this. VarDoubleOption; } set { this.VarDoubleOption = new(value); } } + + /// + /// Used to track the state of VarFloat + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarFloatOption { get; private set; } /// /// Gets or Sets VarFloat /// [JsonPropertyName("float")] - public float VarFloat { get; set; } + public float? VarFloat { get { return this. VarFloatOption; } set { this.VarFloatOption = new(value); } } + + /// + /// Used to track the state of Int32 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int32Option { get; private set; } /// /// Gets or Sets Int32 /// [JsonPropertyName("int32")] - public int Int32 { get; set; } + public int? Int32 { get { return this. Int32Option; } set { this.Int32Option = new(value); } } + + /// + /// Used to track the state of Int64 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int64Option { get; private set; } /// /// Gets or Sets Int64 /// [JsonPropertyName("int64")] - public long Int64 { get; set; } + public long? Int64 { get { return this. Int64Option; } set { this.Int64Option = new(value); } } /// - /// Gets or Sets Integer + /// Used to track the state of Integer /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerOption { get; private set; } /// - /// Gets or Sets Number + /// Gets or Sets Integer /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("integer")] + public int? Integer { get { return this. IntegerOption; } set { this.IntegerOption = new(value); } } /// - /// Gets or Sets Password + /// Used to track the state of PatternWithBackslash /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithBackslashOption { get; private set; } /// /// None /// /// None [JsonPropertyName("pattern_with_backslash")] - public string PatternWithBackslash { get; set; } + public string? PatternWithBackslash { get { return this. PatternWithBackslashOption; } set { this.PatternWithBackslashOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigits + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsOption { get; private set; } /// /// A string that is a 10 digit number. Can have leading zeros. /// /// A string that is a 10 digit number. Can have leading zeros. [JsonPropertyName("pattern_with_digits")] - public string PatternWithDigits { get; set; } + public string? PatternWithDigits { get { return this. PatternWithDigitsOption; } set { this.PatternWithDigitsOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigitsAndDelimiter + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsAndDelimiterOption { get; private set; } /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. [JsonPropertyName("pattern_with_digits_and_delimiter")] - public string PatternWithDigitsAndDelimiter { get; set; } + public string? PatternWithDigitsAndDelimiter { get { return this. PatternWithDigitsAndDelimiterOption; } set { this.PatternWithDigitsAndDelimiterOption = new(value); } } + + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public string VarString { get; set; } + public string? VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } + + /// + /// Used to track the state of UnsignedInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedIntegerOption { get; private set; } /// /// Gets or Sets UnsignedInteger /// [JsonPropertyName("unsigned_integer")] - public uint UnsignedInteger { get; set; } + public uint? UnsignedInteger { get { return this. UnsignedIntegerOption; } set { this.UnsignedIntegerOption = new(value); } } + + /// + /// Used to track the state of UnsignedLong + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedLongOption { get; private set; } /// /// Gets or Sets UnsignedLong /// [JsonPropertyName("unsigned_long")] - public ulong UnsignedLong { get; set; } + public ulong? UnsignedLong { get { return this. UnsignedLongOption; } set { this.UnsignedLongOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -213,9 +319,11 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" VarByte: ").Append(VarByte).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" VarDecimal: ").Append(VarDecimal).Append("\n"); sb.Append(" VarDouble: ").Append(VarDouble).Append("\n"); @@ -223,8 +331,6 @@ public override string ToString() sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" PatternWithBackslash: ").Append(PatternWithBackslash).Append("\n"); sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); @@ -244,122 +350,126 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + // VarDouble (double) maximum - if (this.VarDouble > (double)123.4) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value less than or equal to 123.4.", new [] { "VarDouble" }); } // VarDouble (double) minimum - if (this.VarDouble < (double)67.8) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value greater than or equal to 67.8.", new [] { "VarDouble" }); } // VarFloat (float) maximum - if (this.VarFloat > (float)987.6) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value less than or equal to 987.6.", new [] { "VarFloat" }); } // VarFloat (float) minimum - if (this.VarFloat < (float)54.3) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value greater than or equal to 54.3.", new [] { "VarFloat" }); } // Int32 (int) maximum - if (this.Int32 > (int)200) + if (this.Int32Option.IsSet && this.Int32Option.Value > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if (this.Int32 < (int)20) + if (this.Int32Option.IsSet && this.Int32Option.Value < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Integer (int) maximum - if (this.Integer > (int)100) + if (this.IntegerOption.IsSet && this.IntegerOption.Value > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if (this.Integer < (int)10) + if (this.IntegerOption.IsSet && this.IntegerOption.Value < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } - // Number (decimal) maximum - if (this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if (this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Password (string) maxLength - if (this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if (this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - if (this.PatternWithBackslash != null) { + if (this.PatternWithBackslashOption.Value != null) { // PatternWithBackslash (string) pattern Regex regexPatternWithBackslash = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$", RegexOptions.CultureInvariant); - if (!regexPatternWithBackslash.Match(this.PatternWithBackslash).Success) + + if (this.PatternWithBackslashOption.Value != null &&!regexPatternWithBackslash.Match(this.PatternWithBackslashOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithBackslash, must match a pattern of " + regexPatternWithBackslash, new [] { "PatternWithBackslash" }); } } - if (this.PatternWithDigits != null) { + if (this.PatternWithDigitsOption.Value != null) { // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\d{10}$", RegexOptions.CultureInvariant); - if (!regexPatternWithDigits.Match(this.PatternWithDigits).Success) + + if (this.PatternWithDigitsOption.Value != null &&!regexPatternWithDigits.Match(this.PatternWithDigitsOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); } } - if (this.PatternWithDigitsAndDelimiter != null) { + if (this.PatternWithDigitsAndDelimiterOption.Value != null) { // PatternWithDigitsAndDelimiter (string) pattern Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + + if (this.PatternWithDigitsAndDelimiterOption.Value != null &&!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiterOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } } - if (this.VarString != null) { + if (this.VarStringOption.Value != null) { // VarString (string) pattern Regex regexVarString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexVarString.Match(this.VarString).Success) + + if (this.VarStringOption.Value != null &&!regexVarString.Match(this.VarStringOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarString, must match a pattern of " + regexVarString, new [] { "VarString" }); } } // UnsignedInteger (uint) maximum - if (this.UnsignedInteger > (uint)200) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value > (uint)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value less than or equal to 200.", new [] { "UnsignedInteger" }); } // UnsignedInteger (uint) minimum - if (this.UnsignedInteger < (uint)20) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value < (uint)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value greater than or equal to 20.", new [] { "UnsignedInteger" }); } @@ -400,25 +510,25 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - System.IO.Stream? binary = default; - byte[]? varByte = default; - DateTime? date = default; - DateTime? dateTime = default; - decimal? varDecimal = default; - double? varDouble = default; - float? varFloat = default; - int? int32 = default; - long? int64 = default; - int? integer = default; - decimal? number = default; - string? password = default; - string? patternWithBackslash = default; - string? patternWithDigits = default; - string? patternWithDigitsAndDelimiter = default; - string? varString = default; - uint? unsignedInteger = default; - ulong? unsignedLong = default; - Guid? uuid = default; + Option varByte = default; + Option date = default; + Option number = default; + Option password = default; + Option binary = default; + Option dateTime = default; + Option varDecimal = default; + Option varDouble = default; + Option varFloat = default; + Option int32 = default; + Option int64 = default; + Option integer = default; + Option patternWithBackslash = default; + Option patternWithDigits = default; + Option patternWithDigitsAndDelimiter = default; + Option varString = default; + Option unsignedInteger = default; + Option unsignedLong = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -435,76 +545,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { - case "binary": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - binary = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; case "byte": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varByte = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varByte = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "date": if (utf8JsonReader.TokenType != JsonTokenType.Null) - date = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + number = new Option(utf8JsonReader.GetDecimal()); + break; + case "password": + password = new Option(utf8JsonReader.GetString()!); + break; + case "binary": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + binary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "decimal": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDecimal = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varDecimal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "double": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDouble = utf8JsonReader.GetDouble(); + varDouble = new Option(utf8JsonReader.GetDouble()); break; case "float": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varFloat = (float)utf8JsonReader.GetDouble(); + varFloat = new Option((float)utf8JsonReader.GetDouble()); break; case "int32": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int32 = utf8JsonReader.GetInt32(); + int32 = new Option(utf8JsonReader.GetInt32()); break; case "int64": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int64 = utf8JsonReader.GetInt64(); + int64 = new Option(utf8JsonReader.GetInt64()); break; case "integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integer = utf8JsonReader.GetInt32(); - break; - case "number": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - number = utf8JsonReader.GetDecimal(); - break; - case "password": - password = utf8JsonReader.GetString(); + integer = new Option(utf8JsonReader.GetInt32()); break; case "pattern_with_backslash": - patternWithBackslash = utf8JsonReader.GetString(); + patternWithBackslash = new Option(utf8JsonReader.GetString()!); break; case "pattern_with_digits": - patternWithDigits = utf8JsonReader.GetString(); + patternWithDigits = new Option(utf8JsonReader.GetString()!); break; case "pattern_with_digits_and_delimiter": - patternWithDigitsAndDelimiter = utf8JsonReader.GetString(); + patternWithDigitsAndDelimiter = new Option(utf8JsonReader.GetString()!); break; case "string": - varString = utf8JsonReader.GetString(); + varString = new Option(utf8JsonReader.GetString()!); break; case "unsigned_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedInteger = utf8JsonReader.GetUInt32(); + unsignedInteger = new Option(utf8JsonReader.GetUInt32()); break; case "unsigned_long": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedLong = utf8JsonReader.GetUInt64(); + unsignedLong = new Option(utf8JsonReader.GetUInt64()); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -512,64 +622,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (binary == null) - throw new ArgumentNullException(nameof(binary), "Property is required for class FormatTest."); + if (!varByte.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(varByte)); + + if (!date.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(date)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(number)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(password)); - if (varByte == null) - throw new ArgumentNullException(nameof(varByte), "Property is required for class FormatTest."); + if (varByte.IsSet && varByte.Value == null) + throw new ArgumentNullException(nameof(varByte), "Property is not nullable for class FormatTest."); - if (date == null) - throw new ArgumentNullException(nameof(date), "Property is required for class FormatTest."); + if (date.IsSet && date.Value == null) + throw new ArgumentNullException(nameof(date), "Property is not nullable for class FormatTest."); - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class FormatTest."); + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class FormatTest."); - if (varDecimal == null) - throw new ArgumentNullException(nameof(varDecimal), "Property is required for class FormatTest."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class FormatTest."); - if (varDouble == null) - throw new ArgumentNullException(nameof(varDouble), "Property is required for class FormatTest."); + if (binary.IsSet && binary.Value == null) + throw new ArgumentNullException(nameof(binary), "Property is not nullable for class FormatTest."); - if (varFloat == null) - throw new ArgumentNullException(nameof(varFloat), "Property is required for class FormatTest."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class FormatTest."); - if (int32 == null) - throw new ArgumentNullException(nameof(int32), "Property is required for class FormatTest."); + if (varDecimal.IsSet && varDecimal.Value == null) + throw new ArgumentNullException(nameof(varDecimal), "Property is not nullable for class FormatTest."); - if (int64 == null) - throw new ArgumentNullException(nameof(int64), "Property is required for class FormatTest."); + if (varDouble.IsSet && varDouble.Value == null) + throw new ArgumentNullException(nameof(varDouble), "Property is not nullable for class FormatTest."); - if (integer == null) - throw new ArgumentNullException(nameof(integer), "Property is required for class FormatTest."); + if (varFloat.IsSet && varFloat.Value == null) + throw new ArgumentNullException(nameof(varFloat), "Property is not nullable for class FormatTest."); - if (number == null) - throw new ArgumentNullException(nameof(number), "Property is required for class FormatTest."); + if (int32.IsSet && int32.Value == null) + throw new ArgumentNullException(nameof(int32), "Property is not nullable for class FormatTest."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class FormatTest."); + if (int64.IsSet && int64.Value == null) + throw new ArgumentNullException(nameof(int64), "Property is not nullable for class FormatTest."); - if (patternWithBackslash == null) - throw new ArgumentNullException(nameof(patternWithBackslash), "Property is required for class FormatTest."); + if (integer.IsSet && integer.Value == null) + throw new ArgumentNullException(nameof(integer), "Property is not nullable for class FormatTest."); - if (patternWithDigits == null) - throw new ArgumentNullException(nameof(patternWithDigits), "Property is required for class FormatTest."); + if (patternWithBackslash.IsSet && patternWithBackslash.Value == null) + throw new ArgumentNullException(nameof(patternWithBackslash), "Property is not nullable for class FormatTest."); - if (patternWithDigitsAndDelimiter == null) - throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + if (patternWithDigits.IsSet && patternWithDigits.Value == null) + throw new ArgumentNullException(nameof(patternWithDigits), "Property is not nullable for class FormatTest."); - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FormatTest."); + if (patternWithDigitsAndDelimiter.IsSet && patternWithDigitsAndDelimiter.Value == null) + throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is not nullable for class FormatTest."); - if (unsignedInteger == null) - throw new ArgumentNullException(nameof(unsignedInteger), "Property is required for class FormatTest."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FormatTest."); - if (unsignedLong == null) - throw new ArgumentNullException(nameof(unsignedLong), "Property is required for class FormatTest."); + if (unsignedInteger.IsSet && unsignedInteger.Value == null) + throw new ArgumentNullException(nameof(unsignedInteger), "Property is not nullable for class FormatTest."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class FormatTest."); + if (unsignedLong.IsSet && unsignedLong.Value == null) + throw new ArgumentNullException(nameof(unsignedLong), "Property is not nullable for class FormatTest."); - return new FormatTest(binary, varByte, date.Value, dateTime.Value, varDecimal.Value, varDouble.Value, varFloat.Value, int32.Value, int64.Value, integer.Value, number.Value, password, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger.Value, unsignedLong.Value, uuid.Value); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class FormatTest."); + + return new FormatTest(varByte.Value!, date.Value!.Value!, number.Value!.Value!, password.Value!, binary, dateTime, varDecimal, varDouble, varFloat, int32, int64, integer, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger, unsignedLong, uuid); } /// @@ -596,28 +718,83 @@ public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("binary"); - JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + if (formatTest.VarByte == null) + throw new ArgumentNullException(nameof(formatTest.VarByte), "Property is required for class FormatTest."); + + if (formatTest.Password == null) + throw new ArgumentNullException(nameof(formatTest.Password), "Property is required for class FormatTest."); + + if (formatTest.BinaryOption.IsSet && formatTest.Binary == null) + throw new ArgumentNullException(nameof(formatTest.Binary), "Property is required for class FormatTest."); + + if (formatTest.PatternWithBackslashOption.IsSet && formatTest.PatternWithBackslash == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithBackslash), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsOption.IsSet && formatTest.PatternWithDigits == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigits), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet && formatTest.PatternWithDigitsAndDelimiter == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + + if (formatTest.VarStringOption.IsSet && formatTest.VarString == null) + throw new ArgumentNullException(nameof(formatTest.VarString), "Property is required for class FormatTest."); + writer.WritePropertyName("byte"); JsonSerializer.Serialize(writer, formatTest.VarByte, jsonSerializerOptions); writer.WriteString("date", formatTest.Date.ToString(DateFormat)); - writer.WriteString("dateTime", formatTest.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("decimal"); - JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); - writer.WriteNumber("double", formatTest.VarDouble); - writer.WriteNumber("float", formatTest.VarFloat); - writer.WriteNumber("int32", formatTest.Int32); - writer.WriteNumber("int64", formatTest.Int64); - writer.WriteNumber("integer", formatTest.Integer); + writer.WriteNumber("number", formatTest.Number); + writer.WriteString("password", formatTest.Password); - writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); - writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); - writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); - writer.WriteString("string", formatTest.VarString); - writer.WriteNumber("unsigned_integer", formatTest.UnsignedInteger); - writer.WriteNumber("unsigned_long", formatTest.UnsignedLong); - writer.WriteString("uuid", formatTest.Uuid); + + if (formatTest.BinaryOption.IsSet) + { + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + } + if (formatTest.DateTimeOption.IsSet) + writer.WriteString("dateTime", formatTest.DateTimeOption.Value!.Value.ToString(DateTimeFormat)); + + if (formatTest.VarDecimalOption.IsSet) + { + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); + } + if (formatTest.VarDoubleOption.IsSet) + writer.WriteNumber("double", formatTest.VarDoubleOption.Value!.Value); + + if (formatTest.VarFloatOption.IsSet) + writer.WriteNumber("float", formatTest.VarFloatOption.Value!.Value); + + if (formatTest.Int32Option.IsSet) + writer.WriteNumber("int32", formatTest.Int32Option.Value!.Value); + + if (formatTest.Int64Option.IsSet) + writer.WriteNumber("int64", formatTest.Int64Option.Value!.Value); + + if (formatTest.IntegerOption.IsSet) + writer.WriteNumber("integer", formatTest.IntegerOption.Value!.Value); + + if (formatTest.PatternWithBackslashOption.IsSet) + writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); + + if (formatTest.PatternWithDigitsOption.IsSet) + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet) + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + + if (formatTest.VarStringOption.IsSet) + writer.WriteString("string", formatTest.VarString); + + if (formatTest.UnsignedIntegerOption.IsSet) + writer.WriteNumber("unsigned_integer", formatTest.UnsignedIntegerOption.Value!.Value); + + if (formatTest.UnsignedLongOption.IsSet) + writer.WriteNumber("unsigned_long", formatTest.UnsignedLongOption.Value!.Value); + + if (formatTest.UuidOption.IsSet) + writer.WriteString("uuid", formatTest.UuidOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs index c3e213f48a47..ebb0d41f7201 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Fruit.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,10 +36,10 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple apple, string color) + public Fruit(Apple apple, Option color = default) { Apple = apple; - Color = color; + ColorOption = color; OnCreated(); } @@ -47,10 +48,10 @@ public Fruit(Apple apple, string color) /// /// /// color - public Fruit(Banana banana, string color) + public Fruit(Banana banana, Option color = default) { Banana = banana; - Color = color; + ColorOption = color; OnCreated(); } @@ -66,11 +67,18 @@ public Fruit(Banana banana, string color) /// public Banana? Banana { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -118,7 +126,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -158,7 +166,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -166,8 +174,8 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); if (apple != null) return new Fruit(apple, color); @@ -202,7 +210,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs index 56212b9c18dd..46c3c3b25407 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/FruitReq.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs index 9ed8b2db2d15..0170c34db96b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GmFruit.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,31 +37,52 @@ public partial class GmFruit : IValidatableObject /// /// /// color - public GmFruit(Apple? apple, Banana? banana, string color) + public GmFruit(Option apple, Option banana, Option color = default) { - Apple = apple; - Banana = banana; - Color = color; + AppleOption = apple; + BananaOption = banana; + ColorOption = color; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Apple + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AppleOption { get; private set; } + /// /// Gets or Sets Apple /// - public Apple? Apple { get; set; } + public Apple? Apple { get { return this.AppleOption; } set { this.AppleOption = new(value); } } + + /// + /// Used to track the state of Banana + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BananaOption { get; private set; } /// /// Gets or Sets Banana /// - public Banana? Banana { get; set; } + public Banana? Banana { get { return this.BananaOption; } set { this.BananaOption = new(value); } } + + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -108,7 +130,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -148,7 +170,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -156,10 +178,17 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class GmFruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class GmFruit."); - return new GmFruit(apple, banana, color); + Option appleParsedValue = apple == null + ? default + : new Option(apple); + Option bananaParsedValue = banana == null + ? default + : new Option(banana); + + return new GmFruit(appleParsedValue, bananaParsedValue, color); } /// @@ -173,16 +202,16 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize { writer.WriteStartObject(); - if (gmFruit.Apple != null) + if (gmFruit.AppleOption.IsSet && gmFruit.AppleOption.Value != null) { - AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Apple.GetType())); - AppleJsonConverter.WriteProperties(ref writer, gmFruit.Apple, jsonSerializerOptions); + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.AppleOption.Value.GetType())); + AppleJsonConverter.WriteProperties(ref writer, gmFruit.AppleOption.Value, jsonSerializerOptions); } - if (gmFruit.Banana != null) + if (gmFruit.BananaOption.IsSet && gmFruit.BananaOption.Value != null) { - BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Banana.GetType())); - BananaJsonConverter.WriteProperties(ref writer, gmFruit.Banana, jsonSerializerOptions); + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.BananaOption.Value.GetType())); + BananaJsonConverter.WriteProperties(ref writer, gmFruit.BananaOption.Value, jsonSerializerOptions); } WriteProperties(ref writer, gmFruit, jsonSerializerOptions); @@ -198,7 +227,11 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", gmFruit.Color); + if (gmFruit.ColorOption.IsSet && gmFruit.Color == null) + throw new ArgumentNullException(nameof(gmFruit.Color), "Property is required for class GmFruit."); + + if (gmFruit.ColorOption.IsSet) + writer.WriteString("color", gmFruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index cb7fe43f91cb..a0068cc6781c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -112,7 +113,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -130,7 +131,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -138,10 +139,13 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class GrandparentAnimal."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class GrandparentAnimal.", nameof(petType)); - return new GrandparentAnimal(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class GrandparentAnimal."); + + return new GrandparentAnimal(petType.Value!); } /// @@ -168,6 +172,9 @@ public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentA /// public void WriteProperties(ref Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) { + if (grandparentAnimal.PetType == null) + throw new ArgumentNullException(nameof(grandparentAnimal.PetType), "Property is required for class GrandparentAnimal."); + writer.WriteString("pet_type", grandparentAnimal.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 3b8c651908c8..e9fac6f25e52 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class HasOnlyReadOnly : IEquatable, IValidatabl /// bar /// foo [JsonConstructor] - internal HasOnlyReadOnly(string bar, string foo) + internal HasOnlyReadOnly(Option bar = default, Option foo = default) { - Bar = bar; - Foo = foo; + BarOption = bar; + FooOption = foo; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string? Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Foo + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FooOption { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; } + public string? Foo { get { return this. FooOption; } } /// /// Gets or Sets additional properties @@ -107,8 +122,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); - hashCode = (hashCode * 59) + Foo.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + + if (Foo != null) + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -148,8 +167,8 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; - string? foo = default; + Option bar = default; + Option foo = default; while (utf8JsonReader.Read()) { @@ -167,10 +186,10 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; case "foo": - foo = utf8JsonReader.GetString(); + foo = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -178,11 +197,11 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class HasOnlyReadOnly."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class HasOnlyReadOnly."); - if (foo == null) - throw new ArgumentNullException(nameof(foo), "Property is required for class HasOnlyReadOnly."); + if (foo.IsSet && foo.Value == null) + throw new ArgumentNullException(nameof(foo), "Property is not nullable for class HasOnlyReadOnly."); return new HasOnlyReadOnly(bar, foo); } @@ -211,8 +230,17 @@ public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnl /// public void WriteProperties(ref Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", hasOnlyReadOnly.Bar); - writer.WriteString("foo", hasOnlyReadOnly.Foo); + if (hasOnlyReadOnly.BarOption.IsSet && hasOnlyReadOnly.Bar == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Bar), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.FooOption.IsSet && hasOnlyReadOnly.Foo == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Foo), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.BarOption.IsSet) + writer.WriteString("bar", hasOnlyReadOnly.Bar); + + if (hasOnlyReadOnly.FooOption.IsSet) + writer.WriteString("foo", hasOnlyReadOnly.Foo); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs index ccdc21a06856..e95d79fee9dd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class HealthCheckResult : IValidatableObject /// /// nullableMessage [JsonConstructor] - public HealthCheckResult(string? nullableMessage = default) + public HealthCheckResult(Option nullableMessage = default) { - NullableMessage = nullableMessage; + NullableMessageOption = nullableMessage; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of NullableMessage + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableMessageOption { get; private set; } + /// /// Gets or Sets NullableMessage /// [JsonPropertyName("NullableMessage")] - public string? NullableMessage { get; set; } + public string? NullableMessage { get { return this. NullableMessageOption; } set { this.NullableMessageOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? nullableMessage = default; + Option nullableMessage = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "NullableMessage": - nullableMessage = utf8JsonReader.GetString(); + nullableMessage = new Option(utf8JsonReader.GetString()); break; default: break; @@ -155,7 +163,11 @@ public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckR /// public void WriteProperties(ref Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + if (healthCheckResult.NullableMessageOption.IsSet) + if (healthCheckResult.NullableMessageOption.Value != null) + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + else + writer.WriteNull("NullableMessage"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index f33f99e6dfbf..378561b5e325 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -104,8 +105,8 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -123,10 +124,10 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -134,13 +135,19 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class IsoscelesTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class IsoscelesTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(triangleType)); - return new IsoscelesTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class IsoscelesTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class IsoscelesTriangle."); + + return new IsoscelesTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -167,7 +174,14 @@ public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTri /// public void WriteProperties(ref Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (isoscelesTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.ShapeType), "Property is required for class IsoscelesTriangle."); + + if (isoscelesTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.TriangleType), "Property is required for class IsoscelesTriangle."); + writer.WriteString("shapeType", isoscelesTriangle.ShapeType); + writer.WriteString("triangleType", isoscelesTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs index 8f55db6ee70d..a14d5e9973bd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/List.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class List : IValidatableObject /// /// var123List [JsonConstructor] - public List(string var123List) + public List(Option var123List = default) { - Var123List = var123List; + Var123ListOption = var123List; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Var123List + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123ListOption { get; private set; } + /// /// Gets or Sets Var123List /// [JsonPropertyName("123-list")] - public string Var123List { get; set; } + public string? Var123List { get { return this. Var123ListOption; } set { this.Var123ListOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? var123List = default; + Option var123List = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "123-list": - var123List = utf8JsonReader.GetString(); + var123List = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (var123List == null) - throw new ArgumentNullException(nameof(var123List), "Property is required for class List."); + if (var123List.IsSet && var123List.Value == null) + throw new ArgumentNullException(nameof(var123List), "Property is not nullable for class List."); return new List(var123List); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("123-list", list.Var123List); + if (list.Var123ListOption.IsSet && list.Var123List == null) + throw new ArgumentNullException(nameof(list.Var123List), "Property is required for class List."); + + if (list.Var123ListOption.IsSet) + writer.WriteString("123-list", list.Var123List); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/LiteralStringClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/LiteralStringClass.cs index 8253e7ac7bc8..639e2b6c76df 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/LiteralStringClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/LiteralStringClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class LiteralStringClass : IValidatableObject /// escapedLiteralString (default to "C:\\Users\\username") /// unescapedLiteralString (default to "C:\Users\username") [JsonConstructor] - public LiteralStringClass(string escapedLiteralString = @"C:\\Users\\username", string unescapedLiteralString = @"C:\Users\username") + public LiteralStringClass(Option escapedLiteralString = default, Option unescapedLiteralString = default) { - EscapedLiteralString = escapedLiteralString; - UnescapedLiteralString = unescapedLiteralString; + EscapedLiteralStringOption = escapedLiteralString; + UnescapedLiteralStringOption = unescapedLiteralString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of EscapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EscapedLiteralStringOption { get; private set; } + /// /// Gets or Sets EscapedLiteralString /// [JsonPropertyName("escapedLiteralString")] - public string EscapedLiteralString { get; set; } + public string? EscapedLiteralString { get { return this. EscapedLiteralStringOption; } set { this.EscapedLiteralStringOption = new(value); } } + + /// + /// Used to track the state of UnescapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnescapedLiteralStringOption { get; private set; } /// /// Gets or Sets UnescapedLiteralString /// [JsonPropertyName("unescapedLiteralString")] - public string UnescapedLiteralString { get; set; } + public string? UnescapedLiteralString { get { return this. UnescapedLiteralStringOption; } set { this.UnescapedLiteralStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? escapedLiteralString = default; - string? unescapedLiteralString = default; + Option escapedLiteralString = default; + Option unescapedLiteralString = default; while (utf8JsonReader.Read()) { @@ -130,10 +145,10 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "escapedLiteralString": - escapedLiteralString = utf8JsonReader.GetString(); + escapedLiteralString = new Option(utf8JsonReader.GetString()!); break; case "unescapedLiteralString": - unescapedLiteralString = utf8JsonReader.GetString(); + unescapedLiteralString = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,11 +156,11 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (escapedLiteralString == null) - throw new ArgumentNullException(nameof(escapedLiteralString), "Property is required for class LiteralStringClass."); + if (escapedLiteralString.IsSet && escapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(escapedLiteralString), "Property is not nullable for class LiteralStringClass."); - if (unescapedLiteralString == null) - throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is required for class LiteralStringClass."); + if (unescapedLiteralString.IsSet && unescapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is not nullable for class LiteralStringClass."); return new LiteralStringClass(escapedLiteralString, unescapedLiteralString); } @@ -174,8 +189,17 @@ public override void Write(Utf8JsonWriter writer, LiteralStringClass literalStri /// public void WriteProperties(ref Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); - writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); + if (literalStringClass.EscapedLiteralStringOption.IsSet && literalStringClass.EscapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.EscapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet && literalStringClass.UnescapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.UnescapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.EscapedLiteralStringOption.IsSet) + writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet) + writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs index 0910cbbb0a17..40b4a549ca6c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Mammal.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -152,7 +153,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; Pig? pig = null; Whale? whale = null; @@ -209,7 +210,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -217,17 +218,20 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Mammal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Mammal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Mammal."); if (pig != null) - return new Mammal(pig, className); + return new Mammal(pig, className.Value!); if (whale != null) - return new Mammal(whale, className); + return new Mammal(whale, className.Value!); if (zebra != null) - return new Mammal(zebra, className); + return new Mammal(zebra, className.Value!); throw new JsonException(); } @@ -271,6 +275,9 @@ public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) { + if (mammal.ClassName == null) + throw new ArgumentNullException(nameof(mammal.ClassName), "Property is required for class Mammal."); + writer.WriteString("className", mammal.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs index e29d198fe46b..e5303dbc7889 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MapTest.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,12 +39,12 @@ public partial class MapTest : IValidatableObject /// mapMapOfString /// mapOfEnumString [JsonConstructor] - public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) + public MapTest(Option?> directMap = default, Option?> indirectMap = default, Option>?> mapMapOfString = default, Option?> mapOfEnumString = default) { - DirectMap = directMap; - IndirectMap = indirectMap; - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; + DirectMapOption = directMap; + IndirectMapOption = indirectMap; + MapMapOfStringOption = mapMapOfString; + MapOfEnumStringOption = mapOfEnumString; OnCreated(); } @@ -104,7 +105,7 @@ public static InnerEnum InnerEnumFromString(string value) /// /// /// - public static string InnerEnumToJsonValue(InnerEnum value) + public static string InnerEnumToJsonValue(InnerEnum? value) { if (value == InnerEnum.UPPER) return "UPPER"; @@ -115,29 +116,57 @@ public static string InnerEnumToJsonValue(InnerEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of DirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> DirectMapOption { get; private set; } + /// /// Gets or Sets DirectMap /// [JsonPropertyName("direct_map")] - public Dictionary DirectMap { get; set; } + public Dictionary? DirectMap { get { return this. DirectMapOption; } set { this.DirectMapOption = new(value); } } + + /// + /// Used to track the state of IndirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> IndirectMapOption { get; private set; } /// /// Gets or Sets IndirectMap /// [JsonPropertyName("indirect_map")] - public Dictionary IndirectMap { get; set; } + public Dictionary? IndirectMap { get { return this. IndirectMapOption; } set { this.IndirectMapOption = new(value); } } + + /// + /// Used to track the state of MapMapOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>?> MapMapOfStringOption { get; private set; } /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + public Dictionary>? MapMapOfString { get { return this. MapMapOfStringOption; } set { this.MapMapOfStringOption = new(value); } } + + /// + /// Used to track the state of MapOfEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapOfEnumStringOption { get; private set; } /// /// Gets or Sets MapOfEnumString /// [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + public Dictionary? MapOfEnumString { get { return this. MapOfEnumStringOption; } set { this.MapOfEnumStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -195,10 +224,10 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary? directMap = default; - Dictionary? indirectMap = default; - Dictionary>? mapMapOfString = default; - Dictionary? mapOfEnumString = default; + Option?> directMap = default; + Option?> indirectMap = default; + Option>?> mapMapOfString = default; + Option?> mapOfEnumString = default; while (utf8JsonReader.Read()) { @@ -217,19 +246,19 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "direct_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - directMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + directMap = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "indirect_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - indirectMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + indirectMap = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_map_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapMapOfString = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapMapOfString = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "map_of_enum_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfEnumString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapOfEnumString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -237,17 +266,17 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (directMap == null) - throw new ArgumentNullException(nameof(directMap), "Property is required for class MapTest."); + if (directMap.IsSet && directMap.Value == null) + throw new ArgumentNullException(nameof(directMap), "Property is not nullable for class MapTest."); - if (indirectMap == null) - throw new ArgumentNullException(nameof(indirectMap), "Property is required for class MapTest."); + if (indirectMap.IsSet && indirectMap.Value == null) + throw new ArgumentNullException(nameof(indirectMap), "Property is not nullable for class MapTest."); - if (mapMapOfString == null) - throw new ArgumentNullException(nameof(mapMapOfString), "Property is required for class MapTest."); + if (mapMapOfString.IsSet && mapMapOfString.Value == null) + throw new ArgumentNullException(nameof(mapMapOfString), "Property is not nullable for class MapTest."); - if (mapOfEnumString == null) - throw new ArgumentNullException(nameof(mapOfEnumString), "Property is required for class MapTest."); + if (mapOfEnumString.IsSet && mapOfEnumString.Value == null) + throw new ArgumentNullException(nameof(mapOfEnumString), "Property is not nullable for class MapTest."); return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); } @@ -276,14 +305,38 @@ public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("direct_map"); - JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); - writer.WritePropertyName("indirect_map"); - JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); - writer.WritePropertyName("map_map_of_string"); - JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); - writer.WritePropertyName("map_of_enum_string"); - JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + if (mapTest.DirectMapOption.IsSet && mapTest.DirectMap == null) + throw new ArgumentNullException(nameof(mapTest.DirectMap), "Property is required for class MapTest."); + + if (mapTest.IndirectMapOption.IsSet && mapTest.IndirectMap == null) + throw new ArgumentNullException(nameof(mapTest.IndirectMap), "Property is required for class MapTest."); + + if (mapTest.MapMapOfStringOption.IsSet && mapTest.MapMapOfString == null) + throw new ArgumentNullException(nameof(mapTest.MapMapOfString), "Property is required for class MapTest."); + + if (mapTest.MapOfEnumStringOption.IsSet && mapTest.MapOfEnumString == null) + throw new ArgumentNullException(nameof(mapTest.MapOfEnumString), "Property is required for class MapTest."); + + if (mapTest.DirectMapOption.IsSet) + { + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); + } + if (mapTest.IndirectMapOption.IsSet) + { + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); + } + if (mapTest.MapMapOfStringOption.IsSet) + { + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); + } + if (mapTest.MapOfEnumStringOption.IsSet) + { + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 2ea2d79b05d2..f8d1ff8356a7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,40 +39,68 @@ public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableO /// uuid /// uuidWithPattern [JsonConstructor] - public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid, Guid uuidWithPattern) + public MixedPropertiesAndAdditionalPropertiesClass(Option dateTime = default, Option?> map = default, Option uuid = default, Option uuidWithPattern = default) { - DateTime = dateTime; - Map = map; - Uuid = uuid; - UuidWithPattern = uuidWithPattern; + DateTimeOption = dateTime; + MapOption = map; + UuidOption = uuid; + UuidWithPatternOption = uuidWithPattern; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } + /// /// Gets or Sets DateTime /// [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of Map + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> MapOption { get; private set; } /// /// Gets or Sets Map /// [JsonPropertyName("map")] - public Dictionary Map { get; set; } + public Dictionary? Map { get { return this. MapOption; } set { this.MapOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } + + /// + /// Used to track the state of UuidWithPattern + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidWithPatternOption { get; private set; } /// /// Gets or Sets UuidWithPattern /// [JsonPropertyName("uuid_with_pattern")] - public Guid UuidWithPattern { get; set; } + public Guid? UuidWithPattern { get { return this. UuidWithPatternOption; } set { this.UuidWithPatternOption = new(value); } } /// /// Gets or Sets additional properties @@ -105,7 +134,8 @@ public override string ToString() { // UuidWithPattern (Guid) pattern Regex regexUuidWithPattern = new Regex(@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOptions.CultureInvariant); - if (!regexUuidWithPattern.Match(this.UuidWithPattern.ToString()).Success) + + if (this.UuidWithPatternOption.Value != null &&!regexUuidWithPattern.Match(this.UuidWithPatternOption.Value.ToString()!).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UuidWithPattern, must match a pattern of " + regexUuidWithPattern, new [] { "UuidWithPattern" }); } @@ -140,10 +170,10 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateTime = default; - Dictionary? map = default; - Guid? uuid = default; - Guid? uuidWithPattern = default; + Option dateTime = default; + Option?> map = default; + Option uuid = default; + Option uuidWithPattern = default; while (utf8JsonReader.Read()) { @@ -162,19 +192,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea { case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - map = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + map = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; case "uuid_with_pattern": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuidWithPattern = utf8JsonReader.GetGuid(); + uuidWithPattern = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -182,19 +212,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea } } - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (map == null) - throw new ArgumentNullException(nameof(map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (map.IsSet && map.Value == null) + throw new ArgumentNullException(nameof(map), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuidWithPattern == null) - throw new ArgumentNullException(nameof(uuidWithPattern), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuidWithPattern.IsSet && uuidWithPattern.Value == null) + throw new ArgumentNullException(nameof(uuidWithPattern), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - return new MixedPropertiesAndAdditionalPropertiesClass(dateTime.Value, map, uuid.Value, uuidWithPattern.Value); + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid, uuidWithPattern); } /// @@ -221,11 +251,22 @@ public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("map"); - JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); - writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); - writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPattern); + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet && mixedPropertiesAndAdditionalPropertiesClass.Map == null) + throw new ArgumentNullException(nameof(mixedPropertiesAndAdditionalPropertiesClass.Map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.IsSet) + writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.Value!.Value.ToString(DateTimeFormat)); + + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet) + { + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); + } + if (mixedPropertiesAndAdditionalPropertiesClass.UuidOption.IsSet) + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.UuidOption.Value!.Value); + + if (mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.IsSet) + writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs index b017d0715831..42e64ef20547 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Model200Response.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class Model200Response : IValidatableObject /// varClass /// name [JsonConstructor] - public Model200Response(string varClass, int name) + public Model200Response(Option varClass = default, Option name = default) { - VarClass = varClass; - Name = name; + VarClassOption = varClass; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("class")] - public string VarClass { get; set; } + public string? VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public int Name { get; set; } + public int? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClass = default; - int? name = default; + Option varClass = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -130,11 +145,11 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()!); break; case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - name = utf8JsonReader.GetInt32(); + name = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -142,13 +157,13 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class Model200Response."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class Model200Response."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Model200Response."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Model200Response."); - return new Model200Response(varClass, name.Value); + return new Model200Response(varClass, name); } /// @@ -175,8 +190,14 @@ public override void Write(Utf8JsonWriter writer, Model200Response model200Respo /// public void WriteProperties(ref Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("class", model200Response.VarClass); - writer.WriteNumber("name", model200Response.Name); + if (model200Response.VarClassOption.IsSet && model200Response.VarClass == null) + throw new ArgumentNullException(nameof(model200Response.VarClass), "Property is required for class Model200Response."); + + if (model200Response.VarClassOption.IsSet) + writer.WriteString("class", model200Response.VarClass); + + if (model200Response.NameOption.IsSet) + writer.WriteNumber("name", model200Response.NameOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs index 1883e1d09c88..361969069055 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ModelClient.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class ModelClient : IValidatableObject /// /// varClient [JsonConstructor] - public ModelClient(string varClient) + public ModelClient(Option varClient = default) { - VarClient = varClient; + VarClientOption = varClient; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClient + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClientOption { get; private set; } + /// /// Gets or Sets VarClient /// [JsonPropertyName("client")] - public string VarClient { get; set; } + public string? VarClient { get { return this. VarClientOption; } set { this.VarClientOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varClient = default; + Option varClient = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "client": - varClient = utf8JsonReader.GetString(); + varClient = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (varClient == null) - throw new ArgumentNullException(nameof(varClient), "Property is required for class ModelClient."); + if (varClient.IsSet && varClient.Value == null) + throw new ArgumentNullException(nameof(varClient), "Property is not nullable for class ModelClient."); return new ModelClient(varClient); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("client", modelClient.VarClient); + if (modelClient.VarClientOption.IsSet && modelClient.VarClient == null) + throw new ArgumentNullException(nameof(modelClient.VarClient), "Property is required for class ModelClient."); + + if (modelClient.VarClientOption.IsSet) + writer.WriteString("client", modelClient.VarClient); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs index 83161d26894d..91afe1999fcd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Name.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,12 +39,12 @@ public partial class Name : IEquatable, IValidatableObject /// snakeCase /// var123Number [JsonConstructor] - public Name(int varName, string property, int snakeCase, int var123Number) + public Name(int varName, Option property = default, Option snakeCase = default, Option var123Number = default) { VarName = varName; - Property = property; - SnakeCase = snakeCase; - Var123Number = var123Number; + PropertyOption = property; + SnakeCaseOption = snakeCase; + Var123NumberOption = var123Number; OnCreated(); } @@ -55,23 +56,44 @@ public Name(int varName, string property, int snakeCase, int var123Number) [JsonPropertyName("name")] public int VarName { get; set; } + /// + /// Used to track the state of Property + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PropertyOption { get; private set; } + /// /// Gets or Sets Property /// [JsonPropertyName("property")] - public string Property { get; set; } + public string? Property { get { return this. PropertyOption; } set { this.PropertyOption = new(value); } } + + /// + /// Used to track the state of SnakeCase + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SnakeCaseOption { get; } /// /// Gets or Sets SnakeCase /// [JsonPropertyName("snake_case")] - public int SnakeCase { get; } + public int? SnakeCase { get { return this. SnakeCaseOption; } } + + /// + /// Used to track the state of Var123Number + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123NumberOption { get; } /// /// Gets or Sets Var123Number /// [JsonPropertyName("123Number")] - public int Var123Number { get; } + public int? Var123Number { get { return this. Var123NumberOption; } } /// /// Gets or Sets additional properties @@ -125,8 +147,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); - hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + if (SnakeCase != null) + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + + if (Var123Number != null) + hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -166,10 +192,10 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varName = default; - string? property = default; - int? snakeCase = default; - int? var123Number = default; + Option varName = default; + Option property = default; + Option snakeCase = default; + Option var123Number = default; while (utf8JsonReader.Read()) { @@ -188,18 +214,18 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varName = utf8JsonReader.GetInt32(); + varName = new Option(utf8JsonReader.GetInt32()); break; case "property": - property = utf8JsonReader.GetString(); + property = new Option(utf8JsonReader.GetString()!); break; case "snake_case": if (utf8JsonReader.TokenType != JsonTokenType.Null) - snakeCase = utf8JsonReader.GetInt32(); + snakeCase = new Option(utf8JsonReader.GetInt32()); break; case "123Number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - var123Number = utf8JsonReader.GetInt32(); + var123Number = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -207,19 +233,22 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (varName == null) - throw new ArgumentNullException(nameof(varName), "Property is required for class Name."); + if (!varName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(varName)); + + if (varName.IsSet && varName.Value == null) + throw new ArgumentNullException(nameof(varName), "Property is not nullable for class Name."); - if (property == null) - throw new ArgumentNullException(nameof(property), "Property is required for class Name."); + if (property.IsSet && property.Value == null) + throw new ArgumentNullException(nameof(property), "Property is not nullable for class Name."); - if (snakeCase == null) - throw new ArgumentNullException(nameof(snakeCase), "Property is required for class Name."); + if (snakeCase.IsSet && snakeCase.Value == null) + throw new ArgumentNullException(nameof(snakeCase), "Property is not nullable for class Name."); - if (var123Number == null) - throw new ArgumentNullException(nameof(var123Number), "Property is required for class Name."); + if (var123Number.IsSet && var123Number.Value == null) + throw new ArgumentNullException(nameof(var123Number), "Property is not nullable for class Name."); - return new Name(varName.Value, property, snakeCase.Value, var123Number.Value); + return new Name(varName.Value!.Value!, property, snakeCase, var123Number); } /// @@ -246,10 +275,19 @@ public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) { + if (name.PropertyOption.IsSet && name.Property == null) + throw new ArgumentNullException(nameof(name.Property), "Property is required for class Name."); + writer.WriteNumber("name", name.VarName); - writer.WriteString("property", name.Property); - writer.WriteNumber("snake_case", name.SnakeCase); - writer.WriteNumber("123Number", name.Var123Number); + + if (name.PropertyOption.IsSet) + writer.WriteString("property", name.Property); + + if (name.SnakeCaseOption.IsSet) + writer.WriteNumber("snake_case", name.SnakeCaseOption.Value!.Value); + + if (name.Var123NumberOption.IsSet) + writer.WriteNumber("123Number", name.Var123NumberOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs index 23f7775d8909..0be2516e5112 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -111,8 +112,8 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List>? aObjVariableobject = default; - int? pkiNotificationtestID = default; + Option>?> aObjVariableobject = default; + Option pkiNotificationtestID = default; while (utf8JsonReader.Read()) { @@ -131,11 +132,11 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR { case "a_objVariableobject": if (utf8JsonReader.TokenType != JsonTokenType.Null) - aObjVariableobject = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + aObjVariableobject = new Option>?>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "pkiNotificationtestID": if (utf8JsonReader.TokenType != JsonTokenType.Null) - pkiNotificationtestID = utf8JsonReader.GetInt32(); + pkiNotificationtestID = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -143,13 +144,19 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR } } - if (aObjVariableobject == null) - throw new ArgumentNullException(nameof(aObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!aObjVariableobject.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(aObjVariableobject)); - if (pkiNotificationtestID == null) - throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!pkiNotificationtestID.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(pkiNotificationtestID)); - return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject, pkiNotificationtestID.Value); + if (aObjVariableobject.IsSet && aObjVariableobject.Value == null) + throw new ArgumentNullException(nameof(aObjVariableobject), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + if (pkiNotificationtestID.IsSet && pkiNotificationtestID.Value == null) + throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject.Value!, pkiNotificationtestID.Value!.Value!); } /// @@ -176,6 +183,9 @@ public override void Write(Utf8JsonWriter writer, NotificationtestGetElementsV1R /// public void WriteProperties(ref Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) { + if (notificationtestGetElementsV1ResponseMPayload.AObjVariableobject == null) + throw new ArgumentNullException(nameof(notificationtestGetElementsV1ResponseMPayload.AObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + writer.WritePropertyName("a_objVariableobject"); JsonSerializer.Serialize(writer, notificationtestGetElementsV1ResponseMPayload.AObjVariableobject, jsonSerializerOptions); writer.WriteNumber("pkiNotificationtestID", notificationtestGetElementsV1ResponseMPayload.PkiNotificationtestID); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs index 916746334975..bfb530b894c5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableClass.cs @@ -22,20 +22,20 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// NullableClass /// - public partial class NullableClass : Dictionary, IValidatableObject + public partial class NullableClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayItemsNullable - /// objectItemsNullable /// arrayAndItemsNullableProp + /// arrayItemsNullable /// arrayNullableProp /// booleanProp /// dateProp @@ -43,99 +43,184 @@ public partial class NullableClass : Dictionary, IValidatableObj /// integerProp /// numberProp /// objectAndItemsNullableProp + /// objectItemsNullable /// objectNullableProp /// stringProp [JsonConstructor] - public NullableClass(List arrayItemsNullable, Dictionary objectItemsNullable, List? arrayAndItemsNullableProp = default, List? arrayNullableProp = default, bool? booleanProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, int? integerProp = default, decimal? numberProp = default, Dictionary? objectAndItemsNullableProp = default, Dictionary? objectNullableProp = default, string? stringProp = default) : base() + public NullableClass(Option?> arrayAndItemsNullableProp = default, Option?> arrayItemsNullable = default, Option?> arrayNullableProp = default, Option booleanProp = default, Option dateProp = default, Option datetimeProp = default, Option integerProp = default, Option numberProp = default, Option?> objectAndItemsNullableProp = default, Option?> objectItemsNullable = default, Option?> objectNullableProp = default, Option stringProp = default) { - ArrayItemsNullable = arrayItemsNullable; - ObjectItemsNullable = objectItemsNullable; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayNullableProp = arrayNullableProp; - BooleanProp = booleanProp; - DateProp = dateProp; - DatetimeProp = datetimeProp; - IntegerProp = integerProp; - NumberProp = numberProp; - ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectNullableProp = objectNullableProp; - StringProp = stringProp; + ArrayAndItemsNullablePropOption = arrayAndItemsNullableProp; + ArrayItemsNullableOption = arrayItemsNullable; + ArrayNullablePropOption = arrayNullableProp; + BooleanPropOption = booleanProp; + DatePropOption = dateProp; + DatetimePropOption = datetimeProp; + IntegerPropOption = integerProp; + NumberPropOption = numberProp; + ObjectAndItemsNullablePropOption = objectAndItemsNullableProp; + ObjectItemsNullableOption = objectItemsNullable; + ObjectNullablePropOption = objectNullableProp; + StringPropOption = stringProp; OnCreated(); } partial void OnCreated(); /// - /// Gets or Sets ArrayItemsNullable + /// Used to track the state of ArrayAndItemsNullableProp /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayAndItemsNullablePropOption { get; private set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ArrayAndItemsNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("array_and_items_nullable_prop")] + public List? ArrayAndItemsNullableProp { get { return this. ArrayAndItemsNullablePropOption; } set { this.ArrayAndItemsNullablePropOption = new(value); } } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Used to track the state of ArrayItemsNullable /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List? ArrayAndItemsNullableProp { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ArrayItemsNullable + /// + [JsonPropertyName("array_items_nullable")] + public List? ArrayItemsNullable { get { return this. ArrayItemsNullableOption; } set { this.ArrayItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ArrayNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ArrayNullablePropOption { get; private set; } /// /// Gets or Sets ArrayNullableProp /// [JsonPropertyName("array_nullable_prop")] - public List? ArrayNullableProp { get; set; } + public List? ArrayNullableProp { get { return this. ArrayNullablePropOption; } set { this.ArrayNullablePropOption = new(value); } } + + /// + /// Used to track the state of BooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BooleanPropOption { get; private set; } /// /// Gets or Sets BooleanProp /// [JsonPropertyName("boolean_prop")] - public bool? BooleanProp { get; set; } + public bool? BooleanProp { get { return this. BooleanPropOption; } set { this.BooleanPropOption = new(value); } } + + /// + /// Used to track the state of DateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatePropOption { get; private set; } /// /// Gets or Sets DateProp /// [JsonPropertyName("date_prop")] - public DateTime? DateProp { get; set; } + public DateOnly? DateProp { get { return this. DatePropOption; } set { this.DatePropOption = new(value); } } + + /// + /// Used to track the state of DatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatetimePropOption { get; private set; } /// /// Gets or Sets DatetimeProp /// [JsonPropertyName("datetime_prop")] - public DateTime? DatetimeProp { get; set; } + public DateTime? DatetimeProp { get { return this. DatetimePropOption; } set { this.DatetimePropOption = new(value); } } + + /// + /// Used to track the state of IntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerPropOption { get; private set; } /// /// Gets or Sets IntegerProp /// [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + public int? IntegerProp { get { return this. IntegerPropOption; } set { this.IntegerPropOption = new(value); } } + + /// + /// Used to track the state of NumberProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberPropOption { get; private set; } /// /// Gets or Sets NumberProp /// [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + public decimal? NumberProp { get { return this. NumberPropOption; } set { this.NumberPropOption = new(value); } } + + /// + /// Used to track the state of ObjectAndItemsNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectAndItemsNullablePropOption { get; private set; } /// /// Gets or Sets ObjectAndItemsNullableProp /// [JsonPropertyName("object_and_items_nullable_prop")] - public Dictionary? ObjectAndItemsNullableProp { get; set; } + public Dictionary? ObjectAndItemsNullableProp { get { return this. ObjectAndItemsNullablePropOption; } set { this.ObjectAndItemsNullablePropOption = new(value); } } + + /// + /// Used to track the state of ObjectItemsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [JsonPropertyName("object_items_nullable")] + public Dictionary? ObjectItemsNullable { get { return this. ObjectItemsNullableOption; } set { this.ObjectItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ObjectNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ObjectNullablePropOption { get; private set; } /// /// Gets or Sets ObjectNullableProp /// [JsonPropertyName("object_nullable_prop")] - public Dictionary? ObjectNullableProp { get; set; } + public Dictionary? ObjectNullableProp { get { return this. ObjectNullablePropOption; } set { this.ObjectNullablePropOption = new(value); } } + + /// + /// Used to track the state of StringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StringPropOption { get; private set; } /// /// Gets or Sets StringProp /// [JsonPropertyName("string_prop")] - public string? StringProp { get; set; } + public string? StringProp { get { return this. StringPropOption; } set { this.StringPropOption = new(value); } } /// /// Gets or Sets additional properties @@ -151,10 +236,8 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); @@ -162,6 +245,7 @@ public override string ToString() sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -175,16 +259,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -222,18 +296,18 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? arrayItemsNullable = default; - Dictionary? objectItemsNullable = default; - List? arrayAndItemsNullableProp = default; - List? arrayNullableProp = default; - bool? booleanProp = default; - DateTime? dateProp = default; - DateTime? datetimeProp = default; - int? integerProp = default; - decimal? numberProp = default; - Dictionary? objectAndItemsNullableProp = default; - Dictionary? objectNullableProp = default; - string? stringProp = default; + Option?> arrayAndItemsNullableProp = default; + Option?> arrayItemsNullable = default; + Option?> arrayNullableProp = default; + Option booleanProp = default; + Option dateProp = default; + Option datetimeProp = default; + Option integerProp = default; + Option numberProp = default; + Option?> objectAndItemsNullableProp = default; + Option?> objectItemsNullable = default; + Option?> objectNullableProp = default; + Option stringProp = default; while (utf8JsonReader.Read()) { @@ -250,52 +324,52 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { - case "array_items_nullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "object_items_nullable": + case "array_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayAndItemsNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "array_and_items_nullable_prop": + case "array_items_nullable": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayItemsNullable = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "array_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "boolean_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - booleanProp = utf8JsonReader.GetBoolean(); + booleanProp = new Option(utf8JsonReader.GetBoolean()); break; case "date_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "datetime_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - datetimeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + datetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "integer_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integerProp = utf8JsonReader.GetInt32(); + integerProp = new Option(utf8JsonReader.GetInt32()); break; case "number_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - numberProp = utf8JsonReader.GetDecimal(); + numberProp = new Option(utf8JsonReader.GetDecimal()); break; case "object_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectAndItemsNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "object_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectItemsNullable = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "object_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectNullableProp = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "string_prop": - stringProp = utf8JsonReader.GetString(); + stringProp = new Option(utf8JsonReader.GetString()); break; default: break; @@ -303,13 +377,13 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (arrayItemsNullable == null) - throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is required for class NullableClass."); + if (arrayItemsNullable.IsSet && arrayItemsNullable.Value == null) + throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is not nullable for class NullableClass."); - if (objectItemsNullable == null) - throw new ArgumentNullException(nameof(objectItemsNullable), "Property is required for class NullableClass."); + if (objectItemsNullable.IsSet && objectItemsNullable.Value == null) + throw new ArgumentNullException(nameof(objectItemsNullable), "Property is not nullable for class NullableClass."); - return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + return new NullableClass(arrayAndItemsNullableProp, arrayItemsNullable, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectItemsNullable, objectNullableProp, stringProp); } /// @@ -336,45 +410,89 @@ public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("object_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("array_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("array_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); - - if (nullableClass.BooleanProp != null) - writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); - else - writer.WriteNull("boolean_prop"); - - if (nullableClass.DateProp != null) - writer.WriteString("date_prop", nullableClass.DateProp.Value.ToString(DatePropFormat)); - else - writer.WriteNull("date_prop"); - - if (nullableClass.DatetimeProp != null) - writer.WriteString("datetime_prop", nullableClass.DatetimeProp.Value.ToString(DatetimePropFormat)); - else - writer.WriteNull("datetime_prop"); - - if (nullableClass.IntegerProp != null) - writer.WriteNumber("integer_prop", nullableClass.IntegerProp.Value); - else - writer.WriteNull("integer_prop"); - - if (nullableClass.NumberProp != null) - writer.WriteNumber("number_prop", nullableClass.NumberProp.Value); - else - writer.WriteNull("number_prop"); - - writer.WritePropertyName("object_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("object_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); - writer.WriteString("string_prop", nullableClass.StringProp); + if (nullableClass.ArrayItemsNullableOption.IsSet && nullableClass.ArrayItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ArrayItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ObjectItemsNullableOption.IsSet && nullableClass.ObjectItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ObjectItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ArrayAndItemsNullablePropOption.IsSet) + if (nullableClass.ArrayAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_and_items_nullable_prop"); + if (nullableClass.ArrayItemsNullableOption.IsSet) + { + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ArrayNullablePropOption.IsSet) + if (nullableClass.ArrayNullablePropOption.Value != null) + { + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_nullable_prop"); + if (nullableClass.BooleanPropOption.IsSet) + if (nullableClass.BooleanPropOption.Value != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanPropOption.Value!.Value); + else + writer.WriteNull("boolean_prop"); + + if (nullableClass.DatePropOption.IsSet) + if (nullableClass.DatePropOption.Value != null) + writer.WriteString("date_prop", nullableClass.DatePropOption.Value!.Value.ToString(DatePropFormat)); + else + writer.WriteNull("date_prop"); + + if (nullableClass.DatetimePropOption.IsSet) + if (nullableClass.DatetimePropOption.Value != null) + writer.WriteString("datetime_prop", nullableClass.DatetimePropOption.Value!.Value.ToString(DatetimePropFormat)); + else + writer.WriteNull("datetime_prop"); + + if (nullableClass.IntegerPropOption.IsSet) + if (nullableClass.IntegerPropOption.Value != null) + writer.WriteNumber("integer_prop", nullableClass.IntegerPropOption.Value!.Value); + else + writer.WriteNull("integer_prop"); + + if (nullableClass.NumberPropOption.IsSet) + if (nullableClass.NumberPropOption.Value != null) + writer.WriteNumber("number_prop", nullableClass.NumberPropOption.Value!.Value); + else + writer.WriteNull("number_prop"); + + if (nullableClass.ObjectAndItemsNullablePropOption.IsSet) + if (nullableClass.ObjectAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_and_items_nullable_prop"); + if (nullableClass.ObjectItemsNullableOption.IsSet) + { + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ObjectNullablePropOption.IsSet) + if (nullableClass.ObjectNullablePropOption.Value != null) + { + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_nullable_prop"); + if (nullableClass.StringPropOption.IsSet) + if (nullableClass.StringPropOption.Value != null) + writer.WriteString("string_prop", nullableClass.StringProp); + else + writer.WriteNull("string_prop"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableGuidClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableGuidClass.cs index b5d1bc4e4200..a2e4d0f271f9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableGuidClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableGuidClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,20 +36,27 @@ public partial class NullableGuidClass : IValidatableObject /// /// uuid [JsonConstructor] - public NullableGuidClass(Guid? uuid = default) + public NullableGuidClass(Option uuid = default) { - Uuid = uuid; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } + /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid? Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -103,7 +111,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Guid? uuid = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -122,7 +130,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t { case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -157,11 +165,11 @@ public override void Write(Utf8JsonWriter writer, NullableGuidClass nullableGuid /// public void WriteProperties(ref Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) { - - if (nullableGuidClass.Uuid == null) - writer.WriteNull("uuid"); - else - writer.WriteString("uuid", nullableGuidClass.Uuid.Value); + if (nullableGuidClass.UuidOption.IsSet) + if (nullableGuidClass.UuidOption.Value != null) + writer.WriteString("uuid", nullableGuidClass.UuidOption.Value!.Value); + else + writer.WriteNull("uuid"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs index c6f4dea35852..863a29111dd5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NullableShape.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -135,7 +136,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -186,7 +187,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,14 +195,17 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class NullableShape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class NullableShape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class NullableShape."); if (quadrilateral != null) - return new NullableShape(quadrilateral, shapeType); + return new NullableShape(quadrilateral, shapeType.Value!); if (triangle != null) - return new NullableShape(triangle, shapeType); + return new NullableShape(triangle, shapeType.Value!); throw new JsonException(); } @@ -240,6 +244,9 @@ public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) { + if (nullableShape.ShapeType == null) + throw new ArgumentNullException(nameof(nullableShape.ShapeType), "Property is required for class NullableShape."); + writer.WriteString("shapeType", nullableShape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs index 3e05a1954548..4692869f6193 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class NumberOnly : IValidatableObject /// /// justNumber [JsonConstructor] - public NumberOnly(decimal justNumber) + public NumberOnly(Option justNumber = default) { - JustNumber = justNumber; + JustNumberOption = justNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of JustNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustNumberOption { get; private set; } + /// /// Gets or Sets JustNumber /// [JsonPropertyName("JustNumber")] - public decimal JustNumber { get; set; } + public decimal? JustNumber { get { return this. JustNumberOption; } set { this.JustNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? justNumber = default; + Option justNumber = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "JustNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - justNumber = utf8JsonReader.GetDecimal(); + justNumber = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -129,10 +137,10 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (justNumber == null) - throw new ArgumentNullException(nameof(justNumber), "Property is required for class NumberOnly."); + if (justNumber.IsSet && justNumber.Value == null) + throw new ArgumentNullException(nameof(justNumber), "Property is not nullable for class NumberOnly."); - return new NumberOnly(justNumber.Value); + return new NumberOnly(justNumber); } /// @@ -159,7 +167,8 @@ public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("JustNumber", numberOnly.JustNumber); + if (numberOnly.JustNumberOption.IsSet) + writer.WriteNumber("JustNumber", numberOnly.JustNumberOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 84957dfb4699..6b6087eefac0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,43 +39,71 @@ public partial class ObjectWithDeprecatedFields : IValidatableObject /// id /// uuid [JsonConstructor] - public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) + public ObjectWithDeprecatedFields(Option?> bars = default, Option deprecatedRef = default, Option id = default, Option uuid = default) { - Bars = bars; - DeprecatedRef = deprecatedRef; - Id = id; - Uuid = uuid; + BarsOption = bars; + DeprecatedRefOption = deprecatedRef; + IdOption = id; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bars + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> BarsOption { get; private set; } + /// /// Gets or Sets Bars /// [JsonPropertyName("bars")] [Obsolete] - public List Bars { get; set; } + public List? Bars { get { return this. BarsOption; } set { this.BarsOption = new(value); } } + + /// + /// Used to track the state of DeprecatedRef + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeprecatedRefOption { get; private set; } /// /// Gets or Sets DeprecatedRef /// [JsonPropertyName("deprecatedRef")] [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } + public DeprecatedObject? DeprecatedRef { get { return this. DeprecatedRefOption; } set { this.DeprecatedRefOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] [Obsolete] - public decimal Id { get; set; } + public decimal? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public string Uuid { get; set; } + public string? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -132,10 +161,10 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? bars = default; - DeprecatedObject? deprecatedRef = default; - decimal? id = default; - string? uuid = default; + Option?> bars = default; + Option deprecatedRef = default; + Option id = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -154,18 +183,18 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade { case "bars": if (utf8JsonReader.TokenType != JsonTokenType.Null) - bars = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + bars = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "deprecatedRef": if (utf8JsonReader.TokenType != JsonTokenType.Null) - deprecatedRef = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + deprecatedRef = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetDecimal(); + id = new Option(utf8JsonReader.GetDecimal()); break; case "uuid": - uuid = utf8JsonReader.GetString(); + uuid = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -173,19 +202,19 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade } } - if (bars == null) - throw new ArgumentNullException(nameof(bars), "Property is required for class ObjectWithDeprecatedFields."); + if (bars.IsSet && bars.Value == null) + throw new ArgumentNullException(nameof(bars), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (deprecatedRef == null) - throw new ArgumentNullException(nameof(deprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + if (deprecatedRef.IsSet && deprecatedRef.Value == null) + throw new ArgumentNullException(nameof(deprecatedRef), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class ObjectWithDeprecatedFields."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class ObjectWithDeprecatedFields."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class ObjectWithDeprecatedFields."); - return new ObjectWithDeprecatedFields(bars, deprecatedRef, id.Value, uuid); + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); } /// @@ -212,12 +241,30 @@ public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields obj /// public void WriteProperties(ref Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("bars"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); - writer.WritePropertyName("deprecatedRef"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); - writer.WriteNumber("id", objectWithDeprecatedFields.Id); - writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + if (objectWithDeprecatedFields.BarsOption.IsSet && objectWithDeprecatedFields.Bars == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Bars), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet && objectWithDeprecatedFields.DeprecatedRef == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.DeprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.UuidOption.IsSet && objectWithDeprecatedFields.Uuid == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Uuid), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.BarsOption.IsSet) + { + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet) + { + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.IdOption.IsSet) + writer.WriteNumber("id", objectWithDeprecatedFields.IdOption.Value!.Value); + + if (objectWithDeprecatedFields.UuidOption.IsSet) + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OneOfString.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OneOfString.cs index e84b8aae250e..a0a54c250670 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OneOfString.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OneOfString.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs index 940d22bbd0c1..41874cbf4079 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Order.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,21 +34,21 @@ public partial class Order : IValidatableObject /// /// Initializes a new instance of the class. /// + /// complete (default to false) /// id /// petId /// quantity /// shipDate /// Order Status - /// complete (default to false) [JsonConstructor] - public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) + public Order(Option complete = default, Option id = default, Option petId = default, Option quantity = default, Option shipDate = default, Option status = default) { - Id = id; - PetId = petId; - Quantity = quantity; - ShipDate = shipDate; - Status = status; - Complete = complete; + CompleteOption = complete; + IdOption = id; + PetIdOption = petId; + QuantityOption = quantity; + ShipDateOption = shipDate; + StatusOption = status; OnCreated(); } @@ -120,7 +121,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Placed) return "placed"; @@ -134,43 +135,85 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// Order Status /// /// Order Status [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Complete + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CompleteOption { get; private set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool? Complete { get { return this. CompleteOption; } set { this.CompleteOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of PetId + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PetIdOption { get; private set; } /// /// Gets or Sets PetId /// [JsonPropertyName("petId")] - public long PetId { get; set; } + public long? PetId { get { return this. PetIdOption; } set { this.PetIdOption = new(value); } } + + /// + /// Used to track the state of Quantity + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option QuantityOption { get; private set; } /// /// Gets or Sets Quantity /// [JsonPropertyName("quantity")] - public int Quantity { get; set; } + public int? Quantity { get { return this. QuantityOption; } set { this.QuantityOption = new(value); } } /// - /// Gets or Sets ShipDate + /// Used to track the state of ShipDate /// - /// 2020-02-02T20:20:20.000222Z - [JsonPropertyName("shipDate")] - public DateTime ShipDate { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShipDateOption { get; private set; } /// - /// Gets or Sets Complete + /// Gets or Sets ShipDate /// - [JsonPropertyName("complete")] - public bool Complete { get; set; } + /// 2020-02-02T20:20:20.000222Z + [JsonPropertyName("shipDate")] + public DateTime? ShipDate { get { return this. ShipDateOption; } set { this.ShipDateOption = new(value); } } /// /// Gets or Sets additional properties @@ -186,12 +229,12 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -235,12 +278,12 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - long? petId = default; - int? quantity = default; - DateTime? shipDate = default; - Order.StatusEnum? status = default; - bool? complete = default; + Option complete = default; + Option id = default; + Option petId = default; + Option quantity = default; + Option shipDate = default; + Option status = default; while (utf8JsonReader.Read()) { @@ -257,31 +300,30 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { + case "complete": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + complete = new Option(utf8JsonReader.GetBoolean()); + break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "petId": if (utf8JsonReader.TokenType != JsonTokenType.Null) - petId = utf8JsonReader.GetInt64(); + petId = new Option(utf8JsonReader.GetInt64()); break; case "quantity": if (utf8JsonReader.TokenType != JsonTokenType.Null) - quantity = utf8JsonReader.GetInt32(); + quantity = new Option(utf8JsonReader.GetInt32()); break; case "shipDate": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shipDate = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shipDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "status": string? statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Order.StatusEnumFromStringOrDefault(statusRawValue); - break; - case "complete": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - complete = utf8JsonReader.GetBoolean(); + if (statusRawValue != null) + status = new Option(Order.StatusEnumFromStringOrDefault(statusRawValue)); break; default: break; @@ -289,25 +331,25 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Order."); + if (complete.IsSet && complete.Value == null) + throw new ArgumentNullException(nameof(complete), "Property is not nullable for class Order."); - if (petId == null) - throw new ArgumentNullException(nameof(petId), "Property is required for class Order."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Order."); - if (quantity == null) - throw new ArgumentNullException(nameof(quantity), "Property is required for class Order."); + if (petId.IsSet && petId.Value == null) + throw new ArgumentNullException(nameof(petId), "Property is not nullable for class Order."); - if (shipDate == null) - throw new ArgumentNullException(nameof(shipDate), "Property is required for class Order."); + if (quantity.IsSet && quantity.Value == null) + throw new ArgumentNullException(nameof(quantity), "Property is not nullable for class Order."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Order."); + if (shipDate.IsSet && shipDate.Value == null) + throw new ArgumentNullException(nameof(shipDate), "Property is not nullable for class Order."); - if (complete == null) - throw new ArgumentNullException(nameof(complete), "Property is required for class Order."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Order."); - return new Order(id.Value, petId.Value, quantity.Value, shipDate.Value, status.Value, complete.Value); + return new Order(complete, id, petId, quantity, shipDate, status); } /// @@ -334,18 +376,23 @@ public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", order.Id); - writer.WriteNumber("petId", order.PetId); - writer.WriteNumber("quantity", order.Quantity); - writer.WriteString("shipDate", order.ShipDate.ToString(ShipDateFormat)); - - var statusRawValue = Order.StatusEnumToJsonValue(order.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WriteBoolean("complete", order.Complete); + if (order.CompleteOption.IsSet) + writer.WriteBoolean("complete", order.CompleteOption.Value!.Value); + + if (order.IdOption.IsSet) + writer.WriteNumber("id", order.IdOption.Value!.Value); + + if (order.PetIdOption.IsSet) + writer.WriteNumber("petId", order.PetIdOption.Value!.Value); + + if (order.QuantityOption.IsSet) + writer.WriteNumber("quantity", order.QuantityOption.Value!.Value); + + if (order.ShipDateOption.IsSet) + writer.WriteString("shipDate", order.ShipDateOption.Value!.Value.ToString(ShipDateFormat)); + + var statusRawValue = Order.StatusEnumToJsonValue(order.StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs index 944b48cec72f..06993578e15f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,33 +38,54 @@ public partial class OuterComposite : IValidatableObject /// myNumber /// myString [JsonConstructor] - public OuterComposite(bool myBoolean, decimal myNumber, string myString) + public OuterComposite(Option myBoolean = default, Option myNumber = default, Option myString = default) { - MyBoolean = myBoolean; - MyNumber = myNumber; - MyString = myString; + MyBooleanOption = myBoolean; + MyNumberOption = myNumber; + MyStringOption = myString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MyBoolean + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyBooleanOption { get; private set; } + /// /// Gets or Sets MyBoolean /// [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } + public bool? MyBoolean { get { return this. MyBooleanOption; } set { this.MyBooleanOption = new(value); } } + + /// + /// Used to track the state of MyNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyNumberOption { get; private set; } /// /// Gets or Sets MyNumber /// [JsonPropertyName("my_number")] - public decimal MyNumber { get; set; } + public decimal? MyNumber { get { return this. MyNumberOption; } set { this.MyNumberOption = new(value); } } + + /// + /// Used to track the state of MyString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyStringOption { get; private set; } /// /// Gets or Sets MyString /// [JsonPropertyName("my_string")] - public string MyString { get; set; } + public string? MyString { get { return this. MyStringOption; } set { this.MyStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -120,9 +142,9 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - bool? myBoolean = default; - decimal? myNumber = default; - string? myString = default; + Option myBoolean = default; + Option myNumber = default; + Option myString = default; while (utf8JsonReader.Read()) { @@ -141,14 +163,14 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type { case "my_boolean": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myBoolean = utf8JsonReader.GetBoolean(); + myBoolean = new Option(utf8JsonReader.GetBoolean()); break; case "my_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myNumber = utf8JsonReader.GetDecimal(); + myNumber = new Option(utf8JsonReader.GetDecimal()); break; case "my_string": - myString = utf8JsonReader.GetString(); + myString = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -156,16 +178,16 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (myBoolean == null) - throw new ArgumentNullException(nameof(myBoolean), "Property is required for class OuterComposite."); + if (myBoolean.IsSet && myBoolean.Value == null) + throw new ArgumentNullException(nameof(myBoolean), "Property is not nullable for class OuterComposite."); - if (myNumber == null) - throw new ArgumentNullException(nameof(myNumber), "Property is required for class OuterComposite."); + if (myNumber.IsSet && myNumber.Value == null) + throw new ArgumentNullException(nameof(myNumber), "Property is not nullable for class OuterComposite."); - if (myString == null) - throw new ArgumentNullException(nameof(myString), "Property is required for class OuterComposite."); + if (myString.IsSet && myString.Value == null) + throw new ArgumentNullException(nameof(myString), "Property is not nullable for class OuterComposite."); - return new OuterComposite(myBoolean.Value, myNumber.Value, myString); + return new OuterComposite(myBoolean, myNumber, myString); } /// @@ -192,9 +214,17 @@ public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, /// public void WriteProperties(ref Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); - writer.WriteNumber("my_number", outerComposite.MyNumber); - writer.WriteString("my_string", outerComposite.MyString); + if (outerComposite.MyStringOption.IsSet && outerComposite.MyString == null) + throw new ArgumentNullException(nameof(outerComposite.MyString), "Property is required for class OuterComposite."); + + if (outerComposite.MyBooleanOption.IsSet) + writer.WriteBoolean("my_boolean", outerComposite.MyBooleanOption.Value!.Value); + + if (outerComposite.MyNumberOption.IsSet) + writer.WriteNumber("my_number", outerComposite.MyNumberOption.Value!.Value); + + if (outerComposite.MyStringOption.IsSet) + writer.WriteString("my_string", outerComposite.MyString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs index 01f4f4676274..96af6f3670d8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index 7903c8296487..a50d5c056ecc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index a09978af1c35..41ecebcf8f5b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index 4a73f8886ac8..902dbb066392 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumTest.cs index 9a549df1f0aa..03a8ccdecacd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/OuterEnumTest.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs index 73fc6e3e5ede..de4aa64ceab3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ParentPet.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -78,7 +79,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -96,7 +97,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -104,10 +105,13 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ParentPet."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ParentPet.", nameof(petType)); - return new ParentPet(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ParentPet."); + + return new ParentPet(petType.Value!); } /// @@ -134,6 +138,9 @@ public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) { + if (parentPet.PetType == null) + throw new ArgumentNullException(nameof(parentPet.PetType), "Property is required for class ParentPet."); + writer.WriteString("pet_type", parentPet.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs index 6705bb4138eb..9bfe1b6a2fd2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pet.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,21 +34,21 @@ public partial class Pet : IValidatableObject /// /// Initializes a new instance of the class. /// - /// category - /// id /// name /// photoUrls + /// category + /// id /// pet status in the store /// tags [JsonConstructor] - public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) + public Pet(string name, List photoUrls, Option category = default, Option id = default, Option status = default, Option?> tags = default) { - Category = category; - Id = id; Name = name; PhotoUrls = photoUrls; - Status = status; - Tags = tags; + CategoryOption = category; + IdOption = id; + StatusOption = status; + TagsOption = tags; OnCreated(); } @@ -120,7 +121,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Available) return "available"; @@ -134,43 +135,71 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// pet status in the store /// /// pet status in the store [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Gets or Sets Name + /// + /// doggie + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Used to track the state of Category + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CategoryOption { get; private set; } /// /// Gets or Sets Category /// [JsonPropertyName("category")] - public Category Category { get; set; } + public Category? Category { get { return this. CategoryOption; } set { this.CategoryOption = new(value); } } /// - /// Gets or Sets Id + /// Used to track the state of Id /// - [JsonPropertyName("id")] - public long Id { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// - /// Gets or Sets Name + /// Gets or Sets Id /// - /// doggie - [JsonPropertyName("name")] - public string Name { get; set; } + [JsonPropertyName("id")] + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// - /// Gets or Sets PhotoUrls + /// Used to track the state of Tags /// - [JsonPropertyName("photoUrls")] - public List PhotoUrls { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> TagsOption { get; private set; } /// /// Gets or Sets Tags /// [JsonPropertyName("tags")] - public List Tags { get; set; } + public List? Tags { get { return this. TagsOption; } set { this.TagsOption = new(value); } } /// /// Gets or Sets additional properties @@ -186,10 +215,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -230,12 +259,12 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Category? category = default; - long? id = default; - string? name = default; - List? photoUrls = default; - Pet.StatusEnum? status = default; - List? tags = default; + Option name = default; + Option?> photoUrls = default; + Option category = default; + Option id = default; + Option status = default; + Option?> tags = default; while (utf8JsonReader.Read()) { @@ -252,30 +281,29 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "category": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - category = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + case "name": + name = new Option(utf8JsonReader.GetString()!); break; - case "id": + case "photoUrls": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + photoUrls = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; - case "name": - name = utf8JsonReader.GetString(); + case "category": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + category = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; - case "photoUrls": + case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - photoUrls = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + id = new Option(utf8JsonReader.GetInt64()); break; case "status": string? statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Pet.StatusEnumFromStringOrDefault(statusRawValue); + if (statusRawValue != null) + status = new Option(Pet.StatusEnumFromStringOrDefault(statusRawValue)); break; case "tags": if (utf8JsonReader.TokenType != JsonTokenType.Null) - tags = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + tags = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -283,25 +311,31 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (category == null) - throw new ArgumentNullException(nameof(category), "Property is required for class Pet."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(name)); + + if (!photoUrls.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(photoUrls)); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Pet."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Pet."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Pet."); + if (photoUrls.IsSet && photoUrls.Value == null) + throw new ArgumentNullException(nameof(photoUrls), "Property is not nullable for class Pet."); - if (photoUrls == null) - throw new ArgumentNullException(nameof(photoUrls), "Property is required for class Pet."); + if (category.IsSet && category.Value == null) + throw new ArgumentNullException(nameof(category), "Property is not nullable for class Pet."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Pet."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Pet."); - if (tags == null) - throw new ArgumentNullException(nameof(tags), "Property is required for class Pet."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Pet."); - return new Pet(category, id.Value, name, photoUrls, status.Value, tags); + if (tags.IsSet && tags.Value == null) + throw new ArgumentNullException(nameof(tags), "Property is not nullable for class Pet."); + + return new Pet(name.Value!, photoUrls.Value!, category, id, status, tags); } /// @@ -328,21 +362,37 @@ public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("category"); - JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); - writer.WriteNumber("id", pet.Id); + if (pet.Name == null) + throw new ArgumentNullException(nameof(pet.Name), "Property is required for class Pet."); + + if (pet.PhotoUrls == null) + throw new ArgumentNullException(nameof(pet.PhotoUrls), "Property is required for class Pet."); + + if (pet.CategoryOption.IsSet && pet.Category == null) + throw new ArgumentNullException(nameof(pet.Category), "Property is required for class Pet."); + + if (pet.TagsOption.IsSet && pet.Tags == null) + throw new ArgumentNullException(nameof(pet.Tags), "Property is required for class Pet."); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); JsonSerializer.Serialize(writer, pet.PhotoUrls, jsonSerializerOptions); + if (pet.CategoryOption.IsSet) + { + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); + } + if (pet.IdOption.IsSet) + writer.WriteNumber("id", pet.IdOption.Value!.Value); - var statusRawValue = Pet.StatusEnumToJsonValue(pet.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WritePropertyName("tags"); - JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + var statusRawValue = Pet.StatusEnumToJsonValue(pet.StatusOption.Value!.Value); + writer.WriteString("status", statusRawValue); + if (pet.TagsOption.IsSet) + { + writer.WritePropertyName("tags"); + JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs index 07ecf267e656..727999c59285 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Pig.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -135,7 +136,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; + Option className = default; BasquePig? basquePig = null; DanishPig? danishPig = null; @@ -186,7 +187,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,14 +195,17 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Pig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Pig.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Pig."); if (basquePig != null) - return new Pig(basquePig, className); + return new Pig(basquePig, className.Value!); if (danishPig != null) - return new Pig(danishPig, className); + return new Pig(danishPig, className.Value!); throw new JsonException(); } @@ -240,6 +244,9 @@ public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) { + if (pig.ClassName == null) + throw new ArgumentNullException(nameof(pig.ClassName), "Property is required for class Pig."); + writer.WriteString("className", pig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index 2093843c8d9e..1333f4a725d6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs index 2ac725986a2a..5b20c6e30689 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -135,7 +136,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; + Option quadrilateralType = default; ComplexQuadrilateral? complexQuadrilateral = null; SimpleQuadrilateral? simpleQuadrilateral = null; @@ -186,7 +187,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,14 +195,17 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class Quadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class Quadrilateral.", nameof(quadrilateralType)); + + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class Quadrilateral."); if (complexQuadrilateral != null) - return new Quadrilateral(complexQuadrilateral, quadrilateralType); + return new Quadrilateral(complexQuadrilateral, quadrilateralType.Value!); if (simpleQuadrilateral != null) - return new Quadrilateral(simpleQuadrilateral, quadrilateralType); + return new Quadrilateral(simpleQuadrilateral, quadrilateralType.Value!); throw new JsonException(); } @@ -240,6 +244,9 @@ public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, J /// public void WriteProperties(ref Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateral.QuadrilateralType), "Property is required for class Quadrilateral."); + writer.WriteString("quadrilateralType", quadrilateral.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index a0be19661249..9a15b8828a38 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,7 +103,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; + Option quadrilateralType = default; while (utf8JsonReader.Read()) { @@ -120,7 +121,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,10 +129,13 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class QuadrilateralInterface."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class QuadrilateralInterface.", nameof(quadrilateralType)); - return new QuadrilateralInterface(quadrilateralType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class QuadrilateralInterface."); + + return new QuadrilateralInterface(quadrilateralType.Value!); } /// @@ -158,6 +162,9 @@ public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadril /// public void WriteProperties(ref Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateralInterface.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralInterface.QuadrilateralType), "Property is required for class QuadrilateralInterface."); + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 7dae6b8bb181..945d3a77f611 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class ReadOnlyFirst : IEquatable, IValidatableObj /// bar /// baz [JsonConstructor] - public ReadOnlyFirst(string bar, string baz) + public ReadOnlyFirst(Option bar = default, Option baz = default) { - Bar = bar; - Baz = baz; + BarOption = bar; + BazOption = baz; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string? Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Baz + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BazOption { get; private set; } /// /// Gets or Sets Baz /// [JsonPropertyName("baz")] - public string Baz { get; set; } + public string? Baz { get { return this. BazOption; } set { this.BazOption = new(value); } } /// /// Gets or Sets additional properties @@ -107,7 +122,9 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -147,8 +164,8 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? bar = default; - string? baz = default; + Option bar = default; + Option baz = default; while (utf8JsonReader.Read()) { @@ -166,10 +183,10 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()!); break; case "baz": - baz = utf8JsonReader.GetString(); + baz = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -177,11 +194,11 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class ReadOnlyFirst."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class ReadOnlyFirst."); - if (baz == null) - throw new ArgumentNullException(nameof(baz), "Property is required for class ReadOnlyFirst."); + if (baz.IsSet && baz.Value == null) + throw new ArgumentNullException(nameof(baz), "Property is not nullable for class ReadOnlyFirst."); return new ReadOnlyFirst(bar, baz); } @@ -210,8 +227,17 @@ public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, J /// public void WriteProperties(ref Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", readOnlyFirst.Bar); - writer.WriteString("baz", readOnlyFirst.Baz); + if (readOnlyFirst.BarOption.IsSet && readOnlyFirst.Bar == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Bar), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BazOption.IsSet && readOnlyFirst.Baz == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Baz), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BarOption.IsSet) + writer.WriteString("bar", readOnlyFirst.Bar); + + if (readOnlyFirst.BazOption.IsSet) + writer.WriteString("baz", readOnlyFirst.Baz); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..8807eb698bf7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,2380 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + public partial class RequiredClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// requiredNotNullableDateProp + /// requiredNotnullableArrayOfString + /// requiredNotnullableBooleanProp + /// requiredNotnullableDatetimeProp + /// requiredNotnullableEnumInteger + /// requiredNotnullableEnumIntegerOnly + /// requiredNotnullableEnumString + /// requiredNotnullableOuterEnumDefaultValue + /// requiredNotnullableStringProp + /// requiredNotnullableUuid + /// requiredNotnullableintegerProp + /// requiredNullableArrayOfString + /// requiredNullableBooleanProp + /// requiredNullableDateProp + /// requiredNullableDatetimeProp + /// requiredNullableEnumInteger + /// requiredNullableEnumIntegerOnly + /// requiredNullableEnumString + /// requiredNullableIntegerProp + /// requiredNullableOuterEnumDefaultValue + /// requiredNullableStringProp + /// requiredNullableUuid + /// notRequiredNotnullableDateProp + /// notRequiredNotnullableintegerProp + /// notRequiredNullableDateProp + /// notRequiredNullableIntegerProp + /// notrequiredNotnullableArrayOfString + /// notrequiredNotnullableBooleanProp + /// notrequiredNotnullableDatetimeProp + /// notrequiredNotnullableEnumInteger + /// notrequiredNotnullableEnumIntegerOnly + /// notrequiredNotnullableEnumString + /// notrequiredNotnullableOuterEnumDefaultValue + /// notrequiredNotnullableStringProp + /// notrequiredNotnullableUuid + /// notrequiredNullableArrayOfString + /// notrequiredNullableBooleanProp + /// notrequiredNullableDatetimeProp + /// notrequiredNullableEnumInteger + /// notrequiredNullableEnumIntegerOnly + /// notrequiredNullableEnumString + /// notrequiredNullableOuterEnumDefaultValue + /// notrequiredNullableStringProp + /// notrequiredNullableUuid + [JsonConstructor] + public RequiredClass(DateOnly requiredNotNullableDateProp, List requiredNotnullableArrayOfString, bool requiredNotnullableBooleanProp, DateTime requiredNotnullableDatetimeProp, RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger, RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly, RequiredNotnullableEnumStringEnum requiredNotnullableEnumString, OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue, string requiredNotnullableStringProp, Guid requiredNotnullableUuid, int requiredNotnullableintegerProp, List? requiredNullableArrayOfString = default, bool? requiredNullableBooleanProp = default, DateOnly? requiredNullableDateProp = default, DateTime? requiredNullableDatetimeProp = default, RequiredNullableEnumIntegerEnum? requiredNullableEnumInteger = default, RequiredNullableEnumIntegerOnlyEnum? requiredNullableEnumIntegerOnly = default, RequiredNullableEnumStringEnum? requiredNullableEnumString = default, int? requiredNullableIntegerProp = default, OuterEnumDefaultValue? requiredNullableOuterEnumDefaultValue = default, string? requiredNullableStringProp = default, Guid? requiredNullableUuid = default, Option notRequiredNotnullableDateProp = default, Option notRequiredNotnullableintegerProp = default, Option notRequiredNullableDateProp = default, Option notRequiredNullableIntegerProp = default, Option?> notrequiredNotnullableArrayOfString = default, Option notrequiredNotnullableBooleanProp = default, Option notrequiredNotnullableDatetimeProp = default, Option notrequiredNotnullableEnumInteger = default, Option notrequiredNotnullableEnumIntegerOnly = default, Option notrequiredNotnullableEnumString = default, Option notrequiredNotnullableOuterEnumDefaultValue = default, Option notrequiredNotnullableStringProp = default, Option notrequiredNotnullableUuid = default, Option?> notrequiredNullableArrayOfString = default, Option notrequiredNullableBooleanProp = default, Option notrequiredNullableDatetimeProp = default, Option notrequiredNullableEnumInteger = default, Option notrequiredNullableEnumIntegerOnly = default, Option notrequiredNullableEnumString = default, Option notrequiredNullableOuterEnumDefaultValue = default, Option notrequiredNullableStringProp = default, Option notrequiredNullableUuid = default) + { + RequiredNotNullableDateProp = requiredNotNullableDateProp; + RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + RequiredNotnullableEnumString = requiredNotnullableEnumString; + RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + RequiredNotnullableStringProp = requiredNotnullableStringProp; + RequiredNotnullableUuid = requiredNotnullableUuid; + RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + RequiredNullableArrayOfString = requiredNullableArrayOfString; + RequiredNullableBooleanProp = requiredNullableBooleanProp; + RequiredNullableDateProp = requiredNullableDateProp; + RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + RequiredNullableEnumInteger = requiredNullableEnumInteger; + RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + RequiredNullableEnumString = requiredNullableEnumString; + RequiredNullableIntegerProp = requiredNullableIntegerProp; + RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + RequiredNullableStringProp = requiredNullableStringProp; + RequiredNullableUuid = requiredNullableUuid; + NotRequiredNotnullableDatePropOption = notRequiredNotnullableDateProp; + NotRequiredNotnullableintegerPropOption = notRequiredNotnullableintegerProp; + NotRequiredNullableDatePropOption = notRequiredNullableDateProp; + NotRequiredNullableIntegerPropOption = notRequiredNullableIntegerProp; + NotrequiredNotnullableArrayOfStringOption = notrequiredNotnullableArrayOfString; + NotrequiredNotnullableBooleanPropOption = notrequiredNotnullableBooleanProp; + NotrequiredNotnullableDatetimePropOption = notrequiredNotnullableDatetimeProp; + NotrequiredNotnullableEnumIntegerOption = notrequiredNotnullableEnumInteger; + NotrequiredNotnullableEnumIntegerOnlyOption = notrequiredNotnullableEnumIntegerOnly; + NotrequiredNotnullableEnumStringOption = notrequiredNotnullableEnumString; + NotrequiredNotnullableOuterEnumDefaultValueOption = notrequiredNotnullableOuterEnumDefaultValue; + NotrequiredNotnullableStringPropOption = notrequiredNotnullableStringProp; + NotrequiredNotnullableUuidOption = notrequiredNotnullableUuid; + NotrequiredNullableArrayOfStringOption = notrequiredNullableArrayOfString; + NotrequiredNullableBooleanPropOption = notrequiredNullableBooleanProp; + NotrequiredNullableDatetimePropOption = notrequiredNullableDatetimeProp; + NotrequiredNullableEnumIntegerOption = notrequiredNullableEnumInteger; + NotrequiredNullableEnumIntegerOnlyOption = notrequiredNullableEnumIntegerOnly; + NotrequiredNullableEnumStringOption = notrequiredNullableEnumString; + NotrequiredNullableOuterEnumDefaultValueOption = notrequiredNullableOuterEnumDefaultValue; + NotrequiredNullableStringPropOption = notrequiredNullableStringProp; + NotrequiredNullableUuidOption = notrequiredNullableUuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum? RequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerEnumToJsonValue(RequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [JsonPropertyName("required_notnullable_enum_integer")] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum? RequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(RequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("required_notnullable_enum_integer_only")] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNotnullableEnumString + /// + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumStringEnum RequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumStringEnum? RequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNotnullableEnumStringEnumToJsonValue(RequiredNotnullableEnumStringEnum value) + { + if (value == RequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [JsonPropertyName("required_notnullable_enum_string")] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerEnum RequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerEnum? RequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerEnumToJsonValue(RequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [JsonPropertyName("required_nullable_enum_integer")] + public RequiredNullableEnumIntegerEnum? RequiredNullableEnumInteger { get; set; } + + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerOnlyEnumToJsonValue(RequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("required_nullable_enum_integer_only")] + public RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNullableEnumString + /// + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumStringEnum RequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumStringEnum? RequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string? RequiredNullableEnumStringEnumToJsonValue(RequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == RequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [JsonPropertyName("required_nullable_enum_string")] + public RequiredNullableEnumStringEnum? RequiredNullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum NotrequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerEnumToJsonValue(NotrequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [JsonPropertyName("notrequired_notnullable_enum_integer")] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get { return this.NotrequiredNotnullableEnumIntegerOption; } set { this.NotrequiredNotnullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum NotrequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_notnullable_enum_integer_only")] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get { return this.NotrequiredNotnullableEnumIntegerOnlyOption; } set { this.NotrequiredNotnullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumString + /// + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum NotrequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNotnullableEnumStringEnumToJsonValue(NotrequiredNotnullableEnumStringEnum? value) + { + if (value == NotrequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [JsonPropertyName("notrequired_notnullable_enum_string")] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get { return this.NotrequiredNotnullableEnumStringOption; } set { this.NotrequiredNotnullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get { return this.NotrequiredNotnullableOuterEnumDefaultValueOption; } set { this.NotrequiredNotnullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum NotrequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerEnumToJsonValue(NotrequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [JsonPropertyName("notrequired_nullable_enum_integer")] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get { return this.NotrequiredNullableEnumIntegerOption; } set { this.NotrequiredNullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum NotrequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_nullable_enum_integer_only")] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get { return this.NotrequiredNullableEnumIntegerOnlyOption; } set { this.NotrequiredNullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumString + /// + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumStringEnum NotrequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string? NotrequiredNullableEnumStringEnumToJsonValue(NotrequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == NotrequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [JsonPropertyName("notrequired_nullable_enum_string")] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get { return this.NotrequiredNullableEnumStringOption; } set { this.NotrequiredNullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get { return this.NotrequiredNullableOuterEnumDefaultValueOption; } set { this.NotrequiredNullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [JsonPropertyName("required_not_nullable_date_prop")] + public DateOnly RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [JsonPropertyName("required_notnullable_array_of_string")] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [JsonPropertyName("required_notnullable_boolean_prop")] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [JsonPropertyName("required_notnullable_datetime_prop")] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [JsonPropertyName("required_notnullable_string_prop")] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_notnullable_uuid")] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [JsonPropertyName("required_notnullableinteger_prop")] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [JsonPropertyName("required_nullable_array_of_string")] + public List? RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [JsonPropertyName("required_nullable_boolean_prop")] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [JsonPropertyName("required_nullable_date_prop")] + public DateOnly? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [JsonPropertyName("required_nullable_datetime_prop")] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [JsonPropertyName("required_nullable_integer_prop")] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [JsonPropertyName("required_nullable_string_prop")] + public string? RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_nullable_uuid")] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Used to track the state of NotRequiredNotnullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [JsonPropertyName("not_required_notnullable_date_prop")] + public DateOnly? NotRequiredNotnullableDateProp { get { return this. NotRequiredNotnullableDatePropOption; } set { this.NotRequiredNotnullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNotnullableintegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableintegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [JsonPropertyName("not_required_notnullableinteger_prop")] + public int? NotRequiredNotnullableintegerProp { get { return this. NotRequiredNotnullableintegerPropOption; } set { this.NotRequiredNotnullableintegerPropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [JsonPropertyName("not_required_nullable_date_prop")] + public DateOnly? NotRequiredNullableDateProp { get { return this. NotRequiredNullableDatePropOption; } set { this.NotRequiredNullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableIntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableIntegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [JsonPropertyName("not_required_nullable_integer_prop")] + public int? NotRequiredNullableIntegerProp { get { return this. NotRequiredNullableIntegerPropOption; } set { this.NotRequiredNullableIntegerPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> NotrequiredNotnullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [JsonPropertyName("notrequired_notnullable_array_of_string")] + public List? NotrequiredNotnullableArrayOfString { get { return this. NotrequiredNotnullableArrayOfStringOption; } set { this.NotrequiredNotnullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [JsonPropertyName("notrequired_notnullable_boolean_prop")] + public bool? NotrequiredNotnullableBooleanProp { get { return this. NotrequiredNotnullableBooleanPropOption; } set { this.NotrequiredNotnullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [JsonPropertyName("notrequired_notnullable_datetime_prop")] + public DateTime? NotrequiredNotnullableDatetimeProp { get { return this. NotrequiredNotnullableDatetimePropOption; } set { this.NotrequiredNotnullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [JsonPropertyName("notrequired_notnullable_string_prop")] + public string? NotrequiredNotnullableStringProp { get { return this. NotrequiredNotnullableStringPropOption; } set { this.NotrequiredNotnullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_notnullable_uuid")] + public Guid? NotrequiredNotnullableUuid { get { return this. NotrequiredNotnullableUuidOption; } set { this.NotrequiredNotnullableUuidOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> NotrequiredNullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [JsonPropertyName("notrequired_nullable_array_of_string")] + public List? NotrequiredNullableArrayOfString { get { return this. NotrequiredNullableArrayOfStringOption; } set { this.NotrequiredNullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [JsonPropertyName("notrequired_nullable_boolean_prop")] + public bool? NotrequiredNullableBooleanProp { get { return this. NotrequiredNullableBooleanPropOption; } set { this.NotrequiredNullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [JsonPropertyName("notrequired_nullable_datetime_prop")] + public DateTime? NotrequiredNullableDatetimeProp { get { return this. NotrequiredNullableDatetimePropOption; } set { this.NotrequiredNullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [JsonPropertyName("notrequired_nullable_string_prop")] + public string? NotrequiredNullableStringProp { get { return this. NotrequiredNullableStringPropOption; } set { this.NotrequiredNullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_nullable_uuid")] + public Guid? NotrequiredNullableUuid { get { return this. NotrequiredNullableUuidOption; } set { this.NotrequiredNullableUuidOption = new(value); } } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RequiredClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RequiredNotNullableDateProp + /// + public static string RequiredNotNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNotnullableDatetimeProp + /// + public static string RequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize RequiredNullableDateProp + /// + public static string RequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNullableDatetimeProp + /// + public static string RequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotRequiredNotnullableDateProp + /// + public static string NotRequiredNotnullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotRequiredNullableDateProp + /// + public static string NotRequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotrequiredNotnullableDatetimeProp + /// + public static string NotrequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotrequiredNullableDatetimeProp + /// + public static string NotrequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RequiredClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requiredNotNullableDateProp = default; + Option?> requiredNotnullableArrayOfString = default; + Option requiredNotnullableBooleanProp = default; + Option requiredNotnullableDatetimeProp = default; + Option requiredNotnullableEnumInteger = default; + Option requiredNotnullableEnumIntegerOnly = default; + Option requiredNotnullableEnumString = default; + Option requiredNotnullableOuterEnumDefaultValue = default; + Option requiredNotnullableStringProp = default; + Option requiredNotnullableUuid = default; + Option requiredNotnullableintegerProp = default; + Option?> requiredNullableArrayOfString = default; + Option requiredNullableBooleanProp = default; + Option requiredNullableDateProp = default; + Option requiredNullableDatetimeProp = default; + Option requiredNullableEnumInteger = default; + Option requiredNullableEnumIntegerOnly = default; + Option requiredNullableEnumString = default; + Option requiredNullableIntegerProp = default; + Option requiredNullableOuterEnumDefaultValue = default; + Option requiredNullableStringProp = default; + Option requiredNullableUuid = default; + Option notRequiredNotnullableDateProp = default; + Option notRequiredNotnullableintegerProp = default; + Option notRequiredNullableDateProp = default; + Option notRequiredNullableIntegerProp = default; + Option?> notrequiredNotnullableArrayOfString = default; + Option notrequiredNotnullableBooleanProp = default; + Option notrequiredNotnullableDatetimeProp = default; + Option notrequiredNotnullableEnumInteger = default; + Option notrequiredNotnullableEnumIntegerOnly = default; + Option notrequiredNotnullableEnumString = default; + Option notrequiredNotnullableOuterEnumDefaultValue = default; + Option notrequiredNotnullableStringProp = default; + Option notrequiredNotnullableUuid = default; + Option?> notrequiredNullableArrayOfString = default; + Option notrequiredNullableBooleanProp = default; + Option notrequiredNullableDatetimeProp = default; + Option notrequiredNullableEnumInteger = default; + Option notrequiredNullableEnumIntegerOnly = default; + Option notrequiredNullableEnumString = default; + Option notrequiredNullableOuterEnumDefaultValue = default; + Option notrequiredNullableStringProp = default; + Option notrequiredNullableUuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "required_not_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "required_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumInteger = new Option((RequiredClass.RequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumIntegerOnly = new Option((RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_string": + string? requiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableEnumStringRawValue != null) + requiredNotnullableEnumString = new Option(RequiredClass.RequiredNotnullableEnumStringEnumFromStringOrDefault(requiredNotnullableEnumStringRawValue)); + break; + case "required_notnullable_outerEnumDefaultValue": + string? requiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableOuterEnumDefaultValueRawValue != null) + requiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "required_notnullable_string_prop": + requiredNotnullableStringProp = new Option(utf8JsonReader.GetString()!); + break; + case "required_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumInteger = new Option((RequiredClass.RequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumIntegerOnly = new Option((RequiredClass.RequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_string": + string? requiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNullableEnumStringRawValue != null) + requiredNullableEnumString = new Option(RequiredClass.RequiredNullableEnumStringEnumFromStringOrDefault(requiredNullableEnumStringRawValue)); + break; + case "required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_outerEnumDefaultValue": + string? requiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + requiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNullableOuterEnumDefaultValueRawValue)); + break; + case "required_nullable_string_prop": + requiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "not_required_notnullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "not_required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "notrequired_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumInteger = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_string": + string? notrequiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableEnumStringRawValue != null) + notrequiredNotnullableEnumString = new Option(RequiredClass.NotrequiredNotnullableEnumStringEnumFromStringOrDefault(notrequiredNotnullableEnumStringRawValue)); + break; + case "notrequired_notnullable_outerEnumDefaultValue": + string? notrequiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableOuterEnumDefaultValueRawValue != null) + notrequiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_notnullable_string_prop": + notrequiredNotnullableStringProp = new Option(utf8JsonReader.GetString()!); + break; + case "notrequired_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "notrequired_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableArrayOfString = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumInteger = new Option((RequiredClass.NotrequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_string": + string? notrequiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableEnumStringRawValue != null) + notrequiredNullableEnumString = new Option(RequiredClass.NotrequiredNullableEnumStringEnumFromStringOrDefault(notrequiredNullableEnumStringRawValue)); + break; + case "notrequired_nullable_outerEnumDefaultValue": + string? notrequiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableOuterEnumDefaultValueRawValue != null) + notrequiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_nullable_string_prop": + notrequiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + default: + break; + } + } + } + + if (!requiredNotNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotNullableDateProp)); + + if (!requiredNotnullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableArrayOfString)); + + if (!requiredNotnullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableBooleanProp)); + + if (!requiredNotnullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableDatetimeProp)); + + if (!requiredNotnullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumInteger)); + + if (!requiredNotnullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumIntegerOnly)); + + if (!requiredNotnullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumString)); + + if (!requiredNotnullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableOuterEnumDefaultValue)); + + if (!requiredNotnullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableStringProp)); + + if (!requiredNotnullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableUuid)); + + if (!requiredNotnullableintegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableintegerProp)); + + if (!requiredNullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableArrayOfString)); + + if (!requiredNullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableBooleanProp)); + + if (!requiredNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDateProp)); + + if (!requiredNullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDatetimeProp)); + + if (!requiredNullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumInteger)); + + if (!requiredNullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumIntegerOnly)); + + if (!requiredNullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumString)); + + if (!requiredNullableIntegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableIntegerProp)); + + if (!requiredNullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableOuterEnumDefaultValue)); + + if (!requiredNullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableStringProp)); + + if (!requiredNullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableUuid)); + + if (requiredNotNullableDateProp.IsSet && requiredNotNullableDateProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotNullableDateProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableArrayOfString.IsSet && requiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableBooleanProp.IsSet && requiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableDatetimeProp.IsSet && requiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumInteger.IsSet && requiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumIntegerOnly.IsSet && requiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumString.IsSet && requiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableOuterEnumDefaultValue.IsSet && requiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableStringProp.IsSet && requiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableUuid.IsSet && requiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableintegerProp.IsSet && requiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableDateProp.IsSet && notRequiredNotnullableDateProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableDateProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableintegerProp.IsSet && notRequiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableArrayOfString.IsSet && notrequiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableBooleanProp.IsSet && notrequiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableDatetimeProp.IsSet && notrequiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumInteger.IsSet && notrequiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumIntegerOnly.IsSet && notrequiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumString.IsSet && notrequiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableOuterEnumDefaultValue.IsSet && notrequiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableStringProp.IsSet && notrequiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableUuid.IsSet && notrequiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + return new RequiredClass(requiredNotNullableDateProp.Value!.Value!, requiredNotnullableArrayOfString.Value!, requiredNotnullableBooleanProp.Value!.Value!, requiredNotnullableDatetimeProp.Value!.Value!, requiredNotnullableEnumInteger.Value!.Value!, requiredNotnullableEnumIntegerOnly.Value!.Value!, requiredNotnullableEnumString.Value!.Value!, requiredNotnullableOuterEnumDefaultValue.Value!.Value!, requiredNotnullableStringProp.Value!, requiredNotnullableUuid.Value!.Value!, requiredNotnullableintegerProp.Value!.Value!, requiredNullableArrayOfString.Value!, requiredNullableBooleanProp.Value!, requiredNullableDateProp.Value!, requiredNullableDatetimeProp.Value!, requiredNullableEnumInteger.Value!, requiredNullableEnumIntegerOnly.Value!, requiredNullableEnumString.Value!, requiredNullableIntegerProp.Value!, requiredNullableOuterEnumDefaultValue.Value!, requiredNullableStringProp.Value!, requiredNullableUuid.Value!, notRequiredNotnullableDateProp, notRequiredNotnullableintegerProp, notRequiredNullableDateProp, notRequiredNullableIntegerProp, notrequiredNotnullableArrayOfString, notrequiredNotnullableBooleanProp, notrequiredNotnullableDatetimeProp, notrequiredNotnullableEnumInteger, notrequiredNotnullableEnumIntegerOnly, notrequiredNotnullableEnumString, notrequiredNotnullableOuterEnumDefaultValue, notrequiredNotnullableStringProp, notrequiredNotnullableUuid, notrequiredNullableArrayOfString, notrequiredNullableBooleanProp, notrequiredNullableDatetimeProp, notrequiredNullableEnumInteger, notrequiredNullableEnumIntegerOnly, notrequiredNullableEnumString, notrequiredNullableOuterEnumDefaultValue, notrequiredNullableStringProp, notrequiredNullableUuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, requiredClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + if (requiredClass.RequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.RequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet && requiredClass.NotrequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet && requiredClass.NotrequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + writer.WriteString("required_not_nullable_date_prop", requiredClass.RequiredNotNullableDateProp.ToString(RequiredNotNullableDatePropFormat)); + + writer.WritePropertyName("required_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNotnullableArrayOfString, jsonSerializerOptions); + writer.WriteBoolean("required_notnullable_boolean_prop", requiredClass.RequiredNotnullableBooleanProp); + + writer.WriteString("required_notnullable_datetime_prop", requiredClass.RequiredNotnullableDatetimeProp.ToString(RequiredNotnullableDatetimePropFormat)); + + writer.WriteNumber("required_notnullable_enum_integer", RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNotnullableEnumInteger)); + + writer.WriteNumber("required_notnullable_enum_integer_only", RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNotnullableEnumIntegerOnly)); + + var requiredNotnullableEnumStringRawValue = RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClass.RequiredNotnullableEnumString); + writer.WriteString("required_notnullable_enum_string", requiredNotnullableEnumStringRawValue); + var requiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNotnullableOuterEnumDefaultValue); + writer.WriteString("required_notnullable_outerEnumDefaultValue", requiredNotnullableOuterEnumDefaultValueRawValue); + + writer.WriteString("required_notnullable_string_prop", requiredClass.RequiredNotnullableStringProp); + + writer.WriteString("required_notnullable_uuid", requiredClass.RequiredNotnullableUuid); + + writer.WriteNumber("required_notnullableinteger_prop", requiredClass.RequiredNotnullableintegerProp); + + if (requiredClass.RequiredNullableArrayOfString != null) + { + writer.WritePropertyName("required_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("required_nullable_array_of_string"); + if (requiredClass.RequiredNullableBooleanProp != null) + writer.WriteBoolean("required_nullable_boolean_prop", requiredClass.RequiredNullableBooleanProp.Value); + else + writer.WriteNull("required_nullable_boolean_prop"); + + if (requiredClass.RequiredNullableDateProp != null) + writer.WriteString("required_nullable_date_prop", requiredClass.RequiredNullableDateProp.Value.ToString(RequiredNullableDatePropFormat)); + else + writer.WriteNull("required_nullable_date_prop"); + + if (requiredClass.RequiredNullableDatetimeProp != null) + writer.WriteString("required_nullable_datetime_prop", requiredClass.RequiredNullableDatetimeProp.Value.ToString(RequiredNullableDatetimePropFormat)); + else + writer.WriteNull("required_nullable_datetime_prop"); + + if (requiredClass.RequiredNullableEnumInteger != null) + writer.WriteNumber("required_nullable_enum_integer", RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNullableEnumInteger.Value)); + else + writer.WriteNull("required_nullable_enum_integer"); + + if (requiredClass.RequiredNullableEnumIntegerOnly != null) + writer.WriteNumber("required_nullable_enum_integer_only", RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNullableEnumIntegerOnly.Value)); + else + writer.WriteNull("required_nullable_enum_integer_only"); + + var requiredNullableEnumStringRawValue = RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClass.RequiredNullableEnumString!.Value); + if (requiredNullableEnumStringRawValue != null) + writer.WriteString("required_nullable_enum_string", requiredNullableEnumStringRawValue); + else + writer.WriteNull("required_nullable_enum_string"); + + if (requiredClass.RequiredNullableIntegerProp != null) + writer.WriteNumber("required_nullable_integer_prop", requiredClass.RequiredNullableIntegerProp.Value); + else + writer.WriteNull("required_nullable_integer_prop"); + + if (requiredClass.RequiredNullableOuterEnumDefaultValue == null) + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + else + { + var requiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNullableOuterEnumDefaultValue.Value); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + writer.WriteString("required_nullable_outerEnumDefaultValue", requiredNullableOuterEnumDefaultValueRawValue); + else + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + } + + if (requiredClass.RequiredNullableStringProp != null) + writer.WriteString("required_nullable_string_prop", requiredClass.RequiredNullableStringProp); + else + writer.WriteNull("required_nullable_string_prop"); + + if (requiredClass.RequiredNullableUuid != null) + writer.WriteString("required_nullable_uuid", requiredClass.RequiredNullableUuid.Value); + else + writer.WriteNull("required_nullable_uuid"); + + if (requiredClass.NotRequiredNotnullableDatePropOption.IsSet) + writer.WriteString("not_required_notnullable_date_prop", requiredClass.NotRequiredNotnullableDatePropOption.Value!.Value.ToString(NotRequiredNotnullableDatePropFormat)); + + if (requiredClass.NotRequiredNotnullableintegerPropOption.IsSet) + writer.WriteNumber("not_required_notnullableinteger_prop", requiredClass.NotRequiredNotnullableintegerPropOption.Value!.Value); + + if (requiredClass.NotRequiredNullableDatePropOption.IsSet) + if (requiredClass.NotRequiredNullableDatePropOption.Value != null) + writer.WriteString("not_required_nullable_date_prop", requiredClass.NotRequiredNullableDatePropOption.Value!.Value.ToString(NotRequiredNullableDatePropFormat)); + else + writer.WriteNull("not_required_nullable_date_prop"); + + if (requiredClass.NotRequiredNullableIntegerPropOption.IsSet) + if (requiredClass.NotRequiredNullableIntegerPropOption.Value != null) + writer.WriteNumber("not_required_nullable_integer_prop", requiredClass.NotRequiredNullableIntegerPropOption.Value!.Value); + else + writer.WriteNull("not_required_nullable_integer_prop"); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet) + { + writer.WritePropertyName("notrequired_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNotnullableArrayOfString, jsonSerializerOptions); + } + if (requiredClass.NotrequiredNotnullableBooleanPropOption.IsSet) + writer.WriteBoolean("notrequired_notnullable_boolean_prop", requiredClass.NotrequiredNotnullableBooleanPropOption.Value!.Value); + + if (requiredClass.NotrequiredNotnullableDatetimePropOption.IsSet) + writer.WriteString("notrequired_notnullable_datetime_prop", requiredClass.NotrequiredNotnullableDatetimePropOption.Value!.Value.ToString(NotrequiredNotnullableDatetimePropFormat)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer", RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOption.Value!.Value)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer_only", RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.Value!.Value)); + + var notrequiredNotnullableEnumStringRawValue = RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumStringOption.Value!.Value); + writer.WriteString("notrequired_notnullable_enum_string", notrequiredNotnullableEnumStringRawValue); + if (requiredClass.NotrequiredNotnullableOuterEnumDefaultValueOption.IsSet) + { + var notrequiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNotnullableOuterEnumDefaultValue!.Value); + writer.WriteString("notrequired_notnullable_outerEnumDefaultValue", notrequiredNotnullableOuterEnumDefaultValueRawValue); + } + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet) + writer.WriteString("notrequired_notnullable_string_prop", requiredClass.NotrequiredNotnullableStringProp); + + if (requiredClass.NotrequiredNotnullableUuidOption.IsSet) + writer.WriteString("notrequired_notnullable_uuid", requiredClass.NotrequiredNotnullableUuidOption.Value!.Value); + + if (requiredClass.NotrequiredNullableArrayOfStringOption.IsSet) + if (requiredClass.NotrequiredNullableArrayOfStringOption.Value != null) + { + writer.WritePropertyName("notrequired_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("notrequired_nullable_array_of_string"); + if (requiredClass.NotrequiredNullableBooleanPropOption.IsSet) + if (requiredClass.NotrequiredNullableBooleanPropOption.Value != null) + writer.WriteBoolean("notrequired_nullable_boolean_prop", requiredClass.NotrequiredNullableBooleanPropOption.Value!.Value); + else + writer.WriteNull("notrequired_nullable_boolean_prop"); + + if (requiredClass.NotrequiredNullableDatetimePropOption.IsSet) + if (requiredClass.NotrequiredNullableDatetimePropOption.Value != null) + writer.WriteString("notrequired_nullable_datetime_prop", requiredClass.NotrequiredNullableDatetimePropOption.Value!.Value.ToString(NotrequiredNullableDatetimePropFormat)); + else + writer.WriteNull("notrequired_nullable_datetime_prop"); + + if (requiredClass.NotrequiredNullableEnumIntegerOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer", RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOption.Value!.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer"); + + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer_only", RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value!.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer_only"); + + var notrequiredNullableEnumStringRawValue = RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNullableEnumStringOption.Value!.Value); + if (notrequiredNullableEnumStringRawValue != null) + writer.WriteString("notrequired_nullable_enum_string", notrequiredNullableEnumStringRawValue); + else + writer.WriteNull("notrequired_nullable_enum_string"); + + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.IsSet) + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption!.Value != null) + { + var notrequiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value!.Value); + writer.WriteString("notrequired_nullable_outerEnumDefaultValue", notrequiredNullableOuterEnumDefaultValueRawValue); + } + else + writer.WriteNull("notrequired_nullable_outerEnumDefaultValue"); + if (requiredClass.NotrequiredNullableStringPropOption.IsSet) + if (requiredClass.NotrequiredNullableStringPropOption.Value != null) + writer.WriteString("notrequired_nullable_string_prop", requiredClass.NotrequiredNullableStringProp); + else + writer.WriteNull("notrequired_nullable_string_prop"); + + if (requiredClass.NotrequiredNullableUuidOption.IsSet) + if (requiredClass.NotrequiredNullableUuidOption.Value != null) + writer.WriteString("notrequired_nullable_uuid", requiredClass.NotrequiredNullableUuidOption.Value!.Value); + else + writer.WriteNull("notrequired_nullable_uuid"); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs index 262ecadf740b..5449201bcf15 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Return.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Return : IValidatableObject /// /// varReturn [JsonConstructor] - public Return(int varReturn) + public Return(Option varReturn = default) { - VarReturn = varReturn; + VarReturnOption = varReturn; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarReturn + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarReturnOption { get; private set; } + /// /// Gets or Sets VarReturn /// [JsonPropertyName("return")] - public int VarReturn { get; set; } + public int? VarReturn { get { return this. VarReturnOption; } set { this.VarReturnOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varReturn = default; + Option varReturn = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "return": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varReturn = utf8JsonReader.GetInt32(); + varReturn = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -129,10 +137,10 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (varReturn == null) - throw new ArgumentNullException(nameof(varReturn), "Property is required for class Return."); + if (varReturn.IsSet && varReturn.Value == null) + throw new ArgumentNullException(nameof(varReturn), "Property is not nullable for class Return."); - return new Return(varReturn.Value); + return new Return(varReturn); } /// @@ -159,7 +167,8 @@ public override void Write(Utf8JsonWriter writer, Return varReturn, JsonSerializ /// public void WriteProperties(ref Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("return", varReturn.VarReturn); + if (varReturn.VarReturnOption.IsSet) + writer.WriteNumber("return", varReturn.VarReturnOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHash.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHash.cs index f7be23ecece4..0a00cf07fd74 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHash.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHash.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class RolesReportsHash : IValidatableObject /// role /// roleUuid [JsonConstructor] - public RolesReportsHash(RolesReportsHashRole role, Guid roleUuid) + public RolesReportsHash(Option role = default, Option roleUuid = default) { - Role = role; - RoleUuid = roleUuid; + RoleOption = role; + RoleUuidOption = roleUuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Role + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleOption { get; private set; } + /// /// Gets or Sets Role /// [JsonPropertyName("role")] - public RolesReportsHashRole Role { get; set; } + public RolesReportsHashRole? Role { get { return this. RoleOption; } set { this.RoleOption = new(value); } } + + /// + /// Used to track the state of RoleUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleUuidOption { get; private set; } /// /// Gets or Sets RoleUuid /// [JsonPropertyName("role_uuid")] - public Guid RoleUuid { get; set; } + public Guid? RoleUuid { get { return this. RoleUuidOption; } set { this.RoleUuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - RolesReportsHashRole? role = default; - Guid? roleUuid = default; + Option role = default; + Option roleUuid = default; while (utf8JsonReader.Read()) { @@ -131,11 +146,11 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty { case "role": if (utf8JsonReader.TokenType != JsonTokenType.Null) - role = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + role = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); break; case "role_uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - roleUuid = utf8JsonReader.GetGuid(); + roleUuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -143,13 +158,13 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (role == null) - throw new ArgumentNullException(nameof(role), "Property is required for class RolesReportsHash."); + if (role.IsSet && role.Value == null) + throw new ArgumentNullException(nameof(role), "Property is not nullable for class RolesReportsHash."); - if (roleUuid == null) - throw new ArgumentNullException(nameof(roleUuid), "Property is required for class RolesReportsHash."); + if (roleUuid.IsSet && roleUuid.Value == null) + throw new ArgumentNullException(nameof(roleUuid), "Property is not nullable for class RolesReportsHash."); - return new RolesReportsHash(role, roleUuid.Value); + return new RolesReportsHash(role, roleUuid); } /// @@ -176,9 +191,16 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHash rolesReportsH /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("role"); - JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); - writer.WriteString("role_uuid", rolesReportsHash.RoleUuid); + if (rolesReportsHash.RoleOption.IsSet && rolesReportsHash.Role == null) + throw new ArgumentNullException(nameof(rolesReportsHash.Role), "Property is required for class RolesReportsHash."); + + if (rolesReportsHash.RoleOption.IsSet) + { + writer.WritePropertyName("role"); + JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); + } + if (rolesReportsHash.RoleUuidOption.IsSet) + writer.WriteString("role_uuid", rolesReportsHash.RoleUuidOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs index f64e8c9cd62e..51616042599a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class RolesReportsHashRole : IValidatableObject /// /// name [JsonConstructor] - public RolesReportsHashRole(string name) + public RolesReportsHashRole(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class RolesReportsHashRole."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class RolesReportsHashRole."); return new RolesReportsHashRole(name); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHashRole rolesRepo /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", rolesReportsHashRole.Name); + if (rolesReportsHashRole.NameOption.IsSet && rolesReportsHashRole.Name == null) + throw new ArgumentNullException(nameof(rolesReportsHashRole.Name), "Property is required for class RolesReportsHashRole."); + + if (rolesReportsHashRole.NameOption.IsSet) + writer.WriteString("name", rolesReportsHashRole.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 9e9dc21151e0..4cdb6d4aa46d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -111,8 +112,8 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; - string? triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -130,10 +131,10 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,13 +142,19 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ScaleneTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class ScaleneTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(triangleType)); - return new ScaleneTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ScaleneTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class ScaleneTriangle."); + + return new ScaleneTriangle(shapeType.Value!, triangleType.Value!); } /// @@ -174,7 +181,14 @@ public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangl /// public void WriteProperties(ref Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (scaleneTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.ShapeType), "Property is required for class ScaleneTriangle."); + + if (scaleneTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.TriangleType), "Property is required for class ScaleneTriangle."); + writer.WriteString("shapeType", scaleneTriangle.ShapeType); + writer.WriteString("triangleType", scaleneTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs index d8fbc094d19c..f2e26ef8c5ae 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Shape.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -135,7 +136,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -186,7 +187,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,14 +195,17 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class Shape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class Shape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class Shape."); if (quadrilateral != null) - return new Shape(quadrilateral, shapeType); + return new Shape(quadrilateral, shapeType.Value!); if (triangle != null) - return new Shape(triangle, shapeType); + return new Shape(triangle, shapeType.Value!); throw new JsonException(); } @@ -240,6 +244,9 @@ public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) { + if (shape.ShapeType == null) + throw new ArgumentNullException(nameof(shape.ShapeType), "Property is required for class Shape."); + writer.WriteString("shapeType", shape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs index 1b0a8291f383..2780ac574a8d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,7 +103,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -120,7 +121,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,10 +129,13 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeInterface."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeInterface.", nameof(shapeType)); - return new ShapeInterface(shapeType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeInterface."); + + return new ShapeInterface(shapeType.Value!); } /// @@ -158,6 +162,9 @@ public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) { + if (shapeInterface.ShapeType == null) + throw new ArgumentNullException(nameof(shapeInterface.ShapeType), "Property is required for class ShapeInterface."); + writer.WriteString("shapeType", shapeInterface.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 1b75eada511b..b7c92c1f884e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -135,7 +136,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? shapeType = default; + Option shapeType = default; Quadrilateral? quadrilateral = null; Triangle? triangle = null; @@ -186,7 +187,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -194,14 +195,17 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeOrNull."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeOrNull.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeOrNull."); if (quadrilateral != null) - return new ShapeOrNull(quadrilateral, shapeType); + return new ShapeOrNull(quadrilateral, shapeType.Value!); if (triangle != null) - return new ShapeOrNull(triangle, shapeType); + return new ShapeOrNull(triangle, shapeType.Value!); throw new JsonException(); } @@ -240,6 +244,9 @@ public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) { + if (shapeOrNull.ShapeType == null) + throw new ArgumentNullException(nameof(shapeOrNull.ShapeType), "Property is required for class ShapeOrNull."); + writer.WriteString("shapeType", shapeOrNull.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 8945a243dfd2..279d0b1faa0b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -111,8 +112,8 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? quadrilateralType = default; - string? shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -130,10 +131,10 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()!); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -141,13 +142,19 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class SimpleQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class SimpleQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(shapeType)); - return new SimpleQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class SimpleQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class SimpleQuadrilateral."); + + return new SimpleQuadrilateral(quadrilateralType.Value!, shapeType.Value!); } /// @@ -174,7 +181,14 @@ public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuad /// public void WriteProperties(ref Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (simpleQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.QuadrilateralType), "Property is required for class SimpleQuadrilateral."); + + if (simpleQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.ShapeType), "Property is required for class SimpleQuadrilateral."); + writer.WriteString("quadrilateralType", simpleQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", simpleQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs index 39baf9d3e4f0..e627c778abcd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class SpecialModelName : IValidatableObject /// varSpecialModelName /// specialPropertyName [JsonConstructor] - public SpecialModelName(string varSpecialModelName, long specialPropertyName) + public SpecialModelName(Option varSpecialModelName = default, Option specialPropertyName = default) { - VarSpecialModelName = varSpecialModelName; - SpecialPropertyName = specialPropertyName; + VarSpecialModelNameOption = varSpecialModelName; + SpecialPropertyNameOption = specialPropertyName; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarSpecialModelName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarSpecialModelNameOption { get; private set; } + /// /// Gets or Sets VarSpecialModelName /// [JsonPropertyName("_special_model.name_")] - public string VarSpecialModelName { get; set; } + public string? VarSpecialModelName { get { return this. VarSpecialModelNameOption; } set { this.VarSpecialModelNameOption = new(value); } } + + /// + /// Used to track the state of SpecialPropertyName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SpecialPropertyNameOption { get; private set; } /// /// Gets or Sets SpecialPropertyName /// [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + public long? SpecialPropertyName { get { return this. SpecialPropertyNameOption; } set { this.SpecialPropertyNameOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? varSpecialModelName = default; - long? specialPropertyName = default; + Option varSpecialModelName = default; + Option specialPropertyName = default; while (utf8JsonReader.Read()) { @@ -130,11 +145,11 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "_special_model.name_": - varSpecialModelName = utf8JsonReader.GetString(); + varSpecialModelName = new Option(utf8JsonReader.GetString()!); break; case "$special[property.name]": if (utf8JsonReader.TokenType != JsonTokenType.Null) - specialPropertyName = utf8JsonReader.GetInt64(); + specialPropertyName = new Option(utf8JsonReader.GetInt64()); break; default: break; @@ -142,13 +157,13 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varSpecialModelName == null) - throw new ArgumentNullException(nameof(varSpecialModelName), "Property is required for class SpecialModelName."); + if (varSpecialModelName.IsSet && varSpecialModelName.Value == null) + throw new ArgumentNullException(nameof(varSpecialModelName), "Property is not nullable for class SpecialModelName."); - if (specialPropertyName == null) - throw new ArgumentNullException(nameof(specialPropertyName), "Property is required for class SpecialModelName."); + if (specialPropertyName.IsSet && specialPropertyName.Value == null) + throw new ArgumentNullException(nameof(specialPropertyName), "Property is not nullable for class SpecialModelName."); - return new SpecialModelName(varSpecialModelName, specialPropertyName.Value); + return new SpecialModelName(varSpecialModelName, specialPropertyName); } /// @@ -175,8 +190,14 @@ public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelN /// public void WriteProperties(ref Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); - writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyName); + if (specialModelName.VarSpecialModelNameOption.IsSet && specialModelName.VarSpecialModelName == null) + throw new ArgumentNullException(nameof(specialModelName.VarSpecialModelName), "Property is required for class SpecialModelName."); + + if (specialModelName.VarSpecialModelNameOption.IsSet) + writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); + + if (specialModelName.SpecialPropertyNameOption.IsSet) + writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyNameOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs index 1f69557e7d73..a8f5a1b30082 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Tag.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,26 +37,40 @@ public partial class Tag : IValidatableObject /// id /// name [JsonConstructor] - public Tag(long id, string name) + public Tag(Option id = default, Option name = default) { - Id = id; - Name = name; + IdOption = id; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -111,8 +126,8 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string? name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -131,10 +146,10 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -142,13 +157,13 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Tag."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Tag."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Tag."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Tag."); - return new Tag(id.Value, name); + return new Tag(id, name); } /// @@ -175,8 +190,14 @@ public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", tag.Id); - writer.WriteString("name", tag.Name); + if (tag.NameOption.IsSet && tag.Name == null) + throw new ArgumentNullException(nameof(tag.Name), "Property is required for class Tag."); + + if (tag.IdOption.IsSet) + writer.WriteNumber("id", tag.IdOption.Value!.Value); + + if (tag.NameOption.IsSet) + writer.WriteString("name", tag.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs index fa286e8f3fd6..e98384c82055 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class TestCollectionEndingWithWordList : IValidatableObject /// /// value [JsonConstructor] - public TestCollectionEndingWithWordList(string value) + public TestCollectionEndingWithWordList(Option value = default) { - Value = value; + ValueOption = value; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Value + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ValueOption { get; private set; } + /// /// Gets or Sets Value /// [JsonPropertyName("value")] - public string Value { get; set; } + public string? Value { get { return this. ValueOption; } set { this.ValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? value = default; + Option value = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso switch (localVarJsonPropertyName) { case "value": - value = utf8JsonReader.GetString(); + value = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso } } - if (value == null) - throw new ArgumentNullException(nameof(value), "Property is required for class TestCollectionEndingWithWordList."); + if (value.IsSet && value.Value == null) + throw new ArgumentNullException(nameof(value), "Property is not nullable for class TestCollectionEndingWithWordList."); return new TestCollectionEndingWithWordList(value); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("value", testCollectionEndingWithWordList.Value); + if (testCollectionEndingWithWordList.ValueOption.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList.Value), "Property is required for class TestCollectionEndingWithWordList."); + + if (testCollectionEndingWithWordList.ValueOption.IsSet) + writer.WriteString("value", testCollectionEndingWithWordList.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs index 5c481470c71a..75005fd9bf78 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class TestCollectionEndingWithWordListObject : IValidatableObject /// /// testCollectionEndingWithWordList [JsonConstructor] - public TestCollectionEndingWithWordListObject(List testCollectionEndingWithWordList) + public TestCollectionEndingWithWordListObject(Option?> testCollectionEndingWithWordList = default) { - TestCollectionEndingWithWordList = testCollectionEndingWithWordList; + TestCollectionEndingWithWordListOption = testCollectionEndingWithWordList; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of TestCollectionEndingWithWordList + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> TestCollectionEndingWithWordListOption { get; private set; } + /// /// Gets or Sets TestCollectionEndingWithWordList /// [JsonPropertyName("TestCollectionEndingWithWordList")] - public List TestCollectionEndingWithWordList { get; set; } + public List? TestCollectionEndingWithWordList { get { return this. TestCollectionEndingWithWordListOption; } set { this.TestCollectionEndingWithWordListOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? testCollectionEndingWithWordList = default; + Option?> testCollectionEndingWithWordList = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u { case "TestCollectionEndingWithWordList": if (utf8JsonReader.TokenType != JsonTokenType.Null) - testCollectionEndingWithWordList = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + testCollectionEndingWithWordList = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; default: break; @@ -129,8 +137,8 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u } } - if (testCollectionEndingWithWordList == null) - throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + if (testCollectionEndingWithWordList.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is not nullable for class TestCollectionEndingWithWordListObject."); return new TestCollectionEndingWithWordListObject(testCollectionEndingWithWordList); } @@ -159,8 +167,14 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("TestCollectionEndingWithWordList"); - JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet && testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet) + { + writer.WritePropertyName("TestCollectionEndingWithWordList"); + JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index 95ad0601f978..9c01f36af3d6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -22,32 +22,40 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// TestInlineFreeformAdditionalPropertiesRequest /// - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty [JsonConstructor] - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty) : base() + public TestInlineFreeformAdditionalPropertiesRequest(Option someProperty = default) { - SomeProperty = someProperty; + SomePropertyOption = someProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SomeProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SomePropertyOption { get; private set; } + /// /// Gets or Sets SomeProperty /// [JsonPropertyName("someProperty")] - public string SomeProperty { get; set; } + public string? SomeProperty { get { return this. SomePropertyOption; } set { this.SomePropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -63,7 +71,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -76,16 +83,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -113,7 +110,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? someProperty = default; + Option someProperty = default; while (utf8JsonReader.Read()) { @@ -131,7 +128,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR switch (localVarJsonPropertyName) { case "someProperty": - someProperty = utf8JsonReader.GetString(); + someProperty = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -139,8 +136,8 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR } } - if (someProperty == null) - throw new ArgumentNullException(nameof(someProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + if (someProperty.IsSet && someProperty.Value == null) + throw new ArgumentNullException(nameof(someProperty), "Property is not nullable for class TestInlineFreeformAdditionalPropertiesRequest."); return new TestInlineFreeformAdditionalPropertiesRequest(someProperty); } @@ -169,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, TestInlineFreeformAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet && testInlineFreeformAdditionalPropertiesRequest.SomeProperty == null) + throw new ArgumentNullException(nameof(testInlineFreeformAdditionalPropertiesRequest.SomeProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet) + writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs index c75c83f7d54b..303afee787db 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Triangle.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -152,7 +153,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? triangleType = default; + Option triangleType = default; EquilateralTriangle? equilateralTriangle = null; IsoscelesTriangle? isoscelesTriangle = null; @@ -209,7 +210,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -217,17 +218,20 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class Triangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class Triangle.", nameof(triangleType)); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class Triangle."); if (equilateralTriangle != null) - return new Triangle(equilateralTriangle, triangleType); + return new Triangle(equilateralTriangle, triangleType.Value!); if (isoscelesTriangle != null) - return new Triangle(isoscelesTriangle, triangleType); + return new Triangle(isoscelesTriangle, triangleType.Value!); if (scaleneTriangle != null) - return new Triangle(scaleneTriangle, triangleType); + return new Triangle(scaleneTriangle, triangleType.Value!); throw new JsonException(); } @@ -271,6 +275,9 @@ public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) { + if (triangle.TriangleType == null) + throw new ArgumentNullException(nameof(triangle.TriangleType), "Property is required for class Triangle."); + writer.WriteString("triangleType", triangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs index a724643f7327..f5bb5d307c83 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,7 +103,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? triangleType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -120,7 +121,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,10 +129,13 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class TriangleInterface."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class TriangleInterface.", nameof(triangleType)); - return new TriangleInterface(triangleType); + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class TriangleInterface."); + + return new TriangleInterface(triangleType.Value!); } /// @@ -158,6 +162,9 @@ public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInte /// public void WriteProperties(ref Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) { + if (triangleInterface.TriangleType == null) + throw new ArgumentNullException(nameof(triangleInterface.TriangleType), "Property is required for class TriangleInterface."); + writer.WriteString("triangleType", triangleInterface.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs index 32df8b267426..64db3e2f4623 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/User.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,114 +34,198 @@ public partial class User : IValidatableObject /// /// Initializes a new instance of the class. /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. /// email /// firstName /// id /// lastName /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. /// password /// phone /// User Status /// username - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. [JsonConstructor] - public User(string email, string firstName, long id, string lastName, Object objectWithNoDeclaredProps, string password, string phone, int userStatus, string username, Object? anyTypeProp = default, Object? anyTypePropNullable = default, Object? objectWithNoDeclaredPropsNullable = default) + public User(Option anyTypeProp = default, Option anyTypePropNullable = default, Option email = default, Option firstName = default, Option id = default, Option lastName = default, Option objectWithNoDeclaredProps = default, Option objectWithNoDeclaredPropsNullable = default, Option password = default, Option phone = default, Option userStatus = default, Option username = default) { - Email = email; - FirstName = firstName; - Id = id; - LastName = lastName; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - Password = password; - Phone = phone; - UserStatus = userStatus; - Username = username; - AnyTypeProp = anyTypeProp; - AnyTypePropNullable = anyTypePropNullable; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + AnyTypePropOption = anyTypeProp; + AnyTypePropNullableOption = anyTypePropNullable; + EmailOption = email; + FirstNameOption = firstName; + IdOption = id; + LastNameOption = lastName; + ObjectWithNoDeclaredPropsOption = objectWithNoDeclaredProps; + ObjectWithNoDeclaredPropsNullableOption = objectWithNoDeclaredPropsNullable; + PasswordOption = password; + PhoneOption = phone; + UserStatusOption = userStatus; + UsernameOption = username; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of AnyTypeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [JsonPropertyName("anyTypeProp")] + public Object? AnyTypeProp { get { return this. AnyTypePropOption; } set { this.AnyTypePropOption = new(value); } } + + /// + /// Used to track the state of AnyTypePropNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropNullableOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [JsonPropertyName("anyTypePropNullable")] + public Object? AnyTypePropNullable { get { return this. AnyTypePropNullableOption; } set { this.AnyTypePropNullableOption = new(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + /// /// Gets or Sets Email /// [JsonPropertyName("email")] - public string Email { get; set; } + public string? Email { get { return this. EmailOption; } set { this.EmailOption = new(value); } } + + /// + /// Used to track the state of FirstName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstNameOption { get; private set; } /// /// Gets or Sets FirstName /// [JsonPropertyName("firstName")] - public string FirstName { get; set; } + public string? FirstName { get { return this. FirstNameOption; } set { this.FirstNameOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of LastName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LastNameOption { get; private set; } /// /// Gets or Sets LastName /// [JsonPropertyName("lastName")] - public string LastName { get; set; } + public string? LastName { get { return this. LastNameOption; } set { this.LastNameOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredProps + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsOption { get; private set; } /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. [JsonPropertyName("objectWithNoDeclaredProps")] - public Object ObjectWithNoDeclaredProps { get; set; } + public Object? ObjectWithNoDeclaredProps { get { return this. ObjectWithNoDeclaredPropsOption; } set { this.ObjectWithNoDeclaredPropsOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredPropsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsNullableOption { get; private set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonPropertyName("objectWithNoDeclaredPropsNullable")] + public Object? ObjectWithNoDeclaredPropsNullable { get { return this. ObjectWithNoDeclaredPropsNullableOption; } set { this.ObjectWithNoDeclaredPropsNullableOption = new(value); } } + + /// + /// Used to track the state of Password + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PasswordOption { get; private set; } /// /// Gets or Sets Password /// [JsonPropertyName("password")] - public string Password { get; set; } + public string? Password { get { return this. PasswordOption; } set { this.PasswordOption = new(value); } } /// - /// Gets or Sets Phone + /// Used to track the state of Phone /// - [JsonPropertyName("phone")] - public string Phone { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PhoneOption { get; private set; } /// - /// User Status + /// Gets or Sets Phone /// - /// User Status - [JsonPropertyName("userStatus")] - public int UserStatus { get; set; } + [JsonPropertyName("phone")] + public string? Phone { get { return this. PhoneOption; } set { this.PhoneOption = new(value); } } /// - /// Gets or Sets Username + /// Used to track the state of UserStatus /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UserStatusOption { get; private set; } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// User Status /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - [JsonPropertyName("anyTypeProp")] - public Object? AnyTypeProp { get; set; } + /// User Status + [JsonPropertyName("userStatus")] + public int? UserStatus { get { return this. UserStatusOption; } set { this.UserStatusOption = new(value); } } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// Used to track the state of Username /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - [JsonPropertyName("anyTypePropNullable")] - public Object? AnyTypePropNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UsernameOption { get; private set; } /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// Gets or Sets Username /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. - [JsonPropertyName("objectWithNoDeclaredPropsNullable")] - public Object? ObjectWithNoDeclaredPropsNullable { get; set; } + [JsonPropertyName("username")] + public string? Username { get { return this. UsernameOption; } set { this.UsernameOption = new(value); } } /// /// Gets or Sets additional properties @@ -156,18 +241,18 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); - sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -206,18 +291,18 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? email = default; - string? firstName = default; - long? id = default; - string? lastName = default; - Object? objectWithNoDeclaredProps = default; - string? password = default; - string? phone = default; - int? userStatus = default; - string? username = default; - Object? anyTypeProp = default; - Object? anyTypePropNullable = default; - Object? objectWithNoDeclaredPropsNullable = default; + Option anyTypeProp = default; + Option anyTypePropNullable = default; + Option email = default; + Option firstName = default; + Option id = default; + Option lastName = default; + Option objectWithNoDeclaredProps = default; + Option objectWithNoDeclaredPropsNullable = default; + Option password = default; + Option phone = default; + Option userStatus = default; + Option username = default; while (utf8JsonReader.Read()) { @@ -234,47 +319,47 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { + case "anyTypeProp": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "anyTypePropNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypePropNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "email": - email = utf8JsonReader.GetString(); + email = new Option(utf8JsonReader.GetString()!); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()!); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()!); break; case "objectWithNoDeclaredProps": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + objectWithNoDeclaredProps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)!); + break; + case "objectWithNoDeclaredPropsNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredPropsNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "password": - password = utf8JsonReader.GetString(); + password = new Option(utf8JsonReader.GetString()!); break; case "phone": - phone = utf8JsonReader.GetString(); + phone = new Option(utf8JsonReader.GetString()!); break; case "userStatus": if (utf8JsonReader.TokenType != JsonTokenType.Null) - userStatus = utf8JsonReader.GetInt32(); + userStatus = new Option(utf8JsonReader.GetInt32()); break; case "username": - username = utf8JsonReader.GetString(); - break; - case "anyTypeProp": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anyTypePropNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypePropNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "objectWithNoDeclaredPropsNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + username = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -282,34 +367,34 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (email == null) - throw new ArgumentNullException(nameof(email), "Property is required for class User."); + if (email.IsSet && email.Value == null) + throw new ArgumentNullException(nameof(email), "Property is not nullable for class User."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class User."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class User."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class User."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class User."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class User."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class User."); - if (objectWithNoDeclaredProps == null) - throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is required for class User."); + if (objectWithNoDeclaredProps.IsSet && objectWithNoDeclaredProps.Value == null) + throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is not nullable for class User."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class User."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class User."); - if (phone == null) - throw new ArgumentNullException(nameof(phone), "Property is required for class User."); + if (phone.IsSet && phone.Value == null) + throw new ArgumentNullException(nameof(phone), "Property is not nullable for class User."); - if (userStatus == null) - throw new ArgumentNullException(nameof(userStatus), "Property is required for class User."); + if (userStatus.IsSet && userStatus.Value == null) + throw new ArgumentNullException(nameof(userStatus), "Property is not nullable for class User."); - if (username == null) - throw new ArgumentNullException(nameof(username), "Property is required for class User."); + if (username.IsSet && username.Value == null) + throw new ArgumentNullException(nameof(username), "Property is not nullable for class User."); - return new User(email, firstName, id.Value, lastName, objectWithNoDeclaredProps, password, phone, userStatus.Value, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + return new User(anyTypeProp, anyTypePropNullable, email, firstName, id, lastName, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, password, phone, userStatus, username); } /// @@ -336,22 +421,79 @@ public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("email", user.Email); - writer.WriteString("firstName", user.FirstName); - writer.WriteNumber("id", user.Id); - writer.WriteString("lastName", user.LastName); - writer.WritePropertyName("objectWithNoDeclaredProps"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); - writer.WriteString("password", user.Password); - writer.WriteString("phone", user.Phone); - writer.WriteNumber("userStatus", user.UserStatus); - writer.WriteString("username", user.Username); - writer.WritePropertyName("anyTypeProp"); - JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); - writer.WritePropertyName("anyTypePropNullable"); - JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); - writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + if (user.EmailOption.IsSet && user.Email == null) + throw new ArgumentNullException(nameof(user.Email), "Property is required for class User."); + + if (user.FirstNameOption.IsSet && user.FirstName == null) + throw new ArgumentNullException(nameof(user.FirstName), "Property is required for class User."); + + if (user.LastNameOption.IsSet && user.LastName == null) + throw new ArgumentNullException(nameof(user.LastName), "Property is required for class User."); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet && user.ObjectWithNoDeclaredProps == null) + throw new ArgumentNullException(nameof(user.ObjectWithNoDeclaredProps), "Property is required for class User."); + + if (user.PasswordOption.IsSet && user.Password == null) + throw new ArgumentNullException(nameof(user.Password), "Property is required for class User."); + + if (user.PhoneOption.IsSet && user.Phone == null) + throw new ArgumentNullException(nameof(user.Phone), "Property is required for class User."); + + if (user.UsernameOption.IsSet && user.Username == null) + throw new ArgumentNullException(nameof(user.Username), "Property is required for class User."); + + if (user.AnyTypePropOption.IsSet) + if (user.AnyTypePropOption.Value != null) + { + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypeProp"); + if (user.AnyTypePropNullableOption.IsSet) + if (user.AnyTypePropNullableOption.Value != null) + { + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypePropNullable"); + if (user.EmailOption.IsSet) + writer.WriteString("email", user.Email); + + if (user.FirstNameOption.IsSet) + writer.WriteString("firstName", user.FirstName); + + if (user.IdOption.IsSet) + writer.WriteNumber("id", user.IdOption.Value!.Value); + + if (user.LastNameOption.IsSet) + writer.WriteString("lastName", user.LastName); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet) + { + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); + } + if (user.ObjectWithNoDeclaredPropsNullableOption.IsSet) + if (user.ObjectWithNoDeclaredPropsNullableOption.Value != null) + { + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + } + else + writer.WriteNull("objectWithNoDeclaredPropsNullable"); + if (user.PasswordOption.IsSet) + writer.WriteString("password", user.Password); + + if (user.PhoneOption.IsSet) + writer.WriteString("phone", user.Phone); + + if (user.UserStatusOption.IsSet) + writer.WriteNumber("userStatus", user.UserStatusOption.Value!.Value); + + if (user.UsernameOption.IsSet) + writer.WriteString("username", user.Username); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs index 59099f90e2de..00aeea839e66 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Whale.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,11 +38,11 @@ public partial class Whale : IValidatableObject /// hasBaleen /// hasTeeth [JsonConstructor] - public Whale(string className, bool hasBaleen, bool hasTeeth) + public Whale(string className, Option hasBaleen = default, Option hasTeeth = default) { ClassName = className; - HasBaleen = hasBaleen; - HasTeeth = hasTeeth; + HasBaleenOption = hasBaleen; + HasTeethOption = hasTeeth; OnCreated(); } @@ -53,17 +54,31 @@ public Whale(string className, bool hasBaleen, bool hasTeeth) [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of HasBaleen + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasBaleenOption { get; private set; } + /// /// Gets or Sets HasBaleen /// [JsonPropertyName("hasBaleen")] - public bool HasBaleen { get; set; } + public bool? HasBaleen { get { return this. HasBaleenOption; } set { this.HasBaleenOption = new(value); } } + + /// + /// Used to track the state of HasTeeth + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasTeethOption { get; private set; } /// /// Gets or Sets HasTeeth /// [JsonPropertyName("hasTeeth")] - public bool HasTeeth { get; set; } + public bool? HasTeeth { get { return this. HasTeethOption; } set { this.HasTeethOption = new(value); } } /// /// Gets or Sets additional properties @@ -120,9 +135,9 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - bool? hasBaleen = default; - bool? hasTeeth = default; + Option className = default; + Option hasBaleen = default; + Option hasTeeth = default; while (utf8JsonReader.Read()) { @@ -140,15 +155,15 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "hasBaleen": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasBaleen = utf8JsonReader.GetBoolean(); + hasBaleen = new Option(utf8JsonReader.GetBoolean()); break; case "hasTeeth": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasTeeth = utf8JsonReader.GetBoolean(); + hasTeeth = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -156,16 +171,19 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Whale."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Whale.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Whale."); - if (hasBaleen == null) - throw new ArgumentNullException(nameof(hasBaleen), "Property is required for class Whale."); + if (hasBaleen.IsSet && hasBaleen.Value == null) + throw new ArgumentNullException(nameof(hasBaleen), "Property is not nullable for class Whale."); - if (hasTeeth == null) - throw new ArgumentNullException(nameof(hasTeeth), "Property is required for class Whale."); + if (hasTeeth.IsSet && hasTeeth.Value == null) + throw new ArgumentNullException(nameof(hasTeeth), "Property is not nullable for class Whale."); - return new Whale(className, hasBaleen.Value, hasTeeth.Value); + return new Whale(className.Value!, hasBaleen, hasTeeth); } /// @@ -192,9 +210,16 @@ public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) { + if (whale.ClassName == null) + throw new ArgumentNullException(nameof(whale.ClassName), "Property is required for class Whale."); + writer.WriteString("className", whale.ClassName); - writer.WriteBoolean("hasBaleen", whale.HasBaleen); - writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + if (whale.HasBaleenOption.IsSet) + writer.WriteBoolean("hasBaleen", whale.HasBaleenOption.Value!.Value); + + if (whale.HasTeethOption.IsSet) + writer.WriteBoolean("hasTeeth", whale.HasTeethOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs index 16af2edc89db..92726ea411e5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/Zebra.cs @@ -22,13 +22,14 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Zebra /// - public partial class Zebra : Dictionary, IValidatableObject + public partial class Zebra : IValidatableObject { /// /// Initializes a new instance of the class. @@ -36,10 +37,10 @@ public partial class Zebra : Dictionary, IValidatableObject /// className /// type [JsonConstructor] - public Zebra(string className, TypeEnum type) : base() + public Zebra(string className, Option type = default) { ClassName = className; - Type = type; + TypeOption = type; OnCreated(); } @@ -111,7 +112,7 @@ public static TypeEnum TypeEnumFromString(string value) /// /// /// - public static string TypeEnumToJsonValue(TypeEnum value) + public static string TypeEnumToJsonValue(TypeEnum? value) { if (value == TypeEnum.Plains) return "plains"; @@ -125,11 +126,18 @@ public static string TypeEnumToJsonValue(TypeEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } + /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public TypeEnum Type { get; set; } + public TypeEnum? Type { get { return this.TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets ClassName @@ -151,7 +159,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -165,16 +172,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -202,8 +199,8 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? className = default; - Zebra.TypeEnum? type = default; + Option className = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -221,13 +218,12 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()!); break; case "type": string? typeRawValue = utf8JsonReader.GetString(); - type = typeRawValue == null - ? null - : Zebra.TypeEnumFromStringOrDefault(typeRawValue); + if (typeRawValue != null) + type = new Option(Zebra.TypeEnumFromStringOrDefault(typeRawValue)); break; default: break; @@ -235,13 +231,16 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Zebra."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Zebra.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Zebra."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Zebra."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Zebra."); - return new Zebra(className, type.Value); + return new Zebra(className.Value!, type); } /// @@ -268,13 +267,13 @@ public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) { + if (zebra.ClassName == null) + throw new ArgumentNullException(nameof(zebra.ClassName), "Property is required for class Zebra."); + writer.WriteString("className", zebra.ClassName); - var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); - if (typeRawValue != null) - writer.WriteString("type", typeRawValue); - else - writer.WriteNull("type"); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.TypeOption.Value!.Value); + writer.WriteString("type", typeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs index 60223b9ff74f..1db14d35a9e5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs index b83809de7fb2..3c4832e9a360 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,9 +36,9 @@ public partial class ZeroBasedEnumClass : IValidatableObject /// /// zeroBasedEnum [JsonConstructor] - public ZeroBasedEnumClass(ZeroBasedEnumEnum zeroBasedEnum) + public ZeroBasedEnumClass(Option zeroBasedEnum = default) { - ZeroBasedEnum = zeroBasedEnum; + ZeroBasedEnumOption = zeroBasedEnum; OnCreated(); } @@ -98,7 +99,7 @@ public static ZeroBasedEnumEnum ZeroBasedEnumEnumFromString(string value) /// /// /// - public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) + public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum? value) { if (value == ZeroBasedEnumEnum.Unknown) return "unknown"; @@ -109,11 +110,18 @@ public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of ZeroBasedEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ZeroBasedEnumOption { get; private set; } + /// /// Gets or Sets ZeroBasedEnum /// [JsonPropertyName("ZeroBasedEnum")] - public ZeroBasedEnumEnum ZeroBasedEnum { get; set; } + public ZeroBasedEnumEnum? ZeroBasedEnum { get { return this.ZeroBasedEnumOption; } set { this.ZeroBasedEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -168,7 +176,7 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - ZeroBasedEnumClass.ZeroBasedEnumEnum? zeroBasedEnum = default; + Option zeroBasedEnum = default; while (utf8JsonReader.Read()) { @@ -187,9 +195,8 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "ZeroBasedEnum": string? zeroBasedEnumRawValue = utf8JsonReader.GetString(); - zeroBasedEnum = zeroBasedEnumRawValue == null - ? null - : ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue); + if (zeroBasedEnumRawValue != null) + zeroBasedEnum = new Option(ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue)); break; default: break; @@ -197,10 +204,10 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (zeroBasedEnum == null) - throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is required for class ZeroBasedEnumClass."); + if (zeroBasedEnum.IsSet && zeroBasedEnum.Value == null) + throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is not nullable for class ZeroBasedEnumClass."); - return new ZeroBasedEnumClass(zeroBasedEnum.Value); + return new ZeroBasedEnumClass(zeroBasedEnum); } /// @@ -227,12 +234,8 @@ public override void Write(Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEn /// public void WriteProperties(ref Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) { - - var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnum); - if (zeroBasedEnumRawValue != null) - writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); - else - writer.WriteNull("ZeroBasedEnum"); + var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnumOption.Value!.Value); + writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2b6b21494db0..f32136bde7fb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 Org.OpenAPITools Org.OpenAPITools Library @@ -21,10 +21,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md index 704bd29f834f..a7035fda5db8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0-nrt/src/Org.OpenAPITools/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=true', 'hideGenerationTimestamp=true', @@ -69,42 +69,7 @@ namespace YourProject .ConfigureApi((context, options) => { // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); options.AddTokens(token); // optionally choose the method the tokens will be provided with, default is RateLimitProvider @@ -249,7 +214,7 @@ Authentication schemes defined for the API: - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES index 1179de6767be..0c900b9c260e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/FILES @@ -79,6 +79,7 @@ docs/models/PolymorphicProperty.md docs/models/Quadrilateral.md docs/models/QuadrilateralInterface.md docs/models/ReadOnlyFirst.md +docs/models/RequiredClass.md docs/models/Return.md docs/models/RolesReportsHash.md docs/models/RolesReportsHashRole.md @@ -121,6 +122,8 @@ src/Org.OpenAPITools/Client/BasicToken.cs src/Org.OpenAPITools/Client/BearerToken.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/ExceptionEventArgs.cs @@ -206,6 +209,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md index 76873f715c8e..a89b1cda5acd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) @@ -810,7 +896,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateTime date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) +> void TestEndpointParameters (byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, DateOnly date = null, System.IO.Stream binary = null, float varFloat = null, int integer = null, int int32 = null, long int64 = null, string varString = null, string password = null, string callback = null, DateTime dateTime = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -841,7 +927,7 @@ namespace Example var number = 8.14D; // decimal | None var varDouble = 1.2D; // double | None var patternWithoutDelimiter = "patternWithoutDelimiter_example"; // string | None - var date = DateTime.Parse("2013-10-20"); // DateTime | None (optional) + var date = DateOnly.Parse("2013-10-20"); // DateOnly | None (optional) var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream | None (optional) var varFloat = 3.4F; // float | None (optional) var integer = 56; // int | None (optional) @@ -893,7 +979,7 @@ catch (ApiException e) | **number** | **decimal** | None | | | **varDouble** | **double** | None | | | **patternWithoutDelimiter** | **string** | None | | -| **date** | **DateTime** | None | [optional] | +| **date** | **DateOnly** | None | [optional] | | **binary** | **System.IO.Stream****System.IO.Stream** | None | [optional] | | **varFloat** | **float** | None | [optional] | | **integer** | **int** | None | [optional] | diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md index 44c9eeac76b9..407fb30dccb4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md index 56c1acb79285..ee189c866ec5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/apis/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md index f79869f95a71..2bbe882fcfcc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/AdditionalPropertiesClass.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Anytype1** | **Object** | | [optional] **EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] **MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] **MapProperty** | **Dictionary<string, string>** | | [optional] @@ -11,7 +12,6 @@ Name | Type | Description | Notes **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] **MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] -**Anytype1** | **Object** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/ChildCat.md index b8f7d81fbbee..88fe8f7a7fdd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/DateOnlyClass.md index 5dd63b313ccf..4fc3775ed87d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/DateOnlyClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/DateOnlyClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**DateOnlyProperty** | **DateTime** | | [optional] +**DateOnlyProperty** | **DateOnly** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md index 215793515f64..95f49b2ed600 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Drawing.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] -**Shapes** | [**List<Shape>**](Shape.md) | | [optional] **NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md index 53bbfe31e77c..ebd7ccf2c864 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**EnumStringRequired** | **string** | | **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] **EnumString** | **string** | | [optional] -**EnumStringRequired** | **string** | | +**OuterEnum** | **OuterEnum** | | [optional] **OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] **OuterEnumInteger** | **OuterEnumInteger** | | [optional] **OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md index 28f1a8093581..849cd26c0b6f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/FormatTest.md @@ -4,9 +4,11 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Binary** | **System.IO.Stream** | | [optional] **VarByte** | **byte[]** | | -**Date** | **DateTime** | | +**Date** | **DateOnly** | | +**Number** | **decimal** | | +**Password** | **string** | | +**Binary** | **System.IO.Stream** | | [optional] **DateTime** | **DateTime** | | [optional] **VarDecimal** | **decimal** | | [optional] **VarDouble** | **double** | | [optional] @@ -14,8 +16,6 @@ Name | Type | Description | Notes **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] **Integer** | **int** | | [optional] -**Number** | **decimal** | | -**Password** | **string** | | **PatternWithBackslash** | **string** | None | [optional] **PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] **PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md index 394feef77dbb..c9afe86510da 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/NullableClass.md @@ -4,16 +4,16 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool** | | [optional] -**DateProp** | **DateTime** | | [optional] +**DateProp** | **DateOnly** | | [optional] **DatetimeProp** | **DateTime** | | [optional] **IntegerProp** | **int** | | [optional] **NumberProp** | **decimal** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] **StringProp** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Order.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Order.md index ca5d8992a513..f7d6827ed5c9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Order.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Order.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Complete** | **bool** | | [optional] [default to false] **Id** | **long** | | [optional] **PetId** | **long** | | [optional] **Quantity** | **int** | | [optional] **ShipDate** | **DateTime** | | [optional] **Status** | **string** | Order Status | [optional] -**Complete** | **bool** | | [optional] [default to false] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Pet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Pet.md index b13bb576b450..4f019b613bd7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Pet.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Category** | [**Category**](Category.md) | | [optional] -**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Status** | **string** | pet status in the store | [optional] **Tags** | [**List<Tag>**](Tag.md) | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/RequiredClass.md new file mode 100644 index 000000000000..bbdf6d8407b1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNotNullableDateProp** | **DateOnly** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNotnullableEnumInteger** | **int** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**RequiredNotnullableEnumString** | **string** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableStringProp** | **string** | | +**RequiredNotnullableUuid** | **Guid** | | +**RequiredNotnullableintegerProp** | **int** | | +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNullableBooleanProp** | **bool** | | +**RequiredNullableDateProp** | **DateOnly** | | +**RequiredNullableDatetimeProp** | **DateTime** | | +**RequiredNullableEnumInteger** | **int** | | +**RequiredNullableEnumIntegerOnly** | **int** | | +**RequiredNullableEnumString** | **string** | | +**RequiredNullableIntegerProp** | **int** | | +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNullableStringProp** | **string** | | +**RequiredNullableUuid** | **Guid** | | +**NotRequiredNotnullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**NotRequiredNullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNullableIntegerProp** | **int** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNullableBooleanProp** | **bool** | | [optional] +**NotrequiredNullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNullableEnumInteger** | **int** | | [optional] +**NotrequiredNullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNullableUuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/User.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/User.md index 455f031674d5..b5700f1c75d9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/User.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] **Email** | **string** | | [optional] **FirstName** | **string** | | [optional] **Id** | **long** | | [optional] **LastName** | **string** | | [optional] **ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] **Password** | **string** | | [optional] **Phone** | **string** | | [optional] **UserStatus** | **int** | User Status | [optional] **Username** | **string** | | [optional] -**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index 09680ae4cedd..03ad026fa146 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -52,26 +52,30 @@ public ApiTestsBase(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureApi((context, services, options) => { - string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - ApiKeyToken apiKeyToken = new(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); + string apiKeyTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken1 = new(apiKeyTokenValue1, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); - string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - BearerToken bearerToken = new(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); + string apiKeyTokenValue2 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken2 = new(apiKeyTokenValue2, ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); - string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); - string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); - BasicToken basicToken = new(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); + string bearerTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken1 = new(bearerTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); - HttpSigningConfiguration config = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); + string basicTokenUsername1 = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword1 = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken1 = new(basicTokenUsername1, basicTokenPassword1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); - string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - OAuthToken oauthToken = new(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + HttpSigningConfiguration config1 = new("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + string oauthTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken1 = new(oauthTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 5ad1cd420f95..028d71f43359 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,93 +24,105 @@ namespace Org.OpenAPITools.Test.Api ///
              public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken = new("token", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(oauthToken); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new("", "", null, [], HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) @@ -124,22 +136,22 @@ public void ConfigureApiWithAClientTest() { var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -152,22 +164,22 @@ public void ConfigureApiWithoutAClientTest() { var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -208,22 +220,22 @@ public void AddApiWithoutAClientTest() { var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index 6c82be59af88..f5c8415481d2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -164,7 +164,7 @@ public async Task TestEndpointParametersAsyncTest() decimal number = default; double varDouble = default; string patternWithoutDelimiter = default; - Client.Option date = default; + Client.Option date = default; Client.Option binary = default; Client.Option varFloat = default; Client.Option integer = default; @@ -219,6 +219,16 @@ public async Task TestInlineAdditionalPropertiesAsyncTest() await _instance.TestInlineAdditionalPropertiesAsync(requestBody); } + /// + /// Test TestInlineFreeformAdditionalProperties + /// + [Fact (Skip = "not implemented")] + public async Task TestInlineFreeformAdditionalPropertiesAsyncTest() + { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = default; + await _instance.TestInlineFreeformAdditionalPropertiesAsync(testInlineFreeformAdditionalPropertiesRequest); + } + /// /// Test TestJsonFormData /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index b6bff036a466..e157b477193e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -53,6 +53,15 @@ public void AdditionalPropertiesClassInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// /// Test the property 'EmptyMap' /// @@ -115,14 +124,5 @@ public void MapWithUndeclaredPropertiesStringTest() { // TODO unit test for the property 'MapWithUndeclaredPropertiesString' } - - /// - /// Test the property 'Anytype1' - /// - [Fact] - public void Anytype1Test() - { - // TODO unit test for the property 'Anytype1' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0ed2f54aab54..a2de4a1b97b1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -62,15 +62,6 @@ public void MainShapeTest() // TODO unit test for the property 'MainShape' } - /// - /// Test the property 'Shapes' - /// - [Fact] - public void ShapesTest() - { - // TODO unit test for the property 'Shapes' - } - /// /// Test the property 'NullableShape' /// @@ -88,5 +79,14 @@ public void ShapeOrNullTest() { // TODO unit test for the property 'ShapeOrNull' } + + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e5a97f428662..3781eebbfcf2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -53,6 +53,15 @@ public void EnumTestInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// /// Test the property 'EnumInteger' /// @@ -90,12 +99,12 @@ public void EnumStringTest() } /// - /// Test the property 'EnumStringRequired' + /// Test the property 'OuterEnum' /// [Fact] - public void EnumStringRequiredTest() + public void OuterEnumTest() { - // TODO unit test for the property 'EnumStringRequired' + // TODO unit test for the property 'OuterEnum' } /// @@ -124,14 +133,5 @@ public void OuterEnumIntegerDefaultValueTest() { // TODO unit test for the property 'OuterEnumIntegerDefaultValue' } - - /// - /// Test the property 'OuterEnum' - /// - [Fact] - public void OuterEnumTest() - { - // TODO unit test for the property 'OuterEnum' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index fbffe502af78..164baa8862be 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -53,15 +53,6 @@ public void FormatTestInstanceTest() //Assert.IsType(instance); } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// /// Test the property 'VarByte' /// @@ -80,6 +71,33 @@ public void DateTest() // TODO unit test for the property 'Date' } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// /// Test the property 'DateTime' /// @@ -143,24 +161,6 @@ public void IntegerTest() // TODO unit test for the property 'Integer' } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// /// Test the property 'PatternWithBackslash' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 47901aeb2f4c..1e19aa6b8231 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -54,30 +54,21 @@ public void NullableClassInstanceTest() } /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - - /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ArrayAndItemsNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ArrayAndItemsNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // TODO unit test for the property 'ArrayAndItemsNullableProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// @@ -143,6 +134,15 @@ public void ObjectAndItemsNullablePropTest() // TODO unit test for the property 'ObjectAndItemsNullableProp' } + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + /// /// Test the property 'ObjectNullableProp' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs index afab7d23a20e..e7187bbdc92c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -53,6 +53,15 @@ public void OrderInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + /// /// Test the property 'Id' /// @@ -97,14 +106,5 @@ public void StatusTest() { // TODO unit test for the property 'Status' } - - /// - /// Test the property 'Complete' - /// - [Fact] - public void CompleteTest() - { - // TODO unit test for the property 'Complete' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs index fff8db45faad..8485d1213ce6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -54,39 +54,39 @@ public void PetInstanceTest() } /// - /// Test the property 'Category' + /// Test the property 'Name' /// [Fact] - public void CategoryTest() + public void NameTest() { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Name' } /// - /// Test the property 'Id' + /// Test the property 'PhotoUrls' /// [Fact] - public void IdTest() + public void PhotoUrlsTest() { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Name' + /// Test the property 'Category' /// [Fact] - public void NameTest() + public void CategoryTest() { - // TODO unit test for the property 'Name' + // TODO unit test for the property 'Category' } /// - /// Test the property 'PhotoUrls' + /// Test the property 'Id' /// [Fact] - public void PhotoUrlsTest() + public void IdTest() { - // TODO unit test for the property 'PhotoUrls' + // TODO unit test for the property 'Id' } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..e51863915927 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,452 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs index cc4d133818ac..6415f8561f1f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -53,6 +53,24 @@ public void UserInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + /// /// Test the property 'Email' /// @@ -98,6 +116,15 @@ public void ObjectWithNoDeclaredPropsTest() // TODO unit test for the property 'ObjectWithNoDeclaredProps' } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// /// Test the property 'Password' /// @@ -133,32 +160,5 @@ public void UsernameTest() { // TODO unit test for the property 'Username' } - - /// - /// Test the property 'AnyTypeProp' - /// - [Fact] - public void AnyTypePropTest() - { - // TODO unit test for the property 'AnyTypeProp' - } - - /// - /// Test the property 'AnyTypePropNullable' - /// - [Fact] - public void AnyTypePropNullableTest() - { - // TODO unit test for the property 'AnyTypePropNullable' - } - - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index efc4c2554a4b..6335b173b1af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,14 +3,14 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net8.0 false - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs index 054d56da3cd0..c1c25a3577ec 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -169,6 +169,29 @@ public interface IFakeApi : IApi /// <> Task GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + /// /// /// @@ -263,7 +286,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -287,7 +310,7 @@ public interface IFakeApi : IApi /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); + Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default); /// /// To test enum parameters @@ -542,6 +565,18 @@ public interface IGetArrayOfEnumsApiResponse : Org.OpenAPITools.Client.IApiRespo bool IsOk { get; } } + /// + /// The + /// + public interface ITestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.IApiResponse + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + /// /// The /// @@ -799,6 +834,26 @@ internal void ExecuteOnErrorGetArrayOfEnums(Exception exception) OnErrorGetArrayOfEnums?.Invoke(this, new ExceptionEventArgs(exception)); } + /// + /// The event raised after the server response + /// + public event EventHandler OnTestAdditionalPropertiesReference; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler OnErrorTestAdditionalPropertiesReference; + + internal void ExecuteOnTestAdditionalPropertiesReference(FakeApi.TestAdditionalPropertiesReferenceApiResponse apiResponse) + { + OnTestAdditionalPropertiesReference?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestAdditionalPropertiesReference(Exception exception) + { + OnErrorTestAdditionalPropertiesReference?.Invoke(this, new ExceptionEventArgs(exception)); + } + /// /// The event raised after the server response /// @@ -2373,6 +2428,195 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } + partial void FormatTestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestAdditionalPropertiesReference(Dictionary requestBody) + { + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestAdditionalPropertiesReferenceDefaultImplementation(ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody) + { + bool suppressDefaultLog = false; + AfterTestAdditionalPropertiesReference(ref suppressDefaultLog, apiResponseLocalVar, requestBody); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestAdditionalPropertiesReference(ref bool suppressDefaultLog, ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + bool suppressDefaultLog = false; + OnErrorTestAdditionalPropertiesReference(ref suppressDefaultLog, exception, pathFormat, path, requestBody); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestAdditionalPropertiesReference(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestAdditionalPropertiesReferenceAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestAdditionalPropertiesReference(requestBody); + + FormatTestAdditionalPropertiesReference(requestBody); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/additionalProperties-reference"; + + httpRequestMessageLocalVar.Content = (requestBody as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = HttpMethod.Post; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + + TestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/additionalProperties-reference", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestAdditionalPropertiesReferenceDefaultImplementation(apiResponseLocalVar, requestBody); + + Events.ExecuteOnTestAdditionalPropertiesReference(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(e, "/fake/additionalProperties-reference", uriBuilderLocalVar.Path, requestBody); + Events.ExecuteOnErrorTestAdditionalPropertiesReference(e); + throw; + } + } + + /// + /// The + /// + public partial class TestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.ApiResponse, ITestAdditionalPropertiesReferenceApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public TestAdditionalPropertiesReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + partial void FormatTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); /// @@ -2997,7 +3241,7 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } - partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); + partial void FormatTestEndpointParameters(ref byte[] varByte, ref decimal number, ref double varDouble, ref string patternWithoutDelimiter, ref Option date, ref Option binary, ref Option varFloat, ref Option integer, ref Option int32, ref Option int64, ref Option varString, ref Option password, ref Option callback, ref Option dateTime); /// /// Validates the request parameters @@ -3048,7 +3292,7 @@ private void ValidateTestEndpointParameters(byte[] varByte, string patternWithou /// /// /// - private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; AfterTestEndpointParameters(ref suppressDefaultLog, apiResponseLocalVar, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3075,7 +3319,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void AfterTestEndpointParameters(ref bool suppressDefaultLog, ITestEndpointParametersApiResponse apiResponseLocalVar, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Logs exceptions that occur while retrieving the server response @@ -3097,7 +3341,7 @@ private void AfterTestEndpointParametersDefaultImplementation(ITestEndpointParam /// /// /// - private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) + private void OnErrorTestEndpointParametersDefaultImplementation(Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime) { bool suppressDefaultLog = false; OnErrorTestEndpointParameters(ref suppressDefaultLog, exception, pathFormat, path, varByte, number, varDouble, patternWithoutDelimiter, date, binary, varFloat, integer, int32, int64, varString, password, callback, dateTime); @@ -3126,7 +3370,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// /// /// - partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); + partial void OnErrorTestEndpointParameters(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date, Option binary, Option varFloat, Option integer, Option int32, Option int64, Option varString, Option password, Option callback, Option dateTime); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -3147,7 +3391,7 @@ private void OnErrorTestEndpointParametersDefaultImplementation(Exception except /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersOrDefaultAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { try { @@ -3179,7 +3423,7 @@ public async Task TestEndpointParametersOrDe /// None (optional, default to "2010-02-01T10:20:10.111110+01:00") /// Cancellation Token to cancel the request. /// <> - public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) + public async Task TestEndpointParametersAsync(byte[] varByte, decimal number, double varDouble, string patternWithoutDelimiter, Option date = default, Option binary = default, Option varFloat = default, Option integer = default, Option int32 = default, Option int64 = default, Option varString = default, Option password = default, Option callback = default, Option dateTime = default, System.Threading.CancellationToken cancellationToken = default) { UriBuilder uriBuilderLocalVar = new UriBuilder(); @@ -3243,14 +3487,13 @@ public async Task TestEndpointParametersAsyn formParameterLocalVars.Add(new KeyValuePair("dateTime", ClientUtils.ParameterToString(dateTime.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BasicToken basicTokenLocalVar1 = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(basicTokenLocalVar); + tokenBaseLocalVars.Add(basicTokenLocalVar1); - basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + basicTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -3768,14 +4011,13 @@ public async Task TestGroupParametersAsync(bool httpRequestMessageLocalVar.Headers.Add("boolean_group", ClientUtils.ParameterToString(booleanGroup.Value)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BearerToken bearerTokenLocalVar1 = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(bearerTokenLocalVar); + tokenBaseLocalVars.Add(bearerTokenLocalVar1); - bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + bearerTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index bc3841e55e1b..77506dc3794a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -278,14 +278,12 @@ public async Task TestClassnameAsync(ModelClient mode : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "api_key_query"); + apiKeyTokenLocalVar1.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] contentTypes = new string[] { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs index 5618c593f814..9284aeb1b9cd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -88,7 +88,7 @@ public interface IPetApi : IApi /// Multiple status values can be provided with comma separated strings /// /// Thrown when fails to make API call - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -99,7 +99,7 @@ public interface IPetApi : IApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -114,6 +114,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -125,6 +126,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -766,23 +768,22 @@ public async Task AddPetAsync(Pet pet, System.Threading.Canc : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -984,14 +985,13 @@ public async Task DeletePetAsync(long petId, Option tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = HttpMethod.Delete; @@ -1178,23 +1178,22 @@ public async Task FindPetsByStatusAsync(List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1430,23 +1429,22 @@ public async Task FindPetsByTagsAsync(List t uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1663,14 +1661,19 @@ public async Task GetPetByIdAsync(long petId, System.Thr uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokenBaseLocalVars = new List(); + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + ApiKeyToken apiKeyTokenLocalVar2 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar2); - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + apiKeyTokenLocalVar2.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] acceptLocalVars = new string[] { @@ -1910,23 +1913,22 @@ public async Task UpdatePetAsync(Pet pet, System.Threadin : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -2159,14 +2161,13 @@ public async Task UpdatePetWithFormAsync(long pet formParameterLocalVars.Add(new KeyValuePair("status", ClientUtils.ParameterToString(status.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -2385,14 +2386,13 @@ public async Task UploadFileAsync(long petId, Option("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" @@ -2651,14 +2651,13 @@ public async Task UploadFileWithRequired formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs index 25a31f0a4378..2117e516e1f6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -619,12 +619,9 @@ public async Task GetInventoryAsync(System.Threading.C uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; List tokenBaseLocalVars = new List(); - - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs index d8bba20a4d72..b41d2d18c987 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -10,6 +10,7 @@ using System; using System.Collections.Generic; +using System.Linq; using System.Net; using System.Threading.Tasks; using Microsoft.Extensions.Logging; @@ -277,7 +278,7 @@ public interface IDeleteUserApiResponse : Org.OpenAPITools.Client.IApiResponse /// /// The /// - public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk + public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk, ICustomHttpStatusCode599 { /// /// Returns true if the response is 200 Ok @@ -296,6 +297,18 @@ public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiRespons /// /// bool IsNotFound { get; } + + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + bool IsCustomHttpStatusCode598 { get; } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + bool IsCustomHttpStatusCode599 { get; } } /// @@ -564,6 +577,11 @@ public sealed partial class UserApi : IUserApi /// public TokenProvider OauthTokenProvider { get; } + /// + /// The token cookie container + /// + public Org.OpenAPITools.Client.CookieContainer CookieContainer { get; } + /// /// Initializes a new instance of the class. /// @@ -573,7 +591,8 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient TokenProvider bearerTokenProvider, TokenProvider basicTokenProvider, TokenProvider httpSignatureTokenProvider, - TokenProvider oauthTokenProvider) + TokenProvider oauthTokenProvider, + Org.OpenAPITools.Client.CookieContainer cookieContainer) { _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; LoggerFactory = loggerFactory; @@ -585,6 +604,7 @@ public UserApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient BasicTokenProvider = basicTokenProvider; HttpSignatureTokenProvider = httpSignatureTokenProvider; OauthTokenProvider = oauthTokenProvider; + CookieContainer = cookieContainer; } partial void FormatCreateUser(User user); @@ -1557,6 +1577,50 @@ public bool TryOk([NotNullWhen(true)]out Org.OpenAPITools.Model.User result) /// public bool IsNotFound => 404 == (int)StatusCode; + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + public bool IsCustomHttpStatusCode598 => 598 == (int)StatusCode; + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + public bool IsCustomHttpStatusCode599 => 599 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 599 CustomHttpStatusCode599 + /// + /// + public Org.OpenAPITools.Model.User CustomHttpStatusCode599() + { + // This logic may be modified with the AsModel.mustache template + return IsCustomHttpStatusCode599 + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + public bool TryCustomHttpStatusCode599([NotNullWhen(true)]out Org.OpenAPITools.Model.User result) + { + result = null; + + try + { + result = CustomHttpStatusCode599(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)599); + } + + return result != null; + } + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) { bool suppressDefaultLog = false; @@ -1714,6 +1778,33 @@ public async Task LoginUserAsync(string username, string Events.ExecuteOnLoginUser(apiResponseLocalVar); + if (httpResponseMessageLocalVar.StatusCode == (HttpStatusCode) 200 && httpResponseMessageLocalVar.Headers.TryGetValues("Set-Cookie", out var cookieHeadersLocalVar)) + { + foreach(string cookieHeader in cookieHeadersLocalVar) + { + IList setCookieHeaderValuesLocalVar = Microsoft.Net.Http.Headers.SetCookieHeaderValue.ParseList(cookieHeadersLocalVar.ToArray()); + + foreach(Microsoft.Net.Http.Headers.SetCookieHeaderValue setCookieHeaderValueLocalVar in setCookieHeaderValuesLocalVar) + { + Cookie cookieLocalVar = new Cookie(setCookieHeaderValueLocalVar.Name.ToString(), setCookieHeaderValueLocalVar.Value.ToString()) + { + HttpOnly = setCookieHeaderValueLocalVar.HttpOnly + }; + + if (setCookieHeaderValueLocalVar.Expires.HasValue) + cookieLocalVar.Expires = setCookieHeaderValueLocalVar.Expires.Value.UtcDateTime; + + if (setCookieHeaderValueLocalVar.Path.HasValue) + cookieLocalVar.Path = setCookieHeaderValueLocalVar.Path.Value; + + if (setCookieHeaderValueLocalVar.Domain.HasValue) + cookieLocalVar.Domain = setCookieHeaderValueLocalVar.Domain.Value; + + CookieContainer.Value.Add(new Uri($"{uriBuilderLocalVar.Scheme}://{uriBuilderLocalVar.Host}"), cookieLocalVar); + } + } + } + return apiResponseLocalVar; } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs index 5cc9c254920a..b8bdf9964ffb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -11,14 +11,21 @@ public class ApiKeyToken : TokenBase { private string _raw; + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + /// /// Constructs an ApiKeyToken object. /// /// + /// /// /// - public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { + Header = header; _raw = $"{ prefix }{ value }"; } @@ -26,22 +33,20 @@ public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = /// Places the token in the header. /// /// - /// - public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) { - request.Headers.Add(headerName, _raw); + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); } - + /// /// Places the token in the query. /// /// /// /// - /// - public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) { - parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString(); + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString(); } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs index 9608a10138cd..5f56de8bcc46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -148,6 +148,26 @@ public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); } + /// + /// An interface for responses of type + /// + /// + public interface ICustomHttpStatusCode599 : IApiResponse + { + /// + /// Deserializes the response if the response is CustomHttpStatusCode599 + /// + /// + TType CustomHttpStatusCode599(); + + /// + /// Returns true if the response is CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + bool TryCustomHttpStatusCode599([NotNullWhen(true)]out TType result); + } + /// /// An interface for responses of type /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs index ee025fa27f60..a3bedb429297 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -38,7 +38,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// @@ -50,6 +52,37 @@ static ClientUtils() /// public delegate void EventHandler(object sender, T e) where T : EventArgs; + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + /// + /// The api_key header + /// + Api_key, + /// + /// The api_key_query header + /// + Api_key_query + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + return value switch + { + ApiKeyHeader.Api_key => "api_key", + ApiKeyHeader.Api_key_query => "api_key_query", + _ => throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)), + }; + } + /// /// Returns true when deserialization succeeds. /// @@ -139,6 +172,8 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return EnumArrays.JustSymbolEnumToJsonValue(enumArraysJustSymbolEnum); if (obj is EnumClass enumClass) return EnumClassValueConverter.ToJsonValue(enumClass); + if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) + return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is EnumTest.EnumIntegerEnum enumTestEnumIntegerEnum) return EnumTest.EnumIntegerEnumToJsonValue(enumTestEnumIntegerEnum).ToString(); if (obj is EnumTest.EnumIntegerOnlyEnum enumTestEnumIntegerOnlyEnum) @@ -147,8 +182,6 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return EnumTest.EnumNumberEnumToJsonValue(enumTestEnumNumberEnum).ToString(); if (obj is EnumTest.EnumStringEnum enumTestEnumStringEnum) return EnumTest.EnumStringEnumToJsonValue(enumTestEnumStringEnum); - if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) - return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is MapTest.InnerEnum mapTestInnerEnum) return MapTest.InnerEnumToJsonValue(mapTestInnerEnum); if (obj is Order.StatusEnum orderStatusEnum) @@ -165,6 +198,30 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return OuterEnumTestValueConverter.ToJsonValue(outerEnumTest); if (obj is Pet.StatusEnum petStatusEnum) return Pet.StatusEnumToJsonValue(petStatusEnum); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerEnum requiredClassRequiredNotnullableEnumIntegerEnum) + return RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum requiredClassRequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumStringEnum requiredClassRequiredNotnullableEnumStringEnum) + return RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClassRequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.RequiredNullableEnumIntegerEnum requiredClassRequiredNullableEnumIntegerEnum) + return RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClassRequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumIntegerOnlyEnum requiredClassRequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumStringEnum requiredClassRequiredNullableEnumStringEnum) + return RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClassRequiredNullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerEnum requiredClassNotrequiredNotnullableEnumIntegerEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumStringEnum requiredClassNotrequiredNotnullableEnumStringEnum) + return RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClassNotrequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerEnum requiredClassNotrequiredNullableEnumIntegerEnum) + return RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum requiredClassNotrequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumStringEnum requiredClassNotrequiredNullableEnumStringEnum) + return RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClassNotrequiredNullableEnumStringEnum); if (obj is Zebra.TypeEnum zebraTypeEnum) return Zebra.TypeEnumToJsonValue(zebraTypeEnum); if (obj is ZeroBasedEnum zeroBasedEnum) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..11b100056516 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString(); + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..92ef8f6c92bf --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString(); + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index e8291cb2e1eb..623f3c18353c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index e26c40071cdc..43730a86b868 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs index 5ea9415eba07..063d20ae7ac2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -39,6 +39,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new ActivityJsonConverter()); _jsonOptions.Converters.Add(new ActivityOutputElementRepresentationJsonConverter()); _jsonOptions.Converters.Add(new AdditionalPropertiesClassJsonConverter()); @@ -114,6 +116,7 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new QuadrilateralJsonConverter()); _jsonOptions.Converters.Add(new QuadrilateralInterfaceJsonConverter()); _jsonOptions.Converters.Add(new ReadOnlyFirstJsonConverter()); + _jsonOptions.Converters.Add(new RequiredClassJsonConverter()); _jsonOptions.Converters.Add(new ReturnJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashRoleJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/Option.cs index 70f41078bb68..8cf79a713b74 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/Option.cs @@ -35,5 +35,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index 79a3bd75bfe1..eb894eec8416 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -9,9 +9,11 @@ */ using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -19,7 +21,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -30,17 +32,41 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite - }; + if (container is TokenContainer apiKeyTokenContainer) + { + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); - AvailableTokens = Channel.CreateBounded(options); + foreach (string header in headers) + { + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + AvailableTokens.Add(header, Channel.CreateBounded(options)); + } + } + else + { + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + } + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs index c49f723f8c29..36d7dad03e23 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -25,7 +25,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs index 42747dee35ea..141338516205 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Activity.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Activity : IValidatableObject /// /// activityOutputs [JsonConstructor] - public Activity(Dictionary> activityOutputs) + public Activity(Option>> activityOutputs = default) { - ActivityOutputs = activityOutputs; + ActivityOutputsOption = activityOutputs; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ActivityOutputs + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ActivityOutputsOption { get; private set; } + /// /// Gets or Sets ActivityOutputs /// [JsonPropertyName("activity_outputs")] - public Dictionary> ActivityOutputs { get; set; } + public Dictionary> ActivityOutputs { get { return this. ActivityOutputsOption; } set { this.ActivityOutputsOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary> activityOutputs = default; + Option>> activityOutputs = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "activity_outputs": if (utf8JsonReader.TokenType != JsonTokenType.Null) - activityOutputs = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + activityOutputs = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (activityOutputs == null) - throw new ArgumentNullException(nameof(activityOutputs), "Property is required for class Activity."); + if (activityOutputs.IsSet && activityOutputs.Value == null) + throw new ArgumentNullException(nameof(activityOutputs), "Property is not nullable for class Activity."); return new Activity(activityOutputs); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, Activity activity, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("activity_outputs"); - JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + if (activity.ActivityOutputsOption.IsSet && activity.ActivityOutputs == null) + throw new ArgumentNullException(nameof(activity.ActivityOutputs), "Property is required for class Activity."); + + if (activity.ActivityOutputsOption.IsSet) + { + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index 233d362f51ed..da158a14e414 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class ActivityOutputElementRepresentation : IValidatableObject /// prop1 /// prop2 [JsonConstructor] - public ActivityOutputElementRepresentation(string prop1, Object prop2) + public ActivityOutputElementRepresentation(Option prop1 = default, Option prop2 = default) { - Prop1 = prop1; - Prop2 = prop2; + Prop1Option = prop1; + Prop2Option = prop2; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Prop1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop1Option { get; private set; } + /// /// Gets or Sets Prop1 /// [JsonPropertyName("prop1")] - public string Prop1 { get; set; } + public string Prop1 { get { return this. Prop1Option; } set { this.Prop1Option = new(value); } } + + /// + /// Used to track the state of Prop2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop2Option { get; private set; } /// /// Gets or Sets Prop2 /// [JsonPropertyName("prop2")] - public Object Prop2 { get; set; } + public Object Prop2 { get { return this. Prop2Option; } set { this.Prop2Option = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string prop1 = default; - Object prop2 = default; + Option prop1 = default; + Option prop2 = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 switch (localVarJsonPropertyName) { case "prop1": - prop1 = utf8JsonReader.GetString(); + prop1 = new Option(utf8JsonReader.GetString()); break; case "prop2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - prop2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + prop2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -140,11 +155,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 } } - if (prop1 == null) - throw new ArgumentNullException(nameof(prop1), "Property is required for class ActivityOutputElementRepresentation."); + if (prop1.IsSet && prop1.Value == null) + throw new ArgumentNullException(nameof(prop1), "Property is not nullable for class ActivityOutputElementRepresentation."); - if (prop2 == null) - throw new ArgumentNullException(nameof(prop2), "Property is required for class ActivityOutputElementRepresentation."); + if (prop2.IsSet && prop2.Value == null) + throw new ArgumentNullException(nameof(prop2), "Property is not nullable for class ActivityOutputElementRepresentation."); return new ActivityOutputElementRepresentation(prop1, prop2); } @@ -173,9 +188,20 @@ public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresent /// public void WriteProperties(ref Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); - writer.WritePropertyName("prop2"); - JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + if (activityOutputElementRepresentation.Prop1Option.IsSet && activityOutputElementRepresentation.Prop1 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop1), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop2Option.IsSet && activityOutputElementRepresentation.Prop2 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop2), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop1Option.IsSet) + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + + if (activityOutputElementRepresentation.Prop2Option.IsSet) + { + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index ed15d711b7a7..a3170798f776 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,6 +32,7 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// /// Initializes a new instance of the class. /// + /// anytype1 /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty /// mapProperty @@ -38,71 +40,126 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 /// mapWithUndeclaredPropertiesString - /// anytype1 [JsonConstructor] - public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object anytype1 = default) + public AdditionalPropertiesClass(Option anytype1 = default, Option emptyMap = default, Option>> mapOfMapProperty = default, Option> mapProperty = default, Option mapWithUndeclaredPropertiesAnytype1 = default, Option mapWithUndeclaredPropertiesAnytype2 = default, Option> mapWithUndeclaredPropertiesAnytype3 = default, Option> mapWithUndeclaredPropertiesString = default) { - EmptyMap = emptyMap; - MapOfMapProperty = mapOfMapProperty; - MapProperty = mapProperty; - MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - Anytype1 = anytype1; + Anytype1Option = anytype1; + EmptyMapOption = emptyMap; + MapOfMapPropertyOption = mapOfMapProperty; + MapPropertyOption = mapProperty; + MapWithUndeclaredPropertiesAnytype1Option = mapWithUndeclaredPropertiesAnytype1; + MapWithUndeclaredPropertiesAnytype2Option = mapWithUndeclaredPropertiesAnytype2; + MapWithUndeclaredPropertiesAnytype3Option = mapWithUndeclaredPropertiesAnytype3; + MapWithUndeclaredPropertiesStringOption = mapWithUndeclaredPropertiesString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Anytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Anytype1Option { get; private set; } + + /// + /// Gets or Sets Anytype1 + /// + [JsonPropertyName("anytype_1")] + public Object Anytype1 { get { return this. Anytype1Option; } set { this.Anytype1Option = new(value); } } + + /// + /// Used to track the state of EmptyMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmptyMapOption { get; private set; } + /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. [JsonPropertyName("empty_map")] - public Object EmptyMap { get; set; } + public Object EmptyMap { get { return this. EmptyMapOption; } set { this.EmptyMapOption = new(value); } } + + /// + /// Used to track the state of MapOfMapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> MapOfMapPropertyOption { get; private set; } /// /// Gets or Sets MapOfMapProperty /// [JsonPropertyName("map_of_map_property")] - public Dictionary> MapOfMapProperty { get; set; } + public Dictionary> MapOfMapProperty { get { return this. MapOfMapPropertyOption; } set { this.MapOfMapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapPropertyOption { get; private set; } /// /// Gets or Sets MapProperty /// [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + public Dictionary MapProperty { get { return this. MapPropertyOption; } set { this.MapPropertyOption = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype1Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 /// [JsonPropertyName("map_with_undeclared_properties_anytype_1")] - public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + public Object MapWithUndeclaredPropertiesAnytype1 { get { return this. MapWithUndeclaredPropertiesAnytype1Option; } set { this.MapWithUndeclaredPropertiesAnytype1Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype2Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 /// [JsonPropertyName("map_with_undeclared_properties_anytype_2")] - public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + public Object MapWithUndeclaredPropertiesAnytype2 { get { return this. MapWithUndeclaredPropertiesAnytype2Option; } set { this.MapWithUndeclaredPropertiesAnytype2Option = new(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype3 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapWithUndeclaredPropertiesAnytype3Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 /// [JsonPropertyName("map_with_undeclared_properties_anytype_3")] - public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + public Dictionary MapWithUndeclaredPropertiesAnytype3 { get { return this. MapWithUndeclaredPropertiesAnytype3Option; } set { this.MapWithUndeclaredPropertiesAnytype3Option = new(value); } } /// - /// Gets or Sets MapWithUndeclaredPropertiesString + /// Used to track the state of MapWithUndeclaredPropertiesString /// - [JsonPropertyName("map_with_undeclared_properties_string")] - public Dictionary MapWithUndeclaredPropertiesString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapWithUndeclaredPropertiesStringOption { get; private set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapWithUndeclaredPropertiesString /// - [JsonPropertyName("anytype_1")] - public Object Anytype1 { get; set; } + [JsonPropertyName("map_with_undeclared_properties_string")] + public Dictionary MapWithUndeclaredPropertiesString { get { return this. MapWithUndeclaredPropertiesStringOption; } set { this.MapWithUndeclaredPropertiesStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -118,6 +175,7 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); @@ -125,7 +183,6 @@ public override string ToString() sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -164,14 +221,14 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Object emptyMap = default; - Dictionary> mapOfMapProperty = default; - Dictionary mapProperty = default; - Object mapWithUndeclaredPropertiesAnytype1 = default; - Object mapWithUndeclaredPropertiesAnytype2 = default; - Dictionary mapWithUndeclaredPropertiesAnytype3 = default; - Dictionary mapWithUndeclaredPropertiesString = default; - Object anytype1 = default; + Option anytype1 = default; + Option emptyMap = default; + Option>> mapOfMapProperty = default; + Option> mapProperty = default; + Option mapWithUndeclaredPropertiesAnytype1 = default; + Option mapWithUndeclaredPropertiesAnytype2 = default; + Option> mapWithUndeclaredPropertiesAnytype3 = default; + Option> mapWithUndeclaredPropertiesString = default; while (utf8JsonReader.Read()) { @@ -188,37 +245,37 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader switch (localVarJsonPropertyName) { + case "anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "empty_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - emptyMap = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + emptyMap = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_of_map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfMapProperty = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapOfMapProperty = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapProperty = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapProperty = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_1": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_3": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype3 = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anytype_1": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -226,28 +283,28 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader } } - if (emptyMap == null) - throw new ArgumentNullException(nameof(emptyMap), "Property is required for class AdditionalPropertiesClass."); + if (emptyMap.IsSet && emptyMap.Value == null) + throw new ArgumentNullException(nameof(emptyMap), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapOfMapProperty == null) - throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapOfMapProperty.IsSet && mapOfMapProperty.Value == null) + throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapProperty == null) - throw new ArgumentNullException(nameof(mapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapProperty.IsSet && mapProperty.Value == null) + throw new ArgumentNullException(nameof(mapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype1 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype1.IsSet && mapWithUndeclaredPropertiesAnytype1.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype2 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype2.IsSet && mapWithUndeclaredPropertiesAnytype2.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype3 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype3.IsSet && mapWithUndeclaredPropertiesAnytype3.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesString == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesString.IsSet && mapWithUndeclaredPropertiesString.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is not nullable for class AdditionalPropertiesClass."); - return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + return new AdditionalPropertiesClass(anytype1, emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString); } /// @@ -274,22 +331,70 @@ public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass addi /// public void WriteProperties(ref Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("empty_map"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); - writer.WritePropertyName("map_of_map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_string"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); - writer.WritePropertyName("anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + if (additionalPropertiesClass.EmptyMapOption.IsSet && additionalPropertiesClass.EmptyMap == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.EmptyMap), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet && additionalPropertiesClass.MapOfMapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapPropertyOption.IsSet && additionalPropertiesClass.MapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.Anytype1Option.IsSet) + if (additionalPropertiesClass.Anytype1Option.Value != null) + { + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + } + else + writer.WriteNull("anytype_1"); + if (additionalPropertiesClass.EmptyMapOption.IsSet) + { + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet) + { + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapPropertyOption.IsSet) + { + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs index 460543ebf0df..82333f58eb64 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Animal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class Animal : IValidatableObject /// className /// color (default to "red") [JsonConstructor] - public Animal(string className, string color = @"red") + public Animal(string className, Option color = default) { ClassName = className; - Color = color; + ColorOption = color; OnCreated(); } @@ -49,11 +50,18 @@ public Animal(string className, string color = @"red") [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Gets or Sets additional properties @@ -119,8 +127,8 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - string color = default; + Option className = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -138,10 +146,10 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -149,13 +157,16 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Animal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Animal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Animal."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Animal."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Animal."); - return new Animal(className, color); + return new Animal(className.Value, color); } /// @@ -182,8 +193,16 @@ public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) { + if (animal.ClassName == null) + throw new ArgumentNullException(nameof(animal.ClassName), "Property is required for class Animal."); + + if (animal.ColorOption.IsSet && animal.Color == null) + throw new ArgumentNullException(nameof(animal.Color), "Property is required for class Animal."); + writer.WriteString("className", animal.ClassName); - writer.WriteString("color", animal.Color); + + if (animal.ColorOption.IsSet) + writer.WriteString("color", animal.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs index 5a7be95495cc..eebfe2c75161 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class ApiResponse : IValidatableObject /// message /// type [JsonConstructor] - public ApiResponse(int code, string message, string type) + public ApiResponse(Option code = default, Option message = default, Option type = default) { - Code = code; - Message = message; - Type = type; + CodeOption = code; + MessageOption = message; + TypeOption = type; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Code + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CodeOption { get; private set; } + /// /// Gets or Sets Code /// [JsonPropertyName("code")] - public int Code { get; set; } + public int? Code { get { return this. CodeOption; } set { this.CodeOption = new(value); } } + + /// + /// Used to track the state of Message + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MessageOption { get; private set; } /// /// Gets or Sets Message /// [JsonPropertyName("message")] - public string Message { get; set; } + public string Message { get { return this. MessageOption; } set { this.MessageOption = new(value); } } + + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public string Type { get; set; } + public string Type { get { return this. TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? code = default; - string message = default; - string type = default; + Option code = default; + Option message = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -139,13 +161,13 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC { case "code": if (utf8JsonReader.TokenType != JsonTokenType.Null) - code = utf8JsonReader.GetInt32(); + code = new Option(utf8JsonReader.GetInt32()); break; case "message": - message = utf8JsonReader.GetString(); + message = new Option(utf8JsonReader.GetString()); break; case "type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()); break; default: break; @@ -153,16 +175,16 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (code == null) - throw new ArgumentNullException(nameof(code), "Property is required for class ApiResponse."); + if (code.IsSet && code.Value == null) + throw new ArgumentNullException(nameof(code), "Property is not nullable for class ApiResponse."); - if (message == null) - throw new ArgumentNullException(nameof(message), "Property is required for class ApiResponse."); + if (message.IsSet && message.Value == null) + throw new ArgumentNullException(nameof(message), "Property is not nullable for class ApiResponse."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class ApiResponse."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ApiResponse."); - return new ApiResponse(code.Value, message, type); + return new ApiResponse(code, message, type); } /// @@ -189,9 +211,20 @@ public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("code", apiResponse.Code); - writer.WriteString("message", apiResponse.Message); - writer.WriteString("type", apiResponse.Type); + if (apiResponse.MessageOption.IsSet && apiResponse.Message == null) + throw new ArgumentNullException(nameof(apiResponse.Message), "Property is required for class ApiResponse."); + + if (apiResponse.TypeOption.IsSet && apiResponse.Type == null) + throw new ArgumentNullException(nameof(apiResponse.Type), "Property is required for class ApiResponse."); + + if (apiResponse.CodeOption.IsSet) + writer.WriteNumber("code", apiResponse.CodeOption.Value.Value); + + if (apiResponse.MessageOption.IsSet) + writer.WriteString("message", apiResponse.Message); + + if (apiResponse.TypeOption.IsSet) + writer.WriteString("type", apiResponse.Type); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs index 31246df0422a..a349e6c9d16c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Apple.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class Apple : IValidatableObject /// cultivar /// origin [JsonConstructor] - public Apple(string colorCode, string cultivar, string origin) + public Apple(Option colorCode = default, Option cultivar = default, Option origin = default) { - ColorCode = colorCode; - Cultivar = cultivar; - Origin = origin; + ColorCodeOption = colorCode; + CultivarOption = cultivar; + OriginOption = origin; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ColorCode + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorCodeOption { get; private set; } + /// /// Gets or Sets ColorCode /// [JsonPropertyName("color_code")] - public string ColorCode { get; set; } + public string ColorCode { get { return this. ColorCodeOption; } set { this.ColorCodeOption = new(value); } } + + /// + /// Used to track the state of Cultivar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CultivarOption { get; private set; } /// /// Gets or Sets Cultivar /// [JsonPropertyName("cultivar")] - public string Cultivar { get; set; } + public string Cultivar { get { return this. CultivarOption; } set { this.CultivarOption = new(value); } } + + /// + /// Used to track the state of Origin + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OriginOption { get; private set; } /// /// Gets or Sets Origin /// [JsonPropertyName("origin")] - public string Origin { get; set; } + public string Origin { get { return this. OriginOption; } set { this.OriginOption = new(value); } } /// /// Gets or Sets additional properties @@ -92,28 +114,31 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { - if (this.ColorCode != null) { + if (this.ColorCodeOption.Value != null) { // ColorCode (string) pattern Regex regexColorCode = new Regex(@"^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$", RegexOptions.CultureInvariant); - if (!regexColorCode.Match(this.ColorCode).Success) + + if (this.ColorCodeOption.Value != null &&!regexColorCode.Match(this.ColorCodeOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ColorCode, must match a pattern of " + regexColorCode, new [] { "ColorCode" }); } } - if (this.Cultivar != null) { + if (this.CultivarOption.Value != null) { // Cultivar (string) pattern Regex regexCultivar = new Regex(@"^[a-zA-Z\s]*$", RegexOptions.CultureInvariant); - if (!regexCultivar.Match(this.Cultivar).Success) + + if (this.CultivarOption.Value != null &&!regexCultivar.Match(this.CultivarOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); } } - if (this.Origin != null) { + if (this.OriginOption.Value != null) { // Origin (string) pattern Regex regexOrigin = new Regex(@"^[A-Z\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexOrigin.Match(this.Origin).Success) + + if (this.OriginOption.Value != null &&!regexOrigin.Match(this.OriginOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); } @@ -145,9 +170,9 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string colorCode = default; - string cultivar = default; - string origin = default; + Option colorCode = default; + Option cultivar = default; + Option origin = default; while (utf8JsonReader.Read()) { @@ -165,13 +190,13 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color_code": - colorCode = utf8JsonReader.GetString(); + colorCode = new Option(utf8JsonReader.GetString()); break; case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()); break; case "origin": - origin = utf8JsonReader.GetString(); + origin = new Option(utf8JsonReader.GetString()); break; default: break; @@ -179,14 +204,14 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (colorCode == null) - throw new ArgumentNullException(nameof(colorCode), "Property is required for class Apple."); + if (colorCode.IsSet && colorCode.Value == null) + throw new ArgumentNullException(nameof(colorCode), "Property is not nullable for class Apple."); - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class Apple."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class Apple."); - if (origin == null) - throw new ArgumentNullException(nameof(origin), "Property is required for class Apple."); + if (origin.IsSet && origin.Value == null) + throw new ArgumentNullException(nameof(origin), "Property is not nullable for class Apple."); return new Apple(colorCode, cultivar, origin); } @@ -215,9 +240,23 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color_code", apple.ColorCode); - writer.WriteString("cultivar", apple.Cultivar); - writer.WriteString("origin", apple.Origin); + if (apple.ColorCodeOption.IsSet && apple.ColorCode == null) + throw new ArgumentNullException(nameof(apple.ColorCode), "Property is required for class Apple."); + + if (apple.CultivarOption.IsSet && apple.Cultivar == null) + throw new ArgumentNullException(nameof(apple.Cultivar), "Property is required for class Apple."); + + if (apple.OriginOption.IsSet && apple.Origin == null) + throw new ArgumentNullException(nameof(apple.Origin), "Property is required for class Apple."); + + if (apple.ColorCodeOption.IsSet) + writer.WriteString("color_code", apple.ColorCode); + + if (apple.CultivarOption.IsSet) + writer.WriteString("cultivar", apple.Cultivar); + + if (apple.OriginOption.IsSet) + writer.WriteString("origin", apple.Origin); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs index e0882d925c5d..6bf9766e93c4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class AppleReq : IValidatableObject /// cultivar /// mealy [JsonConstructor] - public AppleReq(string cultivar, bool mealy) + public AppleReq(string cultivar, Option mealy = default) { Cultivar = cultivar; - Mealy = mealy; + MealyOption = mealy; OnCreated(); } @@ -49,11 +50,18 @@ public AppleReq(string cultivar, bool mealy) [JsonPropertyName("cultivar")] public string Cultivar { get; set; } + /// + /// Used to track the state of Mealy + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MealyOption { get; private set; } + /// /// Gets or Sets Mealy /// [JsonPropertyName("mealy")] - public bool Mealy { get; set; } + public bool? Mealy { get { return this. MealyOption; } set { this.MealyOption = new(value); } } /// /// Returns the string presentation of the object @@ -102,8 +110,8 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string cultivar = default; - bool? mealy = default; + Option cultivar = default; + Option mealy = default; while (utf8JsonReader.Read()) { @@ -121,11 +129,11 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()); break; case "mealy": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mealy = utf8JsonReader.GetBoolean(); + mealy = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -133,13 +141,16 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class AppleReq."); + if (!cultivar.IsSet) + throw new ArgumentException("Property is required for class AppleReq.", nameof(cultivar)); - if (mealy == null) - throw new ArgumentNullException(nameof(mealy), "Property is required for class AppleReq."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class AppleReq."); - return new AppleReq(cultivar, mealy.Value); + if (mealy.IsSet && mealy.Value == null) + throw new ArgumentNullException(nameof(mealy), "Property is not nullable for class AppleReq."); + + return new AppleReq(cultivar.Value, mealy); } /// @@ -166,8 +177,13 @@ public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) { + if (appleReq.Cultivar == null) + throw new ArgumentNullException(nameof(appleReq.Cultivar), "Property is required for class AppleReq."); + writer.WriteString("cultivar", appleReq.Cultivar); - writer.WriteBoolean("mealy", appleReq.Mealy); + + if (appleReq.MealyOption.IsSet) + writer.WriteBoolean("mealy", appleReq.MealyOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 6fc0afdbc300..b18638bb4e18 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ArrayOfArrayOfNumberOnly : IValidatableObject /// /// arrayArrayNumber [JsonConstructor] - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) + public ArrayOfArrayOfNumberOnly(Option>> arrayArrayNumber = default) { - ArrayArrayNumber = arrayArrayNumber; + ArrayArrayNumberOption = arrayArrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayArrayNumber /// [JsonPropertyName("ArrayArrayNumber")] - public List> ArrayArrayNumber { get; set; } + public List> ArrayArrayNumber { get { return this. ArrayArrayNumberOption; } set { this.ArrayArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> arrayArrayNumber = default; + Option>> arrayArrayNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, { case "ArrayArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayNumber = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayNumber = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, } } - if (arrayArrayNumber == null) - throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + if (arrayArrayNumber.IsSet && arrayArrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is not nullable for class ArrayOfArrayOfNumberOnly."); return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly array /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet && arrayOfArrayOfNumberOnly.ArrayArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfArrayOfNumberOnly.ArrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 0715a3fdf65f..4b9756fa3638 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ArrayOfNumberOnly : IValidatableObject /// /// arrayNumber [JsonConstructor] - public ArrayOfNumberOnly(List arrayNumber) + public ArrayOfNumberOnly(Option> arrayNumber = default) { - ArrayNumber = arrayNumber; + ArrayNumberOption = arrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayNumber /// [JsonPropertyName("ArrayNumber")] - public List ArrayNumber { get; set; } + public List ArrayNumber { get { return this. ArrayNumberOption; } set { this.ArrayNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayNumber = default; + Option> arrayNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t { case "ArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNumber = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNumber = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (arrayNumber == null) - throw new ArgumentNullException(nameof(arrayNumber), "Property is required for class ArrayOfNumberOnly."); + if (arrayNumber.IsSet && arrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayNumber), "Property is not nullable for class ArrayOfNumberOnly."); return new ArrayOfNumberOnly(arrayNumber); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumbe /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + if (arrayOfNumberOnly.ArrayNumberOption.IsSet && arrayOfNumberOnly.ArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfNumberOnly.ArrayNumber), "Property is required for class ArrayOfNumberOnly."); + + if (arrayOfNumberOnly.ArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs index 43088ca1d97b..0bb57876ce1a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class ArrayTest : IValidatableObject /// arrayArrayOfModel /// arrayOfString [JsonConstructor] - public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) + public ArrayTest(Option>> arrayArrayOfInteger = default, Option>> arrayArrayOfModel = default, Option> arrayOfString = default) { - ArrayArrayOfInteger = arrayArrayOfInteger; - ArrayArrayOfModel = arrayArrayOfModel; - ArrayOfString = arrayOfString; + ArrayArrayOfIntegerOption = arrayArrayOfInteger; + ArrayArrayOfModelOption = arrayArrayOfModel; + ArrayOfStringOption = arrayOfString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayOfInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayOfIntegerOption { get; private set; } + /// /// Gets or Sets ArrayArrayOfInteger /// [JsonPropertyName("array_array_of_integer")] - public List> ArrayArrayOfInteger { get; set; } + public List> ArrayArrayOfInteger { get { return this. ArrayArrayOfIntegerOption; } set { this.ArrayArrayOfIntegerOption = new(value); } } + + /// + /// Used to track the state of ArrayArrayOfModel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayOfModelOption { get; private set; } /// /// Gets or Sets ArrayArrayOfModel /// [JsonPropertyName("array_array_of_model")] - public List> ArrayArrayOfModel { get; set; } + public List> ArrayArrayOfModel { get { return this. ArrayArrayOfModelOption; } set { this.ArrayArrayOfModelOption = new(value); } } + + /// + /// Used to track the state of ArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayOfStringOption { get; private set; } /// /// Gets or Sets ArrayOfString /// [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } + public List ArrayOfString { get { return this. ArrayOfStringOption; } set { this.ArrayOfStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> arrayArrayOfInteger = default; - List> arrayArrayOfModel = default; - List arrayOfString = default; + Option>> arrayArrayOfInteger = default; + Option>> arrayArrayOfModel = default; + Option> arrayOfString = default; while (utf8JsonReader.Read()) { @@ -139,15 +161,15 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "array_array_of_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfInteger = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_array_of_model": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfModel = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfModel = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayOfString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -155,14 +177,14 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (arrayArrayOfInteger == null) - throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is required for class ArrayTest."); + if (arrayArrayOfInteger.IsSet && arrayArrayOfInteger.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is not nullable for class ArrayTest."); - if (arrayArrayOfModel == null) - throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is required for class ArrayTest."); + if (arrayArrayOfModel.IsSet && arrayArrayOfModel.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is not nullable for class ArrayTest."); - if (arrayOfString == null) - throw new ArgumentNullException(nameof(arrayOfString), "Property is required for class ArrayTest."); + if (arrayOfString.IsSet && arrayOfString.Value == null) + throw new ArgumentNullException(nameof(arrayOfString), "Property is not nullable for class ArrayTest."); return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); } @@ -191,12 +213,30 @@ public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_array_of_integer"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); - writer.WritePropertyName("array_array_of_model"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); - writer.WritePropertyName("array_of_string"); - JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + if (arrayTest.ArrayArrayOfIntegerOption.IsSet && arrayTest.ArrayArrayOfInteger == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfInteger), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfModelOption.IsSet && arrayTest.ArrayArrayOfModel == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfModel), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayOfStringOption.IsSet && arrayTest.ArrayOfString == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayOfString), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfIntegerOption.IsSet) + { + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); + } + if (arrayTest.ArrayArrayOfModelOption.IsSet) + { + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); + } + if (arrayTest.ArrayOfStringOption.IsSet) + { + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs index 75bab7a8d056..bb644ada329d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Banana.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Banana : IValidatableObject /// /// lengthCm [JsonConstructor] - public Banana(decimal lengthCm) + public Banana(Option lengthCm = default) { - LengthCm = lengthCm; + LengthCmOption = lengthCm; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of LengthCm + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LengthCmOption { get; private set; } + /// /// Gets or Sets LengthCm /// [JsonPropertyName("lengthCm")] - public decimal LengthCm { get; set; } + public decimal? LengthCm { get { return this. LengthCmOption; } set { this.LengthCmOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; + Option lengthCm = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -127,10 +135,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class Banana."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class Banana."); - return new Banana(lengthCm.Value); + return new Banana(lengthCm); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("lengthCm", banana.LengthCm); + if (banana.LengthCmOption.IsSet) + writer.WriteNumber("lengthCm", banana.LengthCmOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs index 61e5cf312cca..a7eb2c945be1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class BananaReq : IValidatableObject /// lengthCm /// sweet [JsonConstructor] - public BananaReq(decimal lengthCm, bool sweet) + public BananaReq(decimal lengthCm, Option sweet = default) { LengthCm = lengthCm; - Sweet = sweet; + SweetOption = sweet; OnCreated(); } @@ -49,11 +50,18 @@ public BananaReq(decimal lengthCm, bool sweet) [JsonPropertyName("lengthCm")] public decimal LengthCm { get; set; } + /// + /// Used to track the state of Sweet + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SweetOption { get; private set; } + /// /// Gets or Sets Sweet /// [JsonPropertyName("sweet")] - public bool Sweet { get; set; } + public bool? Sweet { get { return this. SweetOption; } set { this.SweetOption = new(value); } } /// /// Returns the string presentation of the object @@ -102,8 +110,8 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; - bool? sweet = default; + Option lengthCm = default; + Option sweet = default; while (utf8JsonReader.Read()) { @@ -122,11 +130,11 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; case "sweet": if (utf8JsonReader.TokenType != JsonTokenType.Null) - sweet = utf8JsonReader.GetBoolean(); + sweet = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -134,13 +142,16 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class BananaReq."); + if (!lengthCm.IsSet) + throw new ArgumentException("Property is required for class BananaReq.", nameof(lengthCm)); - if (sweet == null) - throw new ArgumentNullException(nameof(sweet), "Property is required for class BananaReq."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class BananaReq."); - return new BananaReq(lengthCm.Value, sweet.Value); + if (sweet.IsSet && sweet.Value == null) + throw new ArgumentNullException(nameof(sweet), "Property is not nullable for class BananaReq."); + + return new BananaReq(lengthCm.Value.Value, sweet); } /// @@ -168,7 +179,9 @@ public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSeria public void WriteProperties(ref Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) { writer.WriteNumber("lengthCm", bananaReq.LengthCm); - writer.WriteBoolean("sweet", bananaReq.Sweet); + + if (bananaReq.SweetOption.IsSet) + writer.WriteBoolean("sweet", bananaReq.SweetOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs index c9e4a8bc7120..53c20a25cd10 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class BasquePig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class BasquePig.", nameof(className)); - return new BasquePig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class BasquePig."); + + return new BasquePig(className.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) { + if (basquePig.ClassName == null) + throw new ArgumentNullException(nameof(basquePig.ClassName), "Property is required for class BasquePig."); + writer.WriteString("className", basquePig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs index ca7eb413c65b..46859603bd17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Capitalization.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,55 +39,97 @@ public partial class Capitalization : IValidatableObject /// smallCamel /// smallSnake [JsonConstructor] - public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) + public Capitalization(Option aTTNAME = default, Option capitalCamel = default, Option capitalSnake = default, Option sCAETHFlowPoints = default, Option smallCamel = default, Option smallSnake = default) { - ATT_NAME = aTTNAME; - CapitalCamel = capitalCamel; - CapitalSnake = capitalSnake; - SCAETHFlowPoints = sCAETHFlowPoints; - SmallCamel = smallCamel; - SmallSnake = smallSnake; + ATT_NAMEOption = aTTNAME; + CapitalCamelOption = capitalCamel; + CapitalSnakeOption = capitalSnake; + SCAETHFlowPointsOption = sCAETHFlowPoints; + SmallCamelOption = smallCamel; + SmallSnakeOption = smallSnake; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ATT_NAME + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ATT_NAMEOption { get; private set; } + /// /// Name of the pet /// /// Name of the pet [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + public string ATT_NAME { get { return this. ATT_NAMEOption; } set { this.ATT_NAMEOption = new(value); } } + + /// + /// Used to track the state of CapitalCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalCamelOption { get; private set; } /// /// Gets or Sets CapitalCamel /// [JsonPropertyName("CapitalCamel")] - public string CapitalCamel { get; set; } + public string CapitalCamel { get { return this. CapitalCamelOption; } set { this.CapitalCamelOption = new(value); } } + + /// + /// Used to track the state of CapitalSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalSnakeOption { get; private set; } /// /// Gets or Sets CapitalSnake /// [JsonPropertyName("Capital_Snake")] - public string CapitalSnake { get; set; } + public string CapitalSnake { get { return this. CapitalSnakeOption; } set { this.CapitalSnakeOption = new(value); } } + + /// + /// Used to track the state of SCAETHFlowPoints + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SCAETHFlowPointsOption { get; private set; } /// /// Gets or Sets SCAETHFlowPoints /// [JsonPropertyName("SCA_ETH_Flow_Points")] - public string SCAETHFlowPoints { get; set; } + public string SCAETHFlowPoints { get { return this. SCAETHFlowPointsOption; } set { this.SCAETHFlowPointsOption = new(value); } } + + /// + /// Used to track the state of SmallCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallCamelOption { get; private set; } /// /// Gets or Sets SmallCamel /// [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + public string SmallCamel { get { return this. SmallCamelOption; } set { this.SmallCamelOption = new(value); } } + + /// + /// Used to track the state of SmallSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallSnakeOption { get; private set; } /// /// Gets or Sets SmallSnake /// [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } + public string SmallSnake { get { return this. SmallSnakeOption; } set { this.SmallSnakeOption = new(value); } } /// /// Gets or Sets additional properties @@ -146,12 +189,12 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string aTTNAME = default; - string capitalCamel = default; - string capitalSnake = default; - string sCAETHFlowPoints = default; - string smallCamel = default; - string smallSnake = default; + Option aTTNAME = default; + Option capitalCamel = default; + Option capitalSnake = default; + Option sCAETHFlowPoints = default; + Option smallCamel = default; + Option smallSnake = default; while (utf8JsonReader.Read()) { @@ -169,22 +212,22 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "ATT_NAME": - aTTNAME = utf8JsonReader.GetString(); + aTTNAME = new Option(utf8JsonReader.GetString()); break; case "CapitalCamel": - capitalCamel = utf8JsonReader.GetString(); + capitalCamel = new Option(utf8JsonReader.GetString()); break; case "Capital_Snake": - capitalSnake = utf8JsonReader.GetString(); + capitalSnake = new Option(utf8JsonReader.GetString()); break; case "SCA_ETH_Flow_Points": - sCAETHFlowPoints = utf8JsonReader.GetString(); + sCAETHFlowPoints = new Option(utf8JsonReader.GetString()); break; case "smallCamel": - smallCamel = utf8JsonReader.GetString(); + smallCamel = new Option(utf8JsonReader.GetString()); break; case "small_Snake": - smallSnake = utf8JsonReader.GetString(); + smallSnake = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,23 +235,23 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (aTTNAME == null) - throw new ArgumentNullException(nameof(aTTNAME), "Property is required for class Capitalization."); + if (aTTNAME.IsSet && aTTNAME.Value == null) + throw new ArgumentNullException(nameof(aTTNAME), "Property is not nullable for class Capitalization."); - if (capitalCamel == null) - throw new ArgumentNullException(nameof(capitalCamel), "Property is required for class Capitalization."); + if (capitalCamel.IsSet && capitalCamel.Value == null) + throw new ArgumentNullException(nameof(capitalCamel), "Property is not nullable for class Capitalization."); - if (capitalSnake == null) - throw new ArgumentNullException(nameof(capitalSnake), "Property is required for class Capitalization."); + if (capitalSnake.IsSet && capitalSnake.Value == null) + throw new ArgumentNullException(nameof(capitalSnake), "Property is not nullable for class Capitalization."); - if (sCAETHFlowPoints == null) - throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is required for class Capitalization."); + if (sCAETHFlowPoints.IsSet && sCAETHFlowPoints.Value == null) + throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is not nullable for class Capitalization."); - if (smallCamel == null) - throw new ArgumentNullException(nameof(smallCamel), "Property is required for class Capitalization."); + if (smallCamel.IsSet && smallCamel.Value == null) + throw new ArgumentNullException(nameof(smallCamel), "Property is not nullable for class Capitalization."); - if (smallSnake == null) - throw new ArgumentNullException(nameof(smallSnake), "Property is required for class Capitalization."); + if (smallSnake.IsSet && smallSnake.Value == null) + throw new ArgumentNullException(nameof(smallSnake), "Property is not nullable for class Capitalization."); return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); } @@ -237,12 +280,41 @@ public override void Write(Utf8JsonWriter writer, Capitalization capitalization, /// public void WriteProperties(ref Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("ATT_NAME", capitalization.ATT_NAME); - writer.WriteString("CapitalCamel", capitalization.CapitalCamel); - writer.WriteString("Capital_Snake", capitalization.CapitalSnake); - writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); - writer.WriteString("smallCamel", capitalization.SmallCamel); - writer.WriteString("small_Snake", capitalization.SmallSnake); + if (capitalization.ATT_NAMEOption.IsSet && capitalization.ATT_NAME == null) + throw new ArgumentNullException(nameof(capitalization.ATT_NAME), "Property is required for class Capitalization."); + + if (capitalization.CapitalCamelOption.IsSet && capitalization.CapitalCamel == null) + throw new ArgumentNullException(nameof(capitalization.CapitalCamel), "Property is required for class Capitalization."); + + if (capitalization.CapitalSnakeOption.IsSet && capitalization.CapitalSnake == null) + throw new ArgumentNullException(nameof(capitalization.CapitalSnake), "Property is required for class Capitalization."); + + if (capitalization.SCAETHFlowPointsOption.IsSet && capitalization.SCAETHFlowPoints == null) + throw new ArgumentNullException(nameof(capitalization.SCAETHFlowPoints), "Property is required for class Capitalization."); + + if (capitalization.SmallCamelOption.IsSet && capitalization.SmallCamel == null) + throw new ArgumentNullException(nameof(capitalization.SmallCamel), "Property is required for class Capitalization."); + + if (capitalization.SmallSnakeOption.IsSet && capitalization.SmallSnake == null) + throw new ArgumentNullException(nameof(capitalization.SmallSnake), "Property is required for class Capitalization."); + + if (capitalization.ATT_NAMEOption.IsSet) + writer.WriteString("ATT_NAME", capitalization.ATT_NAME); + + if (capitalization.CapitalCamelOption.IsSet) + writer.WriteString("CapitalCamel", capitalization.CapitalCamel); + + if (capitalization.CapitalSnakeOption.IsSet) + writer.WriteString("Capital_Snake", capitalization.CapitalSnake); + + if (capitalization.SCAETHFlowPointsOption.IsSet) + writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); + + if (capitalization.SmallCamelOption.IsSet) + writer.WriteString("smallCamel", capitalization.SmallCamel); + + if (capitalization.SmallSnakeOption.IsSet) + writer.WriteString("small_Snake", capitalization.SmallSnake); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs index 619fc52ce11c..8de1a656de5d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Cat.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -32,22 +33,29 @@ public partial class Cat : Animal, IValidatableObject /// Initializes a new instance of the class. /// /// className - /// declawed /// color (default to "red") + /// declawed [JsonConstructor] - public Cat(string className, bool declawed, string color = @"red") : base(className, color) + public Cat(string className, Option color = default, Option declawed = default) : base(className, color) { - Declawed = declawed; + DeclawedOption = declawed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Declawed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeclawedOption { get; private set; } + /// /// Gets or Sets Declawed /// [JsonPropertyName("declawed")] - public bool Declawed { get; set; } + public bool? Declawed { get { return this. DeclawedOption; } set { this.DeclawedOption = new(value); } } /// /// Returns the string presentation of the object @@ -86,9 +94,9 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - bool? declawed = default; - string color = default; + Option className = default; + Option color = default; + Option declawed = default; while (utf8JsonReader.Read()) { @@ -106,14 +114,14 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); + break; + case "color": + color = new Option(utf8JsonReader.GetString()); break; case "declawed": if (utf8JsonReader.TokenType != JsonTokenType.Null) - declawed = utf8JsonReader.GetBoolean(); - break; - case "color": - color = utf8JsonReader.GetString(); + declawed = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -121,16 +129,19 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Cat."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Cat.", nameof(className)); - if (declawed == null) - throw new ArgumentNullException(nameof(declawed), "Property is required for class Cat."); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Cat."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Cat."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Cat."); - return new Cat(className, declawed.Value, color); + if (declawed.IsSet && declawed.Value == null) + throw new ArgumentNullException(nameof(declawed), "Property is not nullable for class Cat."); + + return new Cat(className.Value, color, declawed); } /// @@ -157,9 +168,19 @@ public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) { + if (cat.ClassName == null) + throw new ArgumentNullException(nameof(cat.ClassName), "Property is required for class Cat."); + + if (cat.ColorOption.IsSet && cat.Color == null) + throw new ArgumentNullException(nameof(cat.Color), "Property is required for class Cat."); + writer.WriteString("className", cat.ClassName); - writer.WriteBoolean("declawed", cat.Declawed); - writer.WriteString("color", cat.Color); + + if (cat.ColorOption.IsSet) + writer.WriteString("color", cat.Color); + + if (cat.DeclawedOption.IsSet) + writer.WriteBoolean("declawed", cat.DeclawedOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs index 6139c3048390..09d26fdb1fa4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Category.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,20 +35,27 @@ public partial class Category : IValidatableObject /// id /// name (default to "default-name") [JsonConstructor] - public Category(long id, string name = @"default-name") + public Category(Option id = default, string name = @"default-name") { - Id = id; + IdOption = id; Name = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// /// Gets or Sets Name @@ -109,8 +117,8 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -129,10 +137,10 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -140,13 +148,16 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Category."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Category.", nameof(name)); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Category."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Category."); - return new Category(id.Value, name); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Category."); + + return new Category(id, name.Value); } /// @@ -173,7 +184,12 @@ public override void Write(Utf8JsonWriter writer, Category category, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", category.Id); + if (category.Name == null) + throw new ArgumentNullException(nameof(category.Name), "Property is required for class Category."); + + if (category.IdOption.IsSet) + writer.WriteNumber("id", category.IdOption.Value.Value); + writer.WriteString("name", category.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs index 367e08ca3d32..87996761c2ae 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,9 +35,9 @@ public partial class ChildCat : ParentPet, IValidatableObject /// name /// petType (default to PetTypeEnum.ChildCat) [JsonConstructor] - public ChildCat(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) + public ChildCat(Option name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) { - Name = name; + NameOption = name; PetType = petType; OnCreated(); } @@ -101,11 +102,18 @@ public static string PetTypeEnumToJsonValue(PetTypeEnum value) [JsonPropertyName("pet_type")] public new PetTypeEnum PetType { get; set; } + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Returns the string presentation of the object @@ -145,8 +153,8 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; - ChildCat.PetTypeEnum? petType = default; + Option name = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -164,13 +172,12 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; case "pet_type": string petTypeRawValue = utf8JsonReader.GetString(); - petType = petTypeRawValue == null - ? null - : ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue); + if (petTypeRawValue != null) + petType = new Option(ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue)); break; default: break; @@ -178,13 +185,16 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class ChildCat."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ChildCat.", nameof(petType)); - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ChildCat."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class ChildCat."); - return new ChildCat(name, petType.Value); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ChildCat."); + + return new ChildCat(name, petType.Value.Value); } /// @@ -211,13 +221,14 @@ public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", childCat.Name); + if (childCat.NameOption.IsSet && childCat.Name == null) + throw new ArgumentNullException(nameof(childCat.Name), "Property is required for class ChildCat."); + + if (childCat.NameOption.IsSet) + writer.WriteString("name", childCat.Name); var petTypeRawValue = ChildCat.PetTypeEnumToJsonValue(childCat.PetType); - if (petTypeRawValue != null) - writer.WriteString("pet_type", petTypeRawValue); - else - writer.WriteNull("pet_type"); + writer.WriteString("pet_type", petTypeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs index d1c65d368199..bbed8f0df133 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ClassModel.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ClassModel : IValidatableObject /// /// varClass [JsonConstructor] - public ClassModel(string varClass) + public ClassModel(Option varClass = default) { - VarClass = varClass; + VarClassOption = varClass; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("_class")] - public string VarClass { get; set; } + public string VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClass = default; + Option varClass = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { case "_class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class ClassModel."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class ClassModel."); return new ClassModel(varClass); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_class", classModel.VarClass); + if (classModel.VarClassOption.IsSet && classModel.VarClass == null) + throw new ArgumentNullException(nameof(classModel.VarClass), "Property is required for class ClassModel."); + + if (classModel.VarClassOption.IsSet) + writer.WriteString("_class", classModel.VarClass); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 79579247f7e9..747b36ec65bd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; - string shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class ComplexQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ComplexQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(shapeType)); - return new ComplexQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class ComplexQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ComplexQuadrilateral."); + + return new ComplexQuadrilateral(quadrilateralType.Value, shapeType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQu /// public void WriteProperties(ref Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (complexQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.QuadrilateralType), "Property is required for class ComplexQuadrilateral."); + + if (complexQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.ShapeType), "Property is required for class ComplexQuadrilateral."); + writer.WriteString("quadrilateralType", complexQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", complexQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs index 84439210bcfc..c28634e4e13e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class DanishPig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class DanishPig.", nameof(className)); - return new DanishPig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class DanishPig."); + + return new DanishPig(className.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) { + if (danishPig.ClassName == null) + throw new ArgumentNullException(nameof(danishPig.ClassName), "Property is required for class DanishPig."); + writer.WriteString("className", danishPig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs index 4420630af349..c1f1b99a4f6a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class DateOnlyClass : IValidatableObject /// /// dateOnlyProperty [JsonConstructor] - public DateOnlyClass(DateTime dateOnlyProperty) + public DateOnlyClass(Option dateOnlyProperty = default) { - DateOnlyProperty = dateOnlyProperty; + DateOnlyPropertyOption = dateOnlyProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateOnlyProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateOnlyPropertyOption { get; private set; } + /// /// Gets or Sets DateOnlyProperty /// /// Fri Jul 21 00:00:00 UTC 2017 [JsonPropertyName("dateOnlyProperty")] - public DateTime DateOnlyProperty { get; set; } + public DateOnly? DateOnlyProperty { get { return this. DateOnlyPropertyOption; } set { this.DateOnlyPropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -106,7 +114,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateOnlyProperty = default; + Option dateOnlyProperty = default; while (utf8JsonReader.Read()) { @@ -125,7 +133,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT { case "dateOnlyProperty": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateOnlyProperty = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateOnlyProperty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -133,10 +141,10 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (dateOnlyProperty == null) - throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is required for class DateOnlyClass."); + if (dateOnlyProperty.IsSet && dateOnlyProperty.Value == null) + throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is not nullable for class DateOnlyClass."); - return new DateOnlyClass(dateOnlyProperty.Value); + return new DateOnlyClass(dateOnlyProperty); } /// @@ -163,7 +171,8 @@ public override void Write(Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyProperty.ToString(DateOnlyPropertyFormat)); + if (dateOnlyClass.DateOnlyPropertyOption.IsSet) + writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyPropertyOption.Value.Value.ToString(DateOnlyPropertyFormat)); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 16e3dfe57faa..6f0315de5d5a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class DeprecatedObject : IValidatableObject /// /// name [JsonConstructor] - public DeprecatedObject(string name) + public DeprecatedObject(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class DeprecatedObject."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DeprecatedObject."); return new DeprecatedObject(name); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObj /// public void WriteProperties(ref Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", deprecatedObject.Name); + if (deprecatedObject.NameOption.IsSet && deprecatedObject.Name == null) + throw new ArgumentNullException(nameof(deprecatedObject.Name), "Property is required for class DeprecatedObject."); + + if (deprecatedObject.NameOption.IsSet) + writer.WriteString("name", deprecatedObject.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs index 810934b95efe..1d53127161c4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Dog.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,23 +32,30 @@ public partial class Dog : Animal, IValidatableObject /// /// Initializes a new instance of the class. /// - /// breed /// className + /// breed /// color (default to "red") [JsonConstructor] - public Dog(string breed, string className, string color = @"red") : base(className, color) + public Dog(string className, Option breed = default, Option color = default) : base(className, color) { - Breed = breed; + BreedOption = breed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Breed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BreedOption { get; private set; } + /// /// Gets or Sets Breed /// [JsonPropertyName("breed")] - public string Breed { get; set; } + public string Breed { get { return this. BreedOption; } set { this.BreedOption = new(value); } } /// /// Returns the string presentation of the object @@ -86,9 +94,9 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string breed = default; - string className = default; - string color = default; + Option className = default; + Option breed = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -105,14 +113,14 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "breed": - breed = utf8JsonReader.GetString(); - break; case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); + break; + case "breed": + breed = new Option(utf8JsonReader.GetString()); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -120,16 +128,19 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (breed == null) - throw new ArgumentNullException(nameof(breed), "Property is required for class Dog."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Dog.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Dog."); - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Dog."); + if (breed.IsSet && breed.Value == null) + throw new ArgumentNullException(nameof(breed), "Property is not nullable for class Dog."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Dog."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Dog."); - return new Dog(breed, className, color); + return new Dog(className.Value, breed, color); } /// @@ -156,9 +167,22 @@ public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("breed", dog.Breed); + if (dog.ClassName == null) + throw new ArgumentNullException(nameof(dog.ClassName), "Property is required for class Dog."); + + if (dog.BreedOption.IsSet && dog.Breed == null) + throw new ArgumentNullException(nameof(dog.Breed), "Property is required for class Dog."); + + if (dog.ColorOption.IsSet && dog.Color == null) + throw new ArgumentNullException(nameof(dog.Color), "Property is required for class Dog."); + writer.WriteString("className", dog.ClassName); - writer.WriteString("color", dog.Color); + + if (dog.BreedOption.IsSet) + writer.WriteString("breed", dog.Breed); + + if (dog.ColorOption.IsSet) + writer.WriteString("color", dog.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs index 68f7676ff91f..b14dbc3d258f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -20,56 +20,85 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Drawing /// - public partial class Drawing : Dictionary, IValidatableObject + public partial class Drawing : IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape - /// shapes /// nullableShape /// shapeOrNull + /// shapes [JsonConstructor] - public Drawing(Shape mainShape, List shapes, NullableShape nullableShape = default, ShapeOrNull shapeOrNull = default) : base() + public Drawing(Option mainShape = default, Option nullableShape = default, Option shapeOrNull = default, Option> shapes = default) { - MainShape = mainShape; - Shapes = shapes; - NullableShape = nullableShape; - ShapeOrNull = shapeOrNull; + MainShapeOption = mainShape; + NullableShapeOption = nullableShape; + ShapeOrNullOption = shapeOrNull; + ShapesOption = shapes; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MainShape + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MainShapeOption { get; private set; } + /// /// Gets or Sets MainShape /// [JsonPropertyName("mainShape")] - public Shape MainShape { get; set; } + public Shape MainShape { get { return this. MainShapeOption; } set { this.MainShapeOption = new(value); } } /// - /// Gets or Sets Shapes + /// Used to track the state of NullableShape /// - [JsonPropertyName("shapes")] - public List Shapes { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableShapeOption { get; private set; } /// /// Gets or Sets NullableShape /// [JsonPropertyName("nullableShape")] - public NullableShape NullableShape { get; set; } + public NullableShape NullableShape { get { return this. NullableShapeOption; } set { this.NullableShapeOption = new(value); } } + + /// + /// Used to track the state of ShapeOrNull + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShapeOrNullOption { get; private set; } /// /// Gets or Sets ShapeOrNull /// [JsonPropertyName("shapeOrNull")] - public ShapeOrNull ShapeOrNull { get; set; } + public ShapeOrNull ShapeOrNull { get { return this. ShapeOrNullOption; } set { this.ShapeOrNullOption = new(value); } } + + /// + /// Used to track the state of Shapes + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ShapesOption { get; private set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List Shapes { get { return this. ShapesOption; } set { this.ShapesOption = new(value); } } /// /// Gets or Sets additional properties @@ -85,11 +114,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); - sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -101,16 +129,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -138,10 +156,10 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Shape mainShape = default; - List shapes = default; - NullableShape nullableShape = default; - ShapeOrNull shapeOrNull = default; + Option mainShape = default; + Option nullableShape = default; + Option shapeOrNull = default; + Option> shapes = default; while (utf8JsonReader.Read()) { @@ -160,19 +178,19 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "mainShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mainShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "shapes": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapes = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mainShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "nullableShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - nullableShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + nullableShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "shapeOrNull": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapeOrNull = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shapeOrNull = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "shapes": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapes = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -180,13 +198,13 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (mainShape == null) - throw new ArgumentNullException(nameof(mainShape), "Property is required for class Drawing."); + if (mainShape.IsSet && mainShape.Value == null) + throw new ArgumentNullException(nameof(mainShape), "Property is not nullable for class Drawing."); - if (shapes == null) - throw new ArgumentNullException(nameof(shapes), "Property is required for class Drawing."); + if (shapes.IsSet && shapes.Value == null) + throw new ArgumentNullException(nameof(shapes), "Property is not nullable for class Drawing."); - return new Drawing(mainShape, shapes, nullableShape, shapeOrNull); + return new Drawing(mainShape, nullableShape, shapeOrNull, shapes); } /// @@ -213,14 +231,38 @@ public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("mainShape"); - JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); - writer.WritePropertyName("shapes"); - JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); - writer.WritePropertyName("nullableShape"); - JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); - writer.WritePropertyName("shapeOrNull"); - JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + if (drawing.MainShapeOption.IsSet && drawing.MainShape == null) + throw new ArgumentNullException(nameof(drawing.MainShape), "Property is required for class Drawing."); + + if (drawing.ShapesOption.IsSet && drawing.Shapes == null) + throw new ArgumentNullException(nameof(drawing.Shapes), "Property is required for class Drawing."); + + if (drawing.MainShapeOption.IsSet) + { + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); + } + if (drawing.NullableShapeOption.IsSet) + if (drawing.NullableShapeOption.Value != null) + { + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); + } + else + writer.WriteNull("nullableShape"); + if (drawing.ShapeOrNullOption.IsSet) + if (drawing.ShapeOrNullOption.Value != null) + { + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + } + else + writer.WriteNull("shapeOrNull"); + if (drawing.ShapesOption.IsSet) + { + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 37e06cb37e3c..b7ed50d1539e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class EnumArrays : IValidatableObject /// arrayEnum /// justSymbol [JsonConstructor] - public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) + public EnumArrays(Option> arrayEnum = default, Option justSymbol = default) { - ArrayEnum = arrayEnum; - JustSymbol = justSymbol; + ArrayEnumOption = arrayEnum; + JustSymbolOption = justSymbol; OnCreated(); } @@ -164,7 +165,7 @@ public static JustSymbolEnum JustSymbolEnumFromString(string value) /// /// /// - public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) + public static string JustSymbolEnumToJsonValue(JustSymbolEnum? value) { if (value == JustSymbolEnum.GreaterThanOrEqualTo) return ">="; @@ -175,17 +176,31 @@ public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of JustSymbol + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustSymbolOption { get; private set; } + /// /// Gets or Sets JustSymbol /// [JsonPropertyName("just_symbol")] - public JustSymbolEnum JustSymbol { get; set; } + public JustSymbolEnum? JustSymbol { get { return this.JustSymbolOption; } set { this.JustSymbolOption = new(value); } } + + /// + /// Used to track the state of ArrayEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayEnumOption { get; private set; } /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List ArrayEnum { get { return this. ArrayEnumOption; } set { this.ArrayEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -241,8 +256,8 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayEnum = default; - EnumArrays.JustSymbolEnum? justSymbol = default; + Option> arrayEnum = default; + Option justSymbol = default; while (utf8JsonReader.Read()) { @@ -261,13 +276,12 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "array_enum": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayEnum = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayEnum = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "just_symbol": string justSymbolRawValue = utf8JsonReader.GetString(); - justSymbol = justSymbolRawValue == null - ? null - : EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue); + if (justSymbolRawValue != null) + justSymbol = new Option(EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue)); break; default: break; @@ -275,13 +289,13 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (arrayEnum == null) - throw new ArgumentNullException(nameof(arrayEnum), "Property is required for class EnumArrays."); + if (arrayEnum.IsSet && arrayEnum.Value == null) + throw new ArgumentNullException(nameof(arrayEnum), "Property is not nullable for class EnumArrays."); - if (justSymbol == null) - throw new ArgumentNullException(nameof(justSymbol), "Property is required for class EnumArrays."); + if (justSymbol.IsSet && justSymbol.Value == null) + throw new ArgumentNullException(nameof(justSymbol), "Property is not nullable for class EnumArrays."); - return new EnumArrays(arrayEnum, justSymbol.Value); + return new EnumArrays(arrayEnum, justSymbol); } /// @@ -308,14 +322,16 @@ public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_enum"); - JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); - - var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); - if (justSymbolRawValue != null) - writer.WriteString("just_symbol", justSymbolRawValue); - else - writer.WriteNull("just_symbol"); + if (enumArrays.ArrayEnumOption.IsSet && enumArrays.ArrayEnum == null) + throw new ArgumentNullException(nameof(enumArrays.ArrayEnum), "Property is required for class EnumArrays."); + + if (enumArrays.ArrayEnumOption.IsSet) + { + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); + } + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbolOption.Value.Value); + writer.WriteString("just_symbol", justSymbolRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs index 94c2361c8810..b1aff0adf0d8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs index 1d1ed947dc47..9fadfdcbf354 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,32 +32,188 @@ public partial class EnumTest : IValidatableObject /// /// Initializes a new instance of the class. /// + /// enumStringRequired /// enumInteger /// enumIntegerOnly /// enumNumber /// enumString - /// enumStringRequired + /// outerEnum /// outerEnumDefaultValue /// outerEnumInteger /// outerEnumIntegerDefaultValue - /// outerEnum [JsonConstructor] - public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) + public EnumTest(EnumStringRequiredEnum enumStringRequired, Option enumInteger = default, Option enumIntegerOnly = default, Option enumNumber = default, Option enumString = default, Option outerEnum = default, Option outerEnumDefaultValue = default, Option outerEnumInteger = default, Option outerEnumIntegerDefaultValue = default) { - EnumInteger = enumInteger; - EnumIntegerOnly = enumIntegerOnly; - EnumNumber = enumNumber; - EnumString = enumString; EnumStringRequired = enumStringRequired; - OuterEnumDefaultValue = outerEnumDefaultValue; - OuterEnumInteger = outerEnumInteger; - OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - OuterEnum = outerEnum; + EnumIntegerOption = enumInteger; + EnumIntegerOnlyOption = enumIntegerOnly; + EnumNumberOption = enumNumber; + EnumStringOption = enumString; + OuterEnumOption = outerEnum; + OuterEnumDefaultValueOption = outerEnumDefaultValue; + OuterEnumIntegerOption = outerEnumInteger; + OuterEnumIntegerDefaultValueOption = outerEnumIntegerDefaultValue; OnCreated(); } partial void OnCreated(); + /// + /// Defines EnumStringRequired + /// + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) + { + if (value == EnumStringRequiredEnum.UPPER) + return "UPPER"; + + if (value == EnumStringRequiredEnum.Lower) + return "lower"; + + if (value == EnumStringRequiredEnum.Empty) + return ""; + + if (value == EnumStringRequiredEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringRequiredEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringRequiredEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringRequiredEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumStringRequired + /// + [JsonPropertyName("enum_string_required")] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + /// /// Defines EnumInteger /// @@ -116,11 +273,18 @@ public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) return (int) value; } + /// + /// Used to track the state of EnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOption { get; private set; } + /// /// Gets or Sets EnumInteger /// [JsonPropertyName("enum_integer")] - public EnumIntegerEnum EnumInteger { get; set; } + public EnumIntegerEnum? EnumInteger { get { return this.EnumIntegerOption; } set { this.EnumIntegerOption = new(value); } } /// /// Defines EnumIntegerOnly @@ -181,11 +345,18 @@ public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) return (int) value; } + /// + /// Used to track the state of EnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOnlyOption { get; private set; } + /// /// Gets or Sets EnumIntegerOnly /// [JsonPropertyName("enum_integer_only")] - public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } + public EnumIntegerOnlyEnum? EnumIntegerOnly { get { return this.EnumIntegerOnlyOption; } set { this.EnumIntegerOnlyOption = new(value); } } /// /// Defines EnumNumber @@ -242,7 +413,7 @@ public static EnumNumberEnum EnumNumberEnumFromString(string value) /// /// /// - public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) + public static double EnumNumberEnumToJsonValue(EnumNumberEnum? value) { if (value == EnumNumberEnum.NUMBER_1_DOT_1) return 1.1; @@ -253,11 +424,18 @@ public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of EnumNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumNumberOption { get; private set; } + /// /// Gets or Sets EnumNumber /// [JsonPropertyName("enum_number")] - public EnumNumberEnum EnumNumber { get; set; } + public EnumNumberEnum? EnumNumber { get { return this.EnumNumberOption; } set { this.EnumNumberOption = new(value); } } /// /// Defines EnumString @@ -380,7 +558,7 @@ public static EnumStringEnum EnumStringEnumFromString(string value) /// /// /// - public static string EnumStringEnumToJsonValue(EnumStringEnum value) + public static string EnumStringEnumToJsonValue(EnumStringEnum? value) { if (value == EnumStringEnum.UPPER) return "UPPER"; @@ -410,190 +588,69 @@ public static string EnumStringEnumToJsonValue(EnumStringEnum value) } /// - /// Gets or Sets EnumString + /// Used to track the state of EnumString /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumStringOption { get; private set; } /// - /// Defines EnumStringRequired + /// Gets or Sets EnumString /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - Lower = 2, - - /// - /// Enum Empty for value: - /// - Empty = 3, - - /// - /// Enum ValuewithTab for value: Value\twith tab - /// - ValuewithTab = 4, - - /// - /// Enum ValueWithQuote for value: Value with \" quote - /// - ValueWithQuote = 5, - - /// - /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote - /// - ValueWithEscapedQuote = 6, - - /// - /// Enum Duplicatevalue for value: Duplicate\nvalue - /// - Duplicatevalue = 7, - - /// - /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue - /// - Duplicatevalue2 = 8 - } + [JsonPropertyName("enum_string")] + public EnumStringEnum? EnumString { get { return this.EnumStringOption; } set { this.EnumStringOption = new(value); } } /// - /// Returns a + /// Used to track the state of OuterEnum /// - /// - /// - /// - public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumOption { get; private set; } /// - /// Returns a + /// Gets or Sets OuterEnum /// - /// - /// - public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - return null; - } + [JsonPropertyName("outerEnum")] + public OuterEnum? OuterEnum { get { return this.OuterEnumOption; } set { this.OuterEnumOption = new(value); } } /// - /// Converts the to the json value + /// Used to track the state of OuterEnumDefaultValue /// - /// - /// - /// - public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) - { - if (value == EnumStringRequiredEnum.UPPER) - return "UPPER"; - - if (value == EnumStringRequiredEnum.Lower) - return "lower"; - - if (value == EnumStringRequiredEnum.Empty) - return ""; - - if (value == EnumStringRequiredEnum.ValuewithTab) - return "Value\twith tab"; - - if (value == EnumStringRequiredEnum.ValueWithQuote) - return "Value with \" quote"; - - if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) - return "Value with escaped \" quote"; - - if (value == EnumStringRequiredEnum.Duplicatevalue) - return "Duplicate\nvalue"; - - if (value == EnumStringRequiredEnum.Duplicatevalue2) - return "Duplicate\r\nvalue"; - - throw new NotImplementedException($"Value could not be handled: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumDefaultValueOption { get; private set; } /// - /// Gets or Sets EnumStringRequired + /// Gets or Sets OuterEnumDefaultValue /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } + [JsonPropertyName("outerEnumDefaultValue")] + public OuterEnumDefaultValue? OuterEnumDefaultValue { get { return this.OuterEnumDefaultValueOption; } set { this.OuterEnumDefaultValueOption = new(value); } } /// - /// Gets or Sets OuterEnumDefaultValue + /// Used to track the state of OuterEnumInteger /// - [JsonPropertyName("outerEnumDefaultValue")] - public OuterEnumDefaultValue OuterEnumDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerOption { get; private set; } /// /// Gets or Sets OuterEnumInteger /// [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + public OuterEnumInteger? OuterEnumInteger { get { return this.OuterEnumIntegerOption; } set { this.OuterEnumIntegerOption = new(value); } } /// - /// Gets or Sets OuterEnumIntegerDefaultValue + /// Used to track the state of OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnumIntegerDefaultValue")] - public OuterEnumIntegerDefaultValue OuterEnumIntegerDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerDefaultValueOption { get; private set; } /// - /// Gets or Sets OuterEnum + /// Gets or Sets OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnum")] - public OuterEnum? OuterEnum { get; set; } + [JsonPropertyName("outerEnumIntegerDefaultValue")] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get { return this.OuterEnumIntegerDefaultValueOption; } set { this.OuterEnumIntegerDefaultValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -609,15 +666,15 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -656,15 +713,15 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - EnumTest.EnumIntegerEnum? enumInteger = default; - EnumTest.EnumIntegerOnlyEnum? enumIntegerOnly = default; - EnumTest.EnumNumberEnum? enumNumber = default; - EnumTest.EnumStringEnum? enumString = default; - EnumTest.EnumStringRequiredEnum? enumStringRequired = default; - OuterEnumDefaultValue? outerEnumDefaultValue = default; - OuterEnumInteger? outerEnumInteger = default; - OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default; - OuterEnum? outerEnum = default; + Option enumStringRequired = default; + Option enumInteger = default; + Option enumIntegerOnly = default; + Option enumNumber = default; + Option enumString = default; + Option outerEnum = default; + Option outerEnumDefaultValue = default; + Option outerEnumInteger = default; + Option outerEnumIntegerDefaultValue = default; while (utf8JsonReader.Read()) { @@ -681,53 +738,47 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { + case "enum_string_required": + string enumStringRequiredRawValue = utf8JsonReader.GetString(); + if (enumStringRequiredRawValue != null) + enumStringRequired = new Option(EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue)); + break; case "enum_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumInteger = (EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32(); + enumInteger = new Option((EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32()); break; case "enum_integer_only": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32(); + enumIntegerOnly = new Option((EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); break; case "enum_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumNumber = (EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32(); + enumNumber = new Option((EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32()); break; case "enum_string": string enumStringRawValue = utf8JsonReader.GetString(); - enumString = enumStringRawValue == null - ? null - : EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue); + if (enumStringRawValue != null) + enumString = new Option(EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue)); break; - case "enum_string_required": - string enumStringRequiredRawValue = utf8JsonReader.GetString(); - enumStringRequired = enumStringRequiredRawValue == null - ? null - : EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue); + case "outerEnum": + string outerEnumRawValue = utf8JsonReader.GetString(); + if (outerEnumRawValue != null) + outerEnum = new Option(OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue)); break; case "outerEnumDefaultValue": string outerEnumDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumDefaultValue = outerEnumDefaultValueRawValue == null - ? null - : OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue); + if (outerEnumDefaultValueRawValue != null) + outerEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue)); break; case "outerEnumInteger": string outerEnumIntegerRawValue = utf8JsonReader.GetString(); - outerEnumInteger = outerEnumIntegerRawValue == null - ? null - : OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue); + if (outerEnumIntegerRawValue != null) + outerEnumInteger = new Option(OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue)); break; case "outerEnumIntegerDefaultValue": string outerEnumIntegerDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValueRawValue == null - ? null - : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue); - break; - case "outerEnum": - string outerEnumRawValue = utf8JsonReader.GetString(); - outerEnum = outerEnumRawValue == null - ? null - : OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue); + if (outerEnumIntegerDefaultValueRawValue != null) + outerEnumIntegerDefaultValue = new Option(OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue)); break; default: break; @@ -735,31 +786,34 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (enumInteger == null) - throw new ArgumentNullException(nameof(enumInteger), "Property is required for class EnumTest."); + if (!enumStringRequired.IsSet) + throw new ArgumentException("Property is required for class EnumTest.", nameof(enumStringRequired)); + + if (enumStringRequired.IsSet && enumStringRequired.Value == null) + throw new ArgumentNullException(nameof(enumStringRequired), "Property is not nullable for class EnumTest."); - if (enumIntegerOnly == null) - throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is required for class EnumTest."); + if (enumInteger.IsSet && enumInteger.Value == null) + throw new ArgumentNullException(nameof(enumInteger), "Property is not nullable for class EnumTest."); - if (enumNumber == null) - throw new ArgumentNullException(nameof(enumNumber), "Property is required for class EnumTest."); + if (enumIntegerOnly.IsSet && enumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is not nullable for class EnumTest."); - if (enumString == null) - throw new ArgumentNullException(nameof(enumString), "Property is required for class EnumTest."); + if (enumNumber.IsSet && enumNumber.Value == null) + throw new ArgumentNullException(nameof(enumNumber), "Property is not nullable for class EnumTest."); - if (enumStringRequired == null) - throw new ArgumentNullException(nameof(enumStringRequired), "Property is required for class EnumTest."); + if (enumString.IsSet && enumString.Value == null) + throw new ArgumentNullException(nameof(enumString), "Property is not nullable for class EnumTest."); - if (outerEnumDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is required for class EnumTest."); + if (outerEnumDefaultValue.IsSet && outerEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is not nullable for class EnumTest."); - if (outerEnumInteger == null) - throw new ArgumentNullException(nameof(outerEnumInteger), "Property is required for class EnumTest."); + if (outerEnumInteger.IsSet && outerEnumInteger.Value == null) + throw new ArgumentNullException(nameof(outerEnumInteger), "Property is not nullable for class EnumTest."); - if (outerEnumIntegerDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is required for class EnumTest."); + if (outerEnumIntegerDefaultValue.IsSet && outerEnumIntegerDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is not nullable for class EnumTest."); - return new EnumTest(enumInteger.Value, enumIntegerOnly.Value, enumNumber.Value, enumString.Value, enumStringRequired.Value, outerEnumDefaultValue.Value, outerEnumInteger.Value, outerEnumIntegerDefaultValue.Value, outerEnum); + return new EnumTest(enumStringRequired.Value.Value, enumInteger, enumIntegerOnly, enumNumber, enumString, outerEnum, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue); } /// @@ -786,43 +840,41 @@ public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumInteger)); - writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnly)); - writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumber)); - - var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumString); - if (enumStringRawValue != null) - writer.WriteString("enum_string", enumStringRawValue); - else - writer.WriteNull("enum_string"); - var enumStringRequiredRawValue = EnumTest.EnumStringRequiredEnumToJsonValue(enumTest.EnumStringRequired); - if (enumStringRequiredRawValue != null) - writer.WriteString("enum_string_required", enumStringRequiredRawValue); - else - writer.WriteNull("enum_string_required"); + writer.WriteString("enum_string_required", enumStringRequiredRawValue); + if (enumTest.EnumIntegerOption.IsSet) + writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumIntegerOption.Value.Value)); - var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (enumTest.EnumIntegerOnlyOption.IsSet) + writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnlyOption.Value.Value)); - if (outerEnumDefaultValueRawValue != null) - writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); - else - writer.WriteNull("outerEnumDefaultValue"); - - var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger); - writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); - var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); - writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + if (enumTest.EnumNumberOption.IsSet) + writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumberOption.Value.Value)); - if (enumTest.OuterEnum == null) - writer.WriteNull("outerEnum"); - else - { - var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnum.Value); - if (outerEnumRawValue != null) + var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumStringOption.Value.Value); + writer.WriteString("enum_string", enumStringRawValue); + if (enumTest.OuterEnumOption.IsSet) + if (enumTest.OuterEnumOption.Value != null) + { + var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnumOption.Value.Value); writer.WriteString("outerEnum", outerEnumRawValue); + } else writer.WriteNull("outerEnum"); + if (enumTest.OuterEnumDefaultValueOption.IsSet) + { + var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue.Value); + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + } + if (enumTest.OuterEnumIntegerOption.IsSet) + { + var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger.Value); + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + } + if (enumTest.OuterEnumIntegerDefaultValueOption.IsSet) + { + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue.Value); + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 626748ff2097..bbf4bf8f8e09 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class EquilateralTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class EquilateralTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(triangleType)); - return new EquilateralTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class EquilateralTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class EquilateralTriangle."); + + return new EquilateralTriangle(shapeType.Value, triangleType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilatera /// public void WriteProperties(ref Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (equilateralTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.ShapeType), "Property is required for class EquilateralTriangle."); + + if (equilateralTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.TriangleType), "Property is required for class EquilateralTriangle."); + writer.WriteString("shapeType", equilateralTriangle.ShapeType); + writer.WriteString("triangleType", equilateralTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs index 905e5452f7c0..11754d379993 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/File.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class File : IValidatableObject /// /// Test capitalization [JsonConstructor] - public File(string sourceURI) + public File(Option sourceURI = default) { - SourceURI = sourceURI; + SourceURIOption = sourceURI; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SourceURI + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SourceURIOption { get; private set; } + /// /// Test capitalization /// /// Test capitalization [JsonPropertyName("sourceURI")] - public string SourceURI { get; set; } + public string SourceURI { get { return this. SourceURIOption; } set { this.SourceURIOption = new(value); } } /// /// Gets or Sets additional properties @@ -101,7 +109,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string sourceURI = default; + Option sourceURI = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "sourceURI": - sourceURI = utf8JsonReader.GetString(); + sourceURI = new Option(utf8JsonReader.GetString()); break; default: break; @@ -127,8 +135,8 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (sourceURI == null) - throw new ArgumentNullException(nameof(sourceURI), "Property is required for class File."); + if (sourceURI.IsSet && sourceURI.Value == null) + throw new ArgumentNullException(nameof(sourceURI), "Property is not nullable for class File."); return new File(sourceURI); } @@ -157,7 +165,11 @@ public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("sourceURI", file.SourceURI); + if (file.SourceURIOption.IsSet && file.SourceURI == null) + throw new ArgumentNullException(nameof(file.SourceURI), "Property is required for class File."); + + if (file.SourceURIOption.IsSet) + writer.WriteString("sourceURI", file.SourceURI); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 722ba3b949f0..6a07c6d1f950 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class FileSchemaTestClass : IValidatableObject /// file /// files [JsonConstructor] - public FileSchemaTestClass(File file, List files) + public FileSchemaTestClass(Option file = default, Option> files = default) { - File = file; - Files = files; + FileOption = file; + FilesOption = files; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of File + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FileOption { get; private set; } + /// /// Gets or Sets File /// [JsonPropertyName("file")] - public File File { get; set; } + public File File { get { return this. FileOption; } set { this.FileOption = new(value); } } + + /// + /// Used to track the state of Files + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> FilesOption { get; private set; } /// /// Gets or Sets Files /// [JsonPropertyName("files")] - public List Files { get; set; } + public List Files { get { return this. FilesOption; } set { this.FilesOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - File file = default; - List files = default; + Option file = default; + Option> files = default; while (utf8JsonReader.Read()) { @@ -129,11 +144,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "file": if (utf8JsonReader.TokenType != JsonTokenType.Null) - file = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + file = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "files": if (utf8JsonReader.TokenType != JsonTokenType.Null) - files = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + files = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -141,11 +156,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (file == null) - throw new ArgumentNullException(nameof(file), "Property is required for class FileSchemaTestClass."); + if (file.IsSet && file.Value == null) + throw new ArgumentNullException(nameof(file), "Property is not nullable for class FileSchemaTestClass."); - if (files == null) - throw new ArgumentNullException(nameof(files), "Property is required for class FileSchemaTestClass."); + if (files.IsSet && files.Value == null) + throw new ArgumentNullException(nameof(files), "Property is not nullable for class FileSchemaTestClass."); return new FileSchemaTestClass(file, files); } @@ -174,10 +189,22 @@ public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchema /// public void WriteProperties(ref Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("file"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); - writer.WritePropertyName("files"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + if (fileSchemaTestClass.FileOption.IsSet && fileSchemaTestClass.File == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.File), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FilesOption.IsSet && fileSchemaTestClass.Files == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.Files), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FileOption.IsSet) + { + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); + } + if (fileSchemaTestClass.FilesOption.IsSet) + { + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs index 9cfe3b508fe8..98f8d13300ad 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Foo.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Foo : IValidatableObject /// /// bar (default to "bar") [JsonConstructor] - public Foo(string bar = @"bar") + public Foo(Option bar = default) { - Bar = bar; + BarOption = bar; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; private set; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; set; } + public string Bar { get { return this. BarOption; } set { this.BarOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; + Option bar = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class Foo."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class Foo."); return new Foo(bar); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", foo.Bar); + if (foo.BarOption.IsSet && foo.Bar == null) + throw new ArgumentNullException(nameof(foo.Bar), "Property is required for class Foo."); + + if (foo.BarOption.IsSet) + writer.WriteString("bar", foo.Bar); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index c8291e8eae5b..5834385cd5bb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class FooGetDefaultResponse : IValidatableObject /// /// varString [JsonConstructor] - public FooGetDefaultResponse(Foo varString) + public FooGetDefaultResponse(Option varString = default) { - VarString = varString; + VarStringOption = varString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } + /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public Foo VarString { get; set; } + public Foo VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Foo varString = default; + Option varString = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty { case "string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varString = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varString = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty } } - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FooGetDefaultResponse."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FooGetDefaultResponse."); return new FooGetDefaultResponse(varString); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDe /// public void WriteProperties(ref Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("string"); - JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + if (fooGetDefaultResponse.VarStringOption.IsSet && fooGetDefaultResponse.VarString == null) + throw new ArgumentNullException(nameof(fooGetDefaultResponse.VarString), "Property is required for class FooGetDefaultResponse."); + + if (fooGetDefaultResponse.VarStringOption.IsSet) + { + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs index 30a9b189932a..779fb7f81b16 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,9 +32,11 @@ public partial class FormatTest : IValidatableObject /// /// Initializes a new instance of the class. /// - /// binary /// varByte /// date + /// number + /// password + /// binary /// dateTime /// varDecimal /// varDouble @@ -41,8 +44,6 @@ public partial class FormatTest : IValidatableObject /// int32 /// int64 /// integer - /// number - /// password /// None /// A string that is a 10 digit number. Can have leading zeros. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. @@ -51,38 +52,32 @@ public partial class FormatTest : IValidatableObject /// unsignedLong /// uuid [JsonConstructor] - public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTime dateTime, decimal varDecimal, double varDouble, float varFloat, int int32, long int64, int integer, decimal number, string password, string patternWithBackslash, string patternWithDigits, string patternWithDigitsAndDelimiter, string varString, uint unsignedInteger, ulong unsignedLong, Guid uuid) + public FormatTest(byte[] varByte, DateOnly date, decimal number, string password, Option binary = default, Option dateTime = default, Option varDecimal = default, Option varDouble = default, Option varFloat = default, Option int32 = default, Option int64 = default, Option integer = default, Option patternWithBackslash = default, Option patternWithDigits = default, Option patternWithDigitsAndDelimiter = default, Option varString = default, Option unsignedInteger = default, Option unsignedLong = default, Option uuid = default) { - Binary = binary; VarByte = varByte; Date = date; - DateTime = dateTime; - VarDecimal = varDecimal; - VarDouble = varDouble; - VarFloat = varFloat; - Int32 = int32; - Int64 = int64; - Integer = integer; Number = number; Password = password; - PatternWithBackslash = patternWithBackslash; - PatternWithDigits = patternWithDigits; - PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - VarString = varString; - UnsignedInteger = unsignedInteger; - UnsignedLong = unsignedLong; - Uuid = uuid; + BinaryOption = binary; + DateTimeOption = dateTime; + VarDecimalOption = varDecimal; + VarDoubleOption = varDouble; + VarFloatOption = varFloat; + Int32Option = int32; + Int64Option = int64; + IntegerOption = integer; + PatternWithBackslashOption = patternWithBackslash; + PatternWithDigitsOption = patternWithDigits; + PatternWithDigitsAndDelimiterOption = patternWithDigitsAndDelimiter; + VarStringOption = varString; + UnsignedIntegerOption = unsignedInteger; + UnsignedLongOption = unsignedLong; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - /// /// Gets or Sets VarByte /// @@ -94,108 +89,219 @@ public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTi /// /// Sun Feb 02 00:00:00 UTC 2020 [JsonPropertyName("date")] - public DateTime Date { get; set; } + public DateOnly Date { get; set; } + + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public decimal Number { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Used to track the state of Binary + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BinaryOption { get; private set; } + + /// + /// Gets or Sets Binary + /// + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get { return this. BinaryOption; } set { this.BinaryOption = new(value); } } + + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } /// /// Gets or Sets DateTime /// /// 2007-12-03T10:15:30+01:00 [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of VarDecimal + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDecimalOption { get; private set; } /// /// Gets or Sets VarDecimal /// [JsonPropertyName("decimal")] - public decimal VarDecimal { get; set; } + public decimal? VarDecimal { get { return this. VarDecimalOption; } set { this.VarDecimalOption = new(value); } } + + /// + /// Used to track the state of VarDouble + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDoubleOption { get; private set; } /// /// Gets or Sets VarDouble /// [JsonPropertyName("double")] - public double VarDouble { get; set; } + public double? VarDouble { get { return this. VarDoubleOption; } set { this.VarDoubleOption = new(value); } } + + /// + /// Used to track the state of VarFloat + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarFloatOption { get; private set; } /// /// Gets or Sets VarFloat /// [JsonPropertyName("float")] - public float VarFloat { get; set; } + public float? VarFloat { get { return this. VarFloatOption; } set { this.VarFloatOption = new(value); } } + + /// + /// Used to track the state of Int32 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int32Option { get; private set; } /// /// Gets or Sets Int32 /// [JsonPropertyName("int32")] - public int Int32 { get; set; } + public int? Int32 { get { return this. Int32Option; } set { this.Int32Option = new(value); } } + + /// + /// Used to track the state of Int64 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int64Option { get; private set; } /// /// Gets or Sets Int64 /// [JsonPropertyName("int64")] - public long Int64 { get; set; } + public long? Int64 { get { return this. Int64Option; } set { this.Int64Option = new(value); } } /// - /// Gets or Sets Integer + /// Used to track the state of Integer /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerOption { get; private set; } /// - /// Gets or Sets Number + /// Gets or Sets Integer /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("integer")] + public int? Integer { get { return this. IntegerOption; } set { this.IntegerOption = new(value); } } /// - /// Gets or Sets Password + /// Used to track the state of PatternWithBackslash /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithBackslashOption { get; private set; } /// /// None /// /// None [JsonPropertyName("pattern_with_backslash")] - public string PatternWithBackslash { get; set; } + public string PatternWithBackslash { get { return this. PatternWithBackslashOption; } set { this.PatternWithBackslashOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigits + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsOption { get; private set; } /// /// A string that is a 10 digit number. Can have leading zeros. /// /// A string that is a 10 digit number. Can have leading zeros. [JsonPropertyName("pattern_with_digits")] - public string PatternWithDigits { get; set; } + public string PatternWithDigits { get { return this. PatternWithDigitsOption; } set { this.PatternWithDigitsOption = new(value); } } + + /// + /// Used to track the state of PatternWithDigitsAndDelimiter + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsAndDelimiterOption { get; private set; } /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. [JsonPropertyName("pattern_with_digits_and_delimiter")] - public string PatternWithDigitsAndDelimiter { get; set; } + public string PatternWithDigitsAndDelimiter { get { return this. PatternWithDigitsAndDelimiterOption; } set { this.PatternWithDigitsAndDelimiterOption = new(value); } } + + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public string VarString { get; set; } + public string VarString { get { return this. VarStringOption; } set { this.VarStringOption = new(value); } } + + /// + /// Used to track the state of UnsignedInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedIntegerOption { get; private set; } /// /// Gets or Sets UnsignedInteger /// [JsonPropertyName("unsigned_integer")] - public uint UnsignedInteger { get; set; } + public uint? UnsignedInteger { get { return this. UnsignedIntegerOption; } set { this.UnsignedIntegerOption = new(value); } } + + /// + /// Used to track the state of UnsignedLong + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedLongOption { get; private set; } /// /// Gets or Sets UnsignedLong /// [JsonPropertyName("unsigned_long")] - public ulong UnsignedLong { get; set; } + public ulong? UnsignedLong { get { return this. UnsignedLongOption; } set { this.UnsignedLongOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -211,9 +317,11 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" VarByte: ").Append(VarByte).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" VarDecimal: ").Append(VarDecimal).Append("\n"); sb.Append(" VarDouble: ").Append(VarDouble).Append("\n"); @@ -221,8 +329,6 @@ public override string ToString() sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" PatternWithBackslash: ").Append(PatternWithBackslash).Append("\n"); sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); @@ -242,122 +348,126 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + // VarDouble (double) maximum - if (this.VarDouble > (double)123.4) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value less than or equal to 123.4.", new [] { "VarDouble" }); } // VarDouble (double) minimum - if (this.VarDouble < (double)67.8) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value greater than or equal to 67.8.", new [] { "VarDouble" }); } // VarFloat (float) maximum - if (this.VarFloat > (float)987.6) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value less than or equal to 987.6.", new [] { "VarFloat" }); } // VarFloat (float) minimum - if (this.VarFloat < (float)54.3) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value greater than or equal to 54.3.", new [] { "VarFloat" }); } // Int32 (int) maximum - if (this.Int32 > (int)200) + if (this.Int32Option.IsSet && this.Int32Option.Value > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if (this.Int32 < (int)20) + if (this.Int32Option.IsSet && this.Int32Option.Value < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Integer (int) maximum - if (this.Integer > (int)100) + if (this.IntegerOption.IsSet && this.IntegerOption.Value > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if (this.Integer < (int)10) + if (this.IntegerOption.IsSet && this.IntegerOption.Value < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } - // Number (decimal) maximum - if (this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if (this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Password (string) maxLength - if (this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if (this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - if (this.PatternWithBackslash != null) { + if (this.PatternWithBackslashOption.Value != null) { // PatternWithBackslash (string) pattern Regex regexPatternWithBackslash = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$", RegexOptions.CultureInvariant); - if (!regexPatternWithBackslash.Match(this.PatternWithBackslash).Success) + + if (this.PatternWithBackslashOption.Value != null &&!regexPatternWithBackslash.Match(this.PatternWithBackslashOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithBackslash, must match a pattern of " + regexPatternWithBackslash, new [] { "PatternWithBackslash" }); } } - if (this.PatternWithDigits != null) { + if (this.PatternWithDigitsOption.Value != null) { // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\d{10}$", RegexOptions.CultureInvariant); - if (!regexPatternWithDigits.Match(this.PatternWithDigits).Success) + + if (this.PatternWithDigitsOption.Value != null &&!regexPatternWithDigits.Match(this.PatternWithDigitsOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); } } - if (this.PatternWithDigitsAndDelimiter != null) { + if (this.PatternWithDigitsAndDelimiterOption.Value != null) { // PatternWithDigitsAndDelimiter (string) pattern Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + + if (this.PatternWithDigitsAndDelimiterOption.Value != null &&!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiterOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } } - if (this.VarString != null) { + if (this.VarStringOption.Value != null) { // VarString (string) pattern Regex regexVarString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexVarString.Match(this.VarString).Success) + + if (this.VarStringOption.Value != null &&!regexVarString.Match(this.VarStringOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarString, must match a pattern of " + regexVarString, new [] { "VarString" }); } } // UnsignedInteger (uint) maximum - if (this.UnsignedInteger > (uint)200) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value > (uint)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value less than or equal to 200.", new [] { "UnsignedInteger" }); } // UnsignedInteger (uint) minimum - if (this.UnsignedInteger < (uint)20) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value < (uint)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value greater than or equal to 20.", new [] { "UnsignedInteger" }); } @@ -398,25 +508,25 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - System.IO.Stream binary = default; - byte[] varByte = default; - DateTime? date = default; - DateTime? dateTime = default; - decimal? varDecimal = default; - double? varDouble = default; - float? varFloat = default; - int? int32 = default; - long? int64 = default; - int? integer = default; - decimal? number = default; - string password = default; - string patternWithBackslash = default; - string patternWithDigits = default; - string patternWithDigitsAndDelimiter = default; - string varString = default; - uint? unsignedInteger = default; - ulong? unsignedLong = default; - Guid? uuid = default; + Option varByte = default; + Option date = default; + Option number = default; + Option password = default; + Option binary = default; + Option dateTime = default; + Option varDecimal = default; + Option varDouble = default; + Option varFloat = default; + Option int32 = default; + Option int64 = default; + Option integer = default; + Option patternWithBackslash = default; + Option patternWithDigits = default; + Option patternWithDigitsAndDelimiter = default; + Option varString = default; + Option unsignedInteger = default; + Option unsignedLong = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -433,76 +543,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { - case "binary": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - binary = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; case "byte": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varByte = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varByte = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "date": if (utf8JsonReader.TokenType != JsonTokenType.Null) - date = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + number = new Option(utf8JsonReader.GetDecimal()); + break; + case "password": + password = new Option(utf8JsonReader.GetString()); + break; + case "binary": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + binary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "decimal": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDecimal = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varDecimal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "double": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDouble = utf8JsonReader.GetDouble(); + varDouble = new Option(utf8JsonReader.GetDouble()); break; case "float": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varFloat = (float)utf8JsonReader.GetDouble(); + varFloat = new Option((float)utf8JsonReader.GetDouble()); break; case "int32": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int32 = utf8JsonReader.GetInt32(); + int32 = new Option(utf8JsonReader.GetInt32()); break; case "int64": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int64 = utf8JsonReader.GetInt64(); + int64 = new Option(utf8JsonReader.GetInt64()); break; case "integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integer = utf8JsonReader.GetInt32(); - break; - case "number": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - number = utf8JsonReader.GetDecimal(); - break; - case "password": - password = utf8JsonReader.GetString(); + integer = new Option(utf8JsonReader.GetInt32()); break; case "pattern_with_backslash": - patternWithBackslash = utf8JsonReader.GetString(); + patternWithBackslash = new Option(utf8JsonReader.GetString()); break; case "pattern_with_digits": - patternWithDigits = utf8JsonReader.GetString(); + patternWithDigits = new Option(utf8JsonReader.GetString()); break; case "pattern_with_digits_and_delimiter": - patternWithDigitsAndDelimiter = utf8JsonReader.GetString(); + patternWithDigitsAndDelimiter = new Option(utf8JsonReader.GetString()); break; case "string": - varString = utf8JsonReader.GetString(); + varString = new Option(utf8JsonReader.GetString()); break; case "unsigned_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedInteger = utf8JsonReader.GetUInt32(); + unsignedInteger = new Option(utf8JsonReader.GetUInt32()); break; case "unsigned_long": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedLong = utf8JsonReader.GetUInt64(); + unsignedLong = new Option(utf8JsonReader.GetUInt64()); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -510,64 +620,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (binary == null) - throw new ArgumentNullException(nameof(binary), "Property is required for class FormatTest."); + if (!varByte.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(varByte)); + + if (!date.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(date)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(number)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(password)); - if (varByte == null) - throw new ArgumentNullException(nameof(varByte), "Property is required for class FormatTest."); + if (varByte.IsSet && varByte.Value == null) + throw new ArgumentNullException(nameof(varByte), "Property is not nullable for class FormatTest."); - if (date == null) - throw new ArgumentNullException(nameof(date), "Property is required for class FormatTest."); + if (date.IsSet && date.Value == null) + throw new ArgumentNullException(nameof(date), "Property is not nullable for class FormatTest."); - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class FormatTest."); + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class FormatTest."); - if (varDecimal == null) - throw new ArgumentNullException(nameof(varDecimal), "Property is required for class FormatTest."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class FormatTest."); - if (varDouble == null) - throw new ArgumentNullException(nameof(varDouble), "Property is required for class FormatTest."); + if (binary.IsSet && binary.Value == null) + throw new ArgumentNullException(nameof(binary), "Property is not nullable for class FormatTest."); - if (varFloat == null) - throw new ArgumentNullException(nameof(varFloat), "Property is required for class FormatTest."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class FormatTest."); - if (int32 == null) - throw new ArgumentNullException(nameof(int32), "Property is required for class FormatTest."); + if (varDecimal.IsSet && varDecimal.Value == null) + throw new ArgumentNullException(nameof(varDecimal), "Property is not nullable for class FormatTest."); - if (int64 == null) - throw new ArgumentNullException(nameof(int64), "Property is required for class FormatTest."); + if (varDouble.IsSet && varDouble.Value == null) + throw new ArgumentNullException(nameof(varDouble), "Property is not nullable for class FormatTest."); - if (integer == null) - throw new ArgumentNullException(nameof(integer), "Property is required for class FormatTest."); + if (varFloat.IsSet && varFloat.Value == null) + throw new ArgumentNullException(nameof(varFloat), "Property is not nullable for class FormatTest."); - if (number == null) - throw new ArgumentNullException(nameof(number), "Property is required for class FormatTest."); + if (int32.IsSet && int32.Value == null) + throw new ArgumentNullException(nameof(int32), "Property is not nullable for class FormatTest."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class FormatTest."); + if (int64.IsSet && int64.Value == null) + throw new ArgumentNullException(nameof(int64), "Property is not nullable for class FormatTest."); - if (patternWithBackslash == null) - throw new ArgumentNullException(nameof(patternWithBackslash), "Property is required for class FormatTest."); + if (integer.IsSet && integer.Value == null) + throw new ArgumentNullException(nameof(integer), "Property is not nullable for class FormatTest."); - if (patternWithDigits == null) - throw new ArgumentNullException(nameof(patternWithDigits), "Property is required for class FormatTest."); + if (patternWithBackslash.IsSet && patternWithBackslash.Value == null) + throw new ArgumentNullException(nameof(patternWithBackslash), "Property is not nullable for class FormatTest."); - if (patternWithDigitsAndDelimiter == null) - throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + if (patternWithDigits.IsSet && patternWithDigits.Value == null) + throw new ArgumentNullException(nameof(patternWithDigits), "Property is not nullable for class FormatTest."); - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FormatTest."); + if (patternWithDigitsAndDelimiter.IsSet && patternWithDigitsAndDelimiter.Value == null) + throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is not nullable for class FormatTest."); - if (unsignedInteger == null) - throw new ArgumentNullException(nameof(unsignedInteger), "Property is required for class FormatTest."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FormatTest."); - if (unsignedLong == null) - throw new ArgumentNullException(nameof(unsignedLong), "Property is required for class FormatTest."); + if (unsignedInteger.IsSet && unsignedInteger.Value == null) + throw new ArgumentNullException(nameof(unsignedInteger), "Property is not nullable for class FormatTest."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class FormatTest."); + if (unsignedLong.IsSet && unsignedLong.Value == null) + throw new ArgumentNullException(nameof(unsignedLong), "Property is not nullable for class FormatTest."); - return new FormatTest(binary, varByte, date.Value, dateTime.Value, varDecimal.Value, varDouble.Value, varFloat.Value, int32.Value, int64.Value, integer.Value, number.Value, password, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger.Value, unsignedLong.Value, uuid.Value); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class FormatTest."); + + return new FormatTest(varByte.Value, date.Value.Value, number.Value.Value, password.Value, binary, dateTime, varDecimal, varDouble, varFloat, int32, int64, integer, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger, unsignedLong, uuid); } /// @@ -594,28 +716,83 @@ public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("binary"); - JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + if (formatTest.VarByte == null) + throw new ArgumentNullException(nameof(formatTest.VarByte), "Property is required for class FormatTest."); + + if (formatTest.Password == null) + throw new ArgumentNullException(nameof(formatTest.Password), "Property is required for class FormatTest."); + + if (formatTest.BinaryOption.IsSet && formatTest.Binary == null) + throw new ArgumentNullException(nameof(formatTest.Binary), "Property is required for class FormatTest."); + + if (formatTest.PatternWithBackslashOption.IsSet && formatTest.PatternWithBackslash == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithBackslash), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsOption.IsSet && formatTest.PatternWithDigits == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigits), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet && formatTest.PatternWithDigitsAndDelimiter == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + + if (formatTest.VarStringOption.IsSet && formatTest.VarString == null) + throw new ArgumentNullException(nameof(formatTest.VarString), "Property is required for class FormatTest."); + writer.WritePropertyName("byte"); JsonSerializer.Serialize(writer, formatTest.VarByte, jsonSerializerOptions); writer.WriteString("date", formatTest.Date.ToString(DateFormat)); - writer.WriteString("dateTime", formatTest.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("decimal"); - JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); - writer.WriteNumber("double", formatTest.VarDouble); - writer.WriteNumber("float", formatTest.VarFloat); - writer.WriteNumber("int32", formatTest.Int32); - writer.WriteNumber("int64", formatTest.Int64); - writer.WriteNumber("integer", formatTest.Integer); + writer.WriteNumber("number", formatTest.Number); + writer.WriteString("password", formatTest.Password); - writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); - writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); - writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); - writer.WriteString("string", formatTest.VarString); - writer.WriteNumber("unsigned_integer", formatTest.UnsignedInteger); - writer.WriteNumber("unsigned_long", formatTest.UnsignedLong); - writer.WriteString("uuid", formatTest.Uuid); + + if (formatTest.BinaryOption.IsSet) + { + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + } + if (formatTest.DateTimeOption.IsSet) + writer.WriteString("dateTime", formatTest.DateTimeOption.Value.Value.ToString(DateTimeFormat)); + + if (formatTest.VarDecimalOption.IsSet) + { + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); + } + if (formatTest.VarDoubleOption.IsSet) + writer.WriteNumber("double", formatTest.VarDoubleOption.Value.Value); + + if (formatTest.VarFloatOption.IsSet) + writer.WriteNumber("float", formatTest.VarFloatOption.Value.Value); + + if (formatTest.Int32Option.IsSet) + writer.WriteNumber("int32", formatTest.Int32Option.Value.Value); + + if (formatTest.Int64Option.IsSet) + writer.WriteNumber("int64", formatTest.Int64Option.Value.Value); + + if (formatTest.IntegerOption.IsSet) + writer.WriteNumber("integer", formatTest.IntegerOption.Value.Value); + + if (formatTest.PatternWithBackslashOption.IsSet) + writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); + + if (formatTest.PatternWithDigitsOption.IsSet) + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet) + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + + if (formatTest.VarStringOption.IsSet) + writer.WriteString("string", formatTest.VarString); + + if (formatTest.UnsignedIntegerOption.IsSet) + writer.WriteNumber("unsigned_integer", formatTest.UnsignedIntegerOption.Value.Value); + + if (formatTest.UnsignedLongOption.IsSet) + writer.WriteNumber("unsigned_long", formatTest.UnsignedLongOption.Value.Value); + + if (formatTest.UuidOption.IsSet) + writer.WriteString("uuid", formatTest.UuidOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs index 2e05ffb958a4..ea23d8efc424 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Fruit.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,10 +34,10 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple apple, string color) + public Fruit(Apple apple, Option color = default) { Apple = apple; - Color = color; + ColorOption = color; OnCreated(); } @@ -45,10 +46,10 @@ public Fruit(Apple apple, string color) /// /// /// color - public Fruit(Banana banana, string color) + public Fruit(Banana banana, Option color = default) { Banana = banana; - Color = color; + ColorOption = color; OnCreated(); } @@ -64,11 +65,18 @@ public Fruit(Banana banana, string color) /// public Banana Banana { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -116,7 +124,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string color = default; + Option color = default; Apple apple = default; Banana banana = default; @@ -156,7 +164,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -164,8 +172,8 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); if (apple != null) return new Fruit(apple, color); @@ -200,7 +208,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs index aa26d3600c05..75652a1b436e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/FruitReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs index 3c2d1ecefc94..fc6e5a9a4574 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GmFruit.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,31 +35,52 @@ public partial class GmFruit : IValidatableObject /// /// /// color - public GmFruit(Apple apple, Banana banana, string color) + public GmFruit(Option apple, Option banana, Option color = default) { - Apple = apple; - Banana = banana; - Color = color; + AppleOption = apple; + BananaOption = banana; + ColorOption = color; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Apple + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AppleOption { get; private set; } + /// /// Gets or Sets Apple /// - public Apple Apple { get; set; } + public Apple Apple { get { return this.AppleOption; } set { this.AppleOption = new(value); } } + + /// + /// Used to track the state of Banana + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BananaOption { get; private set; } /// /// Gets or Sets Banana /// - public Banana Banana { get; set; } + public Banana Banana { get { return this.BananaOption; } set { this.BananaOption = new(value); } } + + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Returns the string presentation of the object @@ -106,7 +128,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string color = default; + Option color = default; Apple apple = default; Banana banana = default; @@ -146,7 +168,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -154,10 +176,17 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class GmFruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class GmFruit."); - return new GmFruit(apple, banana, color); + Option appleParsedValue = apple == null + ? default + : new Option(apple); + Option bananaParsedValue = banana == null + ? default + : new Option(banana); + + return new GmFruit(appleParsedValue, bananaParsedValue, color); } /// @@ -171,16 +200,16 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize { writer.WriteStartObject(); - if (gmFruit.Apple != null) + if (gmFruit.AppleOption.IsSet && gmFruit.AppleOption.Value != null) { - AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Apple.GetType())); - AppleJsonConverter.WriteProperties(ref writer, gmFruit.Apple, jsonSerializerOptions); + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.AppleOption.Value.GetType())); + AppleJsonConverter.WriteProperties(ref writer, gmFruit.AppleOption.Value, jsonSerializerOptions); } - if (gmFruit.Banana != null) + if (gmFruit.BananaOption.IsSet && gmFruit.BananaOption.Value != null) { - BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Banana.GetType())); - BananaJsonConverter.WriteProperties(ref writer, gmFruit.Banana, jsonSerializerOptions); + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.BananaOption.Value.GetType())); + BananaJsonConverter.WriteProperties(ref writer, gmFruit.BananaOption.Value, jsonSerializerOptions); } WriteProperties(ref writer, gmFruit, jsonSerializerOptions); @@ -196,7 +225,11 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", gmFruit.Color); + if (gmFruit.ColorOption.IsSet && gmFruit.Color == null) + throw new ArgumentNullException(nameof(gmFruit.Color), "Property is required for class GmFruit."); + + if (gmFruit.ColorOption.IsSet) + writer.WriteString("color", gmFruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 7ae4662ed8d4..6b7d7ae8da68 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -110,7 +111,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -128,7 +129,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -136,10 +137,13 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class GrandparentAnimal."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class GrandparentAnimal.", nameof(petType)); - return new GrandparentAnimal(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class GrandparentAnimal."); + + return new GrandparentAnimal(petType.Value); } /// @@ -166,6 +170,9 @@ public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentA /// public void WriteProperties(ref Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) { + if (grandparentAnimal.PetType == null) + throw new ArgumentNullException(nameof(grandparentAnimal.PetType), "Property is required for class GrandparentAnimal."); + writer.WriteString("pet_type", grandparentAnimal.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 31360d73f754..9652b767d130 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class HasOnlyReadOnly : IEquatable, IValidatable /// bar /// foo [JsonConstructor] - internal HasOnlyReadOnly(string bar, string foo) + internal HasOnlyReadOnly(Option bar = default, Option foo = default) { - Bar = bar; - Foo = foo; + BarOption = bar; + FooOption = foo; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Foo + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FooOption { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; } + public string Foo { get { return this. FooOption; } } /// /// Gets or Sets additional properties @@ -105,8 +120,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); - hashCode = (hashCode * 59) + Foo.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + + if (Foo != null) + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -146,8 +165,8 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; - string foo = default; + Option bar = default; + Option foo = default; while (utf8JsonReader.Read()) { @@ -165,10 +184,10 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; case "foo": - foo = utf8JsonReader.GetString(); + foo = new Option(utf8JsonReader.GetString()); break; default: break; @@ -176,11 +195,11 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class HasOnlyReadOnly."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class HasOnlyReadOnly."); - if (foo == null) - throw new ArgumentNullException(nameof(foo), "Property is required for class HasOnlyReadOnly."); + if (foo.IsSet && foo.Value == null) + throw new ArgumentNullException(nameof(foo), "Property is not nullable for class HasOnlyReadOnly."); return new HasOnlyReadOnly(bar, foo); } @@ -209,8 +228,17 @@ public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnl /// public void WriteProperties(ref Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", hasOnlyReadOnly.Bar); - writer.WriteString("foo", hasOnlyReadOnly.Foo); + if (hasOnlyReadOnly.BarOption.IsSet && hasOnlyReadOnly.Bar == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Bar), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.FooOption.IsSet && hasOnlyReadOnly.Foo == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Foo), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.BarOption.IsSet) + writer.WriteString("bar", hasOnlyReadOnly.Bar); + + if (hasOnlyReadOnly.FooOption.IsSet) + writer.WriteString("foo", hasOnlyReadOnly.Foo); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 8355d97fa097..4931d3d73fe5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class HealthCheckResult : IValidatableObject /// /// nullableMessage [JsonConstructor] - public HealthCheckResult(string nullableMessage = default) + public HealthCheckResult(Option nullableMessage = default) { - NullableMessage = nullableMessage; + NullableMessageOption = nullableMessage; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of NullableMessage + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableMessageOption { get; private set; } + /// /// Gets or Sets NullableMessage /// [JsonPropertyName("NullableMessage")] - public string NullableMessage { get; set; } + public string NullableMessage { get { return this. NullableMessageOption; } set { this.NullableMessageOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string nullableMessage = default; + Option nullableMessage = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "NullableMessage": - nullableMessage = utf8JsonReader.GetString(); + nullableMessage = new Option(utf8JsonReader.GetString()); break; default: break; @@ -153,7 +161,11 @@ public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckR /// public void WriteProperties(ref Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + if (healthCheckResult.NullableMessageOption.IsSet) + if (healthCheckResult.NullableMessageOption.Value != null) + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + else + writer.WriteNull("NullableMessage"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 0355613042f2..3f4aa3229c4e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,8 +103,8 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -121,10 +122,10 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -132,13 +133,19 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class IsoscelesTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class IsoscelesTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(triangleType)); - return new IsoscelesTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class IsoscelesTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class IsoscelesTriangle."); + + return new IsoscelesTriangle(shapeType.Value, triangleType.Value); } /// @@ -165,7 +172,14 @@ public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTri /// public void WriteProperties(ref Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (isoscelesTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.ShapeType), "Property is required for class IsoscelesTriangle."); + + if (isoscelesTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.TriangleType), "Property is required for class IsoscelesTriangle."); + writer.WriteString("shapeType", isoscelesTriangle.ShapeType); + writer.WriteString("triangleType", isoscelesTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs index 42b0c9cb2cf1..5d0425e77695 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/List.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class List : IValidatableObject /// /// var123List [JsonConstructor] - public List(string var123List) + public List(Option var123List = default) { - Var123List = var123List; + Var123ListOption = var123List; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Var123List + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123ListOption { get; private set; } + /// /// Gets or Sets Var123List /// [JsonPropertyName("123-list")] - public string Var123List { get; set; } + public string Var123List { get { return this. Var123ListOption; } set { this.Var123ListOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string var123List = default; + Option var123List = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "123-list": - var123List = utf8JsonReader.GetString(); + var123List = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (var123List == null) - throw new ArgumentNullException(nameof(var123List), "Property is required for class List."); + if (var123List.IsSet && var123List.Value == null) + throw new ArgumentNullException(nameof(var123List), "Property is not nullable for class List."); return new List(var123List); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("123-list", list.Var123List); + if (list.Var123ListOption.IsSet && list.Var123List == null) + throw new ArgumentNullException(nameof(list.Var123List), "Property is required for class List."); + + if (list.Var123ListOption.IsSet) + writer.WriteString("123-list", list.Var123List); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs index 0ad8832af885..f5e9d77e61c3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class LiteralStringClass : IValidatableObject /// escapedLiteralString (default to "C:\\Users\\username") /// unescapedLiteralString (default to "C:\Users\username") [JsonConstructor] - public LiteralStringClass(string escapedLiteralString = @"C:\\Users\\username", string unescapedLiteralString = @"C:\Users\username") + public LiteralStringClass(Option escapedLiteralString = default, Option unescapedLiteralString = default) { - EscapedLiteralString = escapedLiteralString; - UnescapedLiteralString = unescapedLiteralString; + EscapedLiteralStringOption = escapedLiteralString; + UnescapedLiteralStringOption = unescapedLiteralString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of EscapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EscapedLiteralStringOption { get; private set; } + /// /// Gets or Sets EscapedLiteralString /// [JsonPropertyName("escapedLiteralString")] - public string EscapedLiteralString { get; set; } + public string EscapedLiteralString { get { return this. EscapedLiteralStringOption; } set { this.EscapedLiteralStringOption = new(value); } } + + /// + /// Used to track the state of UnescapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnescapedLiteralStringOption { get; private set; } /// /// Gets or Sets UnescapedLiteralString /// [JsonPropertyName("unescapedLiteralString")] - public string UnescapedLiteralString { get; set; } + public string UnescapedLiteralString { get { return this. UnescapedLiteralStringOption; } set { this.UnescapedLiteralStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string escapedLiteralString = default; - string unescapedLiteralString = default; + Option escapedLiteralString = default; + Option unescapedLiteralString = default; while (utf8JsonReader.Read()) { @@ -128,10 +143,10 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "escapedLiteralString": - escapedLiteralString = utf8JsonReader.GetString(); + escapedLiteralString = new Option(utf8JsonReader.GetString()); break; case "unescapedLiteralString": - unescapedLiteralString = utf8JsonReader.GetString(); + unescapedLiteralString = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,11 +154,11 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (escapedLiteralString == null) - throw new ArgumentNullException(nameof(escapedLiteralString), "Property is required for class LiteralStringClass."); + if (escapedLiteralString.IsSet && escapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(escapedLiteralString), "Property is not nullable for class LiteralStringClass."); - if (unescapedLiteralString == null) - throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is required for class LiteralStringClass."); + if (unescapedLiteralString.IsSet && unescapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is not nullable for class LiteralStringClass."); return new LiteralStringClass(escapedLiteralString, unescapedLiteralString); } @@ -172,8 +187,17 @@ public override void Write(Utf8JsonWriter writer, LiteralStringClass literalStri /// public void WriteProperties(ref Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); - writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); + if (literalStringClass.EscapedLiteralStringOption.IsSet && literalStringClass.EscapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.EscapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet && literalStringClass.UnescapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.UnescapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.EscapedLiteralStringOption.IsSet) + writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet) + writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs index 92011ad0e1d9..1ea0d944f050 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Mammal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -150,7 +151,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; Pig pig = null; Whale whale = null; @@ -207,7 +208,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -215,17 +216,20 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Mammal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Mammal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Mammal."); if (pig != null) - return new Mammal(pig, className); + return new Mammal(pig, className.Value); if (whale != null) - return new Mammal(whale, className); + return new Mammal(whale, className.Value); if (zebra != null) - return new Mammal(zebra, className); + return new Mammal(zebra, className.Value); throw new JsonException(); } @@ -269,6 +273,9 @@ public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) { + if (mammal.ClassName == null) + throw new ArgumentNullException(nameof(mammal.ClassName), "Property is required for class Mammal."); + writer.WriteString("className", mammal.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs index c99356fbf3a8..0459a633accb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,12 +37,12 @@ public partial class MapTest : IValidatableObject /// mapMapOfString /// mapOfEnumString [JsonConstructor] - public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) + public MapTest(Option> directMap = default, Option> indirectMap = default, Option>> mapMapOfString = default, Option> mapOfEnumString = default) { - DirectMap = directMap; - IndirectMap = indirectMap; - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; + DirectMapOption = directMap; + IndirectMapOption = indirectMap; + MapMapOfStringOption = mapMapOfString; + MapOfEnumStringOption = mapOfEnumString; OnCreated(); } @@ -113,29 +114,57 @@ public static string InnerEnumToJsonValue(InnerEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of DirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> DirectMapOption { get; private set; } + /// /// Gets or Sets DirectMap /// [JsonPropertyName("direct_map")] - public Dictionary DirectMap { get; set; } + public Dictionary DirectMap { get { return this. DirectMapOption; } set { this.DirectMapOption = new(value); } } + + /// + /// Used to track the state of IndirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> IndirectMapOption { get; private set; } /// /// Gets or Sets IndirectMap /// [JsonPropertyName("indirect_map")] - public Dictionary IndirectMap { get; set; } + public Dictionary IndirectMap { get { return this. IndirectMapOption; } set { this.IndirectMapOption = new(value); } } + + /// + /// Used to track the state of MapMapOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> MapMapOfStringOption { get; private set; } /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + public Dictionary> MapMapOfString { get { return this. MapMapOfStringOption; } set { this.MapMapOfStringOption = new(value); } } + + /// + /// Used to track the state of MapOfEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapOfEnumStringOption { get; private set; } /// /// Gets or Sets MapOfEnumString /// [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + public Dictionary MapOfEnumString { get { return this. MapOfEnumStringOption; } set { this.MapOfEnumStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -193,10 +222,10 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary directMap = default; - Dictionary indirectMap = default; - Dictionary> mapMapOfString = default; - Dictionary mapOfEnumString = default; + Option> directMap = default; + Option> indirectMap = default; + Option>> mapMapOfString = default; + Option> mapOfEnumString = default; while (utf8JsonReader.Read()) { @@ -215,19 +244,19 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "direct_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - directMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + directMap = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "indirect_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - indirectMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + indirectMap = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_map_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapMapOfString = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapMapOfString = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_of_enum_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfEnumString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapOfEnumString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -235,17 +264,17 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (directMap == null) - throw new ArgumentNullException(nameof(directMap), "Property is required for class MapTest."); + if (directMap.IsSet && directMap.Value == null) + throw new ArgumentNullException(nameof(directMap), "Property is not nullable for class MapTest."); - if (indirectMap == null) - throw new ArgumentNullException(nameof(indirectMap), "Property is required for class MapTest."); + if (indirectMap.IsSet && indirectMap.Value == null) + throw new ArgumentNullException(nameof(indirectMap), "Property is not nullable for class MapTest."); - if (mapMapOfString == null) - throw new ArgumentNullException(nameof(mapMapOfString), "Property is required for class MapTest."); + if (mapMapOfString.IsSet && mapMapOfString.Value == null) + throw new ArgumentNullException(nameof(mapMapOfString), "Property is not nullable for class MapTest."); - if (mapOfEnumString == null) - throw new ArgumentNullException(nameof(mapOfEnumString), "Property is required for class MapTest."); + if (mapOfEnumString.IsSet && mapOfEnumString.Value == null) + throw new ArgumentNullException(nameof(mapOfEnumString), "Property is not nullable for class MapTest."); return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); } @@ -274,14 +303,38 @@ public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("direct_map"); - JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); - writer.WritePropertyName("indirect_map"); - JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); - writer.WritePropertyName("map_map_of_string"); - JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); - writer.WritePropertyName("map_of_enum_string"); - JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + if (mapTest.DirectMapOption.IsSet && mapTest.DirectMap == null) + throw new ArgumentNullException(nameof(mapTest.DirectMap), "Property is required for class MapTest."); + + if (mapTest.IndirectMapOption.IsSet && mapTest.IndirectMap == null) + throw new ArgumentNullException(nameof(mapTest.IndirectMap), "Property is required for class MapTest."); + + if (mapTest.MapMapOfStringOption.IsSet && mapTest.MapMapOfString == null) + throw new ArgumentNullException(nameof(mapTest.MapMapOfString), "Property is required for class MapTest."); + + if (mapTest.MapOfEnumStringOption.IsSet && mapTest.MapOfEnumString == null) + throw new ArgumentNullException(nameof(mapTest.MapOfEnumString), "Property is required for class MapTest."); + + if (mapTest.DirectMapOption.IsSet) + { + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); + } + if (mapTest.IndirectMapOption.IsSet) + { + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); + } + if (mapTest.MapMapOfStringOption.IsSet) + { + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); + } + if (mapTest.MapOfEnumStringOption.IsSet) + { + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 0ed70f02c2db..99d8e1c2fffe 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,40 +37,68 @@ public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableO /// uuid /// uuidWithPattern [JsonConstructor] - public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid, Guid uuidWithPattern) + public MixedPropertiesAndAdditionalPropertiesClass(Option dateTime = default, Option> map = default, Option uuid = default, Option uuidWithPattern = default) { - DateTime = dateTime; - Map = map; - Uuid = uuid; - UuidWithPattern = uuidWithPattern; + DateTimeOption = dateTime; + MapOption = map; + UuidOption = uuid; + UuidWithPatternOption = uuidWithPattern; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } + /// /// Gets or Sets DateTime /// [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new(value); } } + + /// + /// Used to track the state of Map + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapOption { get; private set; } /// /// Gets or Sets Map /// [JsonPropertyName("map")] - public Dictionary Map { get; set; } + public Dictionary Map { get { return this. MapOption; } set { this.MapOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } + + /// + /// Used to track the state of UuidWithPattern + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidWithPatternOption { get; private set; } /// /// Gets or Sets UuidWithPattern /// [JsonPropertyName("uuid_with_pattern")] - public Guid UuidWithPattern { get; set; } + public Guid? UuidWithPattern { get { return this. UuidWithPatternOption; } set { this.UuidWithPatternOption = new(value); } } /// /// Gets or Sets additional properties @@ -103,7 +132,8 @@ public override string ToString() { // UuidWithPattern (Guid) pattern Regex regexUuidWithPattern = new Regex(@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOptions.CultureInvariant); - if (!regexUuidWithPattern.Match(this.UuidWithPattern.ToString()).Success) + + if (this.UuidWithPatternOption.Value != null &&!regexUuidWithPattern.Match(this.UuidWithPatternOption.Value.ToString()).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UuidWithPattern, must match a pattern of " + regexUuidWithPattern, new [] { "UuidWithPattern" }); } @@ -138,10 +168,10 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateTime = default; - Dictionary map = default; - Guid? uuid = default; - Guid? uuidWithPattern = default; + Option dateTime = default; + Option> map = default; + Option uuid = default; + Option uuidWithPattern = default; while (utf8JsonReader.Read()) { @@ -160,19 +190,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea { case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - map = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + map = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; case "uuid_with_pattern": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuidWithPattern = utf8JsonReader.GetGuid(); + uuidWithPattern = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -180,19 +210,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea } } - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (map == null) - throw new ArgumentNullException(nameof(map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (map.IsSet && map.Value == null) + throw new ArgumentNullException(nameof(map), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuidWithPattern == null) - throw new ArgumentNullException(nameof(uuidWithPattern), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuidWithPattern.IsSet && uuidWithPattern.Value == null) + throw new ArgumentNullException(nameof(uuidWithPattern), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - return new MixedPropertiesAndAdditionalPropertiesClass(dateTime.Value, map, uuid.Value, uuidWithPattern.Value); + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid, uuidWithPattern); } /// @@ -219,11 +249,22 @@ public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("map"); - JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); - writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); - writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPattern); + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet && mixedPropertiesAndAdditionalPropertiesClass.Map == null) + throw new ArgumentNullException(nameof(mixedPropertiesAndAdditionalPropertiesClass.Map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.IsSet) + writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.Value.Value.ToString(DateTimeFormat)); + + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet) + { + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); + } + if (mixedPropertiesAndAdditionalPropertiesClass.UuidOption.IsSet) + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.UuidOption.Value.Value); + + if (mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.IsSet) + writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs index 7969b9ae04ed..5defbb2c2fda 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Model200Response.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class Model200Response : IValidatableObject /// varClass /// name [JsonConstructor] - public Model200Response(string varClass, int name) + public Model200Response(Option varClass = default, Option name = default) { - VarClass = varClass; - Name = name; + VarClassOption = varClass; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("class")] - public string VarClass { get; set; } + public string VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public int Name { get; set; } + public int? Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClass = default; - int? name = default; + Option varClass = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()); break; case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - name = utf8JsonReader.GetInt32(); + name = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -140,13 +155,13 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class Model200Response."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class Model200Response."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Model200Response."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Model200Response."); - return new Model200Response(varClass, name.Value); + return new Model200Response(varClass, name); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, Model200Response model200Respo /// public void WriteProperties(ref Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("class", model200Response.VarClass); - writer.WriteNumber("name", model200Response.Name); + if (model200Response.VarClassOption.IsSet && model200Response.VarClass == null) + throw new ArgumentNullException(nameof(model200Response.VarClass), "Property is required for class Model200Response."); + + if (model200Response.VarClassOption.IsSet) + writer.WriteString("class", model200Response.VarClass); + + if (model200Response.NameOption.IsSet) + writer.WriteNumber("name", model200Response.NameOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs index 810a6a01b8e9..7a2677d7e7f6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ModelClient.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ModelClient : IValidatableObject /// /// varClient [JsonConstructor] - public ModelClient(string varClient) + public ModelClient(Option varClient = default) { - VarClient = varClient; + VarClientOption = varClient; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClient + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClientOption { get; private set; } + /// /// Gets or Sets VarClient /// [JsonPropertyName("client")] - public string VarClient { get; set; } + public string VarClient { get { return this. VarClientOption; } set { this.VarClientOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClient = default; + Option varClient = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "client": - varClient = utf8JsonReader.GetString(); + varClient = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (varClient == null) - throw new ArgumentNullException(nameof(varClient), "Property is required for class ModelClient."); + if (varClient.IsSet && varClient.Value == null) + throw new ArgumentNullException(nameof(varClient), "Property is not nullable for class ModelClient."); return new ModelClient(varClient); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("client", modelClient.VarClient); + if (modelClient.VarClientOption.IsSet && modelClient.VarClient == null) + throw new ArgumentNullException(nameof(modelClient.VarClient), "Property is required for class ModelClient."); + + if (modelClient.VarClientOption.IsSet) + writer.WriteString("client", modelClient.VarClient); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs index edcb6b3403c7..4651bf76c2ce 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Name.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,12 +37,12 @@ public partial class Name : IEquatable, IValidatableObject /// snakeCase /// var123Number [JsonConstructor] - public Name(int varName, string property, int snakeCase, int var123Number) + public Name(int varName, Option property = default, Option snakeCase = default, Option var123Number = default) { VarName = varName; - Property = property; - SnakeCase = snakeCase; - Var123Number = var123Number; + PropertyOption = property; + SnakeCaseOption = snakeCase; + Var123NumberOption = var123Number; OnCreated(); } @@ -53,23 +54,44 @@ public Name(int varName, string property, int snakeCase, int var123Number) [JsonPropertyName("name")] public int VarName { get; set; } + /// + /// Used to track the state of Property + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PropertyOption { get; private set; } + /// /// Gets or Sets Property /// [JsonPropertyName("property")] - public string Property { get; set; } + public string Property { get { return this. PropertyOption; } set { this.PropertyOption = new(value); } } + + /// + /// Used to track the state of SnakeCase + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SnakeCaseOption { get; } /// /// Gets or Sets SnakeCase /// [JsonPropertyName("snake_case")] - public int SnakeCase { get; } + public int? SnakeCase { get { return this. SnakeCaseOption; } } + + /// + /// Used to track the state of Var123Number + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123NumberOption { get; } /// /// Gets or Sets Var123Number /// [JsonPropertyName("123Number")] - public int Var123Number { get; } + public int? Var123Number { get { return this. Var123NumberOption; } } /// /// Gets or Sets additional properties @@ -123,8 +145,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); - hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + if (SnakeCase != null) + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + + if (Var123Number != null) + hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -164,10 +190,10 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varName = default; - string property = default; - int? snakeCase = default; - int? var123Number = default; + Option varName = default; + Option property = default; + Option snakeCase = default; + Option var123Number = default; while (utf8JsonReader.Read()) { @@ -186,18 +212,18 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varName = utf8JsonReader.GetInt32(); + varName = new Option(utf8JsonReader.GetInt32()); break; case "property": - property = utf8JsonReader.GetString(); + property = new Option(utf8JsonReader.GetString()); break; case "snake_case": if (utf8JsonReader.TokenType != JsonTokenType.Null) - snakeCase = utf8JsonReader.GetInt32(); + snakeCase = new Option(utf8JsonReader.GetInt32()); break; case "123Number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - var123Number = utf8JsonReader.GetInt32(); + var123Number = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -205,19 +231,22 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (varName == null) - throw new ArgumentNullException(nameof(varName), "Property is required for class Name."); + if (!varName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(varName)); + + if (varName.IsSet && varName.Value == null) + throw new ArgumentNullException(nameof(varName), "Property is not nullable for class Name."); - if (property == null) - throw new ArgumentNullException(nameof(property), "Property is required for class Name."); + if (property.IsSet && property.Value == null) + throw new ArgumentNullException(nameof(property), "Property is not nullable for class Name."); - if (snakeCase == null) - throw new ArgumentNullException(nameof(snakeCase), "Property is required for class Name."); + if (snakeCase.IsSet && snakeCase.Value == null) + throw new ArgumentNullException(nameof(snakeCase), "Property is not nullable for class Name."); - if (var123Number == null) - throw new ArgumentNullException(nameof(var123Number), "Property is required for class Name."); + if (var123Number.IsSet && var123Number.Value == null) + throw new ArgumentNullException(nameof(var123Number), "Property is not nullable for class Name."); - return new Name(varName.Value, property, snakeCase.Value, var123Number.Value); + return new Name(varName.Value.Value, property, snakeCase, var123Number); } /// @@ -244,10 +273,19 @@ public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) { + if (name.PropertyOption.IsSet && name.Property == null) + throw new ArgumentNullException(nameof(name.Property), "Property is required for class Name."); + writer.WriteNumber("name", name.VarName); - writer.WriteString("property", name.Property); - writer.WriteNumber("snake_case", name.SnakeCase); - writer.WriteNumber("123Number", name.Var123Number); + + if (name.PropertyOption.IsSet) + writer.WriteString("property", name.Property); + + if (name.SnakeCaseOption.IsSet) + writer.WriteNumber("snake_case", name.SnakeCaseOption.Value.Value); + + if (name.Var123NumberOption.IsSet) + writer.WriteNumber("123Number", name.Var123NumberOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs index 83ab7f40b1e8..cd1516104e35 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> aObjVariableobject = default; - int? pkiNotificationtestID = default; + Option>> aObjVariableobject = default; + Option pkiNotificationtestID = default; while (utf8JsonReader.Read()) { @@ -129,11 +130,11 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR { case "a_objVariableobject": if (utf8JsonReader.TokenType != JsonTokenType.Null) - aObjVariableobject = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + aObjVariableobject = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "pkiNotificationtestID": if (utf8JsonReader.TokenType != JsonTokenType.Null) - pkiNotificationtestID = utf8JsonReader.GetInt32(); + pkiNotificationtestID = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -141,13 +142,19 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR } } - if (aObjVariableobject == null) - throw new ArgumentNullException(nameof(aObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!aObjVariableobject.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(aObjVariableobject)); - if (pkiNotificationtestID == null) - throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!pkiNotificationtestID.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(pkiNotificationtestID)); - return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject, pkiNotificationtestID.Value); + if (aObjVariableobject.IsSet && aObjVariableobject.Value == null) + throw new ArgumentNullException(nameof(aObjVariableobject), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + if (pkiNotificationtestID.IsSet && pkiNotificationtestID.Value == null) + throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject.Value, pkiNotificationtestID.Value.Value); } /// @@ -174,6 +181,9 @@ public override void Write(Utf8JsonWriter writer, NotificationtestGetElementsV1R /// public void WriteProperties(ref Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) { + if (notificationtestGetElementsV1ResponseMPayload.AObjVariableobject == null) + throw new ArgumentNullException(nameof(notificationtestGetElementsV1ResponseMPayload.AObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + writer.WritePropertyName("a_objVariableobject"); JsonSerializer.Serialize(writer, notificationtestGetElementsV1ResponseMPayload.AObjVariableobject, jsonSerializerOptions); writer.WriteNumber("pkiNotificationtestID", notificationtestGetElementsV1ResponseMPayload.PkiNotificationtestID); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs index 5d9de18c4a36..67f78b342859 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -20,20 +20,20 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// NullableClass /// - public partial class NullableClass : Dictionary, IValidatableObject + public partial class NullableClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayItemsNullable - /// objectItemsNullable /// arrayAndItemsNullableProp + /// arrayItemsNullable /// arrayNullableProp /// booleanProp /// dateProp @@ -41,99 +41,184 @@ public partial class NullableClass : Dictionary, IValidatableObj /// integerProp /// numberProp /// objectAndItemsNullableProp + /// objectItemsNullable /// objectNullableProp /// stringProp [JsonConstructor] - public NullableClass(List arrayItemsNullable, Dictionary objectItemsNullable, List arrayAndItemsNullableProp = default, List arrayNullableProp = default, bool? booleanProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, int? integerProp = default, decimal? numberProp = default, Dictionary objectAndItemsNullableProp = default, Dictionary objectNullableProp = default, string stringProp = default) : base() + public NullableClass(Option> arrayAndItemsNullableProp = default, Option> arrayItemsNullable = default, Option> arrayNullableProp = default, Option booleanProp = default, Option dateProp = default, Option datetimeProp = default, Option integerProp = default, Option numberProp = default, Option> objectAndItemsNullableProp = default, Option> objectItemsNullable = default, Option> objectNullableProp = default, Option stringProp = default) { - ArrayItemsNullable = arrayItemsNullable; - ObjectItemsNullable = objectItemsNullable; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayNullableProp = arrayNullableProp; - BooleanProp = booleanProp; - DateProp = dateProp; - DatetimeProp = datetimeProp; - IntegerProp = integerProp; - NumberProp = numberProp; - ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectNullableProp = objectNullableProp; - StringProp = stringProp; + ArrayAndItemsNullablePropOption = arrayAndItemsNullableProp; + ArrayItemsNullableOption = arrayItemsNullable; + ArrayNullablePropOption = arrayNullableProp; + BooleanPropOption = booleanProp; + DatePropOption = dateProp; + DatetimePropOption = datetimeProp; + IntegerPropOption = integerProp; + NumberPropOption = numberProp; + ObjectAndItemsNullablePropOption = objectAndItemsNullableProp; + ObjectItemsNullableOption = objectItemsNullable; + ObjectNullablePropOption = objectNullableProp; + StringPropOption = stringProp; OnCreated(); } partial void OnCreated(); /// - /// Gets or Sets ArrayItemsNullable + /// Used to track the state of ArrayAndItemsNullableProp /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayAndItemsNullablePropOption { get; private set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ArrayAndItemsNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("array_and_items_nullable_prop")] + public List ArrayAndItemsNullableProp { get { return this. ArrayAndItemsNullablePropOption; } set { this.ArrayAndItemsNullablePropOption = new(value); } } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Used to track the state of ArrayItemsNullable /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List ArrayAndItemsNullableProp { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ArrayItemsNullable + /// + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get { return this. ArrayItemsNullableOption; } set { this.ArrayItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ArrayNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayNullablePropOption { get; private set; } /// /// Gets or Sets ArrayNullableProp /// [JsonPropertyName("array_nullable_prop")] - public List ArrayNullableProp { get; set; } + public List ArrayNullableProp { get { return this. ArrayNullablePropOption; } set { this.ArrayNullablePropOption = new(value); } } + + /// + /// Used to track the state of BooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BooleanPropOption { get; private set; } /// /// Gets or Sets BooleanProp /// [JsonPropertyName("boolean_prop")] - public bool? BooleanProp { get; set; } + public bool? BooleanProp { get { return this. BooleanPropOption; } set { this.BooleanPropOption = new(value); } } + + /// + /// Used to track the state of DateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatePropOption { get; private set; } /// /// Gets or Sets DateProp /// [JsonPropertyName("date_prop")] - public DateTime? DateProp { get; set; } + public DateOnly? DateProp { get { return this. DatePropOption; } set { this.DatePropOption = new(value); } } + + /// + /// Used to track the state of DatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatetimePropOption { get; private set; } /// /// Gets or Sets DatetimeProp /// [JsonPropertyName("datetime_prop")] - public DateTime? DatetimeProp { get; set; } + public DateTime? DatetimeProp { get { return this. DatetimePropOption; } set { this.DatetimePropOption = new(value); } } + + /// + /// Used to track the state of IntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerPropOption { get; private set; } /// /// Gets or Sets IntegerProp /// [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + public int? IntegerProp { get { return this. IntegerPropOption; } set { this.IntegerPropOption = new(value); } } + + /// + /// Used to track the state of NumberProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberPropOption { get; private set; } /// /// Gets or Sets NumberProp /// [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + public decimal? NumberProp { get { return this. NumberPropOption; } set { this.NumberPropOption = new(value); } } + + /// + /// Used to track the state of ObjectAndItemsNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectAndItemsNullablePropOption { get; private set; } /// /// Gets or Sets ObjectAndItemsNullableProp /// [JsonPropertyName("object_and_items_nullable_prop")] - public Dictionary ObjectAndItemsNullableProp { get; set; } + public Dictionary ObjectAndItemsNullableProp { get { return this. ObjectAndItemsNullablePropOption; } set { this.ObjectAndItemsNullablePropOption = new(value); } } + + /// + /// Used to track the state of ObjectItemsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [JsonPropertyName("object_items_nullable")] + public Dictionary ObjectItemsNullable { get { return this. ObjectItemsNullableOption; } set { this.ObjectItemsNullableOption = new(value); } } + + /// + /// Used to track the state of ObjectNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectNullablePropOption { get; private set; } /// /// Gets or Sets ObjectNullableProp /// [JsonPropertyName("object_nullable_prop")] - public Dictionary ObjectNullableProp { get; set; } + public Dictionary ObjectNullableProp { get { return this. ObjectNullablePropOption; } set { this.ObjectNullablePropOption = new(value); } } + + /// + /// Used to track the state of StringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StringPropOption { get; private set; } /// /// Gets or Sets StringProp /// [JsonPropertyName("string_prop")] - public string StringProp { get; set; } + public string StringProp { get { return this. StringPropOption; } set { this.StringPropOption = new(value); } } /// /// Gets or Sets additional properties @@ -149,10 +234,8 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); @@ -160,6 +243,7 @@ public override string ToString() sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -173,16 +257,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -220,18 +294,18 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayItemsNullable = default; - Dictionary objectItemsNullable = default; - List arrayAndItemsNullableProp = default; - List arrayNullableProp = default; - bool? booleanProp = default; - DateTime? dateProp = default; - DateTime? datetimeProp = default; - int? integerProp = default; - decimal? numberProp = default; - Dictionary objectAndItemsNullableProp = default; - Dictionary objectNullableProp = default; - string stringProp = default; + Option> arrayAndItemsNullableProp = default; + Option> arrayItemsNullable = default; + Option> arrayNullableProp = default; + Option booleanProp = default; + Option dateProp = default; + Option datetimeProp = default; + Option integerProp = default; + Option numberProp = default; + Option> objectAndItemsNullableProp = default; + Option> objectItemsNullable = default; + Option> objectNullableProp = default; + Option stringProp = default; while (utf8JsonReader.Read()) { @@ -248,52 +322,52 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { - case "array_items_nullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "object_items_nullable": + case "array_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayAndItemsNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "array_and_items_nullable_prop": + case "array_items_nullable": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayItemsNullable = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "boolean_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - booleanProp = utf8JsonReader.GetBoolean(); + booleanProp = new Option(utf8JsonReader.GetBoolean()); break; case "date_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "datetime_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - datetimeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + datetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "integer_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integerProp = utf8JsonReader.GetInt32(); + integerProp = new Option(utf8JsonReader.GetInt32()); break; case "number_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - numberProp = utf8JsonReader.GetDecimal(); + numberProp = new Option(utf8JsonReader.GetDecimal()); break; case "object_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectAndItemsNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "object_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectItemsNullable = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "object_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "string_prop": - stringProp = utf8JsonReader.GetString(); + stringProp = new Option(utf8JsonReader.GetString()); break; default: break; @@ -301,13 +375,13 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (arrayItemsNullable == null) - throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is required for class NullableClass."); + if (arrayItemsNullable.IsSet && arrayItemsNullable.Value == null) + throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is not nullable for class NullableClass."); - if (objectItemsNullable == null) - throw new ArgumentNullException(nameof(objectItemsNullable), "Property is required for class NullableClass."); + if (objectItemsNullable.IsSet && objectItemsNullable.Value == null) + throw new ArgumentNullException(nameof(objectItemsNullable), "Property is not nullable for class NullableClass."); - return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + return new NullableClass(arrayAndItemsNullableProp, arrayItemsNullable, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectItemsNullable, objectNullableProp, stringProp); } /// @@ -334,45 +408,89 @@ public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("object_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("array_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("array_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); - - if (nullableClass.BooleanProp != null) - writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); - else - writer.WriteNull("boolean_prop"); - - if (nullableClass.DateProp != null) - writer.WriteString("date_prop", nullableClass.DateProp.Value.ToString(DatePropFormat)); - else - writer.WriteNull("date_prop"); - - if (nullableClass.DatetimeProp != null) - writer.WriteString("datetime_prop", nullableClass.DatetimeProp.Value.ToString(DatetimePropFormat)); - else - writer.WriteNull("datetime_prop"); - - if (nullableClass.IntegerProp != null) - writer.WriteNumber("integer_prop", nullableClass.IntegerProp.Value); - else - writer.WriteNull("integer_prop"); - - if (nullableClass.NumberProp != null) - writer.WriteNumber("number_prop", nullableClass.NumberProp.Value); - else - writer.WriteNull("number_prop"); - - writer.WritePropertyName("object_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("object_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); - writer.WriteString("string_prop", nullableClass.StringProp); + if (nullableClass.ArrayItemsNullableOption.IsSet && nullableClass.ArrayItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ArrayItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ObjectItemsNullableOption.IsSet && nullableClass.ObjectItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ObjectItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ArrayAndItemsNullablePropOption.IsSet) + if (nullableClass.ArrayAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_and_items_nullable_prop"); + if (nullableClass.ArrayItemsNullableOption.IsSet) + { + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ArrayNullablePropOption.IsSet) + if (nullableClass.ArrayNullablePropOption.Value != null) + { + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_nullable_prop"); + if (nullableClass.BooleanPropOption.IsSet) + if (nullableClass.BooleanPropOption.Value != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanPropOption.Value.Value); + else + writer.WriteNull("boolean_prop"); + + if (nullableClass.DatePropOption.IsSet) + if (nullableClass.DatePropOption.Value != null) + writer.WriteString("date_prop", nullableClass.DatePropOption.Value.Value.ToString(DatePropFormat)); + else + writer.WriteNull("date_prop"); + + if (nullableClass.DatetimePropOption.IsSet) + if (nullableClass.DatetimePropOption.Value != null) + writer.WriteString("datetime_prop", nullableClass.DatetimePropOption.Value.Value.ToString(DatetimePropFormat)); + else + writer.WriteNull("datetime_prop"); + + if (nullableClass.IntegerPropOption.IsSet) + if (nullableClass.IntegerPropOption.Value != null) + writer.WriteNumber("integer_prop", nullableClass.IntegerPropOption.Value.Value); + else + writer.WriteNull("integer_prop"); + + if (nullableClass.NumberPropOption.IsSet) + if (nullableClass.NumberPropOption.Value != null) + writer.WriteNumber("number_prop", nullableClass.NumberPropOption.Value.Value); + else + writer.WriteNull("number_prop"); + + if (nullableClass.ObjectAndItemsNullablePropOption.IsSet) + if (nullableClass.ObjectAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_and_items_nullable_prop"); + if (nullableClass.ObjectItemsNullableOption.IsSet) + { + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ObjectNullablePropOption.IsSet) + if (nullableClass.ObjectNullablePropOption.Value != null) + { + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_nullable_prop"); + if (nullableClass.StringPropOption.IsSet) + if (nullableClass.StringPropOption.Value != null) + writer.WriteString("string_prop", nullableClass.StringProp); + else + writer.WriteNull("string_prop"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs index 684109acd50f..ca650f0cce00 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class NullableGuidClass : IValidatableObject /// /// uuid [JsonConstructor] - public NullableGuidClass(Guid? uuid = default) + public NullableGuidClass(Option uuid = default) { - Uuid = uuid; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } + /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid? Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -101,7 +109,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Guid? uuid = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t { case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -155,11 +163,11 @@ public override void Write(Utf8JsonWriter writer, NullableGuidClass nullableGuid /// public void WriteProperties(ref Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) { - - if (nullableGuidClass.Uuid == null) - writer.WriteNull("uuid"); - else - writer.WriteString("uuid", nullableGuidClass.Uuid.Value); + if (nullableGuidClass.UuidOption.IsSet) + if (nullableGuidClass.UuidOption.Value != null) + writer.WriteString("uuid", nullableGuidClass.UuidOption.Value.Value); + else + writer.WriteNull("uuid"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs index a44c950b81bb..1e38640c8af9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NullableShape.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class NullableShape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class NullableShape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class NullableShape."); if (quadrilateral != null) - return new NullableShape(quadrilateral, shapeType); + return new NullableShape(quadrilateral, shapeType.Value); if (triangle != null) - return new NullableShape(triangle, shapeType); + return new NullableShape(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) { + if (nullableShape.ShapeType == null) + throw new ArgumentNullException(nameof(nullableShape.ShapeType), "Property is required for class NullableShape."); + writer.WriteString("shapeType", nullableShape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs index 3f3cbf4c5059..6f89d8278430 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class NumberOnly : IValidatableObject /// /// justNumber [JsonConstructor] - public NumberOnly(decimal justNumber) + public NumberOnly(Option justNumber = default) { - JustNumber = justNumber; + JustNumberOption = justNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of JustNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustNumberOption { get; private set; } + /// /// Gets or Sets JustNumber /// [JsonPropertyName("JustNumber")] - public decimal JustNumber { get; set; } + public decimal? JustNumber { get { return this. JustNumberOption; } set { this.JustNumberOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? justNumber = default; + Option justNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "JustNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - justNumber = utf8JsonReader.GetDecimal(); + justNumber = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -127,10 +135,10 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (justNumber == null) - throw new ArgumentNullException(nameof(justNumber), "Property is required for class NumberOnly."); + if (justNumber.IsSet && justNumber.Value == null) + throw new ArgumentNullException(nameof(justNumber), "Property is not nullable for class NumberOnly."); - return new NumberOnly(justNumber.Value); + return new NumberOnly(justNumber); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("JustNumber", numberOnly.JustNumber); + if (numberOnly.JustNumberOption.IsSet) + writer.WriteNumber("JustNumber", numberOnly.JustNumberOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 57a1614f29f4..4ea953e572f8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,43 +37,71 @@ public partial class ObjectWithDeprecatedFields : IValidatableObject /// id /// uuid [JsonConstructor] - public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) + public ObjectWithDeprecatedFields(Option> bars = default, Option deprecatedRef = default, Option id = default, Option uuid = default) { - Bars = bars; - DeprecatedRef = deprecatedRef; - Id = id; - Uuid = uuid; + BarsOption = bars; + DeprecatedRefOption = deprecatedRef; + IdOption = id; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bars + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> BarsOption { get; private set; } + /// /// Gets or Sets Bars /// [JsonPropertyName("bars")] [Obsolete] - public List Bars { get; set; } + public List Bars { get { return this. BarsOption; } set { this.BarsOption = new(value); } } + + /// + /// Used to track the state of DeprecatedRef + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeprecatedRefOption { get; private set; } /// /// Gets or Sets DeprecatedRef /// [JsonPropertyName("deprecatedRef")] [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } + public DeprecatedObject DeprecatedRef { get { return this. DeprecatedRefOption; } set { this.DeprecatedRefOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] [Obsolete] - public decimal Id { get; set; } + public decimal? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public string Uuid { get; set; } + public string Uuid { get { return this. UuidOption; } set { this.UuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -130,10 +159,10 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List bars = default; - DeprecatedObject deprecatedRef = default; - decimal? id = default; - string uuid = default; + Option> bars = default; + Option deprecatedRef = default; + Option id = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -152,18 +181,18 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade { case "bars": if (utf8JsonReader.TokenType != JsonTokenType.Null) - bars = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + bars = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "deprecatedRef": if (utf8JsonReader.TokenType != JsonTokenType.Null) - deprecatedRef = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + deprecatedRef = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetDecimal(); + id = new Option(utf8JsonReader.GetDecimal()); break; case "uuid": - uuid = utf8JsonReader.GetString(); + uuid = new Option(utf8JsonReader.GetString()); break; default: break; @@ -171,19 +200,19 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade } } - if (bars == null) - throw new ArgumentNullException(nameof(bars), "Property is required for class ObjectWithDeprecatedFields."); + if (bars.IsSet && bars.Value == null) + throw new ArgumentNullException(nameof(bars), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (deprecatedRef == null) - throw new ArgumentNullException(nameof(deprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + if (deprecatedRef.IsSet && deprecatedRef.Value == null) + throw new ArgumentNullException(nameof(deprecatedRef), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class ObjectWithDeprecatedFields."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class ObjectWithDeprecatedFields."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class ObjectWithDeprecatedFields."); - return new ObjectWithDeprecatedFields(bars, deprecatedRef, id.Value, uuid); + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); } /// @@ -210,12 +239,30 @@ public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields obj /// public void WriteProperties(ref Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("bars"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); - writer.WritePropertyName("deprecatedRef"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); - writer.WriteNumber("id", objectWithDeprecatedFields.Id); - writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + if (objectWithDeprecatedFields.BarsOption.IsSet && objectWithDeprecatedFields.Bars == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Bars), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet && objectWithDeprecatedFields.DeprecatedRef == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.DeprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.UuidOption.IsSet && objectWithDeprecatedFields.Uuid == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Uuid), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.BarsOption.IsSet) + { + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet) + { + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.IdOption.IsSet) + writer.WriteNumber("id", objectWithDeprecatedFields.IdOption.Value.Value); + + if (objectWithDeprecatedFields.UuidOption.IsSet) + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OneOfString.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OneOfString.cs index 91dd67631614..660604e3ef17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OneOfString.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OneOfString.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs index 13afecfac3f6..26c5042777a7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Order.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,21 +32,21 @@ public partial class Order : IValidatableObject /// /// Initializes a new instance of the class. /// + /// complete (default to false) /// id /// petId /// quantity /// shipDate /// Order Status - /// complete (default to false) [JsonConstructor] - public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) + public Order(Option complete = default, Option id = default, Option petId = default, Option quantity = default, Option shipDate = default, Option status = default) { - Id = id; - PetId = petId; - Quantity = quantity; - ShipDate = shipDate; - Status = status; - Complete = complete; + CompleteOption = complete; + IdOption = id; + PetIdOption = petId; + QuantityOption = quantity; + ShipDateOption = shipDate; + StatusOption = status; OnCreated(); } @@ -118,7 +119,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Placed) return "placed"; @@ -132,43 +133,85 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// Order Status /// /// Order Status [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Used to track the state of Complete + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CompleteOption { get; private set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool? Complete { get { return this. CompleteOption; } set { this.CompleteOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of PetId + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PetIdOption { get; private set; } /// /// Gets or Sets PetId /// [JsonPropertyName("petId")] - public long PetId { get; set; } + public long? PetId { get { return this. PetIdOption; } set { this.PetIdOption = new(value); } } + + /// + /// Used to track the state of Quantity + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option QuantityOption { get; private set; } /// /// Gets or Sets Quantity /// [JsonPropertyName("quantity")] - public int Quantity { get; set; } + public int? Quantity { get { return this. QuantityOption; } set { this.QuantityOption = new(value); } } /// - /// Gets or Sets ShipDate + /// Used to track the state of ShipDate /// - /// 2020-02-02T20:20:20.000222Z - [JsonPropertyName("shipDate")] - public DateTime ShipDate { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShipDateOption { get; private set; } /// - /// Gets or Sets Complete + /// Gets or Sets ShipDate /// - [JsonPropertyName("complete")] - public bool Complete { get; set; } + /// 2020-02-02T20:20:20.000222Z + [JsonPropertyName("shipDate")] + public DateTime? ShipDate { get { return this. ShipDateOption; } set { this.ShipDateOption = new(value); } } /// /// Gets or Sets additional properties @@ -184,12 +227,12 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -233,12 +276,12 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - long? petId = default; - int? quantity = default; - DateTime? shipDate = default; - Order.StatusEnum? status = default; - bool? complete = default; + Option complete = default; + Option id = default; + Option petId = default; + Option quantity = default; + Option shipDate = default; + Option status = default; while (utf8JsonReader.Read()) { @@ -255,31 +298,30 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { + case "complete": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + complete = new Option(utf8JsonReader.GetBoolean()); + break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "petId": if (utf8JsonReader.TokenType != JsonTokenType.Null) - petId = utf8JsonReader.GetInt64(); + petId = new Option(utf8JsonReader.GetInt64()); break; case "quantity": if (utf8JsonReader.TokenType != JsonTokenType.Null) - quantity = utf8JsonReader.GetInt32(); + quantity = new Option(utf8JsonReader.GetInt32()); break; case "shipDate": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shipDate = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shipDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "status": string statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Order.StatusEnumFromStringOrDefault(statusRawValue); - break; - case "complete": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - complete = utf8JsonReader.GetBoolean(); + if (statusRawValue != null) + status = new Option(Order.StatusEnumFromStringOrDefault(statusRawValue)); break; default: break; @@ -287,25 +329,25 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Order."); + if (complete.IsSet && complete.Value == null) + throw new ArgumentNullException(nameof(complete), "Property is not nullable for class Order."); - if (petId == null) - throw new ArgumentNullException(nameof(petId), "Property is required for class Order."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Order."); - if (quantity == null) - throw new ArgumentNullException(nameof(quantity), "Property is required for class Order."); + if (petId.IsSet && petId.Value == null) + throw new ArgumentNullException(nameof(petId), "Property is not nullable for class Order."); - if (shipDate == null) - throw new ArgumentNullException(nameof(shipDate), "Property is required for class Order."); + if (quantity.IsSet && quantity.Value == null) + throw new ArgumentNullException(nameof(quantity), "Property is not nullable for class Order."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Order."); + if (shipDate.IsSet && shipDate.Value == null) + throw new ArgumentNullException(nameof(shipDate), "Property is not nullable for class Order."); - if (complete == null) - throw new ArgumentNullException(nameof(complete), "Property is required for class Order."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Order."); - return new Order(id.Value, petId.Value, quantity.Value, shipDate.Value, status.Value, complete.Value); + return new Order(complete, id, petId, quantity, shipDate, status); } /// @@ -332,18 +374,23 @@ public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", order.Id); - writer.WriteNumber("petId", order.PetId); - writer.WriteNumber("quantity", order.Quantity); - writer.WriteString("shipDate", order.ShipDate.ToString(ShipDateFormat)); - - var statusRawValue = Order.StatusEnumToJsonValue(order.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WriteBoolean("complete", order.Complete); + if (order.CompleteOption.IsSet) + writer.WriteBoolean("complete", order.CompleteOption.Value.Value); + + if (order.IdOption.IsSet) + writer.WriteNumber("id", order.IdOption.Value.Value); + + if (order.PetIdOption.IsSet) + writer.WriteNumber("petId", order.PetIdOption.Value.Value); + + if (order.QuantityOption.IsSet) + writer.WriteNumber("quantity", order.QuantityOption.Value.Value); + + if (order.ShipDateOption.IsSet) + writer.WriteString("shipDate", order.ShipDateOption.Value.Value.ToString(ShipDateFormat)); + + var statusRawValue = Order.StatusEnumToJsonValue(order.StatusOption.Value.Value); + writer.WriteString("status", statusRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs index c37883db124b..532010be421c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class OuterComposite : IValidatableObject /// myNumber /// myString [JsonConstructor] - public OuterComposite(bool myBoolean, decimal myNumber, string myString) + public OuterComposite(Option myBoolean = default, Option myNumber = default, Option myString = default) { - MyBoolean = myBoolean; - MyNumber = myNumber; - MyString = myString; + MyBooleanOption = myBoolean; + MyNumberOption = myNumber; + MyStringOption = myString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MyBoolean + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyBooleanOption { get; private set; } + /// /// Gets or Sets MyBoolean /// [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } + public bool? MyBoolean { get { return this. MyBooleanOption; } set { this.MyBooleanOption = new(value); } } + + /// + /// Used to track the state of MyNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyNumberOption { get; private set; } /// /// Gets or Sets MyNumber /// [JsonPropertyName("my_number")] - public decimal MyNumber { get; set; } + public decimal? MyNumber { get { return this. MyNumberOption; } set { this.MyNumberOption = new(value); } } + + /// + /// Used to track the state of MyString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyStringOption { get; private set; } /// /// Gets or Sets MyString /// [JsonPropertyName("my_string")] - public string MyString { get; set; } + public string MyString { get { return this. MyStringOption; } set { this.MyStringOption = new(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - bool? myBoolean = default; - decimal? myNumber = default; - string myString = default; + Option myBoolean = default; + Option myNumber = default; + Option myString = default; while (utf8JsonReader.Read()) { @@ -139,14 +161,14 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type { case "my_boolean": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myBoolean = utf8JsonReader.GetBoolean(); + myBoolean = new Option(utf8JsonReader.GetBoolean()); break; case "my_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myNumber = utf8JsonReader.GetDecimal(); + myNumber = new Option(utf8JsonReader.GetDecimal()); break; case "my_string": - myString = utf8JsonReader.GetString(); + myString = new Option(utf8JsonReader.GetString()); break; default: break; @@ -154,16 +176,16 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (myBoolean == null) - throw new ArgumentNullException(nameof(myBoolean), "Property is required for class OuterComposite."); + if (myBoolean.IsSet && myBoolean.Value == null) + throw new ArgumentNullException(nameof(myBoolean), "Property is not nullable for class OuterComposite."); - if (myNumber == null) - throw new ArgumentNullException(nameof(myNumber), "Property is required for class OuterComposite."); + if (myNumber.IsSet && myNumber.Value == null) + throw new ArgumentNullException(nameof(myNumber), "Property is not nullable for class OuterComposite."); - if (myString == null) - throw new ArgumentNullException(nameof(myString), "Property is required for class OuterComposite."); + if (myString.IsSet && myString.Value == null) + throw new ArgumentNullException(nameof(myString), "Property is not nullable for class OuterComposite."); - return new OuterComposite(myBoolean.Value, myNumber.Value, myString); + return new OuterComposite(myBoolean, myNumber, myString); } /// @@ -190,9 +212,17 @@ public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, /// public void WriteProperties(ref Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); - writer.WriteNumber("my_number", outerComposite.MyNumber); - writer.WriteString("my_string", outerComposite.MyString); + if (outerComposite.MyStringOption.IsSet && outerComposite.MyString == null) + throw new ArgumentNullException(nameof(outerComposite.MyString), "Property is required for class OuterComposite."); + + if (outerComposite.MyBooleanOption.IsSet) + writer.WriteBoolean("my_boolean", outerComposite.MyBooleanOption.Value.Value); + + if (outerComposite.MyNumberOption.IsSet) + writer.WriteNumber("my_number", outerComposite.MyNumberOption.Value.Value); + + if (outerComposite.MyStringOption.IsSet) + writer.WriteString("my_string", outerComposite.MyString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs index a4ec335bb386..47bb6793c6ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index 7c67db5ddca3..136fb4c54c4e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 84ea65297ab0..2ed4f18a657e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index 983d194a1998..c6a470cc64d1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs index 51d8bee407e0..a2e789f2edef 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs index eb0129c6ce0f..c451e1a8991b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -76,7 +77,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -94,7 +95,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -102,10 +103,13 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ParentPet."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ParentPet.", nameof(petType)); - return new ParentPet(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ParentPet."); + + return new ParentPet(petType.Value); } /// @@ -132,6 +136,9 @@ public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) { + if (parentPet.PetType == null) + throw new ArgumentNullException(nameof(parentPet.PetType), "Property is required for class ParentPet."); + writer.WriteString("pet_type", parentPet.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs index aa380014a324..5721a962ba21 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pet.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,21 +32,21 @@ public partial class Pet : IValidatableObject /// /// Initializes a new instance of the class. /// - /// category - /// id /// name /// photoUrls + /// category + /// id /// pet status in the store /// tags [JsonConstructor] - public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) + public Pet(string name, List photoUrls, Option category = default, Option id = default, Option status = default, Option> tags = default) { - Category = category; - Id = id; Name = name; PhotoUrls = photoUrls; - Status = status; - Tags = tags; + CategoryOption = category; + IdOption = id; + StatusOption = status; + TagsOption = tags; OnCreated(); } @@ -118,7 +119,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Available) return "available"; @@ -132,43 +133,71 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// pet status in the store /// /// pet status in the store [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new(value); } } + + /// + /// Gets or Sets Name + /// + /// doggie + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Used to track the state of Category + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CategoryOption { get; private set; } /// /// Gets or Sets Category /// [JsonPropertyName("category")] - public Category Category { get; set; } + public Category Category { get { return this. CategoryOption; } set { this.CategoryOption = new(value); } } /// - /// Gets or Sets Id + /// Used to track the state of Id /// - [JsonPropertyName("id")] - public long Id { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// - /// Gets or Sets Name + /// Gets or Sets Id /// - /// doggie - [JsonPropertyName("name")] - public string Name { get; set; } + [JsonPropertyName("id")] + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } /// - /// Gets or Sets PhotoUrls + /// Used to track the state of Tags /// - [JsonPropertyName("photoUrls")] - public List PhotoUrls { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> TagsOption { get; private set; } /// /// Gets or Sets Tags /// [JsonPropertyName("tags")] - public List Tags { get; set; } + public List Tags { get { return this. TagsOption; } set { this.TagsOption = new(value); } } /// /// Gets or Sets additional properties @@ -184,10 +213,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -228,12 +257,12 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Category category = default; - long? id = default; - string name = default; - List photoUrls = default; - Pet.StatusEnum? status = default; - List tags = default; + Option name = default; + Option> photoUrls = default; + Option category = default; + Option id = default; + Option status = default; + Option> tags = default; while (utf8JsonReader.Read()) { @@ -250,30 +279,29 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "category": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - category = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + case "name": + name = new Option(utf8JsonReader.GetString()); break; - case "id": + case "photoUrls": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + photoUrls = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "name": - name = utf8JsonReader.GetString(); + case "category": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + category = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; - case "photoUrls": + case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - photoUrls = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + id = new Option(utf8JsonReader.GetInt64()); break; case "status": string statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Pet.StatusEnumFromStringOrDefault(statusRawValue); + if (statusRawValue != null) + status = new Option(Pet.StatusEnumFromStringOrDefault(statusRawValue)); break; case "tags": if (utf8JsonReader.TokenType != JsonTokenType.Null) - tags = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + tags = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -281,25 +309,31 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (category == null) - throw new ArgumentNullException(nameof(category), "Property is required for class Pet."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(name)); + + if (!photoUrls.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(photoUrls)); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Pet."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Pet."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Pet."); + if (photoUrls.IsSet && photoUrls.Value == null) + throw new ArgumentNullException(nameof(photoUrls), "Property is not nullable for class Pet."); - if (photoUrls == null) - throw new ArgumentNullException(nameof(photoUrls), "Property is required for class Pet."); + if (category.IsSet && category.Value == null) + throw new ArgumentNullException(nameof(category), "Property is not nullable for class Pet."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Pet."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Pet."); - if (tags == null) - throw new ArgumentNullException(nameof(tags), "Property is required for class Pet."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Pet."); - return new Pet(category, id.Value, name, photoUrls, status.Value, tags); + if (tags.IsSet && tags.Value == null) + throw new ArgumentNullException(nameof(tags), "Property is not nullable for class Pet."); + + return new Pet(name.Value, photoUrls.Value, category, id, status, tags); } /// @@ -326,21 +360,37 @@ public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("category"); - JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); - writer.WriteNumber("id", pet.Id); + if (pet.Name == null) + throw new ArgumentNullException(nameof(pet.Name), "Property is required for class Pet."); + + if (pet.PhotoUrls == null) + throw new ArgumentNullException(nameof(pet.PhotoUrls), "Property is required for class Pet."); + + if (pet.CategoryOption.IsSet && pet.Category == null) + throw new ArgumentNullException(nameof(pet.Category), "Property is required for class Pet."); + + if (pet.TagsOption.IsSet && pet.Tags == null) + throw new ArgumentNullException(nameof(pet.Tags), "Property is required for class Pet."); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); JsonSerializer.Serialize(writer, pet.PhotoUrls, jsonSerializerOptions); + if (pet.CategoryOption.IsSet) + { + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); + } + if (pet.IdOption.IsSet) + writer.WriteNumber("id", pet.IdOption.Value.Value); - var statusRawValue = Pet.StatusEnumToJsonValue(pet.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WritePropertyName("tags"); - JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + var statusRawValue = Pet.StatusEnumToJsonValue(pet.StatusOption.Value.Value); + writer.WriteString("status", statusRawValue); + if (pet.TagsOption.IsSet) + { + writer.WritePropertyName("tags"); + JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs index 8185d643e794..d3bbeb8ff326 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Pig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; BasquePig basquePig = null; DanishPig danishPig = null; @@ -184,7 +185,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Pig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Pig.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Pig."); if (basquePig != null) - return new Pig(basquePig, className); + return new Pig(basquePig, className.Value); if (danishPig != null) - return new Pig(danishPig, className); + return new Pig(danishPig, className.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) { + if (pig.ClassName == null) + throw new ArgumentNullException(nameof(pig.ClassName), "Property is required for class Pig."); + writer.WriteString("className", pig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index 3a89a8716e07..2c2227a22512 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs index 65f7b8b4536f..3f4034a17713 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; + Option quadrilateralType = default; ComplexQuadrilateral complexQuadrilateral = null; SimpleQuadrilateral simpleQuadrilateral = null; @@ -184,7 +185,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class Quadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class Quadrilateral.", nameof(quadrilateralType)); + + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class Quadrilateral."); if (complexQuadrilateral != null) - return new Quadrilateral(complexQuadrilateral, quadrilateralType); + return new Quadrilateral(complexQuadrilateral, quadrilateralType.Value); if (simpleQuadrilateral != null) - return new Quadrilateral(simpleQuadrilateral, quadrilateralType); + return new Quadrilateral(simpleQuadrilateral, quadrilateralType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, J /// public void WriteProperties(ref Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateral.QuadrilateralType), "Property is required for class Quadrilateral."); + writer.WriteString("quadrilateralType", quadrilateral.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index c329eed3266b..75b7e516cfca 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; + Option quadrilateralType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class QuadrilateralInterface."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class QuadrilateralInterface.", nameof(quadrilateralType)); - return new QuadrilateralInterface(quadrilateralType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class QuadrilateralInterface."); + + return new QuadrilateralInterface(quadrilateralType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadril /// public void WriteProperties(ref Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateralInterface.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralInterface.QuadrilateralType), "Property is required for class QuadrilateralInterface."); + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 2c8b4fff43d6..16f308cad5f5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class ReadOnlyFirst : IEquatable, IValidatableObje /// bar /// baz [JsonConstructor] - public ReadOnlyFirst(string bar, string baz) + public ReadOnlyFirst(Option bar = default, Option baz = default) { - Bar = bar; - Baz = baz; + BarOption = bar; + BazOption = baz; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Baz + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BazOption { get; private set; } /// /// Gets or Sets Baz /// [JsonPropertyName("baz")] - public string Baz { get; set; } + public string Baz { get { return this. BazOption; } set { this.BazOption = new(value); } } /// /// Gets or Sets additional properties @@ -105,7 +120,9 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -145,8 +162,8 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; - string baz = default; + Option bar = default; + Option baz = default; while (utf8JsonReader.Read()) { @@ -164,10 +181,10 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; case "baz": - baz = utf8JsonReader.GetString(); + baz = new Option(utf8JsonReader.GetString()); break; default: break; @@ -175,11 +192,11 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class ReadOnlyFirst."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class ReadOnlyFirst."); - if (baz == null) - throw new ArgumentNullException(nameof(baz), "Property is required for class ReadOnlyFirst."); + if (baz.IsSet && baz.Value == null) + throw new ArgumentNullException(nameof(baz), "Property is not nullable for class ReadOnlyFirst."); return new ReadOnlyFirst(bar, baz); } @@ -208,8 +225,17 @@ public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, J /// public void WriteProperties(ref Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", readOnlyFirst.Bar); - writer.WriteString("baz", readOnlyFirst.Baz); + if (readOnlyFirst.BarOption.IsSet && readOnlyFirst.Bar == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Bar), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BazOption.IsSet && readOnlyFirst.Baz == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Baz), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BarOption.IsSet) + writer.WriteString("bar", readOnlyFirst.Bar); + + if (readOnlyFirst.BazOption.IsSet) + writer.WriteString("baz", readOnlyFirst.Baz); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..89ed1e729c37 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,2378 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + public partial class RequiredClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// requiredNotNullableDateProp + /// requiredNotnullableArrayOfString + /// requiredNotnullableBooleanProp + /// requiredNotnullableDatetimeProp + /// requiredNotnullableEnumInteger + /// requiredNotnullableEnumIntegerOnly + /// requiredNotnullableEnumString + /// requiredNotnullableOuterEnumDefaultValue + /// requiredNotnullableStringProp + /// requiredNotnullableUuid + /// requiredNotnullableintegerProp + /// requiredNullableArrayOfString + /// requiredNullableBooleanProp + /// requiredNullableDateProp + /// requiredNullableDatetimeProp + /// requiredNullableEnumInteger + /// requiredNullableEnumIntegerOnly + /// requiredNullableEnumString + /// requiredNullableIntegerProp + /// requiredNullableOuterEnumDefaultValue + /// requiredNullableStringProp + /// requiredNullableUuid + /// notRequiredNotnullableDateProp + /// notRequiredNotnullableintegerProp + /// notRequiredNullableDateProp + /// notRequiredNullableIntegerProp + /// notrequiredNotnullableArrayOfString + /// notrequiredNotnullableBooleanProp + /// notrequiredNotnullableDatetimeProp + /// notrequiredNotnullableEnumInteger + /// notrequiredNotnullableEnumIntegerOnly + /// notrequiredNotnullableEnumString + /// notrequiredNotnullableOuterEnumDefaultValue + /// notrequiredNotnullableStringProp + /// notrequiredNotnullableUuid + /// notrequiredNullableArrayOfString + /// notrequiredNullableBooleanProp + /// notrequiredNullableDatetimeProp + /// notrequiredNullableEnumInteger + /// notrequiredNullableEnumIntegerOnly + /// notrequiredNullableEnumString + /// notrequiredNullableOuterEnumDefaultValue + /// notrequiredNullableStringProp + /// notrequiredNullableUuid + [JsonConstructor] + public RequiredClass(DateOnly requiredNotNullableDateProp, List requiredNotnullableArrayOfString, bool requiredNotnullableBooleanProp, DateTime requiredNotnullableDatetimeProp, RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger, RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly, RequiredNotnullableEnumStringEnum requiredNotnullableEnumString, OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue, string requiredNotnullableStringProp, Guid requiredNotnullableUuid, int requiredNotnullableintegerProp, List requiredNullableArrayOfString = default, bool? requiredNullableBooleanProp = default, DateOnly? requiredNullableDateProp = default, DateTime? requiredNullableDatetimeProp = default, RequiredNullableEnumIntegerEnum? requiredNullableEnumInteger = default, RequiredNullableEnumIntegerOnlyEnum? requiredNullableEnumIntegerOnly = default, RequiredNullableEnumStringEnum? requiredNullableEnumString = default, int? requiredNullableIntegerProp = default, OuterEnumDefaultValue? requiredNullableOuterEnumDefaultValue = default, string requiredNullableStringProp = default, Guid? requiredNullableUuid = default, Option notRequiredNotnullableDateProp = default, Option notRequiredNotnullableintegerProp = default, Option notRequiredNullableDateProp = default, Option notRequiredNullableIntegerProp = default, Option> notrequiredNotnullableArrayOfString = default, Option notrequiredNotnullableBooleanProp = default, Option notrequiredNotnullableDatetimeProp = default, Option notrequiredNotnullableEnumInteger = default, Option notrequiredNotnullableEnumIntegerOnly = default, Option notrequiredNotnullableEnumString = default, Option notrequiredNotnullableOuterEnumDefaultValue = default, Option notrequiredNotnullableStringProp = default, Option notrequiredNotnullableUuid = default, Option> notrequiredNullableArrayOfString = default, Option notrequiredNullableBooleanProp = default, Option notrequiredNullableDatetimeProp = default, Option notrequiredNullableEnumInteger = default, Option notrequiredNullableEnumIntegerOnly = default, Option notrequiredNullableEnumString = default, Option notrequiredNullableOuterEnumDefaultValue = default, Option notrequiredNullableStringProp = default, Option notrequiredNullableUuid = default) + { + RequiredNotNullableDateProp = requiredNotNullableDateProp; + RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + RequiredNotnullableEnumString = requiredNotnullableEnumString; + RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + RequiredNotnullableStringProp = requiredNotnullableStringProp; + RequiredNotnullableUuid = requiredNotnullableUuid; + RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + RequiredNullableArrayOfString = requiredNullableArrayOfString; + RequiredNullableBooleanProp = requiredNullableBooleanProp; + RequiredNullableDateProp = requiredNullableDateProp; + RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + RequiredNullableEnumInteger = requiredNullableEnumInteger; + RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + RequiredNullableEnumString = requiredNullableEnumString; + RequiredNullableIntegerProp = requiredNullableIntegerProp; + RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + RequiredNullableStringProp = requiredNullableStringProp; + RequiredNullableUuid = requiredNullableUuid; + NotRequiredNotnullableDatePropOption = notRequiredNotnullableDateProp; + NotRequiredNotnullableintegerPropOption = notRequiredNotnullableintegerProp; + NotRequiredNullableDatePropOption = notRequiredNullableDateProp; + NotRequiredNullableIntegerPropOption = notRequiredNullableIntegerProp; + NotrequiredNotnullableArrayOfStringOption = notrequiredNotnullableArrayOfString; + NotrequiredNotnullableBooleanPropOption = notrequiredNotnullableBooleanProp; + NotrequiredNotnullableDatetimePropOption = notrequiredNotnullableDatetimeProp; + NotrequiredNotnullableEnumIntegerOption = notrequiredNotnullableEnumInteger; + NotrequiredNotnullableEnumIntegerOnlyOption = notrequiredNotnullableEnumIntegerOnly; + NotrequiredNotnullableEnumStringOption = notrequiredNotnullableEnumString; + NotrequiredNotnullableOuterEnumDefaultValueOption = notrequiredNotnullableOuterEnumDefaultValue; + NotrequiredNotnullableStringPropOption = notrequiredNotnullableStringProp; + NotrequiredNotnullableUuidOption = notrequiredNotnullableUuid; + NotrequiredNullableArrayOfStringOption = notrequiredNullableArrayOfString; + NotrequiredNullableBooleanPropOption = notrequiredNullableBooleanProp; + NotrequiredNullableDatetimePropOption = notrequiredNullableDatetimeProp; + NotrequiredNullableEnumIntegerOption = notrequiredNullableEnumInteger; + NotrequiredNullableEnumIntegerOnlyOption = notrequiredNullableEnumIntegerOnly; + NotrequiredNullableEnumStringOption = notrequiredNullableEnumString; + NotrequiredNullableOuterEnumDefaultValueOption = notrequiredNullableOuterEnumDefaultValue; + NotrequiredNullableStringPropOption = notrequiredNullableStringProp; + NotrequiredNullableUuidOption = notrequiredNullableUuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum? RequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerEnumToJsonValue(RequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [JsonPropertyName("required_notnullable_enum_integer")] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum? RequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(RequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("required_notnullable_enum_integer_only")] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNotnullableEnumString + /// + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumStringEnum RequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumStringEnum? RequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNotnullableEnumStringEnumToJsonValue(RequiredNotnullableEnumStringEnum value) + { + if (value == RequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [JsonPropertyName("required_notnullable_enum_string")] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerEnum RequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerEnum? RequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerEnumToJsonValue(RequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [JsonPropertyName("required_nullable_enum_integer")] + public RequiredNullableEnumIntegerEnum? RequiredNullableEnumInteger { get; set; } + + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerOnlyEnumToJsonValue(RequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("required_nullable_enum_integer_only")] + public RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNullableEnumString + /// + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumStringEnum RequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumStringEnum? RequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNullableEnumStringEnumToJsonValue(RequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == RequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [JsonPropertyName("required_nullable_enum_string")] + public RequiredNullableEnumStringEnum? RequiredNullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum NotrequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerEnumToJsonValue(NotrequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [JsonPropertyName("notrequired_notnullable_enum_integer")] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get { return this.NotrequiredNotnullableEnumIntegerOption; } set { this.NotrequiredNotnullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum NotrequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_notnullable_enum_integer_only")] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get { return this.NotrequiredNotnullableEnumIntegerOnlyOption; } set { this.NotrequiredNotnullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNotnullableEnumString + /// + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum NotrequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNotnullableEnumStringEnumToJsonValue(NotrequiredNotnullableEnumStringEnum? value) + { + if (value == NotrequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [JsonPropertyName("notrequired_notnullable_enum_string")] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get { return this.NotrequiredNotnullableEnumStringOption; } set { this.NotrequiredNotnullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get { return this.NotrequiredNotnullableOuterEnumDefaultValueOption; } set { this.NotrequiredNotnullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum NotrequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerEnumToJsonValue(NotrequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [JsonPropertyName("notrequired_nullable_enum_integer")] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get { return this.NotrequiredNullableEnumIntegerOption; } set { this.NotrequiredNullableEnumIntegerOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum NotrequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_nullable_enum_integer_only")] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get { return this.NotrequiredNullableEnumIntegerOnlyOption; } set { this.NotrequiredNullableEnumIntegerOnlyOption = new(value); } } + + /// + /// Defines NotrequiredNullableEnumString + /// + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumStringEnum NotrequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNullableEnumStringEnumToJsonValue(NotrequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == NotrequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [JsonPropertyName("notrequired_nullable_enum_string")] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get { return this.NotrequiredNullableEnumStringOption; } set { this.NotrequiredNullableEnumStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get { return this.NotrequiredNullableOuterEnumDefaultValueOption; } set { this.NotrequiredNullableOuterEnumDefaultValueOption = new(value); } } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [JsonPropertyName("required_not_nullable_date_prop")] + public DateOnly RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [JsonPropertyName("required_notnullable_array_of_string")] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [JsonPropertyName("required_notnullable_boolean_prop")] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [JsonPropertyName("required_notnullable_datetime_prop")] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [JsonPropertyName("required_notnullable_string_prop")] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_notnullable_uuid")] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [JsonPropertyName("required_notnullableinteger_prop")] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [JsonPropertyName("required_nullable_array_of_string")] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [JsonPropertyName("required_nullable_boolean_prop")] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [JsonPropertyName("required_nullable_date_prop")] + public DateOnly? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [JsonPropertyName("required_nullable_datetime_prop")] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [JsonPropertyName("required_nullable_integer_prop")] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [JsonPropertyName("required_nullable_string_prop")] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_nullable_uuid")] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Used to track the state of NotRequiredNotnullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [JsonPropertyName("not_required_notnullable_date_prop")] + public DateOnly? NotRequiredNotnullableDateProp { get { return this. NotRequiredNotnullableDatePropOption; } set { this.NotRequiredNotnullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNotnullableintegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableintegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [JsonPropertyName("not_required_notnullableinteger_prop")] + public int? NotRequiredNotnullableintegerProp { get { return this. NotRequiredNotnullableintegerPropOption; } set { this.NotRequiredNotnullableintegerPropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [JsonPropertyName("not_required_nullable_date_prop")] + public DateOnly? NotRequiredNullableDateProp { get { return this. NotRequiredNullableDatePropOption; } set { this.NotRequiredNullableDatePropOption = new(value); } } + + /// + /// Used to track the state of NotRequiredNullableIntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableIntegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [JsonPropertyName("not_required_nullable_integer_prop")] + public int? NotRequiredNullableIntegerProp { get { return this. NotRequiredNullableIntegerPropOption; } set { this.NotRequiredNullableIntegerPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> NotrequiredNotnullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [JsonPropertyName("notrequired_notnullable_array_of_string")] + public List NotrequiredNotnullableArrayOfString { get { return this. NotrequiredNotnullableArrayOfStringOption; } set { this.NotrequiredNotnullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [JsonPropertyName("notrequired_notnullable_boolean_prop")] + public bool? NotrequiredNotnullableBooleanProp { get { return this. NotrequiredNotnullableBooleanPropOption; } set { this.NotrequiredNotnullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [JsonPropertyName("notrequired_notnullable_datetime_prop")] + public DateTime? NotrequiredNotnullableDatetimeProp { get { return this. NotrequiredNotnullableDatetimePropOption; } set { this.NotrequiredNotnullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [JsonPropertyName("notrequired_notnullable_string_prop")] + public string NotrequiredNotnullableStringProp { get { return this. NotrequiredNotnullableStringPropOption; } set { this.NotrequiredNotnullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_notnullable_uuid")] + public Guid? NotrequiredNotnullableUuid { get { return this. NotrequiredNotnullableUuidOption; } set { this.NotrequiredNotnullableUuidOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> NotrequiredNullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [JsonPropertyName("notrequired_nullable_array_of_string")] + public List NotrequiredNullableArrayOfString { get { return this. NotrequiredNullableArrayOfStringOption; } set { this.NotrequiredNullableArrayOfStringOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [JsonPropertyName("notrequired_nullable_boolean_prop")] + public bool? NotrequiredNullableBooleanProp { get { return this. NotrequiredNullableBooleanPropOption; } set { this.NotrequiredNullableBooleanPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [JsonPropertyName("notrequired_nullable_datetime_prop")] + public DateTime? NotrequiredNullableDatetimeProp { get { return this. NotrequiredNullableDatetimePropOption; } set { this.NotrequiredNullableDatetimePropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [JsonPropertyName("notrequired_nullable_string_prop")] + public string NotrequiredNullableStringProp { get { return this. NotrequiredNullableStringPropOption; } set { this.NotrequiredNullableStringPropOption = new(value); } } + + /// + /// Used to track the state of NotrequiredNullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_nullable_uuid")] + public Guid? NotrequiredNullableUuid { get { return this. NotrequiredNullableUuidOption; } set { this.NotrequiredNullableUuidOption = new(value); } } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RequiredClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RequiredNotNullableDateProp + /// + public static string RequiredNotNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNotnullableDatetimeProp + /// + public static string RequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize RequiredNullableDateProp + /// + public static string RequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNullableDatetimeProp + /// + public static string RequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotRequiredNotnullableDateProp + /// + public static string NotRequiredNotnullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotRequiredNullableDateProp + /// + public static string NotRequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotrequiredNotnullableDatetimeProp + /// + public static string NotrequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotrequiredNullableDatetimeProp + /// + public static string NotrequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RequiredClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requiredNotNullableDateProp = default; + Option> requiredNotnullableArrayOfString = default; + Option requiredNotnullableBooleanProp = default; + Option requiredNotnullableDatetimeProp = default; + Option requiredNotnullableEnumInteger = default; + Option requiredNotnullableEnumIntegerOnly = default; + Option requiredNotnullableEnumString = default; + Option requiredNotnullableOuterEnumDefaultValue = default; + Option requiredNotnullableStringProp = default; + Option requiredNotnullableUuid = default; + Option requiredNotnullableintegerProp = default; + Option> requiredNullableArrayOfString = default; + Option requiredNullableBooleanProp = default; + Option requiredNullableDateProp = default; + Option requiredNullableDatetimeProp = default; + Option requiredNullableEnumInteger = default; + Option requiredNullableEnumIntegerOnly = default; + Option requiredNullableEnumString = default; + Option requiredNullableIntegerProp = default; + Option requiredNullableOuterEnumDefaultValue = default; + Option requiredNullableStringProp = default; + Option requiredNullableUuid = default; + Option notRequiredNotnullableDateProp = default; + Option notRequiredNotnullableintegerProp = default; + Option notRequiredNullableDateProp = default; + Option notRequiredNullableIntegerProp = default; + Option> notrequiredNotnullableArrayOfString = default; + Option notrequiredNotnullableBooleanProp = default; + Option notrequiredNotnullableDatetimeProp = default; + Option notrequiredNotnullableEnumInteger = default; + Option notrequiredNotnullableEnumIntegerOnly = default; + Option notrequiredNotnullableEnumString = default; + Option notrequiredNotnullableOuterEnumDefaultValue = default; + Option notrequiredNotnullableStringProp = default; + Option notrequiredNotnullableUuid = default; + Option> notrequiredNullableArrayOfString = default; + Option notrequiredNullableBooleanProp = default; + Option notrequiredNullableDatetimeProp = default; + Option notrequiredNullableEnumInteger = default; + Option notrequiredNullableEnumIntegerOnly = default; + Option notrequiredNullableEnumString = default; + Option notrequiredNullableOuterEnumDefaultValue = default; + Option notrequiredNullableStringProp = default; + Option notrequiredNullableUuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "required_not_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumInteger = new Option((RequiredClass.RequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumIntegerOnly = new Option((RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_string": + string requiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableEnumStringRawValue != null) + requiredNotnullableEnumString = new Option(RequiredClass.RequiredNotnullableEnumStringEnumFromStringOrDefault(requiredNotnullableEnumStringRawValue)); + break; + case "required_notnullable_outerEnumDefaultValue": + string requiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableOuterEnumDefaultValueRawValue != null) + requiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "required_notnullable_string_prop": + requiredNotnullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumInteger = new Option((RequiredClass.RequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumIntegerOnly = new Option((RequiredClass.RequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_string": + string requiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNullableEnumStringRawValue != null) + requiredNullableEnumString = new Option(RequiredClass.RequiredNullableEnumStringEnumFromStringOrDefault(requiredNullableEnumStringRawValue)); + break; + case "required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_outerEnumDefaultValue": + string requiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + requiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNullableOuterEnumDefaultValueRawValue)); + break; + case "required_nullable_string_prop": + requiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "not_required_notnullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "not_required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumInteger = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_string": + string notrequiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableEnumStringRawValue != null) + notrequiredNotnullableEnumString = new Option(RequiredClass.NotrequiredNotnullableEnumStringEnumFromStringOrDefault(notrequiredNotnullableEnumStringRawValue)); + break; + case "notrequired_notnullable_outerEnumDefaultValue": + string notrequiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableOuterEnumDefaultValueRawValue != null) + notrequiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_notnullable_string_prop": + notrequiredNotnullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "notrequired_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumInteger = new Option((RequiredClass.NotrequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_string": + string notrequiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableEnumStringRawValue != null) + notrequiredNullableEnumString = new Option(RequiredClass.NotrequiredNullableEnumStringEnumFromStringOrDefault(notrequiredNullableEnumStringRawValue)); + break; + case "notrequired_nullable_outerEnumDefaultValue": + string notrequiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableOuterEnumDefaultValueRawValue != null) + notrequiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_nullable_string_prop": + notrequiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + default: + break; + } + } + } + + if (!requiredNotNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotNullableDateProp)); + + if (!requiredNotnullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableArrayOfString)); + + if (!requiredNotnullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableBooleanProp)); + + if (!requiredNotnullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableDatetimeProp)); + + if (!requiredNotnullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumInteger)); + + if (!requiredNotnullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumIntegerOnly)); + + if (!requiredNotnullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumString)); + + if (!requiredNotnullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableOuterEnumDefaultValue)); + + if (!requiredNotnullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableStringProp)); + + if (!requiredNotnullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableUuid)); + + if (!requiredNotnullableintegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableintegerProp)); + + if (!requiredNullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableArrayOfString)); + + if (!requiredNullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableBooleanProp)); + + if (!requiredNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDateProp)); + + if (!requiredNullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDatetimeProp)); + + if (!requiredNullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumInteger)); + + if (!requiredNullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumIntegerOnly)); + + if (!requiredNullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumString)); + + if (!requiredNullableIntegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableIntegerProp)); + + if (!requiredNullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableOuterEnumDefaultValue)); + + if (!requiredNullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableStringProp)); + + if (!requiredNullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableUuid)); + + if (requiredNotNullableDateProp.IsSet && requiredNotNullableDateProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotNullableDateProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableArrayOfString.IsSet && requiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableBooleanProp.IsSet && requiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableDatetimeProp.IsSet && requiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumInteger.IsSet && requiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumIntegerOnly.IsSet && requiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumString.IsSet && requiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableOuterEnumDefaultValue.IsSet && requiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableStringProp.IsSet && requiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableUuid.IsSet && requiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableintegerProp.IsSet && requiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableDateProp.IsSet && notRequiredNotnullableDateProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableDateProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableintegerProp.IsSet && notRequiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableArrayOfString.IsSet && notrequiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableBooleanProp.IsSet && notrequiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableDatetimeProp.IsSet && notrequiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumInteger.IsSet && notrequiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumIntegerOnly.IsSet && notrequiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumString.IsSet && notrequiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableOuterEnumDefaultValue.IsSet && notrequiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableStringProp.IsSet && notrequiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableUuid.IsSet && notrequiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + return new RequiredClass(requiredNotNullableDateProp.Value.Value, requiredNotnullableArrayOfString.Value, requiredNotnullableBooleanProp.Value.Value, requiredNotnullableDatetimeProp.Value.Value, requiredNotnullableEnumInteger.Value.Value, requiredNotnullableEnumIntegerOnly.Value.Value, requiredNotnullableEnumString.Value.Value, requiredNotnullableOuterEnumDefaultValue.Value.Value, requiredNotnullableStringProp.Value, requiredNotnullableUuid.Value.Value, requiredNotnullableintegerProp.Value.Value, requiredNullableArrayOfString.Value, requiredNullableBooleanProp.Value, requiredNullableDateProp.Value, requiredNullableDatetimeProp.Value, requiredNullableEnumInteger.Value, requiredNullableEnumIntegerOnly.Value, requiredNullableEnumString.Value, requiredNullableIntegerProp.Value, requiredNullableOuterEnumDefaultValue.Value, requiredNullableStringProp.Value, requiredNullableUuid.Value, notRequiredNotnullableDateProp, notRequiredNotnullableintegerProp, notRequiredNullableDateProp, notRequiredNullableIntegerProp, notrequiredNotnullableArrayOfString, notrequiredNotnullableBooleanProp, notrequiredNotnullableDatetimeProp, notrequiredNotnullableEnumInteger, notrequiredNotnullableEnumIntegerOnly, notrequiredNotnullableEnumString, notrequiredNotnullableOuterEnumDefaultValue, notrequiredNotnullableStringProp, notrequiredNotnullableUuid, notrequiredNullableArrayOfString, notrequiredNullableBooleanProp, notrequiredNullableDatetimeProp, notrequiredNullableEnumInteger, notrequiredNullableEnumIntegerOnly, notrequiredNullableEnumString, notrequiredNullableOuterEnumDefaultValue, notrequiredNullableStringProp, notrequiredNullableUuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, requiredClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + if (requiredClass.RequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.RequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet && requiredClass.NotrequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet && requiredClass.NotrequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + writer.WriteString("required_not_nullable_date_prop", requiredClass.RequiredNotNullableDateProp.ToString(RequiredNotNullableDatePropFormat)); + + writer.WritePropertyName("required_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNotnullableArrayOfString, jsonSerializerOptions); + writer.WriteBoolean("required_notnullable_boolean_prop", requiredClass.RequiredNotnullableBooleanProp); + + writer.WriteString("required_notnullable_datetime_prop", requiredClass.RequiredNotnullableDatetimeProp.ToString(RequiredNotnullableDatetimePropFormat)); + + writer.WriteNumber("required_notnullable_enum_integer", RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNotnullableEnumInteger)); + + writer.WriteNumber("required_notnullable_enum_integer_only", RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNotnullableEnumIntegerOnly)); + + var requiredNotnullableEnumStringRawValue = RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClass.RequiredNotnullableEnumString); + writer.WriteString("required_notnullable_enum_string", requiredNotnullableEnumStringRawValue); + var requiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNotnullableOuterEnumDefaultValue); + writer.WriteString("required_notnullable_outerEnumDefaultValue", requiredNotnullableOuterEnumDefaultValueRawValue); + + writer.WriteString("required_notnullable_string_prop", requiredClass.RequiredNotnullableStringProp); + + writer.WriteString("required_notnullable_uuid", requiredClass.RequiredNotnullableUuid); + + writer.WriteNumber("required_notnullableinteger_prop", requiredClass.RequiredNotnullableintegerProp); + + if (requiredClass.RequiredNullableArrayOfString != null) + { + writer.WritePropertyName("required_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("required_nullable_array_of_string"); + if (requiredClass.RequiredNullableBooleanProp != null) + writer.WriteBoolean("required_nullable_boolean_prop", requiredClass.RequiredNullableBooleanProp.Value); + else + writer.WriteNull("required_nullable_boolean_prop"); + + if (requiredClass.RequiredNullableDateProp != null) + writer.WriteString("required_nullable_date_prop", requiredClass.RequiredNullableDateProp.Value.ToString(RequiredNullableDatePropFormat)); + else + writer.WriteNull("required_nullable_date_prop"); + + if (requiredClass.RequiredNullableDatetimeProp != null) + writer.WriteString("required_nullable_datetime_prop", requiredClass.RequiredNullableDatetimeProp.Value.ToString(RequiredNullableDatetimePropFormat)); + else + writer.WriteNull("required_nullable_datetime_prop"); + + if (requiredClass.RequiredNullableEnumInteger != null) + writer.WriteNumber("required_nullable_enum_integer", RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNullableEnumInteger.Value)); + else + writer.WriteNull("required_nullable_enum_integer"); + + if (requiredClass.RequiredNullableEnumIntegerOnly != null) + writer.WriteNumber("required_nullable_enum_integer_only", RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNullableEnumIntegerOnly.Value)); + else + writer.WriteNull("required_nullable_enum_integer_only"); + + var requiredNullableEnumStringRawValue = RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClass.RequiredNullableEnumString.Value); + if (requiredNullableEnumStringRawValue != null) + writer.WriteString("required_nullable_enum_string", requiredNullableEnumStringRawValue); + else + writer.WriteNull("required_nullable_enum_string"); + + if (requiredClass.RequiredNullableIntegerProp != null) + writer.WriteNumber("required_nullable_integer_prop", requiredClass.RequiredNullableIntegerProp.Value); + else + writer.WriteNull("required_nullable_integer_prop"); + + if (requiredClass.RequiredNullableOuterEnumDefaultValue == null) + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + else + { + var requiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNullableOuterEnumDefaultValue.Value); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + writer.WriteString("required_nullable_outerEnumDefaultValue", requiredNullableOuterEnumDefaultValueRawValue); + else + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + } + + if (requiredClass.RequiredNullableStringProp != null) + writer.WriteString("required_nullable_string_prop", requiredClass.RequiredNullableStringProp); + else + writer.WriteNull("required_nullable_string_prop"); + + if (requiredClass.RequiredNullableUuid != null) + writer.WriteString("required_nullable_uuid", requiredClass.RequiredNullableUuid.Value); + else + writer.WriteNull("required_nullable_uuid"); + + if (requiredClass.NotRequiredNotnullableDatePropOption.IsSet) + writer.WriteString("not_required_notnullable_date_prop", requiredClass.NotRequiredNotnullableDatePropOption.Value.Value.ToString(NotRequiredNotnullableDatePropFormat)); + + if (requiredClass.NotRequiredNotnullableintegerPropOption.IsSet) + writer.WriteNumber("not_required_notnullableinteger_prop", requiredClass.NotRequiredNotnullableintegerPropOption.Value.Value); + + if (requiredClass.NotRequiredNullableDatePropOption.IsSet) + if (requiredClass.NotRequiredNullableDatePropOption.Value != null) + writer.WriteString("not_required_nullable_date_prop", requiredClass.NotRequiredNullableDatePropOption.Value.Value.ToString(NotRequiredNullableDatePropFormat)); + else + writer.WriteNull("not_required_nullable_date_prop"); + + if (requiredClass.NotRequiredNullableIntegerPropOption.IsSet) + if (requiredClass.NotRequiredNullableIntegerPropOption.Value != null) + writer.WriteNumber("not_required_nullable_integer_prop", requiredClass.NotRequiredNullableIntegerPropOption.Value.Value); + else + writer.WriteNull("not_required_nullable_integer_prop"); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet) + { + writer.WritePropertyName("notrequired_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNotnullableArrayOfString, jsonSerializerOptions); + } + if (requiredClass.NotrequiredNotnullableBooleanPropOption.IsSet) + writer.WriteBoolean("notrequired_notnullable_boolean_prop", requiredClass.NotrequiredNotnullableBooleanPropOption.Value.Value); + + if (requiredClass.NotrequiredNotnullableDatetimePropOption.IsSet) + writer.WriteString("notrequired_notnullable_datetime_prop", requiredClass.NotrequiredNotnullableDatetimePropOption.Value.Value.ToString(NotrequiredNotnullableDatetimePropFormat)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer", RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOption.Value.Value)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer_only", RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.Value.Value)); + + var notrequiredNotnullableEnumStringRawValue = RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumStringOption.Value.Value); + writer.WriteString("notrequired_notnullable_enum_string", notrequiredNotnullableEnumStringRawValue); + if (requiredClass.NotrequiredNotnullableOuterEnumDefaultValueOption.IsSet) + { + var notrequiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNotnullableOuterEnumDefaultValue.Value); + writer.WriteString("notrequired_notnullable_outerEnumDefaultValue", notrequiredNotnullableOuterEnumDefaultValueRawValue); + } + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet) + writer.WriteString("notrequired_notnullable_string_prop", requiredClass.NotrequiredNotnullableStringProp); + + if (requiredClass.NotrequiredNotnullableUuidOption.IsSet) + writer.WriteString("notrequired_notnullable_uuid", requiredClass.NotrequiredNotnullableUuidOption.Value.Value); + + if (requiredClass.NotrequiredNullableArrayOfStringOption.IsSet) + if (requiredClass.NotrequiredNullableArrayOfStringOption.Value != null) + { + writer.WritePropertyName("notrequired_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("notrequired_nullable_array_of_string"); + if (requiredClass.NotrequiredNullableBooleanPropOption.IsSet) + if (requiredClass.NotrequiredNullableBooleanPropOption.Value != null) + writer.WriteBoolean("notrequired_nullable_boolean_prop", requiredClass.NotrequiredNullableBooleanPropOption.Value.Value); + else + writer.WriteNull("notrequired_nullable_boolean_prop"); + + if (requiredClass.NotrequiredNullableDatetimePropOption.IsSet) + if (requiredClass.NotrequiredNullableDatetimePropOption.Value != null) + writer.WriteString("notrequired_nullable_datetime_prop", requiredClass.NotrequiredNullableDatetimePropOption.Value.Value.ToString(NotrequiredNullableDatetimePropFormat)); + else + writer.WriteNull("notrequired_nullable_datetime_prop"); + + if (requiredClass.NotrequiredNullableEnumIntegerOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer", RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOption.Value.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer"); + + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer_only", RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer_only"); + + var notrequiredNullableEnumStringRawValue = RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNullableEnumStringOption.Value.Value); + if (notrequiredNullableEnumStringRawValue != null) + writer.WriteString("notrequired_nullable_enum_string", notrequiredNullableEnumStringRawValue); + else + writer.WriteNull("notrequired_nullable_enum_string"); + + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.IsSet) + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value != null) + { + var notrequiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value.Value); + writer.WriteString("notrequired_nullable_outerEnumDefaultValue", notrequiredNullableOuterEnumDefaultValueRawValue); + } + else + writer.WriteNull("notrequired_nullable_outerEnumDefaultValue"); + if (requiredClass.NotrequiredNullableStringPropOption.IsSet) + if (requiredClass.NotrequiredNullableStringPropOption.Value != null) + writer.WriteString("notrequired_nullable_string_prop", requiredClass.NotrequiredNullableStringProp); + else + writer.WriteNull("notrequired_nullable_string_prop"); + + if (requiredClass.NotrequiredNullableUuidOption.IsSet) + if (requiredClass.NotrequiredNullableUuidOption.Value != null) + writer.WriteString("notrequired_nullable_uuid", requiredClass.NotrequiredNullableUuidOption.Value.Value); + else + writer.WriteNull("notrequired_nullable_uuid"); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs index 86e7223ee957..604c4abd4e06 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Return.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Return : IValidatableObject /// /// varReturn [JsonConstructor] - public Return(int varReturn) + public Return(Option varReturn = default) { - VarReturn = varReturn; + VarReturnOption = varReturn; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarReturn + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarReturnOption { get; private set; } + /// /// Gets or Sets VarReturn /// [JsonPropertyName("return")] - public int VarReturn { get; set; } + public int? VarReturn { get { return this. VarReturnOption; } set { this.VarReturnOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varReturn = default; + Option varReturn = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "return": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varReturn = utf8JsonReader.GetInt32(); + varReturn = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -127,10 +135,10 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (varReturn == null) - throw new ArgumentNullException(nameof(varReturn), "Property is required for class Return."); + if (varReturn.IsSet && varReturn.Value == null) + throw new ArgumentNullException(nameof(varReturn), "Property is not nullable for class Return."); - return new Return(varReturn.Value); + return new Return(varReturn); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, Return varReturn, JsonSerializ /// public void WriteProperties(ref Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("return", varReturn.VarReturn); + if (varReturn.VarReturnOption.IsSet) + writer.WriteNumber("return", varReturn.VarReturnOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs index 86effcebe7ae..b5b205f69914 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class RolesReportsHash : IValidatableObject /// role /// roleUuid [JsonConstructor] - public RolesReportsHash(RolesReportsHashRole role, Guid roleUuid) + public RolesReportsHash(Option role = default, Option roleUuid = default) { - Role = role; - RoleUuid = roleUuid; + RoleOption = role; + RoleUuidOption = roleUuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Role + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleOption { get; private set; } + /// /// Gets or Sets Role /// [JsonPropertyName("role")] - public RolesReportsHashRole Role { get; set; } + public RolesReportsHashRole Role { get { return this. RoleOption; } set { this.RoleOption = new(value); } } + + /// + /// Used to track the state of RoleUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleUuidOption { get; private set; } /// /// Gets or Sets RoleUuid /// [JsonPropertyName("role_uuid")] - public Guid RoleUuid { get; set; } + public Guid? RoleUuid { get { return this. RoleUuidOption; } set { this.RoleUuidOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - RolesReportsHashRole role = default; - Guid? roleUuid = default; + Option role = default; + Option roleUuid = default; while (utf8JsonReader.Read()) { @@ -129,11 +144,11 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty { case "role": if (utf8JsonReader.TokenType != JsonTokenType.Null) - role = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + role = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "role_uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - roleUuid = utf8JsonReader.GetGuid(); + roleUuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -141,13 +156,13 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (role == null) - throw new ArgumentNullException(nameof(role), "Property is required for class RolesReportsHash."); + if (role.IsSet && role.Value == null) + throw new ArgumentNullException(nameof(role), "Property is not nullable for class RolesReportsHash."); - if (roleUuid == null) - throw new ArgumentNullException(nameof(roleUuid), "Property is required for class RolesReportsHash."); + if (roleUuid.IsSet && roleUuid.Value == null) + throw new ArgumentNullException(nameof(roleUuid), "Property is not nullable for class RolesReportsHash."); - return new RolesReportsHash(role, roleUuid.Value); + return new RolesReportsHash(role, roleUuid); } /// @@ -174,9 +189,16 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHash rolesReportsH /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("role"); - JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); - writer.WriteString("role_uuid", rolesReportsHash.RoleUuid); + if (rolesReportsHash.RoleOption.IsSet && rolesReportsHash.Role == null) + throw new ArgumentNullException(nameof(rolesReportsHash.Role), "Property is required for class RolesReportsHash."); + + if (rolesReportsHash.RoleOption.IsSet) + { + writer.WritePropertyName("role"); + JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); + } + if (rolesReportsHash.RoleUuidOption.IsSet) + writer.WriteString("role_uuid", rolesReportsHash.RoleUuidOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs index c7002b77b2e1..7fa32c72ce29 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class RolesReportsHashRole : IValidatableObject /// /// name [JsonConstructor] - public RolesReportsHashRole(string name) + public RolesReportsHashRole(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class RolesReportsHashRole."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class RolesReportsHashRole."); return new RolesReportsHashRole(name); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHashRole rolesRepo /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", rolesReportsHashRole.Name); + if (rolesReportsHashRole.NameOption.IsSet && rolesReportsHashRole.Name == null) + throw new ArgumentNullException(nameof(rolesReportsHashRole.Name), "Property is required for class RolesReportsHashRole."); + + if (rolesReportsHashRole.NameOption.IsSet) + writer.WriteString("name", rolesReportsHashRole.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 4151ead57dfb..52a8e0d69c60 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ScaleneTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class ScaleneTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(triangleType)); - return new ScaleneTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ScaleneTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class ScaleneTriangle."); + + return new ScaleneTriangle(shapeType.Value, triangleType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangl /// public void WriteProperties(ref Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (scaleneTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.ShapeType), "Property is required for class ScaleneTriangle."); + + if (scaleneTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.TriangleType), "Property is required for class ScaleneTriangle."); + writer.WriteString("shapeType", scaleneTriangle.ShapeType); + writer.WriteString("triangleType", scaleneTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs index dae0ef02f966..575069f242e0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Shape.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class Shape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class Shape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class Shape."); if (quadrilateral != null) - return new Shape(quadrilateral, shapeType); + return new Shape(quadrilateral, shapeType.Value); if (triangle != null) - return new Shape(triangle, shapeType); + return new Shape(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) { + if (shape.ShapeType == null) + throw new ArgumentNullException(nameof(shape.ShapeType), "Property is required for class Shape."); + writer.WriteString("shapeType", shape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index de32fa535aec..5bd364cc6a41 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeInterface."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeInterface.", nameof(shapeType)); - return new ShapeInterface(shapeType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeInterface."); + + return new ShapeInterface(shapeType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) { + if (shapeInterface.ShapeType == null) + throw new ArgumentNullException(nameof(shapeInterface.ShapeType), "Property is required for class ShapeInterface."); + writer.WriteString("shapeType", shapeInterface.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 955461e12024..a26dab034230 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeOrNull."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeOrNull.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeOrNull."); if (quadrilateral != null) - return new ShapeOrNull(quadrilateral, shapeType); + return new ShapeOrNull(quadrilateral, shapeType.Value); if (triangle != null) - return new ShapeOrNull(triangle, shapeType); + return new ShapeOrNull(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) { + if (shapeOrNull.ShapeType == null) + throw new ArgumentNullException(nameof(shapeOrNull.ShapeType), "Property is required for class ShapeOrNull."); + writer.WriteString("shapeType", shapeOrNull.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 7f0b8a306f80..a00a87e2efa5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; - string shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class SimpleQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class SimpleQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(shapeType)); - return new SimpleQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class SimpleQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class SimpleQuadrilateral."); + + return new SimpleQuadrilateral(quadrilateralType.Value, shapeType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuad /// public void WriteProperties(ref Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (simpleQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.QuadrilateralType), "Property is required for class SimpleQuadrilateral."); + + if (simpleQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.ShapeType), "Property is required for class SimpleQuadrilateral."); + writer.WriteString("quadrilateralType", simpleQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", simpleQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs index 8328ad3ee121..419b6a022a8f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class SpecialModelName : IValidatableObject /// varSpecialModelName /// specialPropertyName [JsonConstructor] - public SpecialModelName(string varSpecialModelName, long specialPropertyName) + public SpecialModelName(Option varSpecialModelName = default, Option specialPropertyName = default) { - VarSpecialModelName = varSpecialModelName; - SpecialPropertyName = specialPropertyName; + VarSpecialModelNameOption = varSpecialModelName; + SpecialPropertyNameOption = specialPropertyName; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarSpecialModelName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarSpecialModelNameOption { get; private set; } + /// /// Gets or Sets VarSpecialModelName /// [JsonPropertyName("_special_model.name_")] - public string VarSpecialModelName { get; set; } + public string VarSpecialModelName { get { return this. VarSpecialModelNameOption; } set { this.VarSpecialModelNameOption = new(value); } } + + /// + /// Used to track the state of SpecialPropertyName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SpecialPropertyNameOption { get; private set; } /// /// Gets or Sets SpecialPropertyName /// [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + public long? SpecialPropertyName { get { return this. SpecialPropertyNameOption; } set { this.SpecialPropertyNameOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varSpecialModelName = default; - long? specialPropertyName = default; + Option varSpecialModelName = default; + Option specialPropertyName = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "_special_model.name_": - varSpecialModelName = utf8JsonReader.GetString(); + varSpecialModelName = new Option(utf8JsonReader.GetString()); break; case "$special[property.name]": if (utf8JsonReader.TokenType != JsonTokenType.Null) - specialPropertyName = utf8JsonReader.GetInt64(); + specialPropertyName = new Option(utf8JsonReader.GetInt64()); break; default: break; @@ -140,13 +155,13 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varSpecialModelName == null) - throw new ArgumentNullException(nameof(varSpecialModelName), "Property is required for class SpecialModelName."); + if (varSpecialModelName.IsSet && varSpecialModelName.Value == null) + throw new ArgumentNullException(nameof(varSpecialModelName), "Property is not nullable for class SpecialModelName."); - if (specialPropertyName == null) - throw new ArgumentNullException(nameof(specialPropertyName), "Property is required for class SpecialModelName."); + if (specialPropertyName.IsSet && specialPropertyName.Value == null) + throw new ArgumentNullException(nameof(specialPropertyName), "Property is not nullable for class SpecialModelName."); - return new SpecialModelName(varSpecialModelName, specialPropertyName.Value); + return new SpecialModelName(varSpecialModelName, specialPropertyName); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelN /// public void WriteProperties(ref Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); - writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyName); + if (specialModelName.VarSpecialModelNameOption.IsSet && specialModelName.VarSpecialModelName == null) + throw new ArgumentNullException(nameof(specialModelName.VarSpecialModelName), "Property is required for class SpecialModelName."); + + if (specialModelName.VarSpecialModelNameOption.IsSet) + writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); + + if (specialModelName.SpecialPropertyNameOption.IsSet) + writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyNameOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs index 6524d75edcf5..418d24e6f1cf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Tag.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class Tag : IValidatableObject /// id /// name [JsonConstructor] - public Tag(long id, string name) + public Tag(Option id = default, Option name = default) { - Id = id; - Name = name; + IdOption = id; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -129,10 +144,10 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -140,13 +155,13 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Tag."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Tag."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Tag."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Tag."); - return new Tag(id.Value, name); + return new Tag(id, name); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", tag.Id); - writer.WriteString("name", tag.Name); + if (tag.NameOption.IsSet && tag.Name == null) + throw new ArgumentNullException(nameof(tag.Name), "Property is required for class Tag."); + + if (tag.IdOption.IsSet) + writer.WriteNumber("id", tag.IdOption.Value.Value); + + if (tag.NameOption.IsSet) + writer.WriteString("name", tag.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs index b2e110e79f67..4a89db3e4ee6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class TestCollectionEndingWithWordList : IValidatableObject /// /// value [JsonConstructor] - public TestCollectionEndingWithWordList(string value) + public TestCollectionEndingWithWordList(Option value = default) { - Value = value; + ValueOption = value; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Value + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ValueOption { get; private set; } + /// /// Gets or Sets Value /// [JsonPropertyName("value")] - public string Value { get; set; } + public string Value { get { return this. ValueOption; } set { this.ValueOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string value = default; + Option value = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso switch (localVarJsonPropertyName) { case "value": - value = utf8JsonReader.GetString(); + value = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso } } - if (value == null) - throw new ArgumentNullException(nameof(value), "Property is required for class TestCollectionEndingWithWordList."); + if (value.IsSet && value.Value == null) + throw new ArgumentNullException(nameof(value), "Property is not nullable for class TestCollectionEndingWithWordList."); return new TestCollectionEndingWithWordList(value); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("value", testCollectionEndingWithWordList.Value); + if (testCollectionEndingWithWordList.ValueOption.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList.Value), "Property is required for class TestCollectionEndingWithWordList."); + + if (testCollectionEndingWithWordList.ValueOption.IsSet) + writer.WriteString("value", testCollectionEndingWithWordList.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs index 8753edfd9f35..7479f313811a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class TestCollectionEndingWithWordListObject : IValidatableObject /// /// testCollectionEndingWithWordList [JsonConstructor] - public TestCollectionEndingWithWordListObject(List testCollectionEndingWithWordList) + public TestCollectionEndingWithWordListObject(Option> testCollectionEndingWithWordList = default) { - TestCollectionEndingWithWordList = testCollectionEndingWithWordList; + TestCollectionEndingWithWordListOption = testCollectionEndingWithWordList; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of TestCollectionEndingWithWordList + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> TestCollectionEndingWithWordListOption { get; private set; } + /// /// Gets or Sets TestCollectionEndingWithWordList /// [JsonPropertyName("TestCollectionEndingWithWordList")] - public List TestCollectionEndingWithWordList { get; set; } + public List TestCollectionEndingWithWordList { get { return this. TestCollectionEndingWithWordListOption; } set { this.TestCollectionEndingWithWordListOption = new(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List testCollectionEndingWithWordList = default; + Option> testCollectionEndingWithWordList = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u { case "TestCollectionEndingWithWordList": if (utf8JsonReader.TokenType != JsonTokenType.Null) - testCollectionEndingWithWordList = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + testCollectionEndingWithWordList = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u } } - if (testCollectionEndingWithWordList == null) - throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + if (testCollectionEndingWithWordList.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is not nullable for class TestCollectionEndingWithWordListObject."); return new TestCollectionEndingWithWordListObject(testCollectionEndingWithWordList); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("TestCollectionEndingWithWordList"); - JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet && testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet) + { + writer.WritePropertyName("TestCollectionEndingWithWordList"); + JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index 139e92b4c6a8..3b43021d8df0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -20,32 +20,40 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// TestInlineFreeformAdditionalPropertiesRequest /// - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty [JsonConstructor] - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty) : base() + public TestInlineFreeformAdditionalPropertiesRequest(Option someProperty = default) { - SomeProperty = someProperty; + SomePropertyOption = someProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SomeProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SomePropertyOption { get; private set; } + /// /// Gets or Sets SomeProperty /// [JsonPropertyName("someProperty")] - public string SomeProperty { get; set; } + public string SomeProperty { get { return this. SomePropertyOption; } set { this.SomePropertyOption = new(value); } } /// /// Gets or Sets additional properties @@ -61,7 +69,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -74,16 +81,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -111,7 +108,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string someProperty = default; + Option someProperty = default; while (utf8JsonReader.Read()) { @@ -129,7 +126,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR switch (localVarJsonPropertyName) { case "someProperty": - someProperty = utf8JsonReader.GetString(); + someProperty = new Option(utf8JsonReader.GetString()); break; default: break; @@ -137,8 +134,8 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR } } - if (someProperty == null) - throw new ArgumentNullException(nameof(someProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + if (someProperty.IsSet && someProperty.Value == null) + throw new ArgumentNullException(nameof(someProperty), "Property is not nullable for class TestInlineFreeformAdditionalPropertiesRequest."); return new TestInlineFreeformAdditionalPropertiesRequest(someProperty); } @@ -167,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, TestInlineFreeformAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet && testInlineFreeformAdditionalPropertiesRequest.SomeProperty == null) + throw new ArgumentNullException(nameof(testInlineFreeformAdditionalPropertiesRequest.SomeProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet) + writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs index 814316961f91..737124e080b3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Triangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -150,7 +151,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string triangleType = default; + Option triangleType = default; EquilateralTriangle equilateralTriangle = null; IsoscelesTriangle isoscelesTriangle = null; @@ -207,7 +208,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -215,17 +216,20 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class Triangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class Triangle.", nameof(triangleType)); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class Triangle."); if (equilateralTriangle != null) - return new Triangle(equilateralTriangle, triangleType); + return new Triangle(equilateralTriangle, triangleType.Value); if (isoscelesTriangle != null) - return new Triangle(isoscelesTriangle, triangleType); + return new Triangle(isoscelesTriangle, triangleType.Value); if (scaleneTriangle != null) - return new Triangle(scaleneTriangle, triangleType); + return new Triangle(scaleneTriangle, triangleType.Value); throw new JsonException(); } @@ -269,6 +273,9 @@ public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) { + if (triangle.TriangleType == null) + throw new ArgumentNullException(nameof(triangle.TriangleType), "Property is required for class Triangle."); + writer.WriteString("triangleType", triangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index 6bd1e4303a70..270c598de618 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string triangleType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class TriangleInterface."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class TriangleInterface.", nameof(triangleType)); - return new TriangleInterface(triangleType); + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class TriangleInterface."); + + return new TriangleInterface(triangleType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInte /// public void WriteProperties(ref Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) { + if (triangleInterface.TriangleType == null) + throw new ArgumentNullException(nameof(triangleInterface.TriangleType), "Property is required for class TriangleInterface."); + writer.WriteString("triangleType", triangleInterface.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs index ea527b94ec08..b0991a50e48d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/User.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,114 +32,198 @@ public partial class User : IValidatableObject /// /// Initializes a new instance of the class. /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. /// email /// firstName /// id /// lastName /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. /// password /// phone /// User Status /// username - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. [JsonConstructor] - public User(string email, string firstName, long id, string lastName, Object objectWithNoDeclaredProps, string password, string phone, int userStatus, string username, Object anyTypeProp = default, Object anyTypePropNullable = default, Object objectWithNoDeclaredPropsNullable = default) + public User(Option anyTypeProp = default, Option anyTypePropNullable = default, Option email = default, Option firstName = default, Option id = default, Option lastName = default, Option objectWithNoDeclaredProps = default, Option objectWithNoDeclaredPropsNullable = default, Option password = default, Option phone = default, Option userStatus = default, Option username = default) { - Email = email; - FirstName = firstName; - Id = id; - LastName = lastName; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - Password = password; - Phone = phone; - UserStatus = userStatus; - Username = username; - AnyTypeProp = anyTypeProp; - AnyTypePropNullable = anyTypePropNullable; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + AnyTypePropOption = anyTypeProp; + AnyTypePropNullableOption = anyTypePropNullable; + EmailOption = email; + FirstNameOption = firstName; + IdOption = id; + LastNameOption = lastName; + ObjectWithNoDeclaredPropsOption = objectWithNoDeclaredProps; + ObjectWithNoDeclaredPropsNullableOption = objectWithNoDeclaredPropsNullable; + PasswordOption = password; + PhoneOption = phone; + UserStatusOption = userStatus; + UsernameOption = username; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of AnyTypeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [JsonPropertyName("anyTypeProp")] + public Object AnyTypeProp { get { return this. AnyTypePropOption; } set { this.AnyTypePropOption = new(value); } } + + /// + /// Used to track the state of AnyTypePropNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropNullableOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [JsonPropertyName("anyTypePropNullable")] + public Object AnyTypePropNullable { get { return this. AnyTypePropNullableOption; } set { this.AnyTypePropNullableOption = new(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + /// /// Gets or Sets Email /// [JsonPropertyName("email")] - public string Email { get; set; } + public string Email { get { return this. EmailOption; } set { this.EmailOption = new(value); } } + + /// + /// Used to track the state of FirstName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstNameOption { get; private set; } /// /// Gets or Sets FirstName /// [JsonPropertyName("firstName")] - public string FirstName { get; set; } + public string FirstName { get { return this. FirstNameOption; } set { this.FirstNameOption = new(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new(value); } } + + /// + /// Used to track the state of LastName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LastNameOption { get; private set; } /// /// Gets or Sets LastName /// [JsonPropertyName("lastName")] - public string LastName { get; set; } + public string LastName { get { return this. LastNameOption; } set { this.LastNameOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredProps + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsOption { get; private set; } /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. [JsonPropertyName("objectWithNoDeclaredProps")] - public Object ObjectWithNoDeclaredProps { get; set; } + public Object ObjectWithNoDeclaredProps { get { return this. ObjectWithNoDeclaredPropsOption; } set { this.ObjectWithNoDeclaredPropsOption = new(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredPropsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsNullableOption { get; private set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonPropertyName("objectWithNoDeclaredPropsNullable")] + public Object ObjectWithNoDeclaredPropsNullable { get { return this. ObjectWithNoDeclaredPropsNullableOption; } set { this.ObjectWithNoDeclaredPropsNullableOption = new(value); } } + + /// + /// Used to track the state of Password + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PasswordOption { get; private set; } /// /// Gets or Sets Password /// [JsonPropertyName("password")] - public string Password { get; set; } + public string Password { get { return this. PasswordOption; } set { this.PasswordOption = new(value); } } /// - /// Gets or Sets Phone + /// Used to track the state of Phone /// - [JsonPropertyName("phone")] - public string Phone { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PhoneOption { get; private set; } /// - /// User Status + /// Gets or Sets Phone /// - /// User Status - [JsonPropertyName("userStatus")] - public int UserStatus { get; set; } + [JsonPropertyName("phone")] + public string Phone { get { return this. PhoneOption; } set { this.PhoneOption = new(value); } } /// - /// Gets or Sets Username + /// Used to track the state of UserStatus /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UserStatusOption { get; private set; } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// User Status /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - [JsonPropertyName("anyTypeProp")] - public Object AnyTypeProp { get; set; } + /// User Status + [JsonPropertyName("userStatus")] + public int? UserStatus { get { return this. UserStatusOption; } set { this.UserStatusOption = new(value); } } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// Used to track the state of Username /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - [JsonPropertyName("anyTypePropNullable")] - public Object AnyTypePropNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UsernameOption { get; private set; } /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// Gets or Sets Username /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. - [JsonPropertyName("objectWithNoDeclaredPropsNullable")] - public Object ObjectWithNoDeclaredPropsNullable { get; set; } + [JsonPropertyName("username")] + public string Username { get { return this. UsernameOption; } set { this.UsernameOption = new(value); } } /// /// Gets or Sets additional properties @@ -154,18 +239,18 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); - sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -204,18 +289,18 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string email = default; - string firstName = default; - long? id = default; - string lastName = default; - Object objectWithNoDeclaredProps = default; - string password = default; - string phone = default; - int? userStatus = default; - string username = default; - Object anyTypeProp = default; - Object anyTypePropNullable = default; - Object objectWithNoDeclaredPropsNullable = default; + Option anyTypeProp = default; + Option anyTypePropNullable = default; + Option email = default; + Option firstName = default; + Option id = default; + Option lastName = default; + Option objectWithNoDeclaredProps = default; + Option objectWithNoDeclaredPropsNullable = default; + Option password = default; + Option phone = default; + Option userStatus = default; + Option username = default; while (utf8JsonReader.Read()) { @@ -232,47 +317,47 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { + case "anyTypeProp": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "anyTypePropNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypePropNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "email": - email = utf8JsonReader.GetString(); + email = new Option(utf8JsonReader.GetString()); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()); break; case "objectWithNoDeclaredProps": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + objectWithNoDeclaredProps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "objectWithNoDeclaredPropsNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredPropsNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "password": - password = utf8JsonReader.GetString(); + password = new Option(utf8JsonReader.GetString()); break; case "phone": - phone = utf8JsonReader.GetString(); + phone = new Option(utf8JsonReader.GetString()); break; case "userStatus": if (utf8JsonReader.TokenType != JsonTokenType.Null) - userStatus = utf8JsonReader.GetInt32(); + userStatus = new Option(utf8JsonReader.GetInt32()); break; case "username": - username = utf8JsonReader.GetString(); - break; - case "anyTypeProp": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anyTypePropNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypePropNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "objectWithNoDeclaredPropsNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + username = new Option(utf8JsonReader.GetString()); break; default: break; @@ -280,34 +365,34 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (email == null) - throw new ArgumentNullException(nameof(email), "Property is required for class User."); + if (email.IsSet && email.Value == null) + throw new ArgumentNullException(nameof(email), "Property is not nullable for class User."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class User."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class User."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class User."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class User."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class User."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class User."); - if (objectWithNoDeclaredProps == null) - throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is required for class User."); + if (objectWithNoDeclaredProps.IsSet && objectWithNoDeclaredProps.Value == null) + throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is not nullable for class User."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class User."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class User."); - if (phone == null) - throw new ArgumentNullException(nameof(phone), "Property is required for class User."); + if (phone.IsSet && phone.Value == null) + throw new ArgumentNullException(nameof(phone), "Property is not nullable for class User."); - if (userStatus == null) - throw new ArgumentNullException(nameof(userStatus), "Property is required for class User."); + if (userStatus.IsSet && userStatus.Value == null) + throw new ArgumentNullException(nameof(userStatus), "Property is not nullable for class User."); - if (username == null) - throw new ArgumentNullException(nameof(username), "Property is required for class User."); + if (username.IsSet && username.Value == null) + throw new ArgumentNullException(nameof(username), "Property is not nullable for class User."); - return new User(email, firstName, id.Value, lastName, objectWithNoDeclaredProps, password, phone, userStatus.Value, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + return new User(anyTypeProp, anyTypePropNullable, email, firstName, id, lastName, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, password, phone, userStatus, username); } /// @@ -334,22 +419,79 @@ public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("email", user.Email); - writer.WriteString("firstName", user.FirstName); - writer.WriteNumber("id", user.Id); - writer.WriteString("lastName", user.LastName); - writer.WritePropertyName("objectWithNoDeclaredProps"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); - writer.WriteString("password", user.Password); - writer.WriteString("phone", user.Phone); - writer.WriteNumber("userStatus", user.UserStatus); - writer.WriteString("username", user.Username); - writer.WritePropertyName("anyTypeProp"); - JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); - writer.WritePropertyName("anyTypePropNullable"); - JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); - writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + if (user.EmailOption.IsSet && user.Email == null) + throw new ArgumentNullException(nameof(user.Email), "Property is required for class User."); + + if (user.FirstNameOption.IsSet && user.FirstName == null) + throw new ArgumentNullException(nameof(user.FirstName), "Property is required for class User."); + + if (user.LastNameOption.IsSet && user.LastName == null) + throw new ArgumentNullException(nameof(user.LastName), "Property is required for class User."); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet && user.ObjectWithNoDeclaredProps == null) + throw new ArgumentNullException(nameof(user.ObjectWithNoDeclaredProps), "Property is required for class User."); + + if (user.PasswordOption.IsSet && user.Password == null) + throw new ArgumentNullException(nameof(user.Password), "Property is required for class User."); + + if (user.PhoneOption.IsSet && user.Phone == null) + throw new ArgumentNullException(nameof(user.Phone), "Property is required for class User."); + + if (user.UsernameOption.IsSet && user.Username == null) + throw new ArgumentNullException(nameof(user.Username), "Property is required for class User."); + + if (user.AnyTypePropOption.IsSet) + if (user.AnyTypePropOption.Value != null) + { + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypeProp"); + if (user.AnyTypePropNullableOption.IsSet) + if (user.AnyTypePropNullableOption.Value != null) + { + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypePropNullable"); + if (user.EmailOption.IsSet) + writer.WriteString("email", user.Email); + + if (user.FirstNameOption.IsSet) + writer.WriteString("firstName", user.FirstName); + + if (user.IdOption.IsSet) + writer.WriteNumber("id", user.IdOption.Value.Value); + + if (user.LastNameOption.IsSet) + writer.WriteString("lastName", user.LastName); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet) + { + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); + } + if (user.ObjectWithNoDeclaredPropsNullableOption.IsSet) + if (user.ObjectWithNoDeclaredPropsNullableOption.Value != null) + { + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + } + else + writer.WriteNull("objectWithNoDeclaredPropsNullable"); + if (user.PasswordOption.IsSet) + writer.WriteString("password", user.Password); + + if (user.PhoneOption.IsSet) + writer.WriteString("phone", user.Phone); + + if (user.UserStatusOption.IsSet) + writer.WriteNumber("userStatus", user.UserStatusOption.Value.Value); + + if (user.UsernameOption.IsSet) + writer.WriteString("username", user.Username); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs index e633a5c92cf5..1759ab6d1cc7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Whale.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,11 +36,11 @@ public partial class Whale : IValidatableObject /// hasBaleen /// hasTeeth [JsonConstructor] - public Whale(string className, bool hasBaleen, bool hasTeeth) + public Whale(string className, Option hasBaleen = default, Option hasTeeth = default) { ClassName = className; - HasBaleen = hasBaleen; - HasTeeth = hasTeeth; + HasBaleenOption = hasBaleen; + HasTeethOption = hasTeeth; OnCreated(); } @@ -51,17 +52,31 @@ public Whale(string className, bool hasBaleen, bool hasTeeth) [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of HasBaleen + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasBaleenOption { get; private set; } + /// /// Gets or Sets HasBaleen /// [JsonPropertyName("hasBaleen")] - public bool HasBaleen { get; set; } + public bool? HasBaleen { get { return this. HasBaleenOption; } set { this.HasBaleenOption = new(value); } } + + /// + /// Used to track the state of HasTeeth + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasTeethOption { get; private set; } /// /// Gets or Sets HasTeeth /// [JsonPropertyName("hasTeeth")] - public bool HasTeeth { get; set; } + public bool? HasTeeth { get { return this. HasTeethOption; } set { this.HasTeethOption = new(value); } } /// /// Gets or Sets additional properties @@ -118,9 +133,9 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - bool? hasBaleen = default; - bool? hasTeeth = default; + Option className = default; + Option hasBaleen = default; + Option hasTeeth = default; while (utf8JsonReader.Read()) { @@ -138,15 +153,15 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "hasBaleen": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasBaleen = utf8JsonReader.GetBoolean(); + hasBaleen = new Option(utf8JsonReader.GetBoolean()); break; case "hasTeeth": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasTeeth = utf8JsonReader.GetBoolean(); + hasTeeth = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -154,16 +169,19 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Whale."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Whale.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Whale."); - if (hasBaleen == null) - throw new ArgumentNullException(nameof(hasBaleen), "Property is required for class Whale."); + if (hasBaleen.IsSet && hasBaleen.Value == null) + throw new ArgumentNullException(nameof(hasBaleen), "Property is not nullable for class Whale."); - if (hasTeeth == null) - throw new ArgumentNullException(nameof(hasTeeth), "Property is required for class Whale."); + if (hasTeeth.IsSet && hasTeeth.Value == null) + throw new ArgumentNullException(nameof(hasTeeth), "Property is not nullable for class Whale."); - return new Whale(className, hasBaleen.Value, hasTeeth.Value); + return new Whale(className.Value, hasBaleen, hasTeeth); } /// @@ -190,9 +208,16 @@ public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) { + if (whale.ClassName == null) + throw new ArgumentNullException(nameof(whale.ClassName), "Property is required for class Whale."); + writer.WriteString("className", whale.ClassName); - writer.WriteBoolean("hasBaleen", whale.HasBaleen); - writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + if (whale.HasBaleenOption.IsSet) + writer.WriteBoolean("hasBaleen", whale.HasBaleenOption.Value.Value); + + if (whale.HasTeethOption.IsSet) + writer.WriteBoolean("hasTeeth", whale.HasTeethOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs index 503c47228cdf..b8be0d28b132 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -20,13 +20,14 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Zebra /// - public partial class Zebra : Dictionary, IValidatableObject + public partial class Zebra : IValidatableObject { /// /// Initializes a new instance of the class. @@ -34,10 +35,10 @@ public partial class Zebra : Dictionary, IValidatableObject /// className /// type [JsonConstructor] - public Zebra(string className, TypeEnum type) : base() + public Zebra(string className, Option type = default) { ClassName = className; - Type = type; + TypeOption = type; OnCreated(); } @@ -109,7 +110,7 @@ public static TypeEnum TypeEnumFromString(string value) /// /// /// - public static string TypeEnumToJsonValue(TypeEnum value) + public static string TypeEnumToJsonValue(TypeEnum? value) { if (value == TypeEnum.Plains) return "plains"; @@ -123,11 +124,18 @@ public static string TypeEnumToJsonValue(TypeEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } + /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public TypeEnum Type { get; set; } + public TypeEnum? Type { get { return this.TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets ClassName @@ -149,7 +157,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -163,16 +170,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -200,8 +197,8 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - Zebra.TypeEnum? type = default; + Option className = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -219,13 +216,12 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "type": string typeRawValue = utf8JsonReader.GetString(); - type = typeRawValue == null - ? null - : Zebra.TypeEnumFromStringOrDefault(typeRawValue); + if (typeRawValue != null) + type = new Option(Zebra.TypeEnumFromStringOrDefault(typeRawValue)); break; default: break; @@ -233,13 +229,16 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Zebra."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Zebra.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Zebra."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Zebra."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Zebra."); - return new Zebra(className, type.Value); + return new Zebra(className.Value, type); } /// @@ -266,13 +265,13 @@ public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) { + if (zebra.ClassName == null) + throw new ArgumentNullException(nameof(zebra.ClassName), "Property is required for class Zebra."); + writer.WriteString("className", zebra.ClassName); - var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); - if (typeRawValue != null) - writer.WriteString("type", typeRawValue); - else - writer.WriteNull("type"); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.TypeOption.Value.Value); + writer.WriteString("type", typeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs index 20e184f02b2b..34a044fb8b13 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs index c590ea6644ba..511fa98fa5fd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,9 +34,9 @@ public partial class ZeroBasedEnumClass : IValidatableObject /// /// zeroBasedEnum [JsonConstructor] - public ZeroBasedEnumClass(ZeroBasedEnumEnum zeroBasedEnum) + public ZeroBasedEnumClass(Option zeroBasedEnum = default) { - ZeroBasedEnum = zeroBasedEnum; + ZeroBasedEnumOption = zeroBasedEnum; OnCreated(); } @@ -96,7 +97,7 @@ public static ZeroBasedEnumEnum ZeroBasedEnumEnumFromString(string value) /// /// /// - public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) + public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum? value) { if (value == ZeroBasedEnumEnum.Unknown) return "unknown"; @@ -107,11 +108,18 @@ public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of ZeroBasedEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ZeroBasedEnumOption { get; private set; } + /// /// Gets or Sets ZeroBasedEnum /// [JsonPropertyName("ZeroBasedEnum")] - public ZeroBasedEnumEnum ZeroBasedEnum { get; set; } + public ZeroBasedEnumEnum? ZeroBasedEnum { get { return this.ZeroBasedEnumOption; } set { this.ZeroBasedEnumOption = new(value); } } /// /// Gets or Sets additional properties @@ -166,7 +174,7 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - ZeroBasedEnumClass.ZeroBasedEnumEnum? zeroBasedEnum = default; + Option zeroBasedEnum = default; while (utf8JsonReader.Read()) { @@ -185,9 +193,8 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "ZeroBasedEnum": string zeroBasedEnumRawValue = utf8JsonReader.GetString(); - zeroBasedEnum = zeroBasedEnumRawValue == null - ? null - : ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue); + if (zeroBasedEnumRawValue != null) + zeroBasedEnum = new Option(ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue)); break; default: break; @@ -195,10 +202,10 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (zeroBasedEnum == null) - throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is required for class ZeroBasedEnumClass."); + if (zeroBasedEnum.IsSet && zeroBasedEnum.Value == null) + throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is not nullable for class ZeroBasedEnumClass."); - return new ZeroBasedEnumClass(zeroBasedEnum.Value); + return new ZeroBasedEnumClass(zeroBasedEnum); } /// @@ -225,12 +232,8 @@ public override void Write(Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEn /// public void WriteProperties(ref Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) { - - var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnum); - if (zeroBasedEnumRawValue != null) - writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); - else - writer.WriteNull("ZeroBasedEnum"); + var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnumOption.Value.Value); + writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 609b4d3200b0..1cb54dc2bc1f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 Org.OpenAPITools Org.OpenAPITools Library @@ -20,10 +20,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md index f35af0325070..0642123acc13 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net6.0/src/Org.OpenAPITools/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=false', 'hideGenerationTimestamp=true', @@ -69,42 +69,7 @@ namespace YourProject .ConfigureApi((context, options) => { // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); options.AddTokens(token); // optionally choose the method the tokens will be provided with, default is RateLimitProvider @@ -249,7 +214,7 @@ Authentication schemes defined for the API: - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.gitignore b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator-ignore b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/FILES new file mode 100644 index 000000000000..5abbcf46f35c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/FILES @@ -0,0 +1,36 @@ +.gitignore +Org.OpenAPITools.sln +README.md +api/openapi.yaml +appveyor.yml +docs/apis/DefaultApi.md +docs/models/NowGet200Response.md +docs/scripts/git_push.ps1 +docs/scripts/git_push.sh +src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools.Test/README.md +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Api/IApi.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiFactory.cs +src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs +src/Org.OpenAPITools/Client/ApiResponse`1.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +src/Org.OpenAPITools/Client/ExceptionEventArgs.cs +src/Org.OpenAPITools/Client/HostConfiguration.cs +src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs +src/Org.OpenAPITools/Client/Option.cs +src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +src/Org.OpenAPITools/Client/TokenBase.cs +src/Org.OpenAPITools/Client/TokenContainer`1.cs +src/Org.OpenAPITools/Client/TokenProvider`1.cs +src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs +src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs +src/Org.OpenAPITools/Model/NowGet200Response.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj +src/Org.OpenAPITools/README.md diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/Org.OpenAPITools.sln b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/Org.OpenAPITools.sln new file mode 100644 index 000000000000..547505a9856b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}.Debug|Any CPU.Build.0 = Debug|Any CPU + {2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}.Release|Any CPU.ActiveCfg = Release|Any CPU + {2E60EF87-DB0B-4D01-A36E-F5E90F7EC757}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/README.md new file mode 100644 index 000000000000..f9c1c7f74621 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/README.md @@ -0,0 +1 @@ +# Created with Openapi Generator diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/api/openapi.yaml new file mode 100644 index 000000000000..a84e041a00fa --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/api/openapi.yaml @@ -0,0 +1,35 @@ +openapi: 3.0.0 +info: + description: Thic spec contains endpoints with dates in different formats + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Dates + version: 1.0.0 +servers: +- url: / +paths: + /now: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/_now_get_200_response' + description: now dates +components: + schemas: + _now_get_200_response: + example: + today: 2000-01-23 + now: 2000-01-23T04:56:07.000+00:00 + properties: + today: + format: date + type: string + now: + format: date-time + type: string + type: object + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/appveyor.yml b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/apis/DefaultApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/apis/DefaultApi.md new file mode 100644 index 000000000000..6b1991021ac2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/apis/DefaultApi.md @@ -0,0 +1,90 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**NowGet**](DefaultApi.md#nowget) | **GET** /now | | + + +# **NowGet** +> NowGet200Response NowGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class NowGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost"; + var apiInstance = new DefaultApi(config); + + try + { + NowGet200Response result = apiInstance.NowGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.NowGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the NowGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.NowGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.NowGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**NowGet200Response**](NowGet200Response.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | now dates | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/models/NowGet200Response.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/models/NowGet200Response.md new file mode 100644 index 000000000000..58b6c7c79f01 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/models/NowGet200Response.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.NowGet200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Now** | **DateTime** | | [optional] +**Today** | **DateTime** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.ps1 b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.ps1 new file mode 100644 index 000000000000..73ed35c2bb10 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.ps1 @@ -0,0 +1,75 @@ +param( + [Parameter()][Alias("g")][String]$GitHost = "github.com", + [Parameter()][Alias("u")][String]$GitUserId = "GIT_USER_ID", + [Parameter()][Alias("r")][String]$GitRepoId = "GIT_REPO_ID", + [Parameter()][Alias("m")][string]$Message = "Minor update", + [Parameter()][Alias("h")][switch]$Help +) + +function Publish-ToGitHost{ + if ([string]::IsNullOrWhiteSpace($Message) -or $Message -eq "Minor update"){ + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + $Message = Read-Host -Prompt "Please provide a commit message or press enter" + $Message = if([string]::IsNullOrWhiteSpace($Message)) { "no message provided" } else { $Message } + } + + git init + git add . + git commit -am "${Message}" + $branchName=$(git rev-parse --abbrev-ref HEAD) + $gitRemote=$(git remote) + + if([string]::IsNullOrWhiteSpace($gitRemote)){ + git remote add origin https://${GitHost}/${GitUserId}/${GitRepoId}.git + } + + Write-Output "Pulling from https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git pull origin $branchName --ff-only + + if ($LastExitCode -ne 0){ + if (${GitHost} -eq "github.com"){ + Write-Output "The ${GitRepoId} repository may not exist yet. Creating it now with the GitHub CLI." + gh auth login --hostname github.com --web + gh repo create $GitRepoId --private + # sleep 2 seconds to ensure git finishes creation of the repo + Start-Sleep -Seconds 2 + } + else{ + throw "There was an issue pulling the origin branch. The remote repository may not exist yet." + } + } + + Write-Output "Pushing to https://${GitHost}/${GitUserId}/${GitRepoId}.git" + git push origin $branchName +} + +$ErrorActionPreference = "Stop" +Set-StrictMode -Version 3.0 + +if ($Help){ + Write-Output " + This script will initialize a git repository, then add and commit all files. + The local repository will then be pushed to your preferred git provider. + If the remote repository does not exist yet and you are using GitHub, + the repository will be created for you provided you have the GitHub CLI installed. + + Parameters: + -g | -GitHost -> ex: github.com + -m | -Message -> the git commit message + -r | -GitRepoId -> the name of the repository + -u | -GitUserId -> your user id + " + + return +} + +$rootPath=Resolve-Path -Path $PSScriptRoot/../.. + +Push-Location $rootPath + +try { + Publish-ToGitHost $GitHost $GitUserId $GitRepoId $Message +} +finally{ + Pop-Location +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.sh b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.sh new file mode 100644 index 000000000000..882104922184 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/docs/scripts/git_push.sh @@ -0,0 +1,49 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=${1:-GIT_USER_ID} +git_repo_id=${2:-GIT_REPO_ID} +release_note=${3:-Minor update} +git_host=${4:-github.com} + +starting_directory=$(pwd) +script_root="$( cd -- "$(dirname "$0")" >/dev/null 2>&1 ; pwd -P )" +cd $script_root +cd ../.. + +if [ "$release_note" = "" ] || [ "$release_note" = "Minor update" ]; then + # it seems unlikely that we would want our git commit message to be the default, so lets prompt the user + echo "Please provide a commit message or press enter" + read user_input + release_note=$user_input + if [ "$release_note" = "" ]; then + release_note="no message provided" + fi +fi + +git init +git add . +git commit -am "$release_note" +branch_name=$(git rev-parse --abbrev-ref HEAD) +git_remote=$(git remote) + +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +echo "[INFO] Pulling from https://${git_host}/${git_user_id}/${git_repo_id}.git" +git pull origin $branch_name --ff-only + +echo "[INFO] Pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin $branch_name + +cd $starting_directory diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs new file mode 100644 index 000000000000..40e1298ee62c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -0,0 +1,58 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Security.Cryptography; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Extensions; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Base class for API tests + /// + public class ApiTestsBase + { + protected readonly IHost _host; + + public ApiTestsBase(string[] args) + { + _host = CreateHostBuilder(args).Build(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, services, options) => + { + + }); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..05dc933c03b1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,64 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections.Generic; +using System.Threading.Tasks; +using Xunit; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; + + +/* ********************************************************************************* +* Follow these manual steps to construct tests. +* This file will not be overwritten. +* ********************************************************************************* +* 1. Navigate to ApiTests.Base.cs and ensure any tokens are being created correctly. +* Take care not to commit credentials to any repository. +* +* 2. Mocking is coordinated by ApiTestsBase#AddApiHttpClients. +* To mock the client, use the generic AddApiHttpClients. +* To mock the server, change the client's BaseAddress. +* +* 3. Locate the test you want below +* - remove the skip property from the Fact attribute +* - set the value of any variables if necessary +* +* 4. Run the tests and ensure they work. +* +*/ + + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + public sealed class DefaultApiTests : ApiTestsBase + { + private readonly IDefaultApi _instance; + + public DefaultApiTests(): base(Array.Empty()) + { + _instance = _host.Services.GetRequiredService(); + } + + /// + /// Test NowGet + /// + [Fact (Skip = "not implemented")] + public async Task NowGetAsyncTest() + { + var response = await _instance.NowGetAsync(); + var model = response.Ok(); + Assert.IsType(model); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs new file mode 100644 index 000000000000..c910325e620b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -0,0 +1,103 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using System.Collections.Generic; +using System.Security.Cryptography; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Extensions; +using Xunit; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Tests the dependency injection. + /// + public class DependencyInjectionTest + { + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => + { + + }) + .Build(); + + private readonly IHost _hostUsingConfigureWithAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }) + .Build(); + + private readonly IHost _hostUsingAddWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + }); + }) + .Build(); + + private readonly IHost _hostUsingAddWithAClient = + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => + { + services.AddApi(options => + { + + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); + }); + }) + .Build(); + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithAClientTest() + { + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the configure method + /// + [Fact] + public void ConfigureApiWithoutAClientTest() + { + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithAClientTest() + { + var defaultApi = _hostUsingAddWithAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + + /// + /// Test dependency injection when using the add method + /// + [Fact] + public void AddApiWithoutAClientTest() + { + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); + Assert.True(defaultApi.HttpClient.BaseAddress != null); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs new file mode 100644 index 000000000000..920dfd9700ea --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs @@ -0,0 +1,74 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NowGet200Response + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NowGet200ResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NowGet200Response + //private NowGet200Response instance; + + public NowGet200ResponseTests() + { + // TODO uncomment below to create an instance of NowGet200Response + //instance = new NowGet200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NowGet200Response + /// + [Fact] + public void NowGet200ResponseInstanceTest() + { + // TODO uncomment below to test "IsType" NowGet200Response + //Assert.IsType(instance); + } + + /// + /// Test the property 'Now' + /// + [Fact] + public void NowTest() + { + // TODO unit test for the property 'Now' + } + + /// + /// Test the property 'Today' + /// + [Fact] + public void TodayTest() + { + // TODO unit test for the property 'Today' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..872d1687aa20 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net8.0 + false + enable + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/README.md new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..53fa05822147 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,332 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Net; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using System.Net.Http; +using System.Net.Http.Headers; +using System.Text.Json; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +using System.Diagnostics.CodeAnalysis; + +namespace Org.OpenAPITools.Api +{ + /// + /// Represents a collection of functions to interact with the API endpoints + /// This class is registered as transient. + /// + public interface IDefaultApi : IApi + { + /// + /// The class containing the events + /// + DefaultApiEvents Events { get; } + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + Task NowGetAsync(System.Threading.CancellationToken cancellationToken = default); + + /// + /// + /// + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <?> + Task NowGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + } + + /// + /// The + /// + public interface INowGetApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public class DefaultApiEvents + { + /// + /// The event raised after the server response + /// + public event EventHandler? OnNowGet; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler? OnErrorNowGet; + + internal void ExecuteOnNowGet(DefaultApi.NowGetApiResponse apiResponse) + { + OnNowGet?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorNowGet(Exception exception) + { + OnErrorNowGet?.Invoke(this, new ExceptionEventArgs(exception)); + } + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public sealed partial class DefaultApi : IDefaultApi + { + private JsonSerializerOptions _jsonSerializerOptions; + + /// + /// The logger factory + /// + public ILoggerFactory LoggerFactory { get; } + + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The HttpClient + /// + public HttpClient HttpClient { get; } + + /// + /// The class containing the events + /// + public DefaultApiEvents Events { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(ILogger logger, ILoggerFactory loggerFactory, HttpClient httpClient, JsonSerializerOptionsProvider jsonSerializerOptionsProvider, DefaultApiEvents defaultApiEvents) + { + _jsonSerializerOptions = jsonSerializerOptionsProvider.Options; + LoggerFactory = loggerFactory; + Logger = LoggerFactory.CreateLogger(); + HttpClient = httpClient; + Events = defaultApiEvents; + } + + /// + /// Processes the server response + /// + /// + private void AfterNowGetDefaultImplementation(INowGetApiResponse apiResponseLocalVar) + { + bool suppressDefaultLog = false; + AfterNowGet(ref suppressDefaultLog, apiResponseLocalVar); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + partial void AfterNowGet(ref bool suppressDefaultLog, INowGetApiResponse apiResponseLocalVar); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + private void OnErrorNowGetDefaultImplementation(Exception exception, string pathFormat, string path) + { + bool suppressDefaultLog = false; + OnErrorNowGet(ref suppressDefaultLog, exception, pathFormat, path); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + partial void OnErrorNowGet(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path); + + /// + /// + /// + /// Cancellation Token to cancel the request. + /// <> + public async Task NowGetOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await NowGetAsync(cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Cancellation Token to cancel the request. + /// <> + public async Task NowGetAsync(System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress!.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/now"; + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] acceptLocalVars = new string[] { + "application/json" + }; + + string? acceptLocalVar = ClientUtils.SelectHeaderAccept(acceptLocalVars); + + if (acceptLocalVar != null) + httpRequestMessageLocalVar.Headers.Accept.Add(new MediaTypeWithQualityHeaderValue(acceptLocalVar)); + + httpRequestMessageLocalVar.Method = HttpMethod.Get; + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync(cancellationToken).ConfigureAwait(false); + + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + + NowGetApiResponse apiResponseLocalVar = new(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/now", requestedAtLocalVar, _jsonSerializerOptions); + + AfterNowGetDefaultImplementation(apiResponseLocalVar); + + Events.ExecuteOnNowGet(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorNowGetDefaultImplementation(e, "/now", uriBuilderLocalVar.Path); + Events.ExecuteOnErrorNowGet(e); + throw; + } + } + + /// + /// The + /// + public partial class NowGetApiResponse : Org.OpenAPITools.Client.ApiResponse, INowGetApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public NowGetApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 200 Ok + /// + /// + public Org.OpenAPITools.Model.NowGet200Response? Ok() + { + // This logic may be modified with the AsModel.mustache template + return IsOk + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : null; + } + + /// + /// Returns true if the response is 200 Ok and the deserialized response is not null + /// + /// + /// + public bool TryOk([NotNullWhen(true)]out Org.OpenAPITools.Model.NowGet200Response? result) + { + result = null; + + try + { + result = Ok(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)200); + } + + return result != null; + } + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/IApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/IApi.cs new file mode 100644 index 000000000000..28520f043f2d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/IApi.cs @@ -0,0 +1,15 @@ +using System.Net.Http; + +namespace Org.OpenAPITools.Api +{ + /// + /// Any Api client + /// + public interface IApi + { + /// + /// The HttpClient + /// + HttpClient HttpClient { get; } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..f7cda3e72ce2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,52 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// The reason the api request failed + /// + public string? ReasonPhrase { get; } + + /// + /// The HttpStatusCode + /// + public System.Net.HttpStatusCode StatusCode { get; } + + /// + /// The raw data returned by the api + /// + public string RawContent { get; } + + /// + /// Construct the ApiException from parts of the response + /// + /// + /// + /// + public ApiException(string? reasonPhrase, System.Net.HttpStatusCode statusCode, string rawContent) : base(reasonPhrase ?? rawContent) + { + ReasonPhrase = reasonPhrase; + + StatusCode = statusCode; + + RawContent = rawContent; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiFactory.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiFactory.cs new file mode 100644 index 000000000000..b9b27c613f86 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiFactory.cs @@ -0,0 +1,49 @@ +using System; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; + +namespace Org.OpenAPITools.Client +{ + /// + /// An IApiFactory interface + /// + public interface IApiFactory + { + /// + /// A method to create an IApi of type IResult + /// + /// + /// + IResult Create() where IResult : IApi; + } + + /// + /// An ApiFactory + /// + public class ApiFactory : IApiFactory + { + /// + /// The service provider + /// + public IServiceProvider Services { get; } + + /// + /// Initializes a new instance of the class. + /// + /// + public ApiFactory(IServiceProvider services) + { + Services = services; + } + + /// + /// A method to create an IApi of type IResult + /// + /// + /// + public IResult Create() where IResult : IApi + { + return Services.GetRequiredService(); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs new file mode 100644 index 000000000000..3cb65e5adc0b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health + /// + public class ApiResponseEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public ApiResponse ApiResponse { get; } + + /// + /// The ApiResponseEventArgs + /// + /// + public ApiResponseEventArgs(ApiResponse apiResponse) + { + ApiResponse = apiResponse; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse`1.cs new file mode 100644 index 000000000000..7225050acf95 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -0,0 +1,172 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Diagnostics.CodeAnalysis; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public partial interface IApiResponse + { + /// + /// The IsSuccessStatusCode from the api response + /// + bool IsSuccessStatusCode { get; } + + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// The raw content of this response. + /// + string RawContent { get; } + + /// + /// The DateTime when the request was retrieved. + /// + DateTime DownloadedAt { get; } + + /// + /// The headers contained in the api response + /// + System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The path used when making the request. + /// + string Path { get; } + + /// + /// The reason phrase contained in the api response + /// + string? ReasonPhrase { get; } + + /// + /// The DateTime when the request was sent. + /// + DateTime RequestedAt { get; } + + /// + /// The Uri used when making the request. + /// + Uri? RequestUri { get; } + } + + /// + /// API Response + /// + public partial class ApiResponse : IApiResponse + { + /// + /// Gets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// The raw data + /// + public string RawContent { get; protected set; } + + /// + /// The IsSuccessStatusCode from the api response + /// + public bool IsSuccessStatusCode { get; } + + /// + /// The reason phrase contained in the api response + /// + public string? ReasonPhrase { get; } + + /// + /// The headers contained in the api response + /// + public System.Net.Http.Headers.HttpResponseHeaders Headers { get; } + + /// + /// The DateTime when the request was retrieved. + /// + public DateTime DownloadedAt { get; } = DateTime.UtcNow; + + /// + /// The DateTime when the request was sent. + /// + public DateTime RequestedAt { get; } + + /// + /// The path used when making the request. + /// + public string Path { get; } + + /// + /// The Uri used when making the request. + /// + public Uri? RequestUri { get; } + + /// + /// The + /// + protected System.Text.Json.JsonSerializerOptions _jsonSerializerOptions; + + /// + /// Construct the response using an HttpResponseMessage + /// + /// + /// + /// + /// + /// + /// + public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) + { + StatusCode = httpResponseMessage.StatusCode; + Headers = httpResponseMessage.Headers; + IsSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode; + ReasonPhrase = httpResponseMessage.ReasonPhrase; + RawContent = rawContent; + Path = path; + RequestUri = httpRequestMessage.RequestUri; + RequestedAt = requestedAt; + _jsonSerializerOptions = jsonSerializerOptions; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + } + + /// + /// An interface for responses of type + /// + /// + public interface IOk : IApiResponse + { + /// + /// Deserializes the response if the response is Ok + /// + /// + TType Ok(); + + /// + /// Returns true if the response is Ok and the deserialized response is not null + /// + /// + /// + bool TryOk([NotNullWhen(true)]out TType? result); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..03822d5f806d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,279 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.IO; +using System.Linq; +using System.Collections; +using System.Collections.Generic; +using System.Text; +using System.Text.Json; +using System.Text.RegularExpressions; +using Org.OpenAPITools.Model; +using System.Runtime.CompilerServices; + +[assembly: InternalsVisibleTo("Org.OpenAPITools.Test")] + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + + /// + /// A delegate for events. + /// + /// + /// + /// + /// + public delegate void EventHandler(object sender, T e) where T : EventArgs; + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(string json, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(json, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Returns true when deserialization succeeds. + /// + /// + /// + /// + /// + /// + public static bool TryDeserialize(ref Utf8JsonReader reader, JsonSerializerOptions options, [System.Diagnostics.CodeAnalysis.NotNullWhen(true)] out T? result) + { + try + { + result = JsonSerializer.Deserialize(ref reader, options); + return result != null; + } + catch (Exception) + { + result = default; + return false; + } + } + + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// The DateTime serialization format. + /// Formatted string. + public static string? ParameterToString(object obj, string? format = ISO8601_DATETIME_FORMAT) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString(format); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString(format); + if (obj is bool boolean) + return boolean + ? "true" + : "false"; + if (obj is ICollection collection) + { + List entries = new(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry)); + return string.Join(",", entries); + } + + return Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture); + } + + /// + /// URL encode a string + /// Credit/Ref: https://github.com/restsharp/RestSharp/blob/master/RestSharp/Extensions/StringExtensions.cs#L50 + /// + /// string to be URL encoded + /// Byte array + public static string UrlEncode(string input) + { + const int maxLength = 32766; + + if (input == null) + { + throw new ArgumentNullException("input"); + } + + if (input.Length <= maxLength) + { + return Uri.EscapeDataString(input); + } + + StringBuilder sb = new StringBuilder(input.Length * 2); + int index = 0; + + while (index < input.Length) + { + int length = Math.Min(input.Length - index, maxLength); + string subString = input.Substring(index, length); + + sb.Append(Uri.EscapeDataString(subString)); + index += subString.Length; + } + + return sb.ToString(); + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string? SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string? SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// The base path of the API + /// + public const string BASE_ADDRESS = "http://localhost"; + + /// + /// The scheme of the API + /// + public const string SCHEME = "http"; + + /// + /// The context path of the API + /// + public const string CONTEXT_PATH = ""; + + /// + /// The host of the API + /// + public const string HOST = "localhost"; + + /// + /// The format to use for DateTime serialization + /// + public const string ISO8601_DATETIME_FORMAT = "o"; + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/CookieContainer.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/CookieContainer.cs new file mode 100644 index 000000000000..85093b0c1fee --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/CookieContainer.cs @@ -0,0 +1,20 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A class containing a CookieContainer + /// + public sealed class CookieContainer + { + /// + /// The collection of tokens + /// + public System.Net.CookieContainer Value { get; } = new System.Net.CookieContainer(); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs new file mode 100644 index 000000000000..1ebd1220b622 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -0,0 +1,77 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' and 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyy'-'MM'-'dd", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + "yyyyMMdd" + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime dateTimeValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateTimeValue.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs new file mode 100644 index 000000000000..e92db186bb60 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -0,0 +1,82 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' and 'date-time' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateTimeNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", + "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", + "yyyy'-'MM'-'dd", + "yyyyMMddTHHmmss.fffffffK", + "yyyyMMddTHHmmss.ffffffK", + "yyyyMMddTHHmmss.fffffK", + "yyyyMMddTHHmmss.ffffK", + "yyyyMMddTHHmmss.fffK", + "yyyyMMddTHHmmss.ffK", + "yyyyMMddTHHmmss.fK", + "yyyyMMddTHHmmssK", + "yyyyMMdd" + + }; + + /// + /// Returns a DateTime from the Json object + /// + /// + /// + /// + /// + public override DateTime? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateTime.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateTime result)) + return result; + + return null; + } + + /// + /// Writes the DateTime to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateTime? dateTimeValue, JsonSerializerOptions options) + { + if (dateTimeValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateTimeValue.Value.ToString("yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs new file mode 100644 index 000000000000..dcfab6678233 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionEventArgs.cs @@ -0,0 +1,24 @@ +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Useful for tracking server health + /// + public class ExceptionEventArgs : EventArgs + { + /// + /// The ApiResponse + /// + public Exception Exception { get; } + + /// + /// The ExcepetionEventArgs + /// + /// + public ExceptionEventArgs(Exception exception) + { + Exception = exception; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HostConfiguration.cs new file mode 100644 index 000000000000..90dd61c2c492 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -0,0 +1,131 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides hosting configuration for Org.OpenAPITools + /// + public class HostConfiguration + { + private readonly IServiceCollection _services; + private readonly JsonSerializerOptions _jsonOptions = new JsonSerializerOptions(); + + internal bool HttpClientsAdded { get; private set; } + + /// + /// Instantiates the class + /// + /// + public HostConfiguration(IServiceCollection services) + { + _services = services; + _jsonOptions.Converters.Add(new JsonStringEnumConverter()); + _jsonOptions.Converters.Add(new DateTimeJsonConverter()); + _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new NowGet200ResponseJsonConverter()); + JsonSerializerOptionsProvider jsonSerializerOptionsProvider = new(_jsonOptions); + _services.AddSingleton(jsonSerializerOptionsProvider); + _services.AddSingleton(); + _services.AddSingleton(); + _services.AddTransient(); + } + + /// + /// Configures the HttpClients. + /// + /// + /// + /// + public HostConfiguration AddApiHttpClients + ( + Action? client = null, Action? builder = null) + { + if (client == null) + client = c => c.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS); + + List builders = new List(); + + builders.Add(_services.AddHttpClient(client)); + + if (builder != null) + foreach (IHttpClientBuilder instance in builders) + builder(instance); + + HttpClientsAdded = true; + + return this; + } + + /// + /// Configures the JsonSerializerSettings + /// + /// + /// + public HostConfiguration ConfigureJsonOptions(Action options) + { + options(_jsonOptions); + + return this; + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(TTokenBase token) where TTokenBase : TokenBase + { + return AddTokens(new TTokenBase[]{ token }); + } + + /// + /// Adds tokens to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration AddTokens(IEnumerable tokens) where TTokenBase : TokenBase + { + TokenContainer container = new TokenContainer(tokens); + _services.AddSingleton(services => container); + + return this; + } + + /// + /// Adds a token provider to your IServiceCollection + /// + /// + /// + /// + public HostConfiguration UseProvider() + where TTokenProvider : TokenProvider + where TTokenBase : TokenBase + { + _services.AddSingleton(); + _services.AddSingleton>(services => services.GetRequiredService()); + + return this; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs new file mode 100644 index 000000000000..0184d9ad9446 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/JsonSerializerOptionsProvider.cs @@ -0,0 +1,27 @@ +// + +#nullable enable + +using System.Text.Json; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides the JsonSerializerOptions + /// + public class JsonSerializerOptionsProvider + { + /// + /// the JsonSerializerOptions + /// + public JsonSerializerOptions Options { get; } + + /// + /// Instantiates a JsonSerializerOptionsProvider + /// + public JsonSerializerOptionsProvider(JsonSerializerOptions options) + { + Options = options; + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Option.cs new file mode 100644 index 000000000000..1c1677e3e3cb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Option.cs @@ -0,0 +1,53 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + + +namespace Org.OpenAPITools.Client +{ + /// + /// A wrapper for operation parameters which are not required + /// + public struct Option + { + /// + /// The value to send to the server + /// + public TType Value { get; } + + /// + /// When true the value will be sent to the server + /// + internal bool IsSet { get; } + + /// + /// A wrapper for operation parameters which are not required + /// + /// + public Option(TType value) + { + IsSet = true; + Value = value; + } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs new file mode 100644 index 000000000000..30ef47033199 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -0,0 +1,57 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Threading.Channels; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. + /// + /// + public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase + { + internal Dictionary> AvailableTokens { get; } = new(); + + /// + /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. + /// + /// + public RateLimitProvider(TokenContainer container) : base(container.Tokens) + { + foreach(TTokenBase token in _tokens) + token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); + + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite + }; + + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenBase.cs new file mode 100644 index 000000000000..3f713a2ef4bb --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenBase.cs @@ -0,0 +1,71 @@ +// + +#nullable enable + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// The base for all tokens. + /// + public abstract class TokenBase + { + private DateTime _nextAvailable = DateTime.UtcNow; + private object _nextAvailableLock = new object(); + private readonly System.Timers.Timer _timer = new System.Timers.Timer(); + + + internal TimeSpan? Timeout { get; set; } + internal delegate void TokenBecameAvailableEventHandler(object sender); + internal event TokenBecameAvailableEventHandler? TokenBecameAvailable; + + + /// + /// Initialize a TokenBase object. + /// + /// + internal TokenBase(TimeSpan? timeout = null) + { + Timeout = timeout; + + if (Timeout != null) + StartTimer(Timeout.Value); + } + + + /// + /// Starts the token's timer + /// + /// + internal void StartTimer(TimeSpan timeout) + { + Timeout = timeout; + _timer.Interval = Timeout.Value.TotalMilliseconds; + _timer.Elapsed += OnTimer; + _timer.AutoReset = true; + _timer.Start(); + } + + /// + /// Returns true while the token is rate limited. + /// + public bool IsRateLimited => _nextAvailable > DateTime.UtcNow; + + /// + /// Triggered when the server returns status code TooManyRequests + /// Once triggered the local timeout will be extended an arbitrary length of time. + /// + public void BeginRateLimit() + { + lock(_nextAvailableLock) + _nextAvailable = DateTime.UtcNow.AddSeconds(5); + } + + private void OnTimer(object? sender, System.Timers.ElapsedEventArgs e) + { + if (TokenBecameAvailable != null && !IsRateLimited) + TokenBecameAvailable.Invoke(this); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenContainer`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenContainer`1.cs new file mode 100644 index 000000000000..3fba287ad9d3 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenContainer`1.cs @@ -0,0 +1,37 @@ +// + +#nullable enable + +using System.Linq; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for a collection of tokens. + /// + /// + public sealed class TokenContainer where TTokenBase : TokenBase + { + /// + /// The collection of tokens + /// + public List Tokens { get; } = new List(); + + /// + /// Instantiates a TokenContainer + /// + public TokenContainer() + { + } + + /// + /// Instantiates a TokenContainer + /// + /// + public TokenContainer(System.Collections.Generic.IEnumerable tokens) + { + Tokens = tokens.ToList(); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenProvider`1.cs new file mode 100644 index 000000000000..d9c84d5cc775 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -0,0 +1,44 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using System.Collections.Generic; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools +{ + /// + /// A class which will provide tokens. + /// + public abstract class TokenProvider where TTokenBase : TokenBase + { + /// + /// The array of tokens. + /// + protected TTokenBase[] _tokens; + + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); + + /// + /// Instantiates a TokenProvider. + /// + /// + public TokenProvider(IEnumerable tokens) + { + _tokens = tokens.ToArray(); + + if (_tokens.Length == 0) + throw new ArgumentException("You did not provide any tokens."); + } + } +} \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs new file mode 100644 index 000000000000..2c150d1f66e4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHostBuilderExtensions.cs @@ -0,0 +1,59 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Hosting; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHostBuilder + /// + public static class IHostBuilderExtensions + { + /// + /// Add the api to your host builder. + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static IHostBuilder ConfigureApi(this IHostBuilder builder, Action options) + { + builder.ConfigureServices((context, services) => + { + HostConfiguration config = new HostConfiguration(services); + + options(context, services, config); + + IServiceCollectionExtensions.AddApi(services, config); + }); + + return builder; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs new file mode 100644 index 000000000000..549b6e473333 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IHttpClientBuilderExtensions.cs @@ -0,0 +1,79 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Net.Http; +using Microsoft.Extensions.DependencyInjection; +using Polly.Timeout; +using Polly.Extensions.Http; +using Polly; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IHttpClientBuilder + /// + public static class IHttpClientBuilderExtensions + { + /// + /// Adds a Polly retry policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddRetryPolicy(this IHttpClientBuilder client, int retries) + { + client.AddPolicyHandler(RetryPolicy(retries)); + + return client; + } + + /// + /// Adds a Polly timeout policy to your clients. + /// + /// + /// + /// + public static IHttpClientBuilder AddTimeoutPolicy(this IHttpClientBuilder client, TimeSpan timeout) + { + client.AddPolicyHandler(TimeoutPolicy(timeout)); + + return client; + } + + /// + /// Adds a Polly circuit breaker to your clients. + /// + /// + /// + /// + /// + public static IHttpClientBuilder AddCircuitBreakerPolicy(this IHttpClientBuilder client, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + { + client.AddTransientHttpErrorPolicy(builder => CircuitBreakerPolicy(builder, handledEventsAllowedBeforeBreaking, durationOfBreak)); + + return client; + } + + private static Polly.Retry.AsyncRetryPolicy RetryPolicy(int retries) + => HttpPolicyExtensions + .HandleTransientHttpError() + .Or() + .RetryAsync(retries); + + private static AsyncTimeoutPolicy TimeoutPolicy(TimeSpan timeout) + => Policy.TimeoutAsync(timeout); + + private static Polly.CircuitBreaker.AsyncCircuitBreakerPolicy CircuitBreakerPolicy( + PolicyBuilder builder, int handledEventsAllowedBeforeBreaking, TimeSpan durationOfBreak) + => builder.CircuitBreakerAsync(handledEventsAllowedBeforeBreaking, durationOfBreak); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs new file mode 100644 index 000000000000..8b7c34900c07 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Extensions/IServiceCollectionExtensions.cs @@ -0,0 +1,73 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Linq; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Extensions +{ + /// + /// Extension methods for IServiceCollection + /// + public static class IServiceCollectionExtensions + { + /// + /// Add the api to your host builder. + /// + /// + public static void AddApi(this IServiceCollection services) + { + HostConfiguration config = new(services); + AddApi(services, config); + } + + /// + /// Add the api to your host builder. + /// + /// + /// + public static void AddApi(this IServiceCollection services, Action options) + { + HostConfiguration config = new(services); + options(config); + AddApi(services, config); + } + + internal static void AddApi(IServiceCollection services, HostConfiguration host) + { + if (!host.HttpClientsAdded) + host.AddApiHttpClients(); + + services.AddSingleton(); + + // ensure that a token provider was provided for this token type + // if not, default to RateLimitProvider + var containerServices = services.Where(s => s.ServiceType.IsGenericType && + s.ServiceType.GetGenericTypeDefinition().IsAssignableFrom(typeof(TokenContainer<>))).ToArray(); + + foreach(var containerService in containerServices) + { + var tokenType = containerService.ServiceType.GenericTypeArguments[0]; + + var provider = services.FirstOrDefault(s => s.ServiceType.IsAssignableFrom(typeof(TokenProvider<>).MakeGenericType(tokenType))); + + if (provider == null) + { + services.AddSingleton(typeof(RateLimitProvider<>).MakeGenericType(tokenType)); + services.AddSingleton(typeof(TokenProvider<>).MakeGenericType(tokenType), + s => s.GetRequiredService(typeof(RateLimitProvider<>).MakeGenericType(tokenType))); + } + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs new file mode 100644 index 000000000000..d603c50450d6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs @@ -0,0 +1,203 @@ +// +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +#nullable enable + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// NowGet200Response + /// + public partial class NowGet200Response : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// now + /// today + [JsonConstructor] + public NowGet200Response(Option now = default, Option today = default) + { + NowOption = now; + TodayOption = today; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Used to track the state of Now + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NowOption { get; private set; } + + /// + /// Gets or Sets Now + /// + [JsonPropertyName("now")] + public DateTime? Now { get { return this. NowOption; } set { this.NowOption = new(value); } } + + /// + /// Used to track the state of Today + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TodayOption { get; private set; } + + /// + /// Gets or Sets Today + /// + [JsonPropertyName("today")] + public DateTime? Today { get { return this. TodayOption; } set { this.TodayOption = new(value); } } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NowGet200Response {\n"); + sb.Append(" Now: ").Append(Now).Append("\n"); + sb.Append(" Today: ").Append(Today).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class NowGet200ResponseJsonConverter : JsonConverter + { + /// + /// The format to use to serialize Now + /// + public static string NowFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize Today + /// + public static string TodayFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override NowGet200Response Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option now = default; + Option today = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string? localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "now": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + now = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "today": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + today = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + default: + break; + } + } + } + + if (now.IsSet && now.Value == null) + throw new ArgumentNullException(nameof(now), "Property is not nullable for class NowGet200Response."); + + if (today.IsSet && today.Value == null) + throw new ArgumentNullException(nameof(today), "Property is not nullable for class NowGet200Response."); + + return new NowGet200Response(now, today); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, NowGet200Response nowGet200Response, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, nowGet200Response, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, NowGet200Response nowGet200Response, JsonSerializerOptions jsonSerializerOptions) + { + if (nowGet200Response.NowOption.IsSet) + writer.WriteString("now", nowGet200Response.NowOption.Value!.Value.ToString(NowFormat)); + + if (nowGet200Response.TodayOption.IsSet) + writer.WriteString("today", nowGet200Response.TodayOption.Value!.Value.ToString(TodayFormat)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..2c9898be1de8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,30 @@ + + + + true + net8.0 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + enable + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/README.md new file mode 100644 index 000000000000..a07dac693a6d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-net7.0-useDateTimeForDate/src/Org.OpenAPITools/README.md @@ -0,0 +1,176 @@ +# Created with Openapi Generator + + +## Run the following powershell command to generate the library + +```ps1 +$properties = @( + 'apiName=Api', + 'targetFramework=net8.0', + 'validatable=true', + 'nullableReferenceTypes=true', + 'hideGenerationTimestamp=true', + 'packageVersion=1.0.0', + 'packageAuthors=OpenAPI', + 'packageCompany=OpenAPI', + 'packageCopyright=No Copyright', + 'packageDescription=A library generated from a OpenAPI doc', + 'packageName=Org.OpenAPITools', + 'packageTags=', + 'packageTitle=OpenAPI Library' +) -join "," + +$global = @( + 'apiDocs=true', + 'modelDocs=true', + 'apiTests=true', + 'modelTests=true' +) -join "," + +java -jar "/openapi-generator/modules/openapi-generator-cli/target/openapi-generator-cli.jar" generate ` + -g csharp-netcore ` + -i .yaml ` + -o ` + --library generichost ` + --additional-properties $properties ` + --global-property $global ` + --git-host "github.com" ` + --git-repo-id "GIT_REPO_ID" ` + --git-user-id "GIT_USER_ID" ` + --release-note "Minor update" + # -t templates +``` + + +## Using the library in your project + +```cs +using System; +using System.Threading.Tasks; +using Microsoft.Extensions.Hosting; +using Microsoft.Extensions.DependencyInjection; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace YourProject +{ + public class Program + { + public static async Task Main(string[] args) + { + var host = CreateHostBuilder(args).Build(); + var api = host.Services.GetRequiredService(); + NowGetApiResponse apiResponse = await api.NowGetAsync("todo"); + NowGet200Response model = apiResponse.Ok(); + } + + public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) + .ConfigureApi((context, options) => + { + options.ConfigureJsonOptions((jsonOptions) => + { + // your custom converters if any + }); + + options.AddApiHttpClients(builder: builder => builder + .AddRetryPolicy(2) + .AddTimeoutPolicy(TimeSpan.FromSeconds(5)) + .AddCircuitBreakerPolicy(10, TimeSpan.FromSeconds(30)) + // add whatever middleware you prefer + ); + }); + } +} +``` + +## Questions + +- What about HttpRequest failures and retries? + If supportsRetry is enabled, you can configure Polly in the ConfigureClients method. +- How are tokens used? + Tokens are provided by a TokenProvider class. The default is RateLimitProvider which will perform client side rate limiting. + Other providers can be used with the UseProvider method. +- Does an HttpRequest throw an error when the server response is not Ok? + It depends how you made the request. If the return type is ApiResponse no error will be thrown, though the Content property will be null. + StatusCode and ReasonPhrase will contain information about the error. + If the return type is T, then it will throw. If the return type is TOrDefault, it will return null. +- How do I validate requests and process responses? + Use the provided On and After methods in the Api class from the namespace Org.OpenAPITools.Rest.DefaultApi. + Or provide your own class by using the generic ConfigureApi method. + + +## Dependencies + +- [Microsoft.Extensions.Hosting](https://www.nuget.org/packages/Microsoft.Extensions.Hosting/) - 5.0.0 or later +- [Microsoft.Extensions.Http](https://www.nuget.org/packages/Microsoft.Extensions.Http/) - 5.0.0 or later +- [Microsoft.Extensions.Http.Polly](https://www.nuget.org/packages/Microsoft.Extensions.Http.Polly/) - 5.0.1 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 4.7.0 or later + + +## Documentation for Authorization + +Endpoints do not require authorization. + + +## Build +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen + +## Api Information +- appName: OpenAPI Dates +- appVersion: 1.0.0 +- appDescription: Thic spec contains endpoints with dates in different formats + +## [OpenApi Global properties](https://openapi-generator.tech/docs/globals) +- generateAliasAsModel: +- supportingFiles: +- models: omitted for brevity +- apis: omitted for brevity +- apiDocs: true +- modelDocs: true +- apiTests: true +- modelTests: true +- withXml: + +## [OpenApi Generator Parameters](https://openapi-generator.tech/docs/generators/csharp-netcore) +- allowUnicodeIdentifiers: +- apiName: Api +- caseInsensitiveResponseHeaders: +- conditionalSerialization: false +- disallowAdditionalPropertiesIfNotPresent: +- gitHost: github.com +- gitRepoId: GIT_REPO_ID +- gitUserId: GIT_USER_ID +- hideGenerationTimestamp: true +- interfacePrefix: I +- library: generichost +- licenseId: +- modelPropertyNaming: +- netCoreProjectFile: false +- nonPublicApi: false +- nullableReferenceTypes: true +- optionalAssemblyInfo: +- optionalEmitDefaultValues: false +- optionalMethodArgument: true +- optionalProjectFile: +- packageAuthors: OpenAPI +- packageCompany: OpenAPI +- packageCopyright: No Copyright +- packageDescription: A library generated from a OpenAPI doc +- packageGuid: {2E60EF87-DB0B-4D01-A36E-F5E90F7EC757} +- packageName: Org.OpenAPITools +- packageTags: +- packageTitle: OpenAPI Library +- packageVersion: 1.0.0 +- releaseNote: Minor update +- returnICollection: false +- sortParamsByRequiredFlag: +- sourceFolder: src +- targetFramework: net8.0 +- useCollection: false +- useDateTimeOffset: false +- useOneOfDiscriminatorLookup: false +- validatable: true + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES index 47b2b9b5c4f4..b9ab612bd8b5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/FILES @@ -20,6 +20,8 @@ src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/ExceptionEventArgs.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index ee4506c19b2a..f408496be456 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,37 +24,37 @@ namespace Org.OpenAPITools.Test.Api /// public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f7c0eaf370cb..872d1687aa20 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,15 +3,15 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net8.0 false enable - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs index 3daae4eb0bc2..80fd40849a10 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -40,7 +40,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..f7fe93629939 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..a5cb490f3ef1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * Example + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index 245aaa03ef27..79fb8600e4be 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index 8f3c26a58694..26d8b0757ba4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs index a059b5a4de46..89dc36db6665 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -41,6 +41,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new AdultJsonConverter()); _jsonOptions.Converters.Add(new ChildJsonConverter()); _jsonOptions.Converters.Add(new PersonJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/Option.cs index 663aecff33e7..b3419229d654 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/Option.cs @@ -37,5 +37,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index d77743bb7c63..d50991f16ec4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -11,9 +11,11 @@ #nullable enable using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -21,7 +23,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -32,17 +34,24 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite }; - AvailableTokens = Channel.CreateBounded(options); + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs index b0949d3d08e4..25a52d3c7185 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -27,7 +27,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs index 93bfff98acc2..8367b1a64173 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Adult.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,19 +39,26 @@ public partial class Adult : Person, IValidatableObject /// lastName /// type [JsonConstructor] - public Adult(List children, string firstName, string lastName, string type) : base(firstName, lastName, type) + public Adult(Option?> children = default, Option firstName = default, Option lastName = default, Option type = default) : base(firstName, lastName, type) { - Children = children; + ChildrenOption = children; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Children + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option?> ChildrenOption { get; private set; } + /// /// Gets or Sets Children /// [JsonPropertyName("children")] - public List Children { get; set; } + public List? Children { get { return this. ChildrenOption; } set { this.ChildrenOption = new(value); } } /// /// Returns the string presentation of the object @@ -89,10 +97,10 @@ public override Adult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List? children = default; - string? firstName = default; - string? lastName = default; - string? type = default; + Option?> children = default; + Option firstName = default; + Option lastName = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -111,16 +119,16 @@ public override Adult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert { case "children": if (utf8JsonReader.TokenType != JsonTokenType.Null) - children = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + children = new Option?>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)!); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()!); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()!); break; case "$_type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,17 +136,17 @@ public override Adult Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (children == null) - throw new ArgumentNullException(nameof(children), "Property is required for class Adult."); + if (children.IsSet && children.Value == null) + throw new ArgumentNullException(nameof(children), "Property is not nullable for class Adult."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class Adult."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class Adult."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class Adult."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class Adult."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Adult."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Adult."); return new Adult(children, firstName, lastName, type); } @@ -167,11 +175,31 @@ public override void Write(Utf8JsonWriter writer, Adult adult, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Adult adult, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("children"); - JsonSerializer.Serialize(writer, adult.Children, jsonSerializerOptions); - writer.WriteString("firstName", adult.FirstName); - writer.WriteString("lastName", adult.LastName); - writer.WriteString("$_type", adult.Type); + if (adult.ChildrenOption.IsSet && adult.Children == null) + throw new ArgumentNullException(nameof(adult.Children), "Property is required for class Adult."); + + if (adult.FirstNameOption.IsSet && adult.FirstName == null) + throw new ArgumentNullException(nameof(adult.FirstName), "Property is required for class Adult."); + + if (adult.LastNameOption.IsSet && adult.LastName == null) + throw new ArgumentNullException(nameof(adult.LastName), "Property is required for class Adult."); + + if (adult.TypeOption.IsSet && adult.Type == null) + throw new ArgumentNullException(nameof(adult.Type), "Property is required for class Adult."); + + if (adult.ChildrenOption.IsSet) + { + writer.WritePropertyName("children"); + JsonSerializer.Serialize(writer, adult.Children, jsonSerializerOptions); + } + if (adult.FirstNameOption.IsSet) + writer.WriteString("firstName", adult.FirstName); + + if (adult.LastNameOption.IsSet) + writer.WriteString("lastName", adult.LastName); + + if (adult.TypeOption.IsSet) + writer.WriteString("$_type", adult.Type); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs index 0814fec25b7a..dc6b12799fb0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Child.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -39,26 +40,40 @@ public partial class Child : Person, IValidatableObject /// type /// boosterSeat [JsonConstructor] - public Child(int age, string firstName, string lastName, string type, bool boosterSeat) : base(firstName, lastName, type) + public Child(Option age = default, Option firstName = default, Option lastName = default, Option type = default, Option boosterSeat = default) : base(firstName, lastName, type) { - Age = age; - BoosterSeat = boosterSeat; + AgeOption = age; + BoosterSeatOption = boosterSeat; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Age + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AgeOption { get; private set; } + /// /// Gets or Sets Age /// [JsonPropertyName("age")] - public int Age { get; set; } + public int? Age { get { return this. AgeOption; } set { this.AgeOption = new(value); } } + + /// + /// Used to track the state of BoosterSeat + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BoosterSeatOption { get; private set; } /// /// Gets or Sets BoosterSeat /// [JsonPropertyName("boosterSeat")] - public bool BoosterSeat { get; set; } + public bool? BoosterSeat { get { return this. BoosterSeatOption; } set { this.BoosterSeatOption = new(value); } } /// /// Returns the string presentation of the object @@ -98,11 +113,11 @@ public override Child Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? age = default; - string? firstName = default; - string? lastName = default; - string? type = default; - bool? boosterSeat = default; + Option age = default; + Option firstName = default; + Option lastName = default; + Option type = default; + Option boosterSeat = default; while (utf8JsonReader.Read()) { @@ -121,20 +136,20 @@ public override Child Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert { case "age": if (utf8JsonReader.TokenType != JsonTokenType.Null) - age = utf8JsonReader.GetInt32(); + age = new Option(utf8JsonReader.GetInt32()); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()!); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()!); break; case "$_type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()!); break; case "boosterSeat": if (utf8JsonReader.TokenType != JsonTokenType.Null) - boosterSeat = utf8JsonReader.GetBoolean(); + boosterSeat = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -142,22 +157,22 @@ public override Child Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (age == null) - throw new ArgumentNullException(nameof(age), "Property is required for class Child."); + if (age.IsSet && age.Value == null) + throw new ArgumentNullException(nameof(age), "Property is not nullable for class Child."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class Child."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class Child."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class Child."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class Child."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Child."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Child."); - if (boosterSeat == null) - throw new ArgumentNullException(nameof(boosterSeat), "Property is required for class Child."); + if (boosterSeat.IsSet && boosterSeat.Value == null) + throw new ArgumentNullException(nameof(boosterSeat), "Property is not nullable for class Child."); - return new Child(age.Value, firstName, lastName, type, boosterSeat.Value); + return new Child(age, firstName, lastName, type, boosterSeat); } /// @@ -184,11 +199,29 @@ public override void Write(Utf8JsonWriter writer, Child child, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Child child, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("age", child.Age); - writer.WriteString("firstName", child.FirstName); - writer.WriteString("lastName", child.LastName); - writer.WriteString("$_type", child.Type); - writer.WriteBoolean("boosterSeat", child.BoosterSeat); + if (child.FirstNameOption.IsSet && child.FirstName == null) + throw new ArgumentNullException(nameof(child.FirstName), "Property is required for class Child."); + + if (child.LastNameOption.IsSet && child.LastName == null) + throw new ArgumentNullException(nameof(child.LastName), "Property is required for class Child."); + + if (child.TypeOption.IsSet && child.Type == null) + throw new ArgumentNullException(nameof(child.Type), "Property is required for class Child."); + + if (child.AgeOption.IsSet) + writer.WriteNumber("age", child.AgeOption.Value!.Value); + + if (child.FirstNameOption.IsSet) + writer.WriteString("firstName", child.FirstName); + + if (child.LastNameOption.IsSet) + writer.WriteString("lastName", child.LastName); + + if (child.TypeOption.IsSet) + writer.WriteString("$_type", child.Type); + + if (child.BoosterSeatOption.IsSet) + writer.WriteBoolean("boosterSeat", child.BoosterSeatOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs index 150e974367e1..c45a0eb62d17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Model/Person.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -37,33 +38,54 @@ public partial class Person : IValidatableObject /// lastName /// type [JsonConstructor] - public Person(string firstName, string lastName, string type) + public Person(Option firstName = default, Option lastName = default, Option type = default) { - FirstName = firstName; - LastName = lastName; - Type = type; + FirstNameOption = firstName; + LastNameOption = lastName; + TypeOption = type; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of FirstName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstNameOption { get; private set; } + /// /// Gets or Sets FirstName /// [JsonPropertyName("firstName")] - public string FirstName { get; set; } + public string? FirstName { get { return this. FirstNameOption; } set { this.FirstNameOption = new(value); } } + + /// + /// Used to track the state of LastName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LastNameOption { get; private set; } /// /// Gets or Sets LastName /// [JsonPropertyName("lastName")] - public string LastName { get; set; } + public string? LastName { get { return this. LastNameOption; } set { this.LastNameOption = new(value); } } + + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } /// /// Gets or Sets Type /// [JsonPropertyName("$_type")] - public string Type { get; set; } + public string? Type { get { return this. TypeOption; } set { this.TypeOption = new(value); } } /// /// Gets or Sets additional properties @@ -130,9 +152,9 @@ public override Person Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? firstName = default; - string? lastName = default; - string? type = default; + Option firstName = default; + Option lastName = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -150,13 +172,13 @@ public override Person Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()!); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()!); break; case "$_type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -164,14 +186,14 @@ public override Person Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class Person."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class Person."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class Person."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class Person."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Person."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Person."); return new Person(firstName, lastName, type); } @@ -200,9 +222,23 @@ public override void Write(Utf8JsonWriter writer, Person person, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Person person, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("firstName", person.FirstName); - writer.WriteString("lastName", person.LastName); - writer.WriteString("$_type", person.Type); + if (person.FirstNameOption.IsSet && person.FirstName == null) + throw new ArgumentNullException(nameof(person.FirstName), "Property is required for class Person."); + + if (person.LastNameOption.IsSet && person.LastName == null) + throw new ArgumentNullException(nameof(person.LastName), "Property is required for class Person."); + + if (person.TypeOption.IsSet && person.Type == null) + throw new ArgumentNullException(nameof(person.Type), "Property is required for class Person."); + + if (person.FirstNameOption.IsSet) + writer.WriteString("firstName", person.FirstName); + + if (person.LastNameOption.IsSet) + writer.WriteString("lastName", person.LastName); + + if (person.TypeOption.IsSet) + writer.WriteString("$_type", person.Type); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2b6b21494db0..f32136bde7fb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 Org.OpenAPITools Org.OpenAPITools Library @@ -21,10 +21,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md index 404458e0b5a3..a9f072d3f49b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-allOf/src/Org.OpenAPITools/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=true', 'hideGenerationTimestamp=true', @@ -168,7 +168,7 @@ Endpoints do not require authorization. - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES index 59cc1ea25a08..dc42a5d47091 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/FILES @@ -20,6 +20,8 @@ src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/ExceptionEventArgs.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 49e4c5130241..4006d2fc6ba6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,37 +24,37 @@ namespace Org.OpenAPITools.Test.Api /// public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f7c0eaf370cb..872d1687aa20 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,15 +3,15 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net8.0 false enable - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs index 9cd19d4cc3a0..43fc1f290728 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -40,7 +40,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..5009ae5304f7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..02dda463ab26 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index c53e443828d8..4be8e3a725e0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index fd867d948f1e..06d46536f037 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs index 3dfc3e38131d..0cffc3195908 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -41,6 +41,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new AppleJsonConverter()); _jsonOptions.Converters.Add(new BananaJsonConverter()); _jsonOptions.Converters.Add(new FruitJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/Option.cs index 3c370b043a54..6f4db75a4454 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/Option.cs @@ -37,5 +37,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index 89d8079d63f6..b10d5ac58f56 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -11,9 +11,11 @@ #nullable enable using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -21,7 +23,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -32,17 +34,24 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite }; - AvailableTokens = Channel.CreateBounded(options); + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs index 86282695730e..db3ce767d4af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -27,7 +27,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs index 376581340835..22cf086e0e3d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Apple.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Apple : IValidatableObject /// /// kind [JsonConstructor] - public Apple(string kind) + public Apple(Option kind = default) { - Kind = kind; + KindOption = kind; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Kind + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option KindOption { get; private set; } + /// /// Gets or Sets Kind /// [JsonPropertyName("kind")] - public string Kind { get; set; } + public string? Kind { get { return this. KindOption; } set { this.KindOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? kind = default; + Option kind = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "kind": - kind = utf8JsonReader.GetString(); + kind = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (kind == null) - throw new ArgumentNullException(nameof(kind), "Property is required for class Apple."); + if (kind.IsSet && kind.Value == null) + throw new ArgumentNullException(nameof(kind), "Property is not nullable for class Apple."); return new Apple(kind); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("kind", apple.Kind); + if (apple.KindOption.IsSet && apple.Kind == null) + throw new ArgumentNullException(nameof(apple.Kind), "Property is required for class Apple."); + + if (apple.KindOption.IsSet) + writer.WriteString("kind", apple.Kind); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs index 003d499475e9..9d81d60d111c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Banana.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Banana : IValidatableObject /// /// count [JsonConstructor] - public Banana(decimal count) + public Banana(Option count = default) { - Count = count; + CountOption = count; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Count + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CountOption { get; private set; } + /// /// Gets or Sets Count /// [JsonPropertyName("count")] - public decimal Count { get; set; } + public decimal? Count { get { return this. CountOption; } set { this.CountOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? count = default; + Option count = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "count": if (utf8JsonReader.TokenType != JsonTokenType.Null) - count = utf8JsonReader.GetDecimal(); + count = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -129,10 +137,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (count == null) - throw new ArgumentNullException(nameof(count), "Property is required for class Banana."); + if (count.IsSet && count.Value == null) + throw new ArgumentNullException(nameof(count), "Property is not nullable for class Banana."); - return new Banana(count.Value); + return new Banana(count); } /// @@ -159,7 +167,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("count", banana.Count); + if (banana.CountOption.IsSet) + writer.WriteNumber("count", banana.CountOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs index 7cd885961b7b..a0f5762ac114 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Model/Fruit.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,31 +37,52 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple? apple, Banana? banana, string color) + public Fruit(Option apple, Option banana, Option color = default) { - Apple = apple; - Banana = banana; - Color = color; + AppleOption = apple; + BananaOption = banana; + ColorOption = color; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Apple + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AppleOption { get; private set; } + /// /// Gets or Sets Apple /// - public Apple? Apple { get; set; } + public Apple? Apple { get { return this.AppleOption; } set { this.AppleOption = new(value); } } + + /// + /// Used to track the state of Banana + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BananaOption { get; private set; } /// /// Gets or Sets Banana /// - public Banana? Banana { get; set; } + public Banana? Banana { get { return this.BananaOption; } set { this.BananaOption = new(value); } } + + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Gets or Sets additional properties @@ -115,7 +137,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -155,7 +177,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -163,10 +185,17 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); - return new Fruit(apple, banana, color); + Option appleParsedValue = apple == null + ? default + : new Option(apple); + Option bananaParsedValue = banana == null + ? default + : new Option(banana); + + return new Fruit(appleParsedValue, bananaParsedValue, color); } /// @@ -180,16 +209,16 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt { writer.WriteStartObject(); - if (fruit.Apple != null) + if (fruit.AppleOption.IsSet && fruit.AppleOption.Value != null) { - AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(fruit.Apple.GetType())); - AppleJsonConverter.WriteProperties(ref writer, fruit.Apple, jsonSerializerOptions); + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(fruit.AppleOption.Value.GetType())); + AppleJsonConverter.WriteProperties(ref writer, fruit.AppleOption.Value, jsonSerializerOptions); } - if (fruit.Banana != null) + if (fruit.BananaOption.IsSet && fruit.BananaOption.Value != null) { - BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(fruit.Banana.GetType())); - BananaJsonConverter.WriteProperties(ref writer, fruit.Banana, jsonSerializerOptions); + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(fruit.BananaOption.Value.GetType())); + BananaJsonConverter.WriteProperties(ref writer, fruit.BananaOption.Value, jsonSerializerOptions); } WriteProperties(ref writer, fruit, jsonSerializerOptions); @@ -205,7 +234,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2b6b21494db0..f32136bde7fb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 Org.OpenAPITools Org.OpenAPITools Library @@ -21,10 +21,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md index d4c30c3cd7bb..5fbf4cd118b2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-anyOf/src/Org.OpenAPITools/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=true', 'hideGenerationTimestamp=true', @@ -168,7 +168,7 @@ Endpoints do not require authorization. - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES index 59cc1ea25a08..dc42a5d47091 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/FILES @@ -20,6 +20,8 @@ src/Org.OpenAPITools/Client/ApiResponseEventArgs.cs src/Org.OpenAPITools/Client/ApiResponse`1.cs src/Org.OpenAPITools/Client/ClientUtils.cs src/Org.OpenAPITools/Client/CookieContainer.cs +src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs +src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs src/Org.OpenAPITools/Client/ExceptionEventArgs.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 49e4c5130241..4006d2fc6ba6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,37 +24,37 @@ namespace Org.OpenAPITools.Test.Api /// public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + private readonly IHost _hostUsingConfigureWithoutAClient = + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => + Host.CreateDefaultBuilder([]).ConfigureApi((context, services, options) => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }) .Build(); private readonly IHost _hostUsingAddWithoutAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + }); }) .Build(); private readonly IHost _hostUsingAddWithAClient = - Host.CreateDefaultBuilder(Array.Empty()).ConfigureServices((host, services) => + Host.CreateDefaultBuilder([]).ConfigureServices((host, services) => { services.AddApi(options => { - + options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index f7c0eaf370cb..872d1687aa20 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -3,15 +3,15 @@ Org.OpenAPITools.Test Org.OpenAPITools.Test - net7.0 + net8.0 false enable - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs index 9cd19d4cc3a0..43fc1f290728 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -40,7 +40,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs new file mode 100644 index 000000000000..5009ae5304f7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyJsonConverter.cs @@ -0,0 +1,61 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + throw new NotSupportedException(); + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly dateOnlyValue, JsonSerializerOptions options) => + writer.WriteStringValue(dateOnlyValue.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs new file mode 100644 index 000000000000..02dda463ab26 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateOnlyNullableJsonConverter.cs @@ -0,0 +1,66 @@ +/* + * fruity + * + * No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + * + * The version of the OpenAPI document: 0.0.1 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class DateOnlyNullableJsonConverter : JsonConverter + { + /// + /// The formats used to deserialize the date + /// + public static string[] Formats { get; } = { + "yyyy'-'MM'-'dd", + "yyyyMMdd" + + }; + + /// + /// Returns a DateOnly from the Json object + /// + /// + /// + /// + /// + public override DateOnly? Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { + if (reader.TokenType == JsonTokenType.Null) + return null; + + string value = reader.GetString()!; + + foreach(string format in Formats) + if (DateOnly.TryParseExact(value, format, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out DateOnly result)) + return result; + + throw new NotSupportedException(); + } + + /// + /// Writes the DateOnly to the json writer + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, DateOnly? dateOnlyValue, JsonSerializerOptions options) + { + if (dateOnlyValue == null) + writer.WriteNullValue(); + else + writer.WriteStringValue(dateOnlyValue.Value.ToString("yyyy'-'MM'-'dd", CultureInfo.InvariantCulture)); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index c53e443828d8..4be8e3a725e0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index fd867d948f1e..06d46536f037 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -32,7 +32,6 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'ffK", "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fK", "yyyy'-'MM'-'dd'T'HH':'mm':'ssK", - "yyyy'-'MM'-'dd", "yyyyMMddTHHmmss.fffffffK", "yyyyMMddTHHmmss.ffffffK", "yyyyMMddTHHmmss.fffffK", @@ -41,7 +40,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.ffK", "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", - "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs index 3dfc3e38131d..0cffc3195908 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -41,6 +41,8 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new JsonStringEnumConverter()); _jsonOptions.Converters.Add(new DateTimeJsonConverter()); _jsonOptions.Converters.Add(new DateTimeNullableJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyJsonConverter()); + _jsonOptions.Converters.Add(new DateOnlyNullableJsonConverter()); _jsonOptions.Converters.Add(new AppleJsonConverter()); _jsonOptions.Converters.Add(new BananaJsonConverter()); _jsonOptions.Converters.Add(new FruitJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/Option.cs index 3c370b043a54..6f4db75a4454 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/Option.cs @@ -37,5 +37,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index 89d8079d63f6..b10d5ac58f56 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -11,9 +11,11 @@ #nullable enable using System; +using System.Collections.Generic; +using System.Linq; using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -21,7 +23,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal Channel AvailableTokens { get; } + internal Dictionary> AvailableTokens { get; } = new(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -32,17 +34,24 @@ public RateLimitProvider(TokenContainer container) : base(container. foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) - { - FullMode = BoundedChannelFullMode.DropWrite + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) + { + FullMode = BoundedChannelFullMode.DropWrite }; - AvailableTokens = Channel.CreateBounded(options); + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); - for (int i = 0; i < _tokens.Length; i++) - _tokens[i].TokenBecameAvailable += ((sender) => AvailableTokens.Writer.TryWrite((TTokenBase) sender)); + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } + + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel? tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); + + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - => await AvailableTokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } -} +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs index 86282695730e..db3ce767d4af 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -27,7 +27,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs index 376581340835..22cf086e0e3d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Apple.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Apple : IValidatableObject /// /// kind [JsonConstructor] - public Apple(string kind) + public Apple(Option kind = default) { - Kind = kind; + KindOption = kind; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Kind + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option KindOption { get; private set; } + /// /// Gets or Sets Kind /// [JsonPropertyName("kind")] - public string Kind { get; set; } + public string? Kind { get { return this. KindOption; } set { this.KindOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? kind = default; + Option kind = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "kind": - kind = utf8JsonReader.GetString(); + kind = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -128,8 +136,8 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (kind == null) - throw new ArgumentNullException(nameof(kind), "Property is required for class Apple."); + if (kind.IsSet && kind.Value == null) + throw new ArgumentNullException(nameof(kind), "Property is not nullable for class Apple."); return new Apple(kind); } @@ -158,7 +166,11 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("kind", apple.Kind); + if (apple.KindOption.IsSet && apple.Kind == null) + throw new ArgumentNullException(nameof(apple.Kind), "Property is required for class Apple."); + + if (apple.KindOption.IsSet) + writer.WriteString("kind", apple.Kind); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs index 003d499475e9..9d81d60d111c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Banana.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,19 +36,26 @@ public partial class Banana : IValidatableObject /// /// count [JsonConstructor] - public Banana(decimal count) + public Banana(Option count = default) { - Count = count; + CountOption = count; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Count + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CountOption { get; private set; } + /// /// Gets or Sets Count /// [JsonPropertyName("count")] - public decimal Count { get; set; } + public decimal? Count { get { return this. CountOption; } set { this.CountOption = new(value); } } /// /// Gets or Sets additional properties @@ -102,7 +110,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? count = default; + Option count = default; while (utf8JsonReader.Read()) { @@ -121,7 +129,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "count": if (utf8JsonReader.TokenType != JsonTokenType.Null) - count = utf8JsonReader.GetDecimal(); + count = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -129,10 +137,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (count == null) - throw new ArgumentNullException(nameof(count), "Property is required for class Banana."); + if (count.IsSet && count.Value == null) + throw new ArgumentNullException(nameof(count), "Property is not nullable for class Banana."); - return new Banana(count.Value); + return new Banana(count); } /// @@ -159,7 +167,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("count", banana.Count); + if (banana.CountOption.IsSet) + writer.WriteNumber("count", banana.CountOption.Value!.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs index 4310e800fe99..78554584979a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Model/Fruit.cs @@ -22,6 +22,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,10 +36,10 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple apple, string color) + public Fruit(Apple apple, Option color = default) { Apple = apple; - Color = color; + ColorOption = color; OnCreated(); } @@ -47,10 +48,10 @@ public Fruit(Apple apple, string color) /// /// /// color - public Fruit(Banana banana, string color) + public Fruit(Banana banana, Option color = default) { Banana = banana; - Color = color; + ColorOption = color; OnCreated(); } @@ -66,11 +67,18 @@ public Fruit(Banana banana, string color) /// public Banana? Banana { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string? Color { get { return this. ColorOption; } set { this.ColorOption = new(value); } } /// /// Gets or Sets additional properties @@ -125,7 +133,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string? color = default; + Option color = default; Apple? apple = default; Banana? banana = default; @@ -165,7 +173,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()!); break; default: break; @@ -173,8 +181,8 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); if (apple != null) return new Fruit(apple, color); @@ -209,7 +217,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 2b6b21494db0..f32136bde7fb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -2,7 +2,7 @@ true - net7.0 + net8.0 Org.OpenAPITools Org.OpenAPITools Library @@ -21,10 +21,11 @@ - - - - + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md index d4c30c3cd7bb..5fbf4cd118b2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netcore-latest-oneOf/src/Org.OpenAPITools/README.md @@ -6,7 +6,7 @@ ```ps1 $properties = @( 'apiName=Api', - 'targetFramework=net7.0', + 'targetFramework=net8.0', 'validatable=true', 'nullableReferenceTypes=true', 'hideGenerationTimestamp=true', @@ -168,7 +168,7 @@ Endpoints do not require authorization. - returnICollection: false - sortParamsByRequiredFlag: - sourceFolder: src -- targetFramework: net7.0 +- targetFramework: net8.0 - useCollection: false - useDateTimeOffset: false - useOneOfDiscriminatorLookup: false diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES index 1179de6767be..05049077c2ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/FILES @@ -79,6 +79,7 @@ docs/models/PolymorphicProperty.md docs/models/Quadrilateral.md docs/models/QuadrilateralInterface.md docs/models/ReadOnlyFirst.md +docs/models/RequiredClass.md docs/models/Return.md docs/models/RolesReportsHash.md docs/models/RolesReportsHashRole.md @@ -206,6 +207,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md index 76873f715c8e..b5ba5edafdeb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md index 44c9eeac76b9..407fb30dccb4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md index 56c1acb79285..ee189c866ec5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/apis/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to Model list]](../../README.md#documentation-for-models) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md index f79869f95a71..2bbe882fcfcc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/AdditionalPropertiesClass.md @@ -4,6 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Anytype1** | **Object** | | [optional] **EmptyMap** | **Object** | an object with no declared properties and no undeclared properties, hence it's an empty map. | [optional] **MapOfMapProperty** | **Dictionary<string, Dictionary<string, string>>** | | [optional] **MapProperty** | **Dictionary<string, string>** | | [optional] @@ -11,7 +12,6 @@ Name | Type | Description | Notes **MapWithUndeclaredPropertiesAnytype2** | **Object** | | [optional] **MapWithUndeclaredPropertiesAnytype3** | **Dictionary<string, Object>** | | [optional] **MapWithUndeclaredPropertiesString** | **Dictionary<string, string>** | | [optional] -**Anytype1** | **Object** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/ChildCat.md index b8f7d81fbbee..88fe8f7a7fdd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md index 215793515f64..95f49b2ed600 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Drawing.md @@ -5,9 +5,9 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **MainShape** | [**Shape**](Shape.md) | | [optional] -**Shapes** | [**List<Shape>**](Shape.md) | | [optional] **NullableShape** | [**NullableShape**](NullableShape.md) | | [optional] **ShapeOrNull** | [**ShapeOrNull**](ShapeOrNull.md) | | [optional] +**Shapes** | [**List<Shape>**](Shape.md) | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md index 53bbfe31e77c..ebd7ccf2c864 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/EnumTest.md @@ -4,15 +4,15 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**EnumStringRequired** | **string** | | **EnumInteger** | **int** | | [optional] **EnumIntegerOnly** | **int** | | [optional] **EnumNumber** | **double** | | [optional] **EnumString** | **string** | | [optional] -**EnumStringRequired** | **string** | | +**OuterEnum** | **OuterEnum** | | [optional] **OuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] **OuterEnumInteger** | **OuterEnumInteger** | | [optional] **OuterEnumIntegerDefaultValue** | **OuterEnumIntegerDefaultValue** | | [optional] -**OuterEnum** | **OuterEnum** | | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md index 28f1a8093581..ab628ed7bc0b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/FormatTest.md @@ -4,9 +4,11 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Binary** | **System.IO.Stream** | | [optional] **VarByte** | **byte[]** | | **Date** | **DateTime** | | +**Number** | **decimal** | | +**Password** | **string** | | +**Binary** | **System.IO.Stream** | | [optional] **DateTime** | **DateTime** | | [optional] **VarDecimal** | **decimal** | | [optional] **VarDouble** | **double** | | [optional] @@ -14,8 +16,6 @@ Name | Type | Description | Notes **Int32** | **int** | | [optional] **Int64** | **long** | | [optional] **Integer** | **int** | | [optional] -**Number** | **decimal** | | -**Password** | **string** | | **PatternWithBackslash** | **string** | None | [optional] **PatternWithDigits** | **string** | A string that is a 10 digit number. Can have leading zeros. | [optional] **PatternWithDigitsAndDelimiter** | **string** | A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md index 394feef77dbb..5d9965f55c0a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/NullableClass.md @@ -4,9 +4,8 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**ArrayItemsNullable** | **List<Object>** | | [optional] -**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] +**ArrayItemsNullable** | **List<Object>** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **BooleanProp** | **bool** | | [optional] **DateProp** | **DateTime** | | [optional] @@ -14,6 +13,7 @@ Name | Type | Description | Notes **IntegerProp** | **int** | | [optional] **NumberProp** | **decimal** | | [optional] **ObjectAndItemsNullableProp** | **Dictionary<string, Object>** | | [optional] +**ObjectItemsNullable** | **Dictionary<string, Object>** | | [optional] **ObjectNullableProp** | **Dictionary<string, Object>** | | [optional] **StringProp** | **string** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Order.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Order.md index ca5d8992a513..f7d6827ed5c9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Order.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Order.md @@ -4,12 +4,12 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**Complete** | **bool** | | [optional] [default to false] **Id** | **long** | | [optional] **PetId** | **long** | | [optional] **Quantity** | **int** | | [optional] **ShipDate** | **DateTime** | | [optional] **Status** | **string** | Order Status | [optional] -**Complete** | **bool** | | [optional] [default to false] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md index b13bb576b450..4f019b613bd7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/Pet.md @@ -4,10 +4,10 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**Category** | [**Category**](Category.md) | | [optional] -**Id** | **long** | | [optional] **Name** | **string** | | **PhotoUrls** | **List<string>** | | +**Category** | [**Category**](Category.md) | | [optional] +**Id** | **long** | | [optional] **Status** | **string** | pet status in the store | [optional] **Tags** | [**List<Tag>**](Tag.md) | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/RequiredClass.md new file mode 100644 index 000000000000..8f148be840b0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNotNullableDateProp** | **DateTime** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNotnullableEnumInteger** | **int** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**RequiredNotnullableEnumString** | **string** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableStringProp** | **string** | | +**RequiredNotnullableUuid** | **Guid** | | +**RequiredNotnullableintegerProp** | **int** | | +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNullableBooleanProp** | **bool** | | +**RequiredNullableDateProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime** | | +**RequiredNullableEnumInteger** | **int** | | +**RequiredNullableEnumIntegerOnly** | **int** | | +**RequiredNullableEnumString** | **string** | | +**RequiredNullableIntegerProp** | **int** | | +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNullableStringProp** | **string** | | +**RequiredNullableUuid** | **Guid** | | +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**NotRequiredNullableDateProp** | **DateTime** | | [optional] +**NotRequiredNullableIntegerProp** | **int** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNullableBooleanProp** | **bool** | | [optional] +**NotrequiredNullableDatetimeProp** | **DateTime** | | [optional] +**NotrequiredNullableEnumInteger** | **int** | | [optional] +**NotrequiredNullableEnumIntegerOnly** | **int** | | [optional] +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNullableUuid** | **Guid** | | [optional] + +[[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md index 455f031674d5..b5700f1c75d9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/docs/models/User.md @@ -4,18 +4,18 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] +**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] **Email** | **string** | | [optional] **FirstName** | **string** | | [optional] **Id** | **long** | | [optional] **LastName** | **string** | | [optional] **ObjectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] +**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] **Password** | **string** | | [optional] **Phone** | **string** | | [optional] **UserStatus** | **int** | User Status | [optional] **Username** | **string** | | [optional] -**AnyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] -**AnyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] -**ObjectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] [[Back to Model list]](../../README.md#documentation-for-models) [[Back to API list]](../../README.md#documentation-for-api-endpoints) [[Back to README]](../../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs index b44e3191e8d7..c178aac4eabe 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/ApiTestsBase.cs @@ -52,26 +52,30 @@ public ApiTestsBase(string[] args) public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureApi((context, services, options) => { - string apiKeyTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - ApiKeyToken apiKeyToken = new ApiKeyToken(apiKeyTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); + string apiKeyTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken1 = new ApiKeyToken(apiKeyTokenValue1, ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); - string bearerTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - BearerToken bearerToken = new BearerToken(bearerTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); + string apiKeyTokenValue2 = context.Configuration[""] ?? throw new Exception("Token not found."); + ApiKeyToken apiKeyToken2 = new ApiKeyToken(apiKeyTokenValue2, ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); - string basicTokenUsername = context.Configuration[""] ?? throw new Exception("Username not found."); - string basicTokenPassword = context.Configuration[""] ?? throw new Exception("Password not found."); - BasicToken basicToken = new BasicToken(basicTokenUsername, basicTokenPassword, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); + string bearerTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + BearerToken bearerToken1 = new BearerToken(bearerTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); + string basicTokenUsername1 = context.Configuration[""] ?? throw new Exception("Username not found."); + string basicTokenPassword1 = context.Configuration[""] ?? throw new Exception("Password not found."); + BasicToken basicToken1 = new BasicToken(basicTokenUsername1, basicTokenPassword1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); - string oauthTokenValue = context.Configuration[""] ?? throw new Exception("Token not found."); - OAuthToken oauthToken = new OAuthToken(oauthTokenValue, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + HttpSigningConfiguration config1 = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new HttpSignatureToken(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + string oauthTokenValue1 = context.Configuration[""] ?? throw new Exception("Token not found."); + OAuthToken oauthToken1 = new OAuthToken(oauthTokenValue1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs index 5ad1cd420f95..bbccd77b29c1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/DependencyInjectionTests.cs @@ -24,43 +24,49 @@ namespace Org.OpenAPITools.Test.Api ///
              public class DependencyInjectionTest { - private readonly IHost _hostUsingConfigureWithoutAClient = + private readonly IHost _hostUsingConfigureWithoutAClient = Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new BearerToken("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new HttpSignatureToken(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }) .Build(); private readonly IHost _hostUsingConfigureWithAClient = Host.CreateDefaultBuilder(Array.Empty()).ConfigureApi((context, services, options) => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - + ApiKeyToken apiKeyToken1 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new BearerToken("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new HttpSignatureToken(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); options.AddTokens(oauthToken); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); @@ -72,21 +78,24 @@ public class DependencyInjectionTest { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new BearerToken("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new HttpSignatureToken(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); }); }) .Build(); @@ -96,21 +105,24 @@ public class DependencyInjectionTest { services.AddApi(options => { - ApiKeyToken apiKeyToken = new ApiKeyToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(apiKeyToken); - - BearerToken bearerToken = new BearerToken($"", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(bearerToken); - - BasicToken basicToken = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(basicToken); - - HttpSigningConfiguration config = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); - HttpSignatureToken httpSignatureToken = new HttpSignatureToken(config, timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(httpSignatureToken); - - OAuthToken oauthToken = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); - options.AddTokens(oauthToken); + ApiKeyToken apiKeyToken1 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken1); + + ApiKeyToken apiKeyToken2 = new ApiKeyToken("", ClientUtils.ApiKeyHeader.Api_key_query, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(apiKeyToken2); + + BearerToken bearerToken1 = new BearerToken("", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(bearerToken1); + + BasicToken basicToken1 = new BasicToken("", "", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(basicToken1); + + HttpSigningConfiguration config1 = new HttpSigningConfiguration("", "", null, new List(), HashAlgorithmName.SHA256, "", 0); + HttpSignatureToken httpSignatureToken1 = new HttpSignatureToken(config1, timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(httpSignatureToken1); + + OAuthToken oauthToken1 = new OAuthToken("token", timeout: TimeSpan.FromSeconds(1)); + options.AddTokens(oauthToken1); options.AddApiHttpClients(client => client.BaseAddress = new Uri(ClientUtils.BASE_ADDRESS)); }); }) @@ -124,22 +136,22 @@ public void ConfigureApiWithAClientTest() { var anotherFakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -152,22 +164,22 @@ public void ConfigureApiWithoutAClientTest() { var anotherFakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingConfigureWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } @@ -208,22 +220,22 @@ public void AddApiWithoutAClientTest() { var anotherFakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(anotherFakeApi.HttpClient.BaseAddress != null); - + var defaultApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(defaultApi.HttpClient.BaseAddress != null); - + var fakeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeApi.HttpClient.BaseAddress != null); - + var fakeClassnameTags123Api = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(fakeClassnameTags123Api.HttpClient.BaseAddress != null); - + var petApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(petApi.HttpClient.BaseAddress != null); - + var storeApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(storeApi.HttpClient.BaseAddress != null); - + var userApi = _hostUsingAddWithoutAClient.Services.GetRequiredService(); Assert.True(userApi.HttpClient.BaseAddress != null); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs index 6c82be59af88..62a5cdba43b7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Api/FakeApiTests.cs @@ -219,6 +219,16 @@ public async Task TestInlineAdditionalPropertiesAsyncTest() await _instance.TestInlineAdditionalPropertiesAsync(requestBody); } + /// + /// Test TestInlineFreeformAdditionalProperties + /// + [Fact (Skip = "not implemented")] + public async Task TestInlineFreeformAdditionalPropertiesAsyncTest() + { + TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = default; + await _instance.TestInlineFreeformAdditionalPropertiesAsync(testInlineFreeformAdditionalPropertiesRequest); + } + /// /// Test TestJsonFormData /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs index b6bff036a466..e157b477193e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/AdditionalPropertiesClassTests.cs @@ -53,6 +53,15 @@ public void AdditionalPropertiesClassInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Anytype1' + /// + [Fact] + public void Anytype1Test() + { + // TODO unit test for the property 'Anytype1' + } + /// /// Test the property 'EmptyMap' /// @@ -115,14 +124,5 @@ public void MapWithUndeclaredPropertiesStringTest() { // TODO unit test for the property 'MapWithUndeclaredPropertiesString' } - - /// - /// Test the property 'Anytype1' - /// - [Fact] - public void Anytype1Test() - { - // TODO unit test for the property 'Anytype1' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs index 0ed2f54aab54..a2de4a1b97b1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/DrawingTests.cs @@ -62,15 +62,6 @@ public void MainShapeTest() // TODO unit test for the property 'MainShape' } - /// - /// Test the property 'Shapes' - /// - [Fact] - public void ShapesTest() - { - // TODO unit test for the property 'Shapes' - } - /// /// Test the property 'NullableShape' /// @@ -88,5 +79,14 @@ public void ShapeOrNullTest() { // TODO unit test for the property 'ShapeOrNull' } + + /// + /// Test the property 'Shapes' + /// + [Fact] + public void ShapesTest() + { + // TODO unit test for the property 'Shapes' + } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs index e5a97f428662..3781eebbfcf2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/EnumTestTests.cs @@ -53,6 +53,15 @@ public void EnumTestInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'EnumStringRequired' + /// + [Fact] + public void EnumStringRequiredTest() + { + // TODO unit test for the property 'EnumStringRequired' + } + /// /// Test the property 'EnumInteger' /// @@ -90,12 +99,12 @@ public void EnumStringTest() } /// - /// Test the property 'EnumStringRequired' + /// Test the property 'OuterEnum' /// [Fact] - public void EnumStringRequiredTest() + public void OuterEnumTest() { - // TODO unit test for the property 'EnumStringRequired' + // TODO unit test for the property 'OuterEnum' } /// @@ -124,14 +133,5 @@ public void OuterEnumIntegerDefaultValueTest() { // TODO unit test for the property 'OuterEnumIntegerDefaultValue' } - - /// - /// Test the property 'OuterEnum' - /// - [Fact] - public void OuterEnumTest() - { - // TODO unit test for the property 'OuterEnum' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs index fbffe502af78..164baa8862be 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/FormatTestTests.cs @@ -53,15 +53,6 @@ public void FormatTestInstanceTest() //Assert.IsType(instance); } - /// - /// Test the property 'Binary' - /// - [Fact] - public void BinaryTest() - { - // TODO unit test for the property 'Binary' - } - /// /// Test the property 'VarByte' /// @@ -80,6 +71,33 @@ public void DateTest() // TODO unit test for the property 'Date' } + /// + /// Test the property 'Number' + /// + [Fact] + public void NumberTest() + { + // TODO unit test for the property 'Number' + } + + /// + /// Test the property 'Password' + /// + [Fact] + public void PasswordTest() + { + // TODO unit test for the property 'Password' + } + + /// + /// Test the property 'Binary' + /// + [Fact] + public void BinaryTest() + { + // TODO unit test for the property 'Binary' + } + /// /// Test the property 'DateTime' /// @@ -143,24 +161,6 @@ public void IntegerTest() // TODO unit test for the property 'Integer' } - /// - /// Test the property 'Number' - /// - [Fact] - public void NumberTest() - { - // TODO unit test for the property 'Number' - } - - /// - /// Test the property 'Password' - /// - [Fact] - public void PasswordTest() - { - // TODO unit test for the property 'Password' - } - /// /// Test the property 'PatternWithBackslash' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs index 47901aeb2f4c..1e19aa6b8231 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/NullableClassTests.cs @@ -54,30 +54,21 @@ public void NullableClassInstanceTest() } /// - /// Test the property 'ArrayItemsNullable' - /// - [Fact] - public void ArrayItemsNullableTest() - { - // TODO unit test for the property 'ArrayItemsNullable' - } - - /// - /// Test the property 'ObjectItemsNullable' + /// Test the property 'ArrayAndItemsNullableProp' /// [Fact] - public void ObjectItemsNullableTest() + public void ArrayAndItemsNullablePropTest() { - // TODO unit test for the property 'ObjectItemsNullable' + // TODO unit test for the property 'ArrayAndItemsNullableProp' } /// - /// Test the property 'ArrayAndItemsNullableProp' + /// Test the property 'ArrayItemsNullable' /// [Fact] - public void ArrayAndItemsNullablePropTest() + public void ArrayItemsNullableTest() { - // TODO unit test for the property 'ArrayAndItemsNullableProp' + // TODO unit test for the property 'ArrayItemsNullable' } /// @@ -143,6 +134,15 @@ public void ObjectAndItemsNullablePropTest() // TODO unit test for the property 'ObjectAndItemsNullableProp' } + /// + /// Test the property 'ObjectItemsNullable' + /// + [Fact] + public void ObjectItemsNullableTest() + { + // TODO unit test for the property 'ObjectItemsNullable' + } + /// /// Test the property 'ObjectNullableProp' /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs index afab7d23a20e..e7187bbdc92c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/OrderTests.cs @@ -53,6 +53,15 @@ public void OrderInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'Complete' + /// + [Fact] + public void CompleteTest() + { + // TODO unit test for the property 'Complete' + } + /// /// Test the property 'Id' /// @@ -97,14 +106,5 @@ public void StatusTest() { // TODO unit test for the property 'Status' } - - /// - /// Test the property 'Complete' - /// - [Fact] - public void CompleteTest() - { - // TODO unit test for the property 'Complete' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs index fff8db45faad..8485d1213ce6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/PetTests.cs @@ -54,39 +54,39 @@ public void PetInstanceTest() } /// - /// Test the property 'Category' + /// Test the property 'Name' /// [Fact] - public void CategoryTest() + public void NameTest() { - // TODO unit test for the property 'Category' + // TODO unit test for the property 'Name' } /// - /// Test the property 'Id' + /// Test the property 'PhotoUrls' /// [Fact] - public void IdTest() + public void PhotoUrlsTest() { - // TODO unit test for the property 'Id' + // TODO unit test for the property 'PhotoUrls' } /// - /// Test the property 'Name' + /// Test the property 'Category' /// [Fact] - public void NameTest() + public void CategoryTest() { - // TODO unit test for the property 'Name' + // TODO unit test for the property 'Category' } /// - /// Test the property 'PhotoUrls' + /// Test the property 'Id' /// [Fact] - public void PhotoUrlsTest() + public void IdTest() { - // TODO unit test for the property 'PhotoUrls' + // TODO unit test for the property 'Id' } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..e51863915927 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,452 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs index cc4d133818ac..6415f8561f1f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools.Test/Model/UserTests.cs @@ -53,6 +53,24 @@ public void UserInstanceTest() //Assert.IsType(instance); } + /// + /// Test the property 'AnyTypeProp' + /// + [Fact] + public void AnyTypePropTest() + { + // TODO unit test for the property 'AnyTypeProp' + } + + /// + /// Test the property 'AnyTypePropNullable' + /// + [Fact] + public void AnyTypePropNullableTest() + { + // TODO unit test for the property 'AnyTypePropNullable' + } + /// /// Test the property 'Email' /// @@ -98,6 +116,15 @@ public void ObjectWithNoDeclaredPropsTest() // TODO unit test for the property 'ObjectWithNoDeclaredProps' } + /// + /// Test the property 'ObjectWithNoDeclaredPropsNullable' + /// + [Fact] + public void ObjectWithNoDeclaredPropsNullableTest() + { + // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' + } + /// /// Test the property 'Password' /// @@ -133,32 +160,5 @@ public void UsernameTest() { // TODO unit test for the property 'Username' } - - /// - /// Test the property 'AnyTypeProp' - /// - [Fact] - public void AnyTypePropTest() - { - // TODO unit test for the property 'AnyTypeProp' - } - - /// - /// Test the property 'AnyTypePropNullable' - /// - [Fact] - public void AnyTypePropNullableTest() - { - // TODO unit test for the property 'AnyTypePropNullable' - } - - /// - /// Test the property 'ObjectWithNoDeclaredPropsNullable' - /// - [Fact] - public void ObjectWithNoDeclaredPropsNullableTest() - { - // TODO unit test for the property 'ObjectWithNoDeclaredPropsNullable' - } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs index 7dfa027962fd..b26a5d92d5d5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -168,6 +168,29 @@ public interface IFakeApi : IApi /// <> Task GetArrayOfEnumsOrDefaultAsync(System.Threading.CancellationToken cancellationToken = default); + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default); + /// /// /// @@ -541,6 +564,18 @@ public interface IGetArrayOfEnumsApiResponse : Org.OpenAPITools.Client.IApiRespo bool IsOk { get; } } + /// + /// The + /// + public interface ITestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.IApiResponse + { + /// + /// Returns true if the response is 200 Ok + /// + /// + bool IsOk { get; } + } + /// /// The /// @@ -798,6 +833,26 @@ internal void ExecuteOnErrorGetArrayOfEnums(Exception exception) OnErrorGetArrayOfEnums?.Invoke(this, new ExceptionEventArgs(exception)); } + /// + /// The event raised after the server response + /// + public event EventHandler OnTestAdditionalPropertiesReference; + + /// + /// The event raised after an error querying the server + /// + public event EventHandler OnErrorTestAdditionalPropertiesReference; + + internal void ExecuteOnTestAdditionalPropertiesReference(FakeApi.TestAdditionalPropertiesReferenceApiResponse apiResponse) + { + OnTestAdditionalPropertiesReference?.Invoke(this, new ApiResponseEventArgs(apiResponse)); + } + + internal void ExecuteOnErrorTestAdditionalPropertiesReference(Exception exception) + { + OnErrorTestAdditionalPropertiesReference?.Invoke(this, new ExceptionEventArgs(exception)); + } + /// /// The event raised after the server response /// @@ -2366,6 +2421,195 @@ private void OnDeserializationErrorDefaultImplementation(Exception exception, Ht partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); } + partial void FormatTestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// Validates the request parameters + /// + /// + /// + private void ValidateTestAdditionalPropertiesReference(Dictionary requestBody) + { + if (requestBody == null) + throw new ArgumentNullException(nameof(requestBody)); + } + + /// + /// Processes the server response + /// + /// + /// + private void AfterTestAdditionalPropertiesReferenceDefaultImplementation(ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody) + { + bool suppressDefaultLog = false; + AfterTestAdditionalPropertiesReference(ref suppressDefaultLog, apiResponseLocalVar, requestBody); + if (!suppressDefaultLog) + Logger.LogInformation("{0,-9} | {1} | {3}", (apiResponseLocalVar.DownloadedAt - apiResponseLocalVar.RequestedAt).TotalSeconds, apiResponseLocalVar.StatusCode, apiResponseLocalVar.Path); + } + + /// + /// Processes the server response + /// + /// + /// + /// + partial void AfterTestAdditionalPropertiesReference(ref bool suppressDefaultLog, ITestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar, Dictionary requestBody); + + /// + /// Logs exceptions that occur while retrieving the server response + /// + /// + /// + /// + /// + private void OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(Exception exception, string pathFormat, string path, Dictionary requestBody) + { + bool suppressDefaultLog = false; + OnErrorTestAdditionalPropertiesReference(ref suppressDefaultLog, exception, pathFormat, path, requestBody); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while sending the request to the server."); + } + + /// + /// A partial method that gives developers a way to provide customized exception handling + /// + /// + /// + /// + /// + /// + partial void OnErrorTestAdditionalPropertiesReference(ref bool suppressDefaultLog, Exception exception, string pathFormat, string path, Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceOrDefaultAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + try + { + return await TestAdditionalPropertiesReferenceAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + catch (Exception) + { + return null; + } + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// <> + public async Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default) + { + UriBuilder uriBuilderLocalVar = new UriBuilder(); + + try + { + ValidateTestAdditionalPropertiesReference(requestBody); + + FormatTestAdditionalPropertiesReference(requestBody); + + using (HttpRequestMessage httpRequestMessageLocalVar = new HttpRequestMessage()) + { + uriBuilderLocalVar.Host = HttpClient.BaseAddress.Host; + uriBuilderLocalVar.Port = HttpClient.BaseAddress.Port; + uriBuilderLocalVar.Scheme = HttpClient.BaseAddress.Scheme; + uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/fake/additionalProperties-reference"; + + httpRequestMessageLocalVar.Content = (requestBody as object) is System.IO.Stream stream + ? httpRequestMessageLocalVar.Content = new StreamContent(stream) + : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(requestBody, _jsonSerializerOptions)); + + httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; + + string[] contentTypes = new string[] { + "application/json" + }; + + string contentTypeLocalVar = ClientUtils.SelectHeaderContentType(contentTypes); + + if (contentTypeLocalVar != null && httpRequestMessageLocalVar.Content != null) + httpRequestMessageLocalVar.Content.Headers.ContentType = new MediaTypeHeaderValue(contentTypeLocalVar); + + httpRequestMessageLocalVar.Method = new HttpMethod("POST"); + + DateTime requestedAtLocalVar = DateTime.UtcNow; + + using (HttpResponseMessage httpResponseMessageLocalVar = await HttpClient.SendAsync(httpRequestMessageLocalVar, cancellationToken).ConfigureAwait(false)) + { + string responseContentLocalVar = await httpResponseMessageLocalVar.Content.ReadAsStringAsync().ConfigureAwait(false); + + ILogger apiResponseLoggerLocalVar = LoggerFactory.CreateLogger(); + + TestAdditionalPropertiesReferenceApiResponse apiResponseLocalVar = new TestAdditionalPropertiesReferenceApiResponse(apiResponseLoggerLocalVar, httpRequestMessageLocalVar, httpResponseMessageLocalVar, responseContentLocalVar, "/fake/additionalProperties-reference", requestedAtLocalVar, _jsonSerializerOptions); + + AfterTestAdditionalPropertiesReferenceDefaultImplementation(apiResponseLocalVar, requestBody); + + Events.ExecuteOnTestAdditionalPropertiesReference(apiResponseLocalVar); + + return apiResponseLocalVar; + } + } + } + catch(Exception e) + { + OnErrorTestAdditionalPropertiesReferenceDefaultImplementation(e, "/fake/additionalProperties-reference", uriBuilderLocalVar.Path, requestBody); + Events.ExecuteOnErrorTestAdditionalPropertiesReference(e); + throw; + } + } + + /// + /// The + /// + public partial class TestAdditionalPropertiesReferenceApiResponse : Org.OpenAPITools.Client.ApiResponse, ITestAdditionalPropertiesReferenceApiResponse + { + /// + /// The logger + /// + public ILogger Logger { get; } + + /// + /// The + /// + /// + /// + /// + /// + /// + /// + /// + public TestAdditionalPropertiesReferenceApiResponse(ILogger logger, System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage, string rawContent, string path, DateTime requestedAt, System.Text.Json.JsonSerializerOptions jsonSerializerOptions) : base(httpRequestMessage, httpResponseMessage, rawContent, path, requestedAt, jsonSerializerOptions) + { + Logger = logger; + OnCreated(httpRequestMessage, httpResponseMessage); + } + + partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); + + /// + /// Returns true if the response is 200 Ok + /// + /// + public bool IsOk => 200 == (int)StatusCode; + + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) + { + bool suppressDefaultLog = false; + OnDeserializationError(ref suppressDefaultLog, exception, httpStatusCode); + if (!suppressDefaultLog) + Logger.LogError(exception, "An error occurred while deserializing the {code} response.", httpStatusCode); + } + + partial void OnDeserializationError(ref bool suppressDefaultLog, Exception exception, HttpStatusCode httpStatusCode); + } + partial void FormatTestBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); /// @@ -3235,14 +3479,13 @@ public async Task TestEndpointParametersAsyn formParameterLocalVars.Add(new KeyValuePair("dateTime", ClientUtils.ParameterToString(dateTime.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BasicToken basicTokenLocalVar = (BasicToken) await BasicTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BasicToken basicTokenLocalVar1 = (BasicToken) await BasicTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(basicTokenLocalVar); + tokenBaseLocalVars.Add(basicTokenLocalVar1); - basicTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + basicTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -3760,14 +4003,13 @@ public async Task TestGroupParametersAsync(bool httpRequestMessageLocalVar.Headers.Add("boolean_group", ClientUtils.ParameterToString(booleanGroup.Value)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - BearerToken bearerTokenLocalVar = (BearerToken) await BearerTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + BearerToken bearerTokenLocalVar1 = (BearerToken) await BearerTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(bearerTokenLocalVar); + tokenBaseLocalVars.Add(bearerTokenLocalVar1); - bearerTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + bearerTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = new HttpMethod("DELETE"); DateTime requestedAtLocalVar = DateTime.UtcNow; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs index 81b3a94a1b4f..e9cbea054a4c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/FakeClassnameTags123Api.cs @@ -277,14 +277,12 @@ public async Task TestClassnameAsync(ModelClient mode : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(modelClient, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - apiKeyTokenLocalVar.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar, "api_key_query"); + apiKeyTokenLocalVar1.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] contentTypes = new string[] { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs index 153efe214685..89f7ca4a919e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -87,7 +87,7 @@ public interface IPetApi : IApi /// Multiple status values can be provided with comma separated strings /// /// Thrown when fails to make API call - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -98,7 +98,7 @@ public interface IPetApi : IApi /// /// Multiple status values can be provided with comma separated strings /// - /// Status values that need to be considered for filter + /// Status values that need to be considered for filter (deprecated) /// Cancellation Token to cancel the request. /// <> Task FindPetsByStatusOrDefaultAsync(List status, System.Threading.CancellationToken cancellationToken = default); @@ -113,6 +113,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -124,6 +125,7 @@ public interface IPetApi : IApi /// Tags to filter by /// Cancellation Token to cancel the request. /// <> + [Obsolete] Task FindPetsByTagsOrDefaultAsync(List tags, System.Threading.CancellationToken cancellationToken = default); /// @@ -765,23 +767,22 @@ public async Task AddPetAsync(Pet pet, System.Threading.Canc : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync().ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -983,14 +984,13 @@ public async Task DeletePetAsync(long petId, Option tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); httpRequestMessageLocalVar.Method = new HttpMethod("DELETE"); DateTime requestedAtLocalVar = DateTime.UtcNow; @@ -1176,23 +1176,22 @@ public async Task FindPetsByStatusAsync(List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync().ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1427,23 +1426,22 @@ public async Task FindPetsByTagsAsync(List t uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync().ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] acceptLocalVars = new string[] { @@ -1659,14 +1657,19 @@ public async Task GetPetByIdAsync(long petId, System.Thr uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/pet/{petId}"; uriBuilderLocalVar.Path = uriBuilderLocalVar.Path.Replace("%7BpetId%7D", Uri.EscapeDataString(petId.ToString())); - List tokenBaseLocalVars = new List(); + System.Collections.Specialized.NameValueCollection parseQueryStringLocalVar = System.Web.HttpUtility.ParseQueryString(string.Empty); - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); + List tokenBaseLocalVars = new List(); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); + ApiKeyToken apiKeyTokenLocalVar2 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key_query", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar2); - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + apiKeyTokenLocalVar2.UseInQuery(httpRequestMessageLocalVar, uriBuilderLocalVar, parseQueryStringLocalVar); + uriBuilderLocalVar.Query = parseQueryStringLocalVar.ToString(); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; string[] acceptLocalVars = new string[] { @@ -1905,23 +1908,22 @@ public async Task UpdatePetAsync(Pet pet, System.Threadin : httpRequestMessageLocalVar.Content = new StringContent(JsonSerializer.Serialize(pet, _jsonSerializerOptions)); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); - HttpSignatureToken httpSignatureTokenLocalVar = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + HttpSignatureToken httpSignatureTokenLocalVar2 = (HttpSignatureToken) await HttpSignatureTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(httpSignatureTokenLocalVar); + tokenBaseLocalVars.Add(httpSignatureTokenLocalVar2); if (httpRequestMessageLocalVar.Content != null) { string requestBodyLocalVar = await httpRequestMessageLocalVar.Content.ReadAsStringAsync().ConfigureAwait(false); - httpSignatureTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); + httpSignatureTokenLocalVar2.UseInHeader(httpRequestMessageLocalVar, requestBodyLocalVar, cancellationToken); } string[] contentTypes = new string[] { @@ -2154,14 +2156,13 @@ public async Task UpdatePetWithFormAsync(long pet formParameterLocalVars.Add(new KeyValuePair("status", ClientUtils.ParameterToString(status.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "application/x-www-form-urlencoded" @@ -2380,14 +2381,13 @@ public async Task UploadFileAsync(long petId, Option("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" @@ -2645,14 +2645,13 @@ public async Task UploadFileWithRequired formParameterLocalVars.Add(new KeyValuePair("additionalMetadata", ClientUtils.ParameterToString(additionalMetadata.Value))); List tokenBaseLocalVars = new List(); - httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; - OAuthToken oauthTokenLocalVar = (OAuthToken) await OauthTokenProvider.GetAsync(cancellationToken).ConfigureAwait(false); + OAuthToken oauthTokenLocalVar1 = (OAuthToken) await OauthTokenProvider.GetAsync(cancellation: cancellationToken).ConfigureAwait(false); - tokenBaseLocalVars.Add(oauthTokenLocalVar); + tokenBaseLocalVars.Add(oauthTokenLocalVar1); - oauthTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, ""); + oauthTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar, ""); string[] contentTypes = new string[] { "multipart/form-data" diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs index 2bdb19eb968a..6615881a3694 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/StoreApi.cs @@ -617,12 +617,9 @@ public async Task GetInventoryAsync(System.Threading.C uriBuilderLocalVar.Path = ClientUtils.CONTEXT_PATH + "/store/inventory"; List tokenBaseLocalVars = new List(); - - ApiKeyToken apiKeyTokenLocalVar = (ApiKeyToken) await ApiKeyProvider.GetAsync(cancellationToken).ConfigureAwait(false); - - tokenBaseLocalVars.Add(apiKeyTokenLocalVar); - - apiKeyTokenLocalVar.UseInHeader(httpRequestMessageLocalVar, "api_key"); + ApiKeyToken apiKeyTokenLocalVar1 = (ApiKeyToken) await ApiKeyProvider.GetAsync("api_key", cancellationToken).ConfigureAwait(false); + tokenBaseLocalVars.Add(apiKeyTokenLocalVar1); + apiKeyTokenLocalVar1.UseInHeader(httpRequestMessageLocalVar); httpRequestMessageLocalVar.RequestUri = uriBuilderLocalVar.Uri; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs index 411badad6742..9d668e774136 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Api/UserApi.cs @@ -276,7 +276,7 @@ public interface IDeleteUserApiResponse : Org.OpenAPITools.Client.IApiResponse /// /// The /// - public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk + public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiResponse, IOk, ICustomHttpStatusCode599 { /// /// Returns true if the response is 200 Ok @@ -295,6 +295,18 @@ public interface IGetUserByNameApiResponse : Org.OpenAPITools.Client.IApiRespons /// /// bool IsNotFound { get; } + + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + bool IsCustomHttpStatusCode598 { get; } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + bool IsCustomHttpStatusCode599 { get; } } /// @@ -1554,6 +1566,50 @@ public bool TryOk(out Org.OpenAPITools.Model.User result) /// public bool IsNotFound => 404 == (int)StatusCode; + /// + /// Returns true if the response is 598 CustomHttpStatusCode598 + /// + /// + public bool IsCustomHttpStatusCode598 => 598 == (int)StatusCode; + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 + /// + /// + public bool IsCustomHttpStatusCode599 => 599 == (int)StatusCode; + + /// + /// Deserializes the response if the response is 599 CustomHttpStatusCode599 + /// + /// + public Org.OpenAPITools.Model.User CustomHttpStatusCode599() + { + // This logic may be modified with the AsModel.mustache template + return IsCustomHttpStatusCode599 + ? System.Text.Json.JsonSerializer.Deserialize(RawContent, _jsonSerializerOptions) + : default; + } + + /// + /// Returns true if the response is 599 CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + public bool TryCustomHttpStatusCode599(out Org.OpenAPITools.Model.User result) + { + result = null; + + try + { + result = CustomHttpStatusCode599(); + } catch (Exception e) + { + OnDeserializationErrorDefaultImplementation(e, (HttpStatusCode)599); + } + + return result != null; + } + private void OnDeserializationErrorDefaultImplementation(Exception exception, HttpStatusCode httpStatusCode) { bool suppressDefaultLog = false; diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs index 5cc9c254920a..b8bdf9964ffb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiKeyToken.cs @@ -11,14 +11,21 @@ public class ApiKeyToken : TokenBase { private string _raw; + /// + /// The header that this token will be used with. + /// + public ClientUtils.ApiKeyHeader Header { get; } + /// /// Constructs an ApiKeyToken object. /// /// + /// /// /// - public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) + public ApiKeyToken(string value, ClientUtils.ApiKeyHeader header, string prefix = "Bearer ", TimeSpan? timeout = null) : base(timeout) { + Header = header; _raw = $"{ prefix }{ value }"; } @@ -26,22 +33,20 @@ public ApiKeyToken(string value, string prefix = "Bearer ", TimeSpan? timeout = /// Places the token in the header. /// /// - /// - public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request, string headerName) + public virtual void UseInHeader(System.Net.Http.HttpRequestMessage request) { - request.Headers.Add(headerName, _raw); + request.Headers.Add(ClientUtils.ApiKeyHeaderToString(Header), _raw); } - + /// /// Places the token in the query. /// /// /// /// - /// - public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString, string parameterName) + public virtual void UseInQuery(System.Net.Http.HttpRequestMessage request, UriBuilder uriBuilder, System.Collections.Specialized.NameValueCollection parseQueryString) { - parseQueryString[parameterName] = Uri.EscapeDataString(_raw).ToString(); + parseQueryString[ClientUtils.ApiKeyHeaderToString(Header)] = Uri.EscapeDataString(_raw).ToString(); } } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs index e922816db530..073c239d75df 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ApiResponse`1.cs @@ -147,6 +147,26 @@ public ApiResponse(System.Net.Http.HttpRequestMessage httpRequestMessage, System partial void OnCreated(System.Net.Http.HttpRequestMessage httpRequestMessage, System.Net.Http.HttpResponseMessage httpResponseMessage); } + /// + /// An interface for responses of type + /// + /// + public interface ICustomHttpStatusCode599 : IApiResponse + { + /// + /// Deserializes the response if the response is CustomHttpStatusCode599 + /// + /// + TType CustomHttpStatusCode599(); + + /// + /// Returns true if the response is CustomHttpStatusCode599 and the deserialized response is not null + /// + /// + /// + bool TryCustomHttpStatusCode599(out TType result); + } + /// /// An interface for responses of type /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs index fdb21c230bf9..32d8880e04e3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -38,7 +38,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// @@ -50,6 +52,40 @@ static ClientUtils() /// public delegate void EventHandler(object sender, T e) where T : EventArgs; + /// + /// An enum of headers + /// + public enum ApiKeyHeader + { + /// + /// The api_key header + /// + Api_key, + /// + /// The api_key_query header + /// + Api_key_query + } + + /// + /// Converte an ApiKeyHeader to a string + /// + /// + /// + /// + public static string ApiKeyHeaderToString(ApiKeyHeader value) + { + switch(value) + { + case ApiKeyHeader.Api_key: + return "api_key"; + case ApiKeyHeader.Api_key_query: + return "api_key_query"; + default: + throw new System.ComponentModel.InvalidEnumArgumentException(nameof(value), (int)value, typeof(ApiKeyHeader)); + } + } + /// /// Returns true when deserialization succeeds. /// @@ -139,6 +175,8 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return EnumArrays.JustSymbolEnumToJsonValue(enumArraysJustSymbolEnum); if (obj is EnumClass enumClass) return EnumClassValueConverter.ToJsonValue(enumClass); + if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) + return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is EnumTest.EnumIntegerEnum enumTestEnumIntegerEnum) return EnumTest.EnumIntegerEnumToJsonValue(enumTestEnumIntegerEnum).ToString(); if (obj is EnumTest.EnumIntegerOnlyEnum enumTestEnumIntegerOnlyEnum) @@ -147,8 +185,6 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return EnumTest.EnumNumberEnumToJsonValue(enumTestEnumNumberEnum).ToString(); if (obj is EnumTest.EnumStringEnum enumTestEnumStringEnum) return EnumTest.EnumStringEnumToJsonValue(enumTestEnumStringEnum); - if (obj is EnumTest.EnumStringRequiredEnum enumTestEnumStringRequiredEnum) - return EnumTest.EnumStringRequiredEnumToJsonValue(enumTestEnumStringRequiredEnum); if (obj is MapTest.InnerEnum mapTestInnerEnum) return MapTest.InnerEnumToJsonValue(mapTestInnerEnum); if (obj is Order.StatusEnum orderStatusEnum) @@ -165,6 +201,30 @@ public static string ParameterToString(object obj, string format = ISO8601_DATET return OuterEnumTestValueConverter.ToJsonValue(outerEnumTest); if (obj is Pet.StatusEnum petStatusEnum) return Pet.StatusEnumToJsonValue(petStatusEnum); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerEnum requiredClassRequiredNotnullableEnumIntegerEnum) + return RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum requiredClassRequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNotnullableEnumStringEnum requiredClassRequiredNotnullableEnumStringEnum) + return RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClassRequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.RequiredNullableEnumIntegerEnum requiredClassRequiredNullableEnumIntegerEnum) + return RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClassRequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumIntegerOnlyEnum requiredClassRequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassRequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.RequiredNullableEnumStringEnum requiredClassRequiredNullableEnumStringEnum) + return RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClassRequiredNullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerEnum requiredClassNotrequiredNotnullableEnumIntegerEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNotnullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNotnullableEnumStringEnum requiredClassNotrequiredNotnullableEnumStringEnum) + return RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClassNotrequiredNotnullableEnumStringEnum); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerEnum requiredClassNotrequiredNullableEnumIntegerEnum) + return RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum requiredClassNotrequiredNullableEnumIntegerOnlyEnum) + return RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClassNotrequiredNullableEnumIntegerOnlyEnum).ToString(); + if (obj is RequiredClass.NotrequiredNullableEnumStringEnum requiredClassNotrequiredNullableEnumStringEnum) + return RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClassNotrequiredNullableEnumStringEnum); if (obj is Zebra.TypeEnum zebraTypeEnum) return Zebra.TypeEnumToJsonValue(zebraTypeEnum); if (obj is ZeroBasedEnum zeroBasedEnum) diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs index e8291cb2e1eb..973f9e9d4e80 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date' and 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeJsonConverter : JsonConverter @@ -42,6 +42,7 @@ public class DateTimeJsonConverter : JsonConverter "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs index e26c40071cdc..b491c61f07fa 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/DateTimeNullableJsonConverter.cs @@ -15,7 +15,7 @@ namespace Org.OpenAPITools.Client { /// - /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// Formatter for 'date' and 'date-time' openapi formats ss defined by full-date - RFC3339 /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types /// public class DateTimeNullableJsonConverter : JsonConverter @@ -42,6 +42,7 @@ public class DateTimeNullableJsonConverter : JsonConverter "yyyyMMddTHHmmss.fK", "yyyyMMddTHHmmssK", "yyyyMMdd" + }; /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs index 964d9c24a144..903a95cb48ae 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/HostConfiguration.cs @@ -114,6 +114,7 @@ public HostConfiguration(IServiceCollection services) _jsonOptions.Converters.Add(new QuadrilateralJsonConverter()); _jsonOptions.Converters.Add(new QuadrilateralInterfaceJsonConverter()); _jsonOptions.Converters.Add(new ReadOnlyFirstJsonConverter()); + _jsonOptions.Converters.Add(new RequiredClassJsonConverter()); _jsonOptions.Converters.Add(new ReturnJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashJsonConverter()); _jsonOptions.Converters.Add(new RolesReportsHashRoleJsonConverter()); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/Option.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/Option.cs index 70f41078bb68..8cf79a713b74 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/Option.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/Option.cs @@ -35,5 +35,17 @@ public Option(TType value) IsSet = true; Value = value; } + + /// + /// Implicitly converts this option to the contained type + /// + /// + public static implicit operator TType(Option option) => option.Value; + + /// + /// Implicitly converts the provided value to an Option + /// + /// + public static implicit operator Option(TType value) => new Option(value); } } \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs index 9e28ab28eee0..534f27a8cc52 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/RateLimitProvider`1.cs @@ -9,12 +9,11 @@ */ using System; -using System.Collections.Concurrent; +using System.Collections.Generic; using System.Linq; -using System.Threading; -using System.Threading.Tasks; +using System.Threading.Channels; -namespace Org.OpenAPITools.Client +namespace Org.OpenAPITools.Client { /// /// Provides a token to the api clients. Tokens will be rate limited based on the provided TimeSpan. @@ -22,8 +21,7 @@ namespace Org.OpenAPITools.Client /// public class RateLimitProvider : TokenProvider where TTokenBase : TokenBase { - internal ConcurrentDictionary AvailableTokens = new ConcurrentDictionary(); - private SemaphoreSlim _semaphore; + internal Dictionary> AvailableTokens { get; } = new Dictionary>(); /// /// Instantiates a ThrottledTokenProvider. Your tokens will be rate limited based on the token's timeout. @@ -31,48 +29,44 @@ public class RateLimitProvider : TokenProvider where TTo /// public RateLimitProvider(TokenContainer container) : base(container.Tokens) { - _semaphore = new SemaphoreSlim(1, 1); - foreach(TTokenBase token in _tokens) token.StartTimer(token.Timeout ?? TimeSpan.FromMilliseconds(40)); - for (int i = 0; i < _tokens.Length; i++) + if (container is TokenContainer apiKeyTokenContainer) { - _tokens[i].TokenBecameAvailable += ((sender) => + string[] headers = apiKeyTokenContainer.Tokens.Select(t => ClientUtils.ApiKeyHeaderToString(t.Header)).Distinct().ToArray(); + + foreach (string header in headers) { - TTokenBase token = (TTokenBase)sender; + BoundedChannelOptions options = new BoundedChannelOptions(apiKeyTokenContainer.Tokens.Count(t => ClientUtils.ApiKeyHeaderToString(t.Header).Equals(header))) + { + FullMode = BoundedChannelFullMode.DropWrite + }; - AvailableTokens.TryAdd(token, token); - }); + AvailableTokens.Add(header, Channel.CreateBounded(options)); + } } - } - - internal override async System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default) - { - await _semaphore.WaitAsync().ConfigureAwait(false); - - try + else { - TTokenBase result = null; - - while (result == null) + BoundedChannelOptions options = new BoundedChannelOptions(_tokens.Length) { - TTokenBase tokenToRemove = AvailableTokens.FirstOrDefault().Value; + FullMode = BoundedChannelFullMode.DropWrite + }; - if (tokenToRemove != null && AvailableTokens.TryRemove(tokenToRemove, out result)) - return result; + AvailableTokens.Add(string.Empty, Channel.CreateBounded(options)); + } - await Task.Delay(40).ConfigureAwait(false); + foreach(Channel tokens in AvailableTokens.Values) + for (int i = 0; i < _tokens.Length; i++) + _tokens[i].TokenBecameAvailable += ((sender) => tokens.Writer.TryWrite((TTokenBase) sender)); + } - tokenToRemove = AvailableTokens.FirstOrDefault().Value; - } + internal override async System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default) + { + if (!AvailableTokens.TryGetValue(header, out Channel tokens)) + throw new KeyNotFoundException($"Could not locate a token for header '{header}'."); - return result; - } - finally - { - _semaphore.Release(); - } + return await tokens.Reader.ReadAsync(cancellation).ConfigureAwait(false); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs index c49f723f8c29..36d7dad03e23 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Client/TokenProvider`1.cs @@ -25,7 +25,7 @@ public abstract class TokenProvider where TTokenBase : TokenBase /// protected TTokenBase[] _tokens; - internal abstract System.Threading.Tasks.ValueTask GetAsync(System.Threading.CancellationToken cancellation = default); + internal abstract System.Threading.Tasks.ValueTask GetAsync(string header = "", System.Threading.CancellationToken cancellation = default); /// /// Instantiates a TokenProvider. diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs index 42747dee35ea..306058f38c3a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Activity.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Activity : IValidatableObject /// /// activityOutputs [JsonConstructor] - public Activity(Dictionary> activityOutputs) + public Activity(Option>> activityOutputs = default) { - ActivityOutputs = activityOutputs; + ActivityOutputsOption = activityOutputs; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ActivityOutputs + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ActivityOutputsOption { get; private set; } + /// /// Gets or Sets ActivityOutputs /// [JsonPropertyName("activity_outputs")] - public Dictionary> ActivityOutputs { get; set; } + public Dictionary> ActivityOutputs { get { return this. ActivityOutputsOption; } set { this.ActivityOutputsOption = new Option>>(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary> activityOutputs = default; + Option>> activityOutputs = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "activity_outputs": if (utf8JsonReader.TokenType != JsonTokenType.Null) - activityOutputs = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + activityOutputs = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override Activity Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (activityOutputs == null) - throw new ArgumentNullException(nameof(activityOutputs), "Property is required for class Activity."); + if (activityOutputs.IsSet && activityOutputs.Value == null) + throw new ArgumentNullException(nameof(activityOutputs), "Property is not nullable for class Activity."); return new Activity(activityOutputs); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, Activity activity, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Activity activity, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("activity_outputs"); - JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + if (activity.ActivityOutputsOption.IsSet && activity.ActivityOutputs == null) + throw new ArgumentNullException(nameof(activity.ActivityOutputs), "Property is required for class Activity."); + + if (activity.ActivityOutputsOption.IsSet) + { + writer.WritePropertyName("activity_outputs"); + JsonSerializer.Serialize(writer, activity.ActivityOutputs, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs index 233d362f51ed..70b907a2f5c3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ActivityOutputElementRepresentation.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class ActivityOutputElementRepresentation : IValidatableObject /// prop1 /// prop2 [JsonConstructor] - public ActivityOutputElementRepresentation(string prop1, Object prop2) + public ActivityOutputElementRepresentation(Option prop1 = default, Option prop2 = default) { - Prop1 = prop1; - Prop2 = prop2; + Prop1Option = prop1; + Prop2Option = prop2; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Prop1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop1Option { get; private set; } + /// /// Gets or Sets Prop1 /// [JsonPropertyName("prop1")] - public string Prop1 { get; set; } + public string Prop1 { get { return this. Prop1Option; } set { this.Prop1Option = new Option(value); } } + + /// + /// Used to track the state of Prop2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Prop2Option { get; private set; } /// /// Gets or Sets Prop2 /// [JsonPropertyName("prop2")] - public Object Prop2 { get; set; } + public Object Prop2 { get { return this. Prop2Option; } set { this.Prop2Option = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string prop1 = default; - Object prop2 = default; + Option prop1 = default; + Option prop2 = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 switch (localVarJsonPropertyName) { case "prop1": - prop1 = utf8JsonReader.GetString(); + prop1 = new Option(utf8JsonReader.GetString()); break; case "prop2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - prop2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + prop2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -140,11 +155,11 @@ public override ActivityOutputElementRepresentation Read(ref Utf8JsonReader utf8 } } - if (prop1 == null) - throw new ArgumentNullException(nameof(prop1), "Property is required for class ActivityOutputElementRepresentation."); + if (prop1.IsSet && prop1.Value == null) + throw new ArgumentNullException(nameof(prop1), "Property is not nullable for class ActivityOutputElementRepresentation."); - if (prop2 == null) - throw new ArgumentNullException(nameof(prop2), "Property is required for class ActivityOutputElementRepresentation."); + if (prop2.IsSet && prop2.Value == null) + throw new ArgumentNullException(nameof(prop2), "Property is not nullable for class ActivityOutputElementRepresentation."); return new ActivityOutputElementRepresentation(prop1, prop2); } @@ -173,9 +188,20 @@ public override void Write(Utf8JsonWriter writer, ActivityOutputElementRepresent /// public void WriteProperties(ref Utf8JsonWriter writer, ActivityOutputElementRepresentation activityOutputElementRepresentation, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); - writer.WritePropertyName("prop2"); - JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + if (activityOutputElementRepresentation.Prop1Option.IsSet && activityOutputElementRepresentation.Prop1 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop1), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop2Option.IsSet && activityOutputElementRepresentation.Prop2 == null) + throw new ArgumentNullException(nameof(activityOutputElementRepresentation.Prop2), "Property is required for class ActivityOutputElementRepresentation."); + + if (activityOutputElementRepresentation.Prop1Option.IsSet) + writer.WriteString("prop1", activityOutputElementRepresentation.Prop1); + + if (activityOutputElementRepresentation.Prop2Option.IsSet) + { + writer.WritePropertyName("prop2"); + JsonSerializer.Serialize(writer, activityOutputElementRepresentation.Prop2, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs index ed15d711b7a7..e723f090a2d5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AdditionalPropertiesClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,6 +32,7 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// /// Initializes a new instance of the class. /// + /// anytype1 /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// mapOfMapProperty /// mapProperty @@ -38,71 +40,126 @@ public partial class AdditionalPropertiesClass : IValidatableObject /// mapWithUndeclaredPropertiesAnytype2 /// mapWithUndeclaredPropertiesAnytype3 /// mapWithUndeclaredPropertiesString - /// anytype1 [JsonConstructor] - public AdditionalPropertiesClass(Object emptyMap, Dictionary> mapOfMapProperty, Dictionary mapProperty, Object mapWithUndeclaredPropertiesAnytype1, Object mapWithUndeclaredPropertiesAnytype2, Dictionary mapWithUndeclaredPropertiesAnytype3, Dictionary mapWithUndeclaredPropertiesString, Object anytype1 = default) + public AdditionalPropertiesClass(Option anytype1 = default, Option emptyMap = default, Option>> mapOfMapProperty = default, Option> mapProperty = default, Option mapWithUndeclaredPropertiesAnytype1 = default, Option mapWithUndeclaredPropertiesAnytype2 = default, Option> mapWithUndeclaredPropertiesAnytype3 = default, Option> mapWithUndeclaredPropertiesString = default) { - EmptyMap = emptyMap; - MapOfMapProperty = mapOfMapProperty; - MapProperty = mapProperty; - MapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; - MapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; - MapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; - MapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; - Anytype1 = anytype1; + Anytype1Option = anytype1; + EmptyMapOption = emptyMap; + MapOfMapPropertyOption = mapOfMapProperty; + MapPropertyOption = mapProperty; + MapWithUndeclaredPropertiesAnytype1Option = mapWithUndeclaredPropertiesAnytype1; + MapWithUndeclaredPropertiesAnytype2Option = mapWithUndeclaredPropertiesAnytype2; + MapWithUndeclaredPropertiesAnytype3Option = mapWithUndeclaredPropertiesAnytype3; + MapWithUndeclaredPropertiesStringOption = mapWithUndeclaredPropertiesString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Anytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Anytype1Option { get; private set; } + + /// + /// Gets or Sets Anytype1 + /// + [JsonPropertyName("anytype_1")] + public Object Anytype1 { get { return this. Anytype1Option; } set { this.Anytype1Option = new Option(value); } } + + /// + /// Used to track the state of EmptyMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmptyMapOption { get; private set; } + /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. /// /// an object with no declared properties and no undeclared properties, hence it's an empty map. [JsonPropertyName("empty_map")] - public Object EmptyMap { get; set; } + public Object EmptyMap { get { return this. EmptyMapOption; } set { this.EmptyMapOption = new Option(value); } } + + /// + /// Used to track the state of MapOfMapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> MapOfMapPropertyOption { get; private set; } /// /// Gets or Sets MapOfMapProperty /// [JsonPropertyName("map_of_map_property")] - public Dictionary> MapOfMapProperty { get; set; } + public Dictionary> MapOfMapProperty { get { return this. MapOfMapPropertyOption; } set { this.MapOfMapPropertyOption = new Option>>(value); } } + + /// + /// Used to track the state of MapProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapPropertyOption { get; private set; } /// /// Gets or Sets MapProperty /// [JsonPropertyName("map_property")] - public Dictionary MapProperty { get; set; } + public Dictionary MapProperty { get { return this. MapPropertyOption; } set { this.MapPropertyOption = new Option>(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype1 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype1Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype1 /// [JsonPropertyName("map_with_undeclared_properties_anytype_1")] - public Object MapWithUndeclaredPropertiesAnytype1 { get; set; } + public Object MapWithUndeclaredPropertiesAnytype1 { get { return this. MapWithUndeclaredPropertiesAnytype1Option; } set { this.MapWithUndeclaredPropertiesAnytype1Option = new Option(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype2 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MapWithUndeclaredPropertiesAnytype2Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype2 /// [JsonPropertyName("map_with_undeclared_properties_anytype_2")] - public Object MapWithUndeclaredPropertiesAnytype2 { get; set; } + public Object MapWithUndeclaredPropertiesAnytype2 { get { return this. MapWithUndeclaredPropertiesAnytype2Option; } set { this.MapWithUndeclaredPropertiesAnytype2Option = new Option(value); } } + + /// + /// Used to track the state of MapWithUndeclaredPropertiesAnytype3 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapWithUndeclaredPropertiesAnytype3Option { get; private set; } /// /// Gets or Sets MapWithUndeclaredPropertiesAnytype3 /// [JsonPropertyName("map_with_undeclared_properties_anytype_3")] - public Dictionary MapWithUndeclaredPropertiesAnytype3 { get; set; } + public Dictionary MapWithUndeclaredPropertiesAnytype3 { get { return this. MapWithUndeclaredPropertiesAnytype3Option; } set { this.MapWithUndeclaredPropertiesAnytype3Option = new Option>(value); } } /// - /// Gets or Sets MapWithUndeclaredPropertiesString + /// Used to track the state of MapWithUndeclaredPropertiesString /// - [JsonPropertyName("map_with_undeclared_properties_string")] - public Dictionary MapWithUndeclaredPropertiesString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapWithUndeclaredPropertiesStringOption { get; private set; } /// - /// Gets or Sets Anytype1 + /// Gets or Sets MapWithUndeclaredPropertiesString /// - [JsonPropertyName("anytype_1")] - public Object Anytype1 { get; set; } + [JsonPropertyName("map_with_undeclared_properties_string")] + public Dictionary MapWithUndeclaredPropertiesString { get { return this. MapWithUndeclaredPropertiesStringOption; } set { this.MapWithUndeclaredPropertiesStringOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -118,6 +175,7 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class AdditionalPropertiesClass {\n"); + sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" EmptyMap: ").Append(EmptyMap).Append("\n"); sb.Append(" MapOfMapProperty: ").Append(MapOfMapProperty).Append("\n"); sb.Append(" MapProperty: ").Append(MapProperty).Append("\n"); @@ -125,7 +183,6 @@ public override string ToString() sb.Append(" MapWithUndeclaredPropertiesAnytype2: ").Append(MapWithUndeclaredPropertiesAnytype2).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesAnytype3: ").Append(MapWithUndeclaredPropertiesAnytype3).Append("\n"); sb.Append(" MapWithUndeclaredPropertiesString: ").Append(MapWithUndeclaredPropertiesString).Append("\n"); - sb.Append(" Anytype1: ").Append(Anytype1).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -164,14 +221,14 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Object emptyMap = default; - Dictionary> mapOfMapProperty = default; - Dictionary mapProperty = default; - Object mapWithUndeclaredPropertiesAnytype1 = default; - Object mapWithUndeclaredPropertiesAnytype2 = default; - Dictionary mapWithUndeclaredPropertiesAnytype3 = default; - Dictionary mapWithUndeclaredPropertiesString = default; - Object anytype1 = default; + Option anytype1 = default; + Option emptyMap = default; + Option>> mapOfMapProperty = default; + Option> mapProperty = default; + Option mapWithUndeclaredPropertiesAnytype1 = default; + Option mapWithUndeclaredPropertiesAnytype2 = default; + Option> mapWithUndeclaredPropertiesAnytype3 = default; + Option> mapWithUndeclaredPropertiesString = default; while (utf8JsonReader.Read()) { @@ -188,37 +245,37 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader switch (localVarJsonPropertyName) { + case "anytype_1": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "empty_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - emptyMap = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + emptyMap = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_of_map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfMapProperty = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapOfMapProperty = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_property": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapProperty = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapProperty = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_1": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype1 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_2": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype2 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype2 = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_anytype_3": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesAnytype3 = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesAnytype3 = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_with_undeclared_properties_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapWithUndeclaredPropertiesString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anytype_1": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anytype1 = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + mapWithUndeclaredPropertiesString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -226,28 +283,28 @@ public override AdditionalPropertiesClass Read(ref Utf8JsonReader utf8JsonReader } } - if (emptyMap == null) - throw new ArgumentNullException(nameof(emptyMap), "Property is required for class AdditionalPropertiesClass."); + if (emptyMap.IsSet && emptyMap.Value == null) + throw new ArgumentNullException(nameof(emptyMap), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapOfMapProperty == null) - throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapOfMapProperty.IsSet && mapOfMapProperty.Value == null) + throw new ArgumentNullException(nameof(mapOfMapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapProperty == null) - throw new ArgumentNullException(nameof(mapProperty), "Property is required for class AdditionalPropertiesClass."); + if (mapProperty.IsSet && mapProperty.Value == null) + throw new ArgumentNullException(nameof(mapProperty), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype1 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype1.IsSet && mapWithUndeclaredPropertiesAnytype1.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype1), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype2 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype2.IsSet && mapWithUndeclaredPropertiesAnytype2.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype2), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesAnytype3 == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesAnytype3.IsSet && mapWithUndeclaredPropertiesAnytype3.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesAnytype3), "Property is not nullable for class AdditionalPropertiesClass."); - if (mapWithUndeclaredPropertiesString == null) - throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + if (mapWithUndeclaredPropertiesString.IsSet && mapWithUndeclaredPropertiesString.Value == null) + throw new ArgumentNullException(nameof(mapWithUndeclaredPropertiesString), "Property is not nullable for class AdditionalPropertiesClass."); - return new AdditionalPropertiesClass(emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString, anytype1); + return new AdditionalPropertiesClass(anytype1, emptyMap, mapOfMapProperty, mapProperty, mapWithUndeclaredPropertiesAnytype1, mapWithUndeclaredPropertiesAnytype2, mapWithUndeclaredPropertiesAnytype3, mapWithUndeclaredPropertiesString); } /// @@ -274,22 +331,70 @@ public override void Write(Utf8JsonWriter writer, AdditionalPropertiesClass addi /// public void WriteProperties(ref Utf8JsonWriter writer, AdditionalPropertiesClass additionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("empty_map"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); - writer.WritePropertyName("map_of_map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_property"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); - writer.WritePropertyName("map_with_undeclared_properties_string"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); - writer.WritePropertyName("anytype_1"); - JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + if (additionalPropertiesClass.EmptyMapOption.IsSet && additionalPropertiesClass.EmptyMap == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.EmptyMap), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet && additionalPropertiesClass.MapOfMapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapOfMapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapPropertyOption.IsSet && additionalPropertiesClass.MapProperty == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapProperty), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3 == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet && additionalPropertiesClass.MapWithUndeclaredPropertiesString == null) + throw new ArgumentNullException(nameof(additionalPropertiesClass.MapWithUndeclaredPropertiesString), "Property is required for class AdditionalPropertiesClass."); + + if (additionalPropertiesClass.Anytype1Option.IsSet) + if (additionalPropertiesClass.Anytype1Option.Value != null) + { + writer.WritePropertyName("anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.Anytype1, jsonSerializerOptions); + } + else + writer.WriteNull("anytype_1"); + if (additionalPropertiesClass.EmptyMapOption.IsSet) + { + writer.WritePropertyName("empty_map"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.EmptyMap, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapOfMapPropertyOption.IsSet) + { + writer.WritePropertyName("map_of_map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapOfMapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapPropertyOption.IsSet) + { + writer.WritePropertyName("map_property"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapProperty, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_1"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype1, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_2"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype2, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3Option.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_anytype_3"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesAnytype3, jsonSerializerOptions); + } + if (additionalPropertiesClass.MapWithUndeclaredPropertiesStringOption.IsSet) + { + writer.WritePropertyName("map_with_undeclared_properties_string"); + JsonSerializer.Serialize(writer, additionalPropertiesClass.MapWithUndeclaredPropertiesString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs index 460543ebf0df..017eb4dc94bf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Animal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class Animal : IValidatableObject /// className /// color (default to "red") [JsonConstructor] - public Animal(string className, string color = @"red") + public Animal(string className, Option color = default) { ClassName = className; - Color = color; + ColorOption = color; OnCreated(); } @@ -49,11 +50,18 @@ public Animal(string className, string color = @"red") [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -119,8 +127,8 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - string color = default; + Option className = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -138,10 +146,10 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -149,13 +157,16 @@ public override Animal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Animal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Animal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Animal."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Animal."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Animal."); - return new Animal(className, color); + return new Animal(className.Value, color); } /// @@ -182,8 +193,16 @@ public override void Write(Utf8JsonWriter writer, Animal animal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Animal animal, JsonSerializerOptions jsonSerializerOptions) { + if (animal.ClassName == null) + throw new ArgumentNullException(nameof(animal.ClassName), "Property is required for class Animal."); + + if (animal.ColorOption.IsSet && animal.Color == null) + throw new ArgumentNullException(nameof(animal.Color), "Property is required for class Animal."); + writer.WriteString("className", animal.ClassName); - writer.WriteString("color", animal.Color); + + if (animal.ColorOption.IsSet) + writer.WriteString("color", animal.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs index 5a7be95495cc..51008671a471 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ApiResponse.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class ApiResponse : IValidatableObject /// message /// type [JsonConstructor] - public ApiResponse(int code, string message, string type) + public ApiResponse(Option code = default, Option message = default, Option type = default) { - Code = code; - Message = message; - Type = type; + CodeOption = code; + MessageOption = message; + TypeOption = type; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Code + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CodeOption { get; private set; } + /// /// Gets or Sets Code /// [JsonPropertyName("code")] - public int Code { get; set; } + public int? Code { get { return this. CodeOption; } set { this.CodeOption = new Option(value); } } + + /// + /// Used to track the state of Message + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MessageOption { get; private set; } /// /// Gets or Sets Message /// [JsonPropertyName("message")] - public string Message { get; set; } + public string Message { get { return this. MessageOption; } set { this.MessageOption = new Option(value); } } + + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public string Type { get; set; } + public string Type { get { return this. TypeOption; } set { this.TypeOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? code = default; - string message = default; - string type = default; + Option code = default; + Option message = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -139,13 +161,13 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC { case "code": if (utf8JsonReader.TokenType != JsonTokenType.Null) - code = utf8JsonReader.GetInt32(); + code = new Option(utf8JsonReader.GetInt32()); break; case "message": - message = utf8JsonReader.GetString(); + message = new Option(utf8JsonReader.GetString()); break; case "type": - type = utf8JsonReader.GetString(); + type = new Option(utf8JsonReader.GetString()); break; default: break; @@ -153,16 +175,16 @@ public override ApiResponse Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (code == null) - throw new ArgumentNullException(nameof(code), "Property is required for class ApiResponse."); + if (code.IsSet && code.Value == null) + throw new ArgumentNullException(nameof(code), "Property is not nullable for class ApiResponse."); - if (message == null) - throw new ArgumentNullException(nameof(message), "Property is required for class ApiResponse."); + if (message.IsSet && message.Value == null) + throw new ArgumentNullException(nameof(message), "Property is not nullable for class ApiResponse."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class ApiResponse."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class ApiResponse."); - return new ApiResponse(code.Value, message, type); + return new ApiResponse(code, message, type); } /// @@ -189,9 +211,20 @@ public override void Write(Utf8JsonWriter writer, ApiResponse apiResponse, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ApiResponse apiResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("code", apiResponse.Code); - writer.WriteString("message", apiResponse.Message); - writer.WriteString("type", apiResponse.Type); + if (apiResponse.MessageOption.IsSet && apiResponse.Message == null) + throw new ArgumentNullException(nameof(apiResponse.Message), "Property is required for class ApiResponse."); + + if (apiResponse.TypeOption.IsSet && apiResponse.Type == null) + throw new ArgumentNullException(nameof(apiResponse.Type), "Property is required for class ApiResponse."); + + if (apiResponse.CodeOption.IsSet) + writer.WriteNumber("code", apiResponse.CodeOption.Value.Value); + + if (apiResponse.MessageOption.IsSet) + writer.WriteString("message", apiResponse.Message); + + if (apiResponse.TypeOption.IsSet) + writer.WriteString("type", apiResponse.Type); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs index 31246df0422a..e193be63a225 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Apple.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class Apple : IValidatableObject /// cultivar /// origin [JsonConstructor] - public Apple(string colorCode, string cultivar, string origin) + public Apple(Option colorCode = default, Option cultivar = default, Option origin = default) { - ColorCode = colorCode; - Cultivar = cultivar; - Origin = origin; + ColorCodeOption = colorCode; + CultivarOption = cultivar; + OriginOption = origin; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ColorCode + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorCodeOption { get; private set; } + /// /// Gets or Sets ColorCode /// [JsonPropertyName("color_code")] - public string ColorCode { get; set; } + public string ColorCode { get { return this. ColorCodeOption; } set { this.ColorCodeOption = new Option(value); } } + + /// + /// Used to track the state of Cultivar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CultivarOption { get; private set; } /// /// Gets or Sets Cultivar /// [JsonPropertyName("cultivar")] - public string Cultivar { get; set; } + public string Cultivar { get { return this. CultivarOption; } set { this.CultivarOption = new Option(value); } } + + /// + /// Used to track the state of Origin + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OriginOption { get; private set; } /// /// Gets or Sets Origin /// [JsonPropertyName("origin")] - public string Origin { get; set; } + public string Origin { get { return this. OriginOption; } set { this.OriginOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -92,28 +114,31 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { - if (this.ColorCode != null) { + if (this.ColorCodeOption.Value != null) { // ColorCode (string) pattern Regex regexColorCode = new Regex(@"^#(([0-9a-fA-F]{2}){3}|([0-9a-fA-F]){3})$", RegexOptions.CultureInvariant); - if (!regexColorCode.Match(this.ColorCode).Success) + + if (this.ColorCodeOption.Value != null &&!regexColorCode.Match(this.ColorCodeOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for ColorCode, must match a pattern of " + regexColorCode, new [] { "ColorCode" }); } } - if (this.Cultivar != null) { + if (this.CultivarOption.Value != null) { // Cultivar (string) pattern Regex regexCultivar = new Regex(@"^[a-zA-Z\s]*$", RegexOptions.CultureInvariant); - if (!regexCultivar.Match(this.Cultivar).Success) + + if (this.CultivarOption.Value != null &&!regexCultivar.Match(this.CultivarOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Cultivar, must match a pattern of " + regexCultivar, new [] { "Cultivar" }); } } - if (this.Origin != null) { + if (this.OriginOption.Value != null) { // Origin (string) pattern Regex regexOrigin = new Regex(@"^[A-Z\s]*$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexOrigin.Match(this.Origin).Success) + + if (this.OriginOption.Value != null &&!regexOrigin.Match(this.OriginOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Origin, must match a pattern of " + regexOrigin, new [] { "Origin" }); } @@ -145,9 +170,9 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string colorCode = default; - string cultivar = default; - string origin = default; + Option colorCode = default; + Option cultivar = default; + Option origin = default; while (utf8JsonReader.Read()) { @@ -165,13 +190,13 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color_code": - colorCode = utf8JsonReader.GetString(); + colorCode = new Option(utf8JsonReader.GetString()); break; case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()); break; case "origin": - origin = utf8JsonReader.GetString(); + origin = new Option(utf8JsonReader.GetString()); break; default: break; @@ -179,14 +204,14 @@ public override Apple Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (colorCode == null) - throw new ArgumentNullException(nameof(colorCode), "Property is required for class Apple."); + if (colorCode.IsSet && colorCode.Value == null) + throw new ArgumentNullException(nameof(colorCode), "Property is not nullable for class Apple."); - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class Apple."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class Apple."); - if (origin == null) - throw new ArgumentNullException(nameof(origin), "Property is required for class Apple."); + if (origin.IsSet && origin.Value == null) + throw new ArgumentNullException(nameof(origin), "Property is not nullable for class Apple."); return new Apple(colorCode, cultivar, origin); } @@ -215,9 +240,23 @@ public override void Write(Utf8JsonWriter writer, Apple apple, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Apple apple, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color_code", apple.ColorCode); - writer.WriteString("cultivar", apple.Cultivar); - writer.WriteString("origin", apple.Origin); + if (apple.ColorCodeOption.IsSet && apple.ColorCode == null) + throw new ArgumentNullException(nameof(apple.ColorCode), "Property is required for class Apple."); + + if (apple.CultivarOption.IsSet && apple.Cultivar == null) + throw new ArgumentNullException(nameof(apple.Cultivar), "Property is required for class Apple."); + + if (apple.OriginOption.IsSet && apple.Origin == null) + throw new ArgumentNullException(nameof(apple.Origin), "Property is required for class Apple."); + + if (apple.ColorCodeOption.IsSet) + writer.WriteString("color_code", apple.ColorCode); + + if (apple.CultivarOption.IsSet) + writer.WriteString("cultivar", apple.Cultivar); + + if (apple.OriginOption.IsSet) + writer.WriteString("origin", apple.Origin); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs index e0882d925c5d..b4551174f52f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/AppleReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class AppleReq : IValidatableObject /// cultivar /// mealy [JsonConstructor] - public AppleReq(string cultivar, bool mealy) + public AppleReq(string cultivar, Option mealy = default) { Cultivar = cultivar; - Mealy = mealy; + MealyOption = mealy; OnCreated(); } @@ -49,11 +50,18 @@ public AppleReq(string cultivar, bool mealy) [JsonPropertyName("cultivar")] public string Cultivar { get; set; } + /// + /// Used to track the state of Mealy + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MealyOption { get; private set; } + /// /// Gets or Sets Mealy /// [JsonPropertyName("mealy")] - public bool Mealy { get; set; } + public bool? Mealy { get { return this. MealyOption; } set { this.MealyOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -102,8 +110,8 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string cultivar = default; - bool? mealy = default; + Option cultivar = default; + Option mealy = default; while (utf8JsonReader.Read()) { @@ -121,11 +129,11 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "cultivar": - cultivar = utf8JsonReader.GetString(); + cultivar = new Option(utf8JsonReader.GetString()); break; case "mealy": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mealy = utf8JsonReader.GetBoolean(); + mealy = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -133,13 +141,16 @@ public override AppleReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (cultivar == null) - throw new ArgumentNullException(nameof(cultivar), "Property is required for class AppleReq."); + if (!cultivar.IsSet) + throw new ArgumentException("Property is required for class AppleReq.", nameof(cultivar)); - if (mealy == null) - throw new ArgumentNullException(nameof(mealy), "Property is required for class AppleReq."); + if (cultivar.IsSet && cultivar.Value == null) + throw new ArgumentNullException(nameof(cultivar), "Property is not nullable for class AppleReq."); - return new AppleReq(cultivar, mealy.Value); + if (mealy.IsSet && mealy.Value == null) + throw new ArgumentNullException(nameof(mealy), "Property is not nullable for class AppleReq."); + + return new AppleReq(cultivar.Value, mealy); } /// @@ -166,8 +177,13 @@ public override void Write(Utf8JsonWriter writer, AppleReq appleReq, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, AppleReq appleReq, JsonSerializerOptions jsonSerializerOptions) { + if (appleReq.Cultivar == null) + throw new ArgumentNullException(nameof(appleReq.Cultivar), "Property is required for class AppleReq."); + writer.WriteString("cultivar", appleReq.Cultivar); - writer.WriteBoolean("mealy", appleReq.Mealy); + + if (appleReq.MealyOption.IsSet) + writer.WriteBoolean("mealy", appleReq.MealyOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs index 6fc0afdbc300..5eed5f320141 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfArrayOfNumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ArrayOfArrayOfNumberOnly : IValidatableObject /// /// arrayArrayNumber [JsonConstructor] - public ArrayOfArrayOfNumberOnly(List> arrayArrayNumber) + public ArrayOfArrayOfNumberOnly(Option>> arrayArrayNumber = default) { - ArrayArrayNumber = arrayArrayNumber; + ArrayArrayNumberOption = arrayArrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayArrayNumber /// [JsonPropertyName("ArrayArrayNumber")] - public List> ArrayArrayNumber { get; set; } + public List> ArrayArrayNumber { get { return this. ArrayArrayNumberOption; } set { this.ArrayArrayNumberOption = new Option>>(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> arrayArrayNumber = default; + Option>> arrayArrayNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, { case "ArrayArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayNumber = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayNumber = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override ArrayOfArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, } } - if (arrayArrayNumber == null) - throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + if (arrayArrayNumber.IsSet && arrayArrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayArrayNumber), "Property is not nullable for class ArrayOfArrayOfNumberOnly."); return new ArrayOfArrayOfNumberOnly(arrayArrayNumber); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly array /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet && arrayOfArrayOfNumberOnly.ArrayArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfArrayOfNumberOnly.ArrayArrayNumber), "Property is required for class ArrayOfArrayOfNumberOnly."); + + if (arrayOfArrayOfNumberOnly.ArrayArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfArrayOfNumberOnly.ArrayArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs index 0715a3fdf65f..5336a5b2dbbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayOfNumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ArrayOfNumberOnly : IValidatableObject /// /// arrayNumber [JsonConstructor] - public ArrayOfNumberOnly(List arrayNumber) + public ArrayOfNumberOnly(Option> arrayNumber = default) { - ArrayNumber = arrayNumber; + ArrayNumberOption = arrayNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayNumberOption { get; private set; } + /// /// Gets or Sets ArrayNumber /// [JsonPropertyName("ArrayNumber")] - public List ArrayNumber { get; set; } + public List ArrayNumber { get { return this. ArrayNumberOption; } set { this.ArrayNumberOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayNumber = default; + Option> arrayNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t { case "ArrayNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNumber = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNumber = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override ArrayOfNumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (arrayNumber == null) - throw new ArgumentNullException(nameof(arrayNumber), "Property is required for class ArrayOfNumberOnly."); + if (arrayNumber.IsSet && arrayNumber.Value == null) + throw new ArgumentNullException(nameof(arrayNumber), "Property is not nullable for class ArrayOfNumberOnly."); return new ArrayOfNumberOnly(arrayNumber); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumbe /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayOfNumberOnly arrayOfNumberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("ArrayNumber"); - JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + if (arrayOfNumberOnly.ArrayNumberOption.IsSet && arrayOfNumberOnly.ArrayNumber == null) + throw new ArgumentNullException(nameof(arrayOfNumberOnly.ArrayNumber), "Property is required for class ArrayOfNumberOnly."); + + if (arrayOfNumberOnly.ArrayNumberOption.IsSet) + { + writer.WritePropertyName("ArrayNumber"); + JsonSerializer.Serialize(writer, arrayOfNumberOnly.ArrayNumber, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs index 43088ca1d97b..9ec2bd39bfed 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ArrayTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class ArrayTest : IValidatableObject /// arrayArrayOfModel /// arrayOfString [JsonConstructor] - public ArrayTest(List> arrayArrayOfInteger, List> arrayArrayOfModel, List arrayOfString) + public ArrayTest(Option>> arrayArrayOfInteger = default, Option>> arrayArrayOfModel = default, Option> arrayOfString = default) { - ArrayArrayOfInteger = arrayArrayOfInteger; - ArrayArrayOfModel = arrayArrayOfModel; - ArrayOfString = arrayOfString; + ArrayArrayOfIntegerOption = arrayArrayOfInteger; + ArrayArrayOfModelOption = arrayArrayOfModel; + ArrayOfStringOption = arrayOfString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ArrayArrayOfInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayOfIntegerOption { get; private set; } + /// /// Gets or Sets ArrayArrayOfInteger /// [JsonPropertyName("array_array_of_integer")] - public List> ArrayArrayOfInteger { get; set; } + public List> ArrayArrayOfInteger { get { return this. ArrayArrayOfIntegerOption; } set { this.ArrayArrayOfIntegerOption = new Option>>(value); } } + + /// + /// Used to track the state of ArrayArrayOfModel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> ArrayArrayOfModelOption { get; private set; } /// /// Gets or Sets ArrayArrayOfModel /// [JsonPropertyName("array_array_of_model")] - public List> ArrayArrayOfModel { get; set; } + public List> ArrayArrayOfModel { get { return this. ArrayArrayOfModelOption; } set { this.ArrayArrayOfModelOption = new Option>>(value); } } + + /// + /// Used to track the state of ArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayOfStringOption { get; private set; } /// /// Gets or Sets ArrayOfString /// [JsonPropertyName("array_of_string")] - public List ArrayOfString { get; set; } + public List ArrayOfString { get { return this. ArrayOfStringOption; } set { this.ArrayOfStringOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> arrayArrayOfInteger = default; - List> arrayArrayOfModel = default; - List arrayOfString = default; + Option>> arrayArrayOfInteger = default; + Option>> arrayArrayOfModel = default; + Option> arrayOfString = default; while (utf8JsonReader.Read()) { @@ -139,15 +161,15 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "array_array_of_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfInteger = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfInteger = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_array_of_model": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayArrayOfModel = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + arrayArrayOfModel = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayOfString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -155,14 +177,14 @@ public override ArrayTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (arrayArrayOfInteger == null) - throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is required for class ArrayTest."); + if (arrayArrayOfInteger.IsSet && arrayArrayOfInteger.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfInteger), "Property is not nullable for class ArrayTest."); - if (arrayArrayOfModel == null) - throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is required for class ArrayTest."); + if (arrayArrayOfModel.IsSet && arrayArrayOfModel.Value == null) + throw new ArgumentNullException(nameof(arrayArrayOfModel), "Property is not nullable for class ArrayTest."); - if (arrayOfString == null) - throw new ArgumentNullException(nameof(arrayOfString), "Property is required for class ArrayTest."); + if (arrayOfString.IsSet && arrayOfString.Value == null) + throw new ArgumentNullException(nameof(arrayOfString), "Property is not nullable for class ArrayTest."); return new ArrayTest(arrayArrayOfInteger, arrayArrayOfModel, arrayOfString); } @@ -191,12 +213,30 @@ public override void Write(Utf8JsonWriter writer, ArrayTest arrayTest, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ArrayTest arrayTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_array_of_integer"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); - writer.WritePropertyName("array_array_of_model"); - JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); - writer.WritePropertyName("array_of_string"); - JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + if (arrayTest.ArrayArrayOfIntegerOption.IsSet && arrayTest.ArrayArrayOfInteger == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfInteger), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfModelOption.IsSet && arrayTest.ArrayArrayOfModel == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayArrayOfModel), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayOfStringOption.IsSet && arrayTest.ArrayOfString == null) + throw new ArgumentNullException(nameof(arrayTest.ArrayOfString), "Property is required for class ArrayTest."); + + if (arrayTest.ArrayArrayOfIntegerOption.IsSet) + { + writer.WritePropertyName("array_array_of_integer"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfInteger, jsonSerializerOptions); + } + if (arrayTest.ArrayArrayOfModelOption.IsSet) + { + writer.WritePropertyName("array_array_of_model"); + JsonSerializer.Serialize(writer, arrayTest.ArrayArrayOfModel, jsonSerializerOptions); + } + if (arrayTest.ArrayOfStringOption.IsSet) + { + writer.WritePropertyName("array_of_string"); + JsonSerializer.Serialize(writer, arrayTest.ArrayOfString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs index 75bab7a8d056..bab9e17b8245 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Banana.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Banana : IValidatableObject /// /// lengthCm [JsonConstructor] - public Banana(decimal lengthCm) + public Banana(Option lengthCm = default) { - LengthCm = lengthCm; + LengthCmOption = lengthCm; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of LengthCm + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LengthCmOption { get; private set; } + /// /// Gets or Sets LengthCm /// [JsonPropertyName("lengthCm")] - public decimal LengthCm { get; set; } + public decimal? LengthCm { get { return this. LengthCmOption; } set { this.LengthCmOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; + Option lengthCm = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -127,10 +135,10 @@ public override Banana Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class Banana."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class Banana."); - return new Banana(lengthCm.Value); + return new Banana(lengthCm); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, Banana banana, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Banana banana, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("lengthCm", banana.LengthCm); + if (banana.LengthCmOption.IsSet) + writer.WriteNumber("lengthCm", banana.LengthCmOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs index 61e5cf312cca..82a047319d31 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BananaReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class BananaReq : IValidatableObject /// lengthCm /// sweet [JsonConstructor] - public BananaReq(decimal lengthCm, bool sweet) + public BananaReq(decimal lengthCm, Option sweet = default) { LengthCm = lengthCm; - Sweet = sweet; + SweetOption = sweet; OnCreated(); } @@ -49,11 +50,18 @@ public BananaReq(decimal lengthCm, bool sweet) [JsonPropertyName("lengthCm")] public decimal LengthCm { get; set; } + /// + /// Used to track the state of Sweet + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SweetOption { get; private set; } + /// /// Gets or Sets Sweet /// [JsonPropertyName("sweet")] - public bool Sweet { get; set; } + public bool? Sweet { get { return this. SweetOption; } set { this.SweetOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -102,8 +110,8 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? lengthCm = default; - bool? sweet = default; + Option lengthCm = default; + Option sweet = default; while (utf8JsonReader.Read()) { @@ -122,11 +130,11 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon { case "lengthCm": if (utf8JsonReader.TokenType != JsonTokenType.Null) - lengthCm = utf8JsonReader.GetDecimal(); + lengthCm = new Option(utf8JsonReader.GetDecimal()); break; case "sweet": if (utf8JsonReader.TokenType != JsonTokenType.Null) - sweet = utf8JsonReader.GetBoolean(); + sweet = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -134,13 +142,16 @@ public override BananaReq Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (lengthCm == null) - throw new ArgumentNullException(nameof(lengthCm), "Property is required for class BananaReq."); + if (!lengthCm.IsSet) + throw new ArgumentException("Property is required for class BananaReq.", nameof(lengthCm)); - if (sweet == null) - throw new ArgumentNullException(nameof(sweet), "Property is required for class BananaReq."); + if (lengthCm.IsSet && lengthCm.Value == null) + throw new ArgumentNullException(nameof(lengthCm), "Property is not nullable for class BananaReq."); - return new BananaReq(lengthCm.Value, sweet.Value); + if (sweet.IsSet && sweet.Value == null) + throw new ArgumentNullException(nameof(sweet), "Property is not nullable for class BananaReq."); + + return new BananaReq(lengthCm.Value.Value, sweet); } /// @@ -168,7 +179,9 @@ public override void Write(Utf8JsonWriter writer, BananaReq bananaReq, JsonSeria public void WriteProperties(ref Utf8JsonWriter writer, BananaReq bananaReq, JsonSerializerOptions jsonSerializerOptions) { writer.WriteNumber("lengthCm", bananaReq.LengthCm); - writer.WriteBoolean("sweet", bananaReq.Sweet); + + if (bananaReq.SweetOption.IsSet) + writer.WriteBoolean("sweet", bananaReq.SweetOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs index c9e4a8bc7120..53c20a25cd10 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/BasquePig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override BasquePig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class BasquePig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class BasquePig.", nameof(className)); - return new BasquePig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class BasquePig."); + + return new BasquePig(className.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, BasquePig basquePig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, BasquePig basquePig, JsonSerializerOptions jsonSerializerOptions) { + if (basquePig.ClassName == null) + throw new ArgumentNullException(nameof(basquePig.ClassName), "Property is required for class BasquePig."); + writer.WriteString("className", basquePig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs index ca7eb413c65b..b038e95b9c01 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Capitalization.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -38,55 +39,97 @@ public partial class Capitalization : IValidatableObject /// smallCamel /// smallSnake [JsonConstructor] - public Capitalization(string aTTNAME, string capitalCamel, string capitalSnake, string sCAETHFlowPoints, string smallCamel, string smallSnake) + public Capitalization(Option aTTNAME = default, Option capitalCamel = default, Option capitalSnake = default, Option sCAETHFlowPoints = default, Option smallCamel = default, Option smallSnake = default) { - ATT_NAME = aTTNAME; - CapitalCamel = capitalCamel; - CapitalSnake = capitalSnake; - SCAETHFlowPoints = sCAETHFlowPoints; - SmallCamel = smallCamel; - SmallSnake = smallSnake; + ATT_NAMEOption = aTTNAME; + CapitalCamelOption = capitalCamel; + CapitalSnakeOption = capitalSnake; + SCAETHFlowPointsOption = sCAETHFlowPoints; + SmallCamelOption = smallCamel; + SmallSnakeOption = smallSnake; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of ATT_NAME + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ATT_NAMEOption { get; private set; } + /// /// Name of the pet /// /// Name of the pet [JsonPropertyName("ATT_NAME")] - public string ATT_NAME { get; set; } + public string ATT_NAME { get { return this. ATT_NAMEOption; } set { this.ATT_NAMEOption = new Option(value); } } + + /// + /// Used to track the state of CapitalCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalCamelOption { get; private set; } /// /// Gets or Sets CapitalCamel /// [JsonPropertyName("CapitalCamel")] - public string CapitalCamel { get; set; } + public string CapitalCamel { get { return this. CapitalCamelOption; } set { this.CapitalCamelOption = new Option(value); } } + + /// + /// Used to track the state of CapitalSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CapitalSnakeOption { get; private set; } /// /// Gets or Sets CapitalSnake /// [JsonPropertyName("Capital_Snake")] - public string CapitalSnake { get; set; } + public string CapitalSnake { get { return this. CapitalSnakeOption; } set { this.CapitalSnakeOption = new Option(value); } } + + /// + /// Used to track the state of SCAETHFlowPoints + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SCAETHFlowPointsOption { get; private set; } /// /// Gets or Sets SCAETHFlowPoints /// [JsonPropertyName("SCA_ETH_Flow_Points")] - public string SCAETHFlowPoints { get; set; } + public string SCAETHFlowPoints { get { return this. SCAETHFlowPointsOption; } set { this.SCAETHFlowPointsOption = new Option(value); } } + + /// + /// Used to track the state of SmallCamel + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallCamelOption { get; private set; } /// /// Gets or Sets SmallCamel /// [JsonPropertyName("smallCamel")] - public string SmallCamel { get; set; } + public string SmallCamel { get { return this. SmallCamelOption; } set { this.SmallCamelOption = new Option(value); } } + + /// + /// Used to track the state of SmallSnake + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SmallSnakeOption { get; private set; } /// /// Gets or Sets SmallSnake /// [JsonPropertyName("small_Snake")] - public string SmallSnake { get; set; } + public string SmallSnake { get { return this. SmallSnakeOption; } set { this.SmallSnakeOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -146,12 +189,12 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string aTTNAME = default; - string capitalCamel = default; - string capitalSnake = default; - string sCAETHFlowPoints = default; - string smallCamel = default; - string smallSnake = default; + Option aTTNAME = default; + Option capitalCamel = default; + Option capitalSnake = default; + Option sCAETHFlowPoints = default; + Option smallCamel = default; + Option smallSnake = default; while (utf8JsonReader.Read()) { @@ -169,22 +212,22 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "ATT_NAME": - aTTNAME = utf8JsonReader.GetString(); + aTTNAME = new Option(utf8JsonReader.GetString()); break; case "CapitalCamel": - capitalCamel = utf8JsonReader.GetString(); + capitalCamel = new Option(utf8JsonReader.GetString()); break; case "Capital_Snake": - capitalSnake = utf8JsonReader.GetString(); + capitalSnake = new Option(utf8JsonReader.GetString()); break; case "SCA_ETH_Flow_Points": - sCAETHFlowPoints = utf8JsonReader.GetString(); + sCAETHFlowPoints = new Option(utf8JsonReader.GetString()); break; case "smallCamel": - smallCamel = utf8JsonReader.GetString(); + smallCamel = new Option(utf8JsonReader.GetString()); break; case "small_Snake": - smallSnake = utf8JsonReader.GetString(); + smallSnake = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,23 +235,23 @@ public override Capitalization Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (aTTNAME == null) - throw new ArgumentNullException(nameof(aTTNAME), "Property is required for class Capitalization."); + if (aTTNAME.IsSet && aTTNAME.Value == null) + throw new ArgumentNullException(nameof(aTTNAME), "Property is not nullable for class Capitalization."); - if (capitalCamel == null) - throw new ArgumentNullException(nameof(capitalCamel), "Property is required for class Capitalization."); + if (capitalCamel.IsSet && capitalCamel.Value == null) + throw new ArgumentNullException(nameof(capitalCamel), "Property is not nullable for class Capitalization."); - if (capitalSnake == null) - throw new ArgumentNullException(nameof(capitalSnake), "Property is required for class Capitalization."); + if (capitalSnake.IsSet && capitalSnake.Value == null) + throw new ArgumentNullException(nameof(capitalSnake), "Property is not nullable for class Capitalization."); - if (sCAETHFlowPoints == null) - throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is required for class Capitalization."); + if (sCAETHFlowPoints.IsSet && sCAETHFlowPoints.Value == null) + throw new ArgumentNullException(nameof(sCAETHFlowPoints), "Property is not nullable for class Capitalization."); - if (smallCamel == null) - throw new ArgumentNullException(nameof(smallCamel), "Property is required for class Capitalization."); + if (smallCamel.IsSet && smallCamel.Value == null) + throw new ArgumentNullException(nameof(smallCamel), "Property is not nullable for class Capitalization."); - if (smallSnake == null) - throw new ArgumentNullException(nameof(smallSnake), "Property is required for class Capitalization."); + if (smallSnake.IsSet && smallSnake.Value == null) + throw new ArgumentNullException(nameof(smallSnake), "Property is not nullable for class Capitalization."); return new Capitalization(aTTNAME, capitalCamel, capitalSnake, sCAETHFlowPoints, smallCamel, smallSnake); } @@ -237,12 +280,41 @@ public override void Write(Utf8JsonWriter writer, Capitalization capitalization, /// public void WriteProperties(ref Utf8JsonWriter writer, Capitalization capitalization, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("ATT_NAME", capitalization.ATT_NAME); - writer.WriteString("CapitalCamel", capitalization.CapitalCamel); - writer.WriteString("Capital_Snake", capitalization.CapitalSnake); - writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); - writer.WriteString("smallCamel", capitalization.SmallCamel); - writer.WriteString("small_Snake", capitalization.SmallSnake); + if (capitalization.ATT_NAMEOption.IsSet && capitalization.ATT_NAME == null) + throw new ArgumentNullException(nameof(capitalization.ATT_NAME), "Property is required for class Capitalization."); + + if (capitalization.CapitalCamelOption.IsSet && capitalization.CapitalCamel == null) + throw new ArgumentNullException(nameof(capitalization.CapitalCamel), "Property is required for class Capitalization."); + + if (capitalization.CapitalSnakeOption.IsSet && capitalization.CapitalSnake == null) + throw new ArgumentNullException(nameof(capitalization.CapitalSnake), "Property is required for class Capitalization."); + + if (capitalization.SCAETHFlowPointsOption.IsSet && capitalization.SCAETHFlowPoints == null) + throw new ArgumentNullException(nameof(capitalization.SCAETHFlowPoints), "Property is required for class Capitalization."); + + if (capitalization.SmallCamelOption.IsSet && capitalization.SmallCamel == null) + throw new ArgumentNullException(nameof(capitalization.SmallCamel), "Property is required for class Capitalization."); + + if (capitalization.SmallSnakeOption.IsSet && capitalization.SmallSnake == null) + throw new ArgumentNullException(nameof(capitalization.SmallSnake), "Property is required for class Capitalization."); + + if (capitalization.ATT_NAMEOption.IsSet) + writer.WriteString("ATT_NAME", capitalization.ATT_NAME); + + if (capitalization.CapitalCamelOption.IsSet) + writer.WriteString("CapitalCamel", capitalization.CapitalCamel); + + if (capitalization.CapitalSnakeOption.IsSet) + writer.WriteString("Capital_Snake", capitalization.CapitalSnake); + + if (capitalization.SCAETHFlowPointsOption.IsSet) + writer.WriteString("SCA_ETH_Flow_Points", capitalization.SCAETHFlowPoints); + + if (capitalization.SmallCamelOption.IsSet) + writer.WriteString("smallCamel", capitalization.SmallCamel); + + if (capitalization.SmallSnakeOption.IsSet) + writer.WriteString("small_Snake", capitalization.SmallSnake); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs index 619fc52ce11c..d032e72761dd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Cat.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -32,22 +33,29 @@ public partial class Cat : Animal, IValidatableObject /// Initializes a new instance of the class. /// /// className - /// declawed /// color (default to "red") + /// declawed [JsonConstructor] - public Cat(string className, bool declawed, string color = @"red") : base(className, color) + public Cat(string className, Option color = default, Option declawed = default) : base(className, color) { - Declawed = declawed; + DeclawedOption = declawed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Declawed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeclawedOption { get; private set; } + /// /// Gets or Sets Declawed /// [JsonPropertyName("declawed")] - public bool Declawed { get; set; } + public bool? Declawed { get { return this. DeclawedOption; } set { this.DeclawedOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -86,9 +94,9 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - bool? declawed = default; - string color = default; + Option className = default; + Option color = default; + Option declawed = default; while (utf8JsonReader.Read()) { @@ -106,14 +114,14 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); + break; + case "color": + color = new Option(utf8JsonReader.GetString()); break; case "declawed": if (utf8JsonReader.TokenType != JsonTokenType.Null) - declawed = utf8JsonReader.GetBoolean(); - break; - case "color": - color = utf8JsonReader.GetString(); + declawed = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -121,16 +129,19 @@ public override Cat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Cat."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Cat.", nameof(className)); - if (declawed == null) - throw new ArgumentNullException(nameof(declawed), "Property is required for class Cat."); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Cat."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Cat."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Cat."); - return new Cat(className, declawed.Value, color); + if (declawed.IsSet && declawed.Value == null) + throw new ArgumentNullException(nameof(declawed), "Property is not nullable for class Cat."); + + return new Cat(className.Value, color, declawed); } /// @@ -157,9 +168,19 @@ public override void Write(Utf8JsonWriter writer, Cat cat, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Cat cat, JsonSerializerOptions jsonSerializerOptions) { + if (cat.ClassName == null) + throw new ArgumentNullException(nameof(cat.ClassName), "Property is required for class Cat."); + + if (cat.ColorOption.IsSet && cat.Color == null) + throw new ArgumentNullException(nameof(cat.Color), "Property is required for class Cat."); + writer.WriteString("className", cat.ClassName); - writer.WriteBoolean("declawed", cat.Declawed); - writer.WriteString("color", cat.Color); + + if (cat.ColorOption.IsSet) + writer.WriteString("color", cat.Color); + + if (cat.DeclawedOption.IsSet) + writer.WriteBoolean("declawed", cat.DeclawedOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs index 6139c3048390..315dd17bd315 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Category.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,20 +35,27 @@ public partial class Category : IValidatableObject /// id /// name (default to "default-name") [JsonConstructor] - public Category(long id, string name = @"default-name") + public Category(Option id = default, string name = @"default-name") { - Id = id; + IdOption = id; Name = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } /// /// Gets or Sets Name @@ -109,8 +117,8 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -129,10 +137,10 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -140,13 +148,16 @@ public override Category Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Category."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Category.", nameof(name)); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Category."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Category."); - return new Category(id.Value, name); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Category."); + + return new Category(id, name.Value); } /// @@ -173,7 +184,12 @@ public override void Write(Utf8JsonWriter writer, Category category, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Category category, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", category.Id); + if (category.Name == null) + throw new ArgumentNullException(nameof(category.Name), "Property is required for class Category."); + + if (category.IdOption.IsSet) + writer.WriteNumber("id", category.IdOption.Value.Value); + writer.WriteString("name", category.Name); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs index 367e08ca3d32..557fdc97b0ad 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,9 +35,9 @@ public partial class ChildCat : ParentPet, IValidatableObject /// name /// petType (default to PetTypeEnum.ChildCat) [JsonConstructor] - public ChildCat(string name, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) + public ChildCat(Option name = default, PetTypeEnum petType = PetTypeEnum.ChildCat) : base(ChildCat.PetTypeEnumToJsonValue(petType)) { - Name = name; + NameOption = name; PetType = petType; OnCreated(); } @@ -101,11 +102,18 @@ public static string PetTypeEnumToJsonValue(PetTypeEnum value) [JsonPropertyName("pet_type")] public new PetTypeEnum PetType { get; set; } + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -145,8 +153,8 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; - ChildCat.PetTypeEnum? petType = default; + Option name = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -164,13 +172,12 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; case "pet_type": string petTypeRawValue = utf8JsonReader.GetString(); - petType = petTypeRawValue == null - ? null - : ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue); + if (petTypeRawValue != null) + petType = new Option(ChildCat.PetTypeEnumFromStringOrDefault(petTypeRawValue)); break; default: break; @@ -178,13 +185,16 @@ public override ChildCat Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class ChildCat."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ChildCat.", nameof(petType)); - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ChildCat."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class ChildCat."); - return new ChildCat(name, petType.Value); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ChildCat."); + + return new ChildCat(name, petType.Value.Value); } /// @@ -211,13 +221,14 @@ public override void Write(Utf8JsonWriter writer, ChildCat childCat, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, ChildCat childCat, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", childCat.Name); + if (childCat.NameOption.IsSet && childCat.Name == null) + throw new ArgumentNullException(nameof(childCat.Name), "Property is required for class ChildCat."); + + if (childCat.NameOption.IsSet) + writer.WriteString("name", childCat.Name); var petTypeRawValue = ChildCat.PetTypeEnumToJsonValue(childCat.PetType); - if (petTypeRawValue != null) - writer.WriteString("pet_type", petTypeRawValue); - else - writer.WriteNull("pet_type"); + writer.WriteString("pet_type", petTypeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs index d1c65d368199..b7ef5105c6a1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ClassModel.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ClassModel : IValidatableObject /// /// varClass [JsonConstructor] - public ClassModel(string varClass) + public ClassModel(Option varClass = default) { - VarClass = varClass; + VarClassOption = varClass; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("_class")] - public string VarClass { get; set; } + public string VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClass = default; + Option varClass = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { case "_class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override ClassModel Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class ClassModel."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class ClassModel."); return new ClassModel(varClass); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, ClassModel classModel, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, ClassModel classModel, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_class", classModel.VarClass); + if (classModel.VarClassOption.IsSet && classModel.VarClass == null) + throw new ArgumentNullException(nameof(classModel.VarClass), "Property is required for class ClassModel."); + + if (classModel.VarClassOption.IsSet) + writer.WriteString("_class", classModel.VarClass); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs index 79579247f7e9..747b36ec65bd 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ComplexQuadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; - string shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override ComplexQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class ComplexQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ComplexQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ComplexQuadrilateral.", nameof(shapeType)); - return new ComplexQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class ComplexQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ComplexQuadrilateral."); + + return new ComplexQuadrilateral(quadrilateralType.Value, shapeType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, ComplexQuadrilateral complexQu /// public void WriteProperties(ref Utf8JsonWriter writer, ComplexQuadrilateral complexQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (complexQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.QuadrilateralType), "Property is required for class ComplexQuadrilateral."); + + if (complexQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(complexQuadrilateral.ShapeType), "Property is required for class ComplexQuadrilateral."); + writer.WriteString("quadrilateralType", complexQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", complexQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs index 84439210bcfc..c28634e4e13e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DanishPig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override DanishPig Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class DanishPig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class DanishPig.", nameof(className)); - return new DanishPig(className); + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class DanishPig."); + + return new DanishPig(className.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, DanishPig danishPig, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, DanishPig danishPig, JsonSerializerOptions jsonSerializerOptions) { + if (danishPig.ClassName == null) + throw new ArgumentNullException(nameof(danishPig.ClassName), "Property is required for class DanishPig."); + writer.WriteString("className", danishPig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs index 4420630af349..9bfd36317daf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class DateOnlyClass : IValidatableObject /// /// dateOnlyProperty [JsonConstructor] - public DateOnlyClass(DateTime dateOnlyProperty) + public DateOnlyClass(Option dateOnlyProperty = default) { - DateOnlyProperty = dateOnlyProperty; + DateOnlyPropertyOption = dateOnlyProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateOnlyProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateOnlyPropertyOption { get; private set; } + /// /// Gets or Sets DateOnlyProperty /// /// Fri Jul 21 00:00:00 UTC 2017 [JsonPropertyName("dateOnlyProperty")] - public DateTime DateOnlyProperty { get; set; } + public DateTime? DateOnlyProperty { get { return this. DateOnlyPropertyOption; } set { this.DateOnlyPropertyOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -106,7 +114,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateOnlyProperty = default; + Option dateOnlyProperty = default; while (utf8JsonReader.Read()) { @@ -125,7 +133,7 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT { case "dateOnlyProperty": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateOnlyProperty = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateOnlyProperty = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -133,10 +141,10 @@ public override DateOnlyClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (dateOnlyProperty == null) - throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is required for class DateOnlyClass."); + if (dateOnlyProperty.IsSet && dateOnlyProperty.Value == null) + throw new ArgumentNullException(nameof(dateOnlyProperty), "Property is not nullable for class DateOnlyClass."); - return new DateOnlyClass(dateOnlyProperty.Value); + return new DateOnlyClass(dateOnlyProperty); } /// @@ -163,7 +171,8 @@ public override void Write(Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, DateOnlyClass dateOnlyClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyProperty.ToString(DateOnlyPropertyFormat)); + if (dateOnlyClass.DateOnlyPropertyOption.IsSet) + writer.WriteString("dateOnlyProperty", dateOnlyClass.DateOnlyPropertyOption.Value.Value.ToString(DateOnlyPropertyFormat)); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs index 16e3dfe57faa..1ef8301d0c3d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/DeprecatedObject.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class DeprecatedObject : IValidatableObject /// /// name [JsonConstructor] - public DeprecatedObject(string name) + public DeprecatedObject(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override DeprecatedObject Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class DeprecatedObject."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class DeprecatedObject."); return new DeprecatedObject(name); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, DeprecatedObject deprecatedObj /// public void WriteProperties(ref Utf8JsonWriter writer, DeprecatedObject deprecatedObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", deprecatedObject.Name); + if (deprecatedObject.NameOption.IsSet && deprecatedObject.Name == null) + throw new ArgumentNullException(nameof(deprecatedObject.Name), "Property is required for class DeprecatedObject."); + + if (deprecatedObject.NameOption.IsSet) + writer.WriteString("name", deprecatedObject.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs index 810934b95efe..933668a94262 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Dog.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,23 +32,30 @@ public partial class Dog : Animal, IValidatableObject /// /// Initializes a new instance of the class. /// - /// breed /// className + /// breed /// color (default to "red") [JsonConstructor] - public Dog(string breed, string className, string color = @"red") : base(className, color) + public Dog(string className, Option breed = default, Option color = default) : base(className, color) { - Breed = breed; + BreedOption = breed; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Breed + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BreedOption { get; private set; } + /// /// Gets or Sets Breed /// [JsonPropertyName("breed")] - public string Breed { get; set; } + public string Breed { get { return this. BreedOption; } set { this.BreedOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -86,9 +94,9 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string breed = default; - string className = default; - string color = default; + Option className = default; + Option breed = default; + Option color = default; while (utf8JsonReader.Read()) { @@ -105,14 +113,14 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "breed": - breed = utf8JsonReader.GetString(); - break; case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); + break; + case "breed": + breed = new Option(utf8JsonReader.GetString()); break; case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -120,16 +128,19 @@ public override Dog Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (breed == null) - throw new ArgumentNullException(nameof(breed), "Property is required for class Dog."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Dog.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Dog."); - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Dog."); + if (breed.IsSet && breed.Value == null) + throw new ArgumentNullException(nameof(breed), "Property is not nullable for class Dog."); - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Dog."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Dog."); - return new Dog(breed, className, color); + return new Dog(className.Value, breed, color); } /// @@ -156,9 +167,22 @@ public override void Write(Utf8JsonWriter writer, Dog dog, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Dog dog, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("breed", dog.Breed); + if (dog.ClassName == null) + throw new ArgumentNullException(nameof(dog.ClassName), "Property is required for class Dog."); + + if (dog.BreedOption.IsSet && dog.Breed == null) + throw new ArgumentNullException(nameof(dog.Breed), "Property is required for class Dog."); + + if (dog.ColorOption.IsSet && dog.Color == null) + throw new ArgumentNullException(nameof(dog.Color), "Property is required for class Dog."); + writer.WriteString("className", dog.ClassName); - writer.WriteString("color", dog.Color); + + if (dog.BreedOption.IsSet) + writer.WriteString("breed", dog.Breed); + + if (dog.ColorOption.IsSet) + writer.WriteString("color", dog.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs index 68f7676ff91f..6d373f696674 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -20,56 +20,85 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Drawing /// - public partial class Drawing : Dictionary, IValidatableObject + public partial class Drawing : IValidatableObject { /// /// Initializes a new instance of the class. /// /// mainShape - /// shapes /// nullableShape /// shapeOrNull + /// shapes [JsonConstructor] - public Drawing(Shape mainShape, List shapes, NullableShape nullableShape = default, ShapeOrNull shapeOrNull = default) : base() + public Drawing(Option mainShape = default, Option nullableShape = default, Option shapeOrNull = default, Option> shapes = default) { - MainShape = mainShape; - Shapes = shapes; - NullableShape = nullableShape; - ShapeOrNull = shapeOrNull; + MainShapeOption = mainShape; + NullableShapeOption = nullableShape; + ShapeOrNullOption = shapeOrNull; + ShapesOption = shapes; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MainShape + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MainShapeOption { get; private set; } + /// /// Gets or Sets MainShape /// [JsonPropertyName("mainShape")] - public Shape MainShape { get; set; } + public Shape MainShape { get { return this. MainShapeOption; } set { this.MainShapeOption = new Option(value); } } /// - /// Gets or Sets Shapes + /// Used to track the state of NullableShape /// - [JsonPropertyName("shapes")] - public List Shapes { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableShapeOption { get; private set; } /// /// Gets or Sets NullableShape /// [JsonPropertyName("nullableShape")] - public NullableShape NullableShape { get; set; } + public NullableShape NullableShape { get { return this. NullableShapeOption; } set { this.NullableShapeOption = new Option(value); } } + + /// + /// Used to track the state of ShapeOrNull + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShapeOrNullOption { get; private set; } /// /// Gets or Sets ShapeOrNull /// [JsonPropertyName("shapeOrNull")] - public ShapeOrNull ShapeOrNull { get; set; } + public ShapeOrNull ShapeOrNull { get { return this. ShapeOrNullOption; } set { this.ShapeOrNullOption = new Option(value); } } + + /// + /// Used to track the state of Shapes + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ShapesOption { get; private set; } + + /// + /// Gets or Sets Shapes + /// + [JsonPropertyName("shapes")] + public List Shapes { get { return this. ShapesOption; } set { this.ShapesOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -85,11 +114,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); - sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); + sb.Append(" Shapes: ").Append(Shapes).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -101,16 +129,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -138,10 +156,10 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Shape mainShape = default; - List shapes = default; - NullableShape nullableShape = default; - ShapeOrNull shapeOrNull = default; + Option mainShape = default; + Option nullableShape = default; + Option shapeOrNull = default; + Option> shapes = default; while (utf8JsonReader.Read()) { @@ -160,19 +178,19 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "mainShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mainShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "shapes": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapes = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mainShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "nullableShape": if (utf8JsonReader.TokenType != JsonTokenType.Null) - nullableShape = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + nullableShape = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "shapeOrNull": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shapeOrNull = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shapeOrNull = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "shapes": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + shapes = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -180,13 +198,13 @@ public override Drawing Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (mainShape == null) - throw new ArgumentNullException(nameof(mainShape), "Property is required for class Drawing."); + if (mainShape.IsSet && mainShape.Value == null) + throw new ArgumentNullException(nameof(mainShape), "Property is not nullable for class Drawing."); - if (shapes == null) - throw new ArgumentNullException(nameof(shapes), "Property is required for class Drawing."); + if (shapes.IsSet && shapes.Value == null) + throw new ArgumentNullException(nameof(shapes), "Property is not nullable for class Drawing."); - return new Drawing(mainShape, shapes, nullableShape, shapeOrNull); + return new Drawing(mainShape, nullableShape, shapeOrNull, shapes); } /// @@ -213,14 +231,38 @@ public override void Write(Utf8JsonWriter writer, Drawing drawing, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, Drawing drawing, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("mainShape"); - JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); - writer.WritePropertyName("shapes"); - JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); - writer.WritePropertyName("nullableShape"); - JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); - writer.WritePropertyName("shapeOrNull"); - JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + if (drawing.MainShapeOption.IsSet && drawing.MainShape == null) + throw new ArgumentNullException(nameof(drawing.MainShape), "Property is required for class Drawing."); + + if (drawing.ShapesOption.IsSet && drawing.Shapes == null) + throw new ArgumentNullException(nameof(drawing.Shapes), "Property is required for class Drawing."); + + if (drawing.MainShapeOption.IsSet) + { + writer.WritePropertyName("mainShape"); + JsonSerializer.Serialize(writer, drawing.MainShape, jsonSerializerOptions); + } + if (drawing.NullableShapeOption.IsSet) + if (drawing.NullableShapeOption.Value != null) + { + writer.WritePropertyName("nullableShape"); + JsonSerializer.Serialize(writer, drawing.NullableShape, jsonSerializerOptions); + } + else + writer.WriteNull("nullableShape"); + if (drawing.ShapeOrNullOption.IsSet) + if (drawing.ShapeOrNullOption.Value != null) + { + writer.WritePropertyName("shapeOrNull"); + JsonSerializer.Serialize(writer, drawing.ShapeOrNull, jsonSerializerOptions); + } + else + writer.WriteNull("shapeOrNull"); + if (drawing.ShapesOption.IsSet) + { + writer.WritePropertyName("shapes"); + JsonSerializer.Serialize(writer, drawing.Shapes, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs index 37e06cb37e3c..0234ed5742e5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumArrays.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,10 +35,10 @@ public partial class EnumArrays : IValidatableObject /// arrayEnum /// justSymbol [JsonConstructor] - public EnumArrays(List arrayEnum, JustSymbolEnum justSymbol) + public EnumArrays(Option> arrayEnum = default, Option justSymbol = default) { - ArrayEnum = arrayEnum; - JustSymbol = justSymbol; + ArrayEnumOption = arrayEnum; + JustSymbolOption = justSymbol; OnCreated(); } @@ -164,7 +165,7 @@ public static JustSymbolEnum JustSymbolEnumFromString(string value) /// /// /// - public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) + public static string JustSymbolEnumToJsonValue(JustSymbolEnum? value) { if (value == JustSymbolEnum.GreaterThanOrEqualTo) return ">="; @@ -175,17 +176,31 @@ public static string JustSymbolEnumToJsonValue(JustSymbolEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of JustSymbol + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustSymbolOption { get; private set; } + /// /// Gets or Sets JustSymbol /// [JsonPropertyName("just_symbol")] - public JustSymbolEnum JustSymbol { get; set; } + public JustSymbolEnum? JustSymbol { get { return this.JustSymbolOption; } set { this.JustSymbolOption = new Option(value); } } + + /// + /// Used to track the state of ArrayEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayEnumOption { get; private set; } /// /// Gets or Sets ArrayEnum /// [JsonPropertyName("array_enum")] - public List ArrayEnum { get; set; } + public List ArrayEnum { get { return this. ArrayEnumOption; } set { this.ArrayEnumOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -241,8 +256,8 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayEnum = default; - EnumArrays.JustSymbolEnum? justSymbol = default; + Option> arrayEnum = default; + Option justSymbol = default; while (utf8JsonReader.Read()) { @@ -261,13 +276,12 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "array_enum": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayEnum = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayEnum = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "just_symbol": string justSymbolRawValue = utf8JsonReader.GetString(); - justSymbol = justSymbolRawValue == null - ? null - : EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue); + if (justSymbolRawValue != null) + justSymbol = new Option(EnumArrays.JustSymbolEnumFromStringOrDefault(justSymbolRawValue)); break; default: break; @@ -275,13 +289,13 @@ public override EnumArrays Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (arrayEnum == null) - throw new ArgumentNullException(nameof(arrayEnum), "Property is required for class EnumArrays."); + if (arrayEnum.IsSet && arrayEnum.Value == null) + throw new ArgumentNullException(nameof(arrayEnum), "Property is not nullable for class EnumArrays."); - if (justSymbol == null) - throw new ArgumentNullException(nameof(justSymbol), "Property is required for class EnumArrays."); + if (justSymbol.IsSet && justSymbol.Value == null) + throw new ArgumentNullException(nameof(justSymbol), "Property is not nullable for class EnumArrays."); - return new EnumArrays(arrayEnum, justSymbol.Value); + return new EnumArrays(arrayEnum, justSymbol); } /// @@ -308,14 +322,16 @@ public override void Write(Utf8JsonWriter writer, EnumArrays enumArrays, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, EnumArrays enumArrays, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_enum"); - JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); - - var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbol); - if (justSymbolRawValue != null) - writer.WriteString("just_symbol", justSymbolRawValue); - else - writer.WriteNull("just_symbol"); + if (enumArrays.ArrayEnumOption.IsSet && enumArrays.ArrayEnum == null) + throw new ArgumentNullException(nameof(enumArrays.ArrayEnum), "Property is required for class EnumArrays."); + + if (enumArrays.ArrayEnumOption.IsSet) + { + writer.WritePropertyName("array_enum"); + JsonSerializer.Serialize(writer, enumArrays.ArrayEnum, jsonSerializerOptions); + } + var justSymbolRawValue = EnumArrays.JustSymbolEnumToJsonValue(enumArrays.JustSymbolOption.Value.Value); + writer.WriteString("just_symbol", justSymbolRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs index 94c2361c8810..b1aff0adf0d8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs index 1d1ed947dc47..a49eb0130a41 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EnumTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,32 +32,188 @@ public partial class EnumTest : IValidatableObject /// /// Initializes a new instance of the class. /// + /// enumStringRequired /// enumInteger /// enumIntegerOnly /// enumNumber /// enumString - /// enumStringRequired + /// outerEnum /// outerEnumDefaultValue /// outerEnumInteger /// outerEnumIntegerDefaultValue - /// outerEnum [JsonConstructor] - public EnumTest(EnumIntegerEnum enumInteger, EnumIntegerOnlyEnum enumIntegerOnly, EnumNumberEnum enumNumber, EnumStringEnum enumString, EnumStringRequiredEnum enumStringRequired, OuterEnumDefaultValue outerEnumDefaultValue, OuterEnumInteger outerEnumInteger, OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue, OuterEnum? outerEnum = default) + public EnumTest(EnumStringRequiredEnum enumStringRequired, Option enumInteger = default, Option enumIntegerOnly = default, Option enumNumber = default, Option enumString = default, Option outerEnum = default, Option outerEnumDefaultValue = default, Option outerEnumInteger = default, Option outerEnumIntegerDefaultValue = default) { - EnumInteger = enumInteger; - EnumIntegerOnly = enumIntegerOnly; - EnumNumber = enumNumber; - EnumString = enumString; EnumStringRequired = enumStringRequired; - OuterEnumDefaultValue = outerEnumDefaultValue; - OuterEnumInteger = outerEnumInteger; - OuterEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; - OuterEnum = outerEnum; + EnumIntegerOption = enumInteger; + EnumIntegerOnlyOption = enumIntegerOnly; + EnumNumberOption = enumNumber; + EnumStringOption = enumString; + OuterEnumOption = outerEnum; + OuterEnumDefaultValueOption = outerEnumDefaultValue; + OuterEnumIntegerOption = outerEnumInteger; + OuterEnumIntegerDefaultValueOption = outerEnumIntegerDefaultValue; OnCreated(); } partial void OnCreated(); + /// + /// Defines EnumStringRequired + /// + public enum EnumStringRequiredEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return EnumStringRequiredEnum.UPPER; + + if (value.Equals("lower")) + return EnumStringRequiredEnum.Lower; + + if (value.Equals("")) + return EnumStringRequiredEnum.Empty; + + if (value.Equals("Value\twith tab")) + return EnumStringRequiredEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return EnumStringRequiredEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return EnumStringRequiredEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return EnumStringRequiredEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) + { + if (value == EnumStringRequiredEnum.UPPER) + return "UPPER"; + + if (value == EnumStringRequiredEnum.Lower) + return "lower"; + + if (value == EnumStringRequiredEnum.Empty) + return ""; + + if (value == EnumStringRequiredEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == EnumStringRequiredEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == EnumStringRequiredEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == EnumStringRequiredEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets EnumStringRequired + /// + [JsonPropertyName("enum_string_required")] + public EnumStringRequiredEnum EnumStringRequired { get; set; } + /// /// Defines EnumInteger /// @@ -116,11 +273,18 @@ public static int EnumIntegerEnumToJsonValue(EnumIntegerEnum value) return (int) value; } + /// + /// Used to track the state of EnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOption { get; private set; } + /// /// Gets or Sets EnumInteger /// [JsonPropertyName("enum_integer")] - public EnumIntegerEnum EnumInteger { get; set; } + public EnumIntegerEnum? EnumInteger { get { return this.EnumIntegerOption; } set { this.EnumIntegerOption = new Option(value); } } /// /// Defines EnumIntegerOnly @@ -181,11 +345,18 @@ public static int EnumIntegerOnlyEnumToJsonValue(EnumIntegerOnlyEnum value) return (int) value; } + /// + /// Used to track the state of EnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumIntegerOnlyOption { get; private set; } + /// /// Gets or Sets EnumIntegerOnly /// [JsonPropertyName("enum_integer_only")] - public EnumIntegerOnlyEnum EnumIntegerOnly { get; set; } + public EnumIntegerOnlyEnum? EnumIntegerOnly { get { return this.EnumIntegerOnlyOption; } set { this.EnumIntegerOnlyOption = new Option(value); } } /// /// Defines EnumNumber @@ -242,7 +413,7 @@ public static EnumNumberEnum EnumNumberEnumFromString(string value) /// /// /// - public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) + public static double EnumNumberEnumToJsonValue(EnumNumberEnum? value) { if (value == EnumNumberEnum.NUMBER_1_DOT_1) return 1.1; @@ -253,11 +424,18 @@ public static double EnumNumberEnumToJsonValue(EnumNumberEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of EnumNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumNumberOption { get; private set; } + /// /// Gets or Sets EnumNumber /// [JsonPropertyName("enum_number")] - public EnumNumberEnum EnumNumber { get; set; } + public EnumNumberEnum? EnumNumber { get { return this.EnumNumberOption; } set { this.EnumNumberOption = new Option(value); } } /// /// Defines EnumString @@ -380,7 +558,7 @@ public static EnumStringEnum EnumStringEnumFromString(string value) /// /// /// - public static string EnumStringEnumToJsonValue(EnumStringEnum value) + public static string EnumStringEnumToJsonValue(EnumStringEnum? value) { if (value == EnumStringEnum.UPPER) return "UPPER"; @@ -410,190 +588,69 @@ public static string EnumStringEnumToJsonValue(EnumStringEnum value) } /// - /// Gets or Sets EnumString + /// Used to track the state of EnumString /// - [JsonPropertyName("enum_string")] - public EnumStringEnum EnumString { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EnumStringOption { get; private set; } /// - /// Defines EnumStringRequired + /// Gets or Sets EnumString /// - public enum EnumStringRequiredEnum - { - /// - /// Enum UPPER for value: UPPER - /// - UPPER = 1, - - /// - /// Enum Lower for value: lower - /// - Lower = 2, - - /// - /// Enum Empty for value: - /// - Empty = 3, - - /// - /// Enum ValuewithTab for value: Value\twith tab - /// - ValuewithTab = 4, - - /// - /// Enum ValueWithQuote for value: Value with \" quote - /// - ValueWithQuote = 5, - - /// - /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote - /// - ValueWithEscapedQuote = 6, - - /// - /// Enum Duplicatevalue for value: Duplicate\nvalue - /// - Duplicatevalue = 7, - - /// - /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue - /// - Duplicatevalue2 = 8 - } + [JsonPropertyName("enum_string")] + public EnumStringEnum? EnumString { get { return this.EnumStringOption; } set { this.EnumStringOption = new Option(value); } } /// - /// Returns a + /// Used to track the state of OuterEnum /// - /// - /// - /// - public static EnumStringRequiredEnum EnumStringRequiredEnumFromString(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - throw new NotImplementedException($"Could not convert value to type EnumStringRequiredEnum: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumOption { get; private set; } /// - /// Returns a + /// Gets or Sets OuterEnum /// - /// - /// - public static EnumStringRequiredEnum? EnumStringRequiredEnumFromStringOrDefault(string value) - { - if (value.Equals("UPPER")) - return EnumStringRequiredEnum.UPPER; - - if (value.Equals("lower")) - return EnumStringRequiredEnum.Lower; - - if (value.Equals("")) - return EnumStringRequiredEnum.Empty; - - if (value.Equals("Value\twith tab")) - return EnumStringRequiredEnum.ValuewithTab; - - if (value.Equals("Value with \" quote")) - return EnumStringRequiredEnum.ValueWithQuote; - - if (value.Equals("Value with escaped \" quote")) - return EnumStringRequiredEnum.ValueWithEscapedQuote; - - if (value.Equals("Duplicate\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue; - - if (value.Equals("Duplicate\r\nvalue")) - return EnumStringRequiredEnum.Duplicatevalue2; - - return null; - } + [JsonPropertyName("outerEnum")] + public OuterEnum? OuterEnum { get { return this.OuterEnumOption; } set { this.OuterEnumOption = new Option(value); } } /// - /// Converts the to the json value + /// Used to track the state of OuterEnumDefaultValue /// - /// - /// - /// - public static string EnumStringRequiredEnumToJsonValue(EnumStringRequiredEnum value) - { - if (value == EnumStringRequiredEnum.UPPER) - return "UPPER"; - - if (value == EnumStringRequiredEnum.Lower) - return "lower"; - - if (value == EnumStringRequiredEnum.Empty) - return ""; - - if (value == EnumStringRequiredEnum.ValuewithTab) - return "Value\twith tab"; - - if (value == EnumStringRequiredEnum.ValueWithQuote) - return "Value with \" quote"; - - if (value == EnumStringRequiredEnum.ValueWithEscapedQuote) - return "Value with escaped \" quote"; - - if (value == EnumStringRequiredEnum.Duplicatevalue) - return "Duplicate\nvalue"; - - if (value == EnumStringRequiredEnum.Duplicatevalue2) - return "Duplicate\r\nvalue"; - - throw new NotImplementedException($"Value could not be handled: '{value}'"); - } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumDefaultValueOption { get; private set; } /// - /// Gets or Sets EnumStringRequired + /// Gets or Sets OuterEnumDefaultValue /// - [JsonPropertyName("enum_string_required")] - public EnumStringRequiredEnum EnumStringRequired { get; set; } + [JsonPropertyName("outerEnumDefaultValue")] + public OuterEnumDefaultValue? OuterEnumDefaultValue { get { return this.OuterEnumDefaultValueOption; } set { this.OuterEnumDefaultValueOption = new Option(value); } } /// - /// Gets or Sets OuterEnumDefaultValue + /// Used to track the state of OuterEnumInteger /// - [JsonPropertyName("outerEnumDefaultValue")] - public OuterEnumDefaultValue OuterEnumDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerOption { get; private set; } /// /// Gets or Sets OuterEnumInteger /// [JsonPropertyName("outerEnumInteger")] - public OuterEnumInteger OuterEnumInteger { get; set; } + public OuterEnumInteger? OuterEnumInteger { get { return this.OuterEnumIntegerOption; } set { this.OuterEnumIntegerOption = new Option(value); } } /// - /// Gets or Sets OuterEnumIntegerDefaultValue + /// Used to track the state of OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnumIntegerDefaultValue")] - public OuterEnumIntegerDefaultValue OuterEnumIntegerDefaultValue { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option OuterEnumIntegerDefaultValueOption { get; private set; } /// - /// Gets or Sets OuterEnum + /// Gets or Sets OuterEnumIntegerDefaultValue /// - [JsonPropertyName("outerEnum")] - public OuterEnum? OuterEnum { get; set; } + [JsonPropertyName("outerEnumIntegerDefaultValue")] + public OuterEnumIntegerDefaultValue? OuterEnumIntegerDefaultValue { get { return this.OuterEnumIntegerDefaultValueOption; } set { this.OuterEnumIntegerDefaultValueOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -609,15 +666,15 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class EnumTest {\n"); + sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); sb.Append(" EnumInteger: ").Append(EnumInteger).Append("\n"); sb.Append(" EnumIntegerOnly: ").Append(EnumIntegerOnly).Append("\n"); sb.Append(" EnumNumber: ").Append(EnumNumber).Append("\n"); sb.Append(" EnumString: ").Append(EnumString).Append("\n"); - sb.Append(" EnumStringRequired: ").Append(EnumStringRequired).Append("\n"); + sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" OuterEnumDefaultValue: ").Append(OuterEnumDefaultValue).Append("\n"); sb.Append(" OuterEnumInteger: ").Append(OuterEnumInteger).Append("\n"); sb.Append(" OuterEnumIntegerDefaultValue: ").Append(OuterEnumIntegerDefaultValue).Append("\n"); - sb.Append(" OuterEnum: ").Append(OuterEnum).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -656,15 +713,15 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - EnumTest.EnumIntegerEnum? enumInteger = default; - EnumTest.EnumIntegerOnlyEnum? enumIntegerOnly = default; - EnumTest.EnumNumberEnum? enumNumber = default; - EnumTest.EnumStringEnum? enumString = default; - EnumTest.EnumStringRequiredEnum? enumStringRequired = default; - OuterEnumDefaultValue? outerEnumDefaultValue = default; - OuterEnumInteger? outerEnumInteger = default; - OuterEnumIntegerDefaultValue? outerEnumIntegerDefaultValue = default; - OuterEnum? outerEnum = default; + Option enumStringRequired = default; + Option enumInteger = default; + Option enumIntegerOnly = default; + Option enumNumber = default; + Option enumString = default; + Option outerEnum = default; + Option outerEnumDefaultValue = default; + Option outerEnumInteger = default; + Option outerEnumIntegerDefaultValue = default; while (utf8JsonReader.Read()) { @@ -681,53 +738,47 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { + case "enum_string_required": + string enumStringRequiredRawValue = utf8JsonReader.GetString(); + if (enumStringRequiredRawValue != null) + enumStringRequired = new Option(EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue)); + break; case "enum_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumInteger = (EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32(); + enumInteger = new Option((EnumTest.EnumIntegerEnum)utf8JsonReader.GetInt32()); break; case "enum_integer_only": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumIntegerOnly = (EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32(); + enumIntegerOnly = new Option((EnumTest.EnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); break; case "enum_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - enumNumber = (EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32(); + enumNumber = new Option((EnumTest.EnumNumberEnum)utf8JsonReader.GetInt32()); break; case "enum_string": string enumStringRawValue = utf8JsonReader.GetString(); - enumString = enumStringRawValue == null - ? null - : EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue); + if (enumStringRawValue != null) + enumString = new Option(EnumTest.EnumStringEnumFromStringOrDefault(enumStringRawValue)); break; - case "enum_string_required": - string enumStringRequiredRawValue = utf8JsonReader.GetString(); - enumStringRequired = enumStringRequiredRawValue == null - ? null - : EnumTest.EnumStringRequiredEnumFromStringOrDefault(enumStringRequiredRawValue); + case "outerEnum": + string outerEnumRawValue = utf8JsonReader.GetString(); + if (outerEnumRawValue != null) + outerEnum = new Option(OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue)); break; case "outerEnumDefaultValue": string outerEnumDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumDefaultValue = outerEnumDefaultValueRawValue == null - ? null - : OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue); + if (outerEnumDefaultValueRawValue != null) + outerEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(outerEnumDefaultValueRawValue)); break; case "outerEnumInteger": string outerEnumIntegerRawValue = utf8JsonReader.GetString(); - outerEnumInteger = outerEnumIntegerRawValue == null - ? null - : OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue); + if (outerEnumIntegerRawValue != null) + outerEnumInteger = new Option(OuterEnumIntegerValueConverter.FromStringOrDefault(outerEnumIntegerRawValue)); break; case "outerEnumIntegerDefaultValue": string outerEnumIntegerDefaultValueRawValue = utf8JsonReader.GetString(); - outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValueRawValue == null - ? null - : OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue); - break; - case "outerEnum": - string outerEnumRawValue = utf8JsonReader.GetString(); - outerEnum = outerEnumRawValue == null - ? null - : OuterEnumValueConverter.FromStringOrDefault(outerEnumRawValue); + if (outerEnumIntegerDefaultValueRawValue != null) + outerEnumIntegerDefaultValue = new Option(OuterEnumIntegerDefaultValueValueConverter.FromStringOrDefault(outerEnumIntegerDefaultValueRawValue)); break; default: break; @@ -735,31 +786,34 @@ public override EnumTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (enumInteger == null) - throw new ArgumentNullException(nameof(enumInteger), "Property is required for class EnumTest."); + if (!enumStringRequired.IsSet) + throw new ArgumentException("Property is required for class EnumTest.", nameof(enumStringRequired)); + + if (enumStringRequired.IsSet && enumStringRequired.Value == null) + throw new ArgumentNullException(nameof(enumStringRequired), "Property is not nullable for class EnumTest."); - if (enumIntegerOnly == null) - throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is required for class EnumTest."); + if (enumInteger.IsSet && enumInteger.Value == null) + throw new ArgumentNullException(nameof(enumInteger), "Property is not nullable for class EnumTest."); - if (enumNumber == null) - throw new ArgumentNullException(nameof(enumNumber), "Property is required for class EnumTest."); + if (enumIntegerOnly.IsSet && enumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(enumIntegerOnly), "Property is not nullable for class EnumTest."); - if (enumString == null) - throw new ArgumentNullException(nameof(enumString), "Property is required for class EnumTest."); + if (enumNumber.IsSet && enumNumber.Value == null) + throw new ArgumentNullException(nameof(enumNumber), "Property is not nullable for class EnumTest."); - if (enumStringRequired == null) - throw new ArgumentNullException(nameof(enumStringRequired), "Property is required for class EnumTest."); + if (enumString.IsSet && enumString.Value == null) + throw new ArgumentNullException(nameof(enumString), "Property is not nullable for class EnumTest."); - if (outerEnumDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is required for class EnumTest."); + if (outerEnumDefaultValue.IsSet && outerEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumDefaultValue), "Property is not nullable for class EnumTest."); - if (outerEnumInteger == null) - throw new ArgumentNullException(nameof(outerEnumInteger), "Property is required for class EnumTest."); + if (outerEnumInteger.IsSet && outerEnumInteger.Value == null) + throw new ArgumentNullException(nameof(outerEnumInteger), "Property is not nullable for class EnumTest."); - if (outerEnumIntegerDefaultValue == null) - throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is required for class EnumTest."); + if (outerEnumIntegerDefaultValue.IsSet && outerEnumIntegerDefaultValue.Value == null) + throw new ArgumentNullException(nameof(outerEnumIntegerDefaultValue), "Property is not nullable for class EnumTest."); - return new EnumTest(enumInteger.Value, enumIntegerOnly.Value, enumNumber.Value, enumString.Value, enumStringRequired.Value, outerEnumDefaultValue.Value, outerEnumInteger.Value, outerEnumIntegerDefaultValue.Value, outerEnum); + return new EnumTest(enumStringRequired.Value.Value, enumInteger, enumIntegerOnly, enumNumber, enumString, outerEnum, outerEnumDefaultValue, outerEnumInteger, outerEnumIntegerDefaultValue); } /// @@ -786,43 +840,41 @@ public override void Write(Utf8JsonWriter writer, EnumTest enumTest, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, EnumTest enumTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumInteger)); - writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnly)); - writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumber)); - - var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumString); - if (enumStringRawValue != null) - writer.WriteString("enum_string", enumStringRawValue); - else - writer.WriteNull("enum_string"); - var enumStringRequiredRawValue = EnumTest.EnumStringRequiredEnumToJsonValue(enumTest.EnumStringRequired); - if (enumStringRequiredRawValue != null) - writer.WriteString("enum_string_required", enumStringRequiredRawValue); - else - writer.WriteNull("enum_string_required"); + writer.WriteString("enum_string_required", enumStringRequiredRawValue); + if (enumTest.EnumIntegerOption.IsSet) + writer.WriteNumber("enum_integer", EnumTest.EnumIntegerEnumToJsonValue(enumTest.EnumIntegerOption.Value.Value)); - var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue); + if (enumTest.EnumIntegerOnlyOption.IsSet) + writer.WriteNumber("enum_integer_only", EnumTest.EnumIntegerOnlyEnumToJsonValue(enumTest.EnumIntegerOnlyOption.Value.Value)); - if (outerEnumDefaultValueRawValue != null) - writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); - else - writer.WriteNull("outerEnumDefaultValue"); - - var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger); - writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); - var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue); - writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); + if (enumTest.EnumNumberOption.IsSet) + writer.WriteNumber("enum_number", EnumTest.EnumNumberEnumToJsonValue(enumTest.EnumNumberOption.Value.Value)); - if (enumTest.OuterEnum == null) - writer.WriteNull("outerEnum"); - else - { - var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnum.Value); - if (outerEnumRawValue != null) + var enumStringRawValue = EnumTest.EnumStringEnumToJsonValue(enumTest.EnumStringOption.Value.Value); + writer.WriteString("enum_string", enumStringRawValue); + if (enumTest.OuterEnumOption.IsSet) + if (enumTest.OuterEnumOption.Value != null) + { + var outerEnumRawValue = OuterEnumValueConverter.ToJsonValue(enumTest.OuterEnumOption.Value.Value); writer.WriteString("outerEnum", outerEnumRawValue); + } else writer.WriteNull("outerEnum"); + if (enumTest.OuterEnumDefaultValueOption.IsSet) + { + var outerEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumDefaultValue.Value); + writer.WriteString("outerEnumDefaultValue", outerEnumDefaultValueRawValue); + } + if (enumTest.OuterEnumIntegerOption.IsSet) + { + var outerEnumIntegerRawValue = OuterEnumIntegerValueConverter.ToJsonValue(enumTest.OuterEnumInteger.Value); + writer.WriteNumber("outerEnumInteger", outerEnumIntegerRawValue); + } + if (enumTest.OuterEnumIntegerDefaultValueOption.IsSet) + { + var outerEnumIntegerDefaultValueRawValue = OuterEnumIntegerDefaultValueValueConverter.ToJsonValue(enumTest.OuterEnumIntegerDefaultValue.Value); + writer.WriteNumber("outerEnumIntegerDefaultValue", outerEnumIntegerDefaultValueRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs index 626748ff2097..bbf4bf8f8e09 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/EquilateralTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override EquilateralTriangle Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class EquilateralTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class EquilateralTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class EquilateralTriangle.", nameof(triangleType)); - return new EquilateralTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class EquilateralTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class EquilateralTriangle."); + + return new EquilateralTriangle(shapeType.Value, triangleType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, EquilateralTriangle equilatera /// public void WriteProperties(ref Utf8JsonWriter writer, EquilateralTriangle equilateralTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (equilateralTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.ShapeType), "Property is required for class EquilateralTriangle."); + + if (equilateralTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(equilateralTriangle.TriangleType), "Property is required for class EquilateralTriangle."); + writer.WriteString("shapeType", equilateralTriangle.ShapeType); + writer.WriteString("triangleType", equilateralTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs index 905e5452f7c0..213451addd45 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/File.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class File : IValidatableObject /// /// Test capitalization [JsonConstructor] - public File(string sourceURI) + public File(Option sourceURI = default) { - SourceURI = sourceURI; + SourceURIOption = sourceURI; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SourceURI + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SourceURIOption { get; private set; } + /// /// Test capitalization /// /// Test capitalization [JsonPropertyName("sourceURI")] - public string SourceURI { get; set; } + public string SourceURI { get { return this. SourceURIOption; } set { this.SourceURIOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -101,7 +109,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string sourceURI = default; + Option sourceURI = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "sourceURI": - sourceURI = utf8JsonReader.GetString(); + sourceURI = new Option(utf8JsonReader.GetString()); break; default: break; @@ -127,8 +135,8 @@ public override File Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (sourceURI == null) - throw new ArgumentNullException(nameof(sourceURI), "Property is required for class File."); + if (sourceURI.IsSet && sourceURI.Value == null) + throw new ArgumentNullException(nameof(sourceURI), "Property is not nullable for class File."); return new File(sourceURI); } @@ -157,7 +165,11 @@ public override void Write(Utf8JsonWriter writer, File file, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, File file, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("sourceURI", file.SourceURI); + if (file.SourceURIOption.IsSet && file.SourceURI == null) + throw new ArgumentNullException(nameof(file.SourceURI), "Property is required for class File."); + + if (file.SourceURIOption.IsSet) + writer.WriteString("sourceURI", file.SourceURI); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs index 722ba3b949f0..525183c27c96 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FileSchemaTestClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class FileSchemaTestClass : IValidatableObject /// file /// files [JsonConstructor] - public FileSchemaTestClass(File file, List files) + public FileSchemaTestClass(Option file = default, Option> files = default) { - File = file; - Files = files; + FileOption = file; + FilesOption = files; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of File + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FileOption { get; private set; } + /// /// Gets or Sets File /// [JsonPropertyName("file")] - public File File { get; set; } + public File File { get { return this. FileOption; } set { this.FileOption = new Option(value); } } + + /// + /// Used to track the state of Files + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> FilesOption { get; private set; } /// /// Gets or Sets Files /// [JsonPropertyName("files")] - public List Files { get; set; } + public List Files { get { return this. FilesOption; } set { this.FilesOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - File file = default; - List files = default; + Option file = default; + Option> files = default; while (utf8JsonReader.Read()) { @@ -129,11 +144,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "file": if (utf8JsonReader.TokenType != JsonTokenType.Null) - file = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + file = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "files": if (utf8JsonReader.TokenType != JsonTokenType.Null) - files = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + files = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -141,11 +156,11 @@ public override FileSchemaTestClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (file == null) - throw new ArgumentNullException(nameof(file), "Property is required for class FileSchemaTestClass."); + if (file.IsSet && file.Value == null) + throw new ArgumentNullException(nameof(file), "Property is not nullable for class FileSchemaTestClass."); - if (files == null) - throw new ArgumentNullException(nameof(files), "Property is required for class FileSchemaTestClass."); + if (files.IsSet && files.Value == null) + throw new ArgumentNullException(nameof(files), "Property is not nullable for class FileSchemaTestClass."); return new FileSchemaTestClass(file, files); } @@ -174,10 +189,22 @@ public override void Write(Utf8JsonWriter writer, FileSchemaTestClass fileSchema /// public void WriteProperties(ref Utf8JsonWriter writer, FileSchemaTestClass fileSchemaTestClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("file"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); - writer.WritePropertyName("files"); - JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + if (fileSchemaTestClass.FileOption.IsSet && fileSchemaTestClass.File == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.File), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FilesOption.IsSet && fileSchemaTestClass.Files == null) + throw new ArgumentNullException(nameof(fileSchemaTestClass.Files), "Property is required for class FileSchemaTestClass."); + + if (fileSchemaTestClass.FileOption.IsSet) + { + writer.WritePropertyName("file"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.File, jsonSerializerOptions); + } + if (fileSchemaTestClass.FilesOption.IsSet) + { + writer.WritePropertyName("files"); + JsonSerializer.Serialize(writer, fileSchemaTestClass.Files, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs index 9cfe3b508fe8..f4b99d158e8b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Foo.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Foo : IValidatableObject /// /// bar (default to "bar") [JsonConstructor] - public Foo(string bar = @"bar") + public Foo(Option bar = default) { - Bar = bar; + BarOption = bar; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; private set; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; set; } + public string Bar { get { return this. BarOption; } set { this.BarOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; + Option bar = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override Foo Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class Foo."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class Foo."); return new Foo(bar); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, Foo foo, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Foo foo, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", foo.Bar); + if (foo.BarOption.IsSet && foo.Bar == null) + throw new ArgumentNullException(nameof(foo.Bar), "Property is required for class Foo."); + + if (foo.BarOption.IsSet) + writer.WriteString("bar", foo.Bar); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs index c8291e8eae5b..7e6890ba3bf8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FooGetDefaultResponse.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class FooGetDefaultResponse : IValidatableObject /// /// varString [JsonConstructor] - public FooGetDefaultResponse(Foo varString) + public FooGetDefaultResponse(Option varString = default) { - VarString = varString; + VarStringOption = varString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } + /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public Foo VarString { get; set; } + public Foo VarString { get { return this. VarStringOption; } set { this.VarStringOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Foo varString = default; + Option varString = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty { case "string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varString = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varString = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override FooGetDefaultResponse Read(ref Utf8JsonReader utf8JsonReader, Ty } } - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FooGetDefaultResponse."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FooGetDefaultResponse."); return new FooGetDefaultResponse(varString); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, FooGetDefaultResponse fooGetDe /// public void WriteProperties(ref Utf8JsonWriter writer, FooGetDefaultResponse fooGetDefaultResponse, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("string"); - JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + if (fooGetDefaultResponse.VarStringOption.IsSet && fooGetDefaultResponse.VarString == null) + throw new ArgumentNullException(nameof(fooGetDefaultResponse.VarString), "Property is required for class FooGetDefaultResponse."); + + if (fooGetDefaultResponse.VarStringOption.IsSet) + { + writer.WritePropertyName("string"); + JsonSerializer.Serialize(writer, fooGetDefaultResponse.VarString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs index 30a9b189932a..29eff0cd769f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,9 +32,11 @@ public partial class FormatTest : IValidatableObject /// /// Initializes a new instance of the class. /// - /// binary /// varByte /// date + /// number + /// password + /// binary /// dateTime /// varDecimal /// varDouble @@ -41,8 +44,6 @@ public partial class FormatTest : IValidatableObject /// int32 /// int64 /// integer - /// number - /// password /// None /// A string that is a 10 digit number. Can have leading zeros. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. @@ -51,38 +52,32 @@ public partial class FormatTest : IValidatableObject /// unsignedLong /// uuid [JsonConstructor] - public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTime dateTime, decimal varDecimal, double varDouble, float varFloat, int int32, long int64, int integer, decimal number, string password, string patternWithBackslash, string patternWithDigits, string patternWithDigitsAndDelimiter, string varString, uint unsignedInteger, ulong unsignedLong, Guid uuid) + public FormatTest(byte[] varByte, DateTime date, decimal number, string password, Option binary = default, Option dateTime = default, Option varDecimal = default, Option varDouble = default, Option varFloat = default, Option int32 = default, Option int64 = default, Option integer = default, Option patternWithBackslash = default, Option patternWithDigits = default, Option patternWithDigitsAndDelimiter = default, Option varString = default, Option unsignedInteger = default, Option unsignedLong = default, Option uuid = default) { - Binary = binary; VarByte = varByte; Date = date; - DateTime = dateTime; - VarDecimal = varDecimal; - VarDouble = varDouble; - VarFloat = varFloat; - Int32 = int32; - Int64 = int64; - Integer = integer; Number = number; Password = password; - PatternWithBackslash = patternWithBackslash; - PatternWithDigits = patternWithDigits; - PatternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; - VarString = varString; - UnsignedInteger = unsignedInteger; - UnsignedLong = unsignedLong; - Uuid = uuid; + BinaryOption = binary; + DateTimeOption = dateTime; + VarDecimalOption = varDecimal; + VarDoubleOption = varDouble; + VarFloatOption = varFloat; + Int32Option = int32; + Int64Option = int64; + IntegerOption = integer; + PatternWithBackslashOption = patternWithBackslash; + PatternWithDigitsOption = patternWithDigits; + PatternWithDigitsAndDelimiterOption = patternWithDigitsAndDelimiter; + VarStringOption = varString; + UnsignedIntegerOption = unsignedInteger; + UnsignedLongOption = unsignedLong; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); - /// - /// Gets or Sets Binary - /// - [JsonPropertyName("binary")] - public System.IO.Stream Binary { get; set; } - /// /// Gets or Sets VarByte /// @@ -96,106 +91,217 @@ public FormatTest(System.IO.Stream binary, byte[] varByte, DateTime date, DateTi [JsonPropertyName("date")] public DateTime Date { get; set; } + /// + /// Gets or Sets Number + /// + [JsonPropertyName("number")] + public decimal Number { get; set; } + + /// + /// Gets or Sets Password + /// + [JsonPropertyName("password")] + public string Password { get; set; } + + /// + /// Used to track the state of Binary + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BinaryOption { get; private set; } + + /// + /// Gets or Sets Binary + /// + [JsonPropertyName("binary")] + public System.IO.Stream Binary { get { return this. BinaryOption; } set { this.BinaryOption = new Option(value); } } + + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } + /// /// Gets or Sets DateTime /// /// 2007-12-03T10:15:30+01:00 [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new Option(value); } } + + /// + /// Used to track the state of VarDecimal + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDecimalOption { get; private set; } /// /// Gets or Sets VarDecimal /// [JsonPropertyName("decimal")] - public decimal VarDecimal { get; set; } + public decimal? VarDecimal { get { return this. VarDecimalOption; } set { this.VarDecimalOption = new Option(value); } } + + /// + /// Used to track the state of VarDouble + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarDoubleOption { get; private set; } /// /// Gets or Sets VarDouble /// [JsonPropertyName("double")] - public double VarDouble { get; set; } + public double? VarDouble { get { return this. VarDoubleOption; } set { this.VarDoubleOption = new Option(value); } } + + /// + /// Used to track the state of VarFloat + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarFloatOption { get; private set; } /// /// Gets or Sets VarFloat /// [JsonPropertyName("float")] - public float VarFloat { get; set; } + public float? VarFloat { get { return this. VarFloatOption; } set { this.VarFloatOption = new Option(value); } } + + /// + /// Used to track the state of Int32 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int32Option { get; private set; } /// /// Gets or Sets Int32 /// [JsonPropertyName("int32")] - public int Int32 { get; set; } + public int? Int32 { get { return this. Int32Option; } set { this.Int32Option = new Option(value); } } + + /// + /// Used to track the state of Int64 + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Int64Option { get; private set; } /// /// Gets or Sets Int64 /// [JsonPropertyName("int64")] - public long Int64 { get; set; } + public long? Int64 { get { return this. Int64Option; } set { this.Int64Option = new Option(value); } } /// - /// Gets or Sets Integer + /// Used to track the state of Integer /// - [JsonPropertyName("integer")] - public int Integer { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerOption { get; private set; } /// - /// Gets or Sets Number + /// Gets or Sets Integer /// - [JsonPropertyName("number")] - public decimal Number { get; set; } + [JsonPropertyName("integer")] + public int? Integer { get { return this. IntegerOption; } set { this.IntegerOption = new Option(value); } } /// - /// Gets or Sets Password + /// Used to track the state of PatternWithBackslash /// - [JsonPropertyName("password")] - public string Password { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithBackslashOption { get; private set; } /// /// None /// /// None [JsonPropertyName("pattern_with_backslash")] - public string PatternWithBackslash { get; set; } + public string PatternWithBackslash { get { return this. PatternWithBackslashOption; } set { this.PatternWithBackslashOption = new Option(value); } } + + /// + /// Used to track the state of PatternWithDigits + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsOption { get; private set; } /// /// A string that is a 10 digit number. Can have leading zeros. /// /// A string that is a 10 digit number. Can have leading zeros. [JsonPropertyName("pattern_with_digits")] - public string PatternWithDigits { get; set; } + public string PatternWithDigits { get { return this. PatternWithDigitsOption; } set { this.PatternWithDigitsOption = new Option(value); } } + + /// + /// Used to track the state of PatternWithDigitsAndDelimiter + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PatternWithDigitsAndDelimiterOption { get; private set; } /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. /// /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01. [JsonPropertyName("pattern_with_digits_and_delimiter")] - public string PatternWithDigitsAndDelimiter { get; set; } + public string PatternWithDigitsAndDelimiter { get { return this. PatternWithDigitsAndDelimiterOption; } set { this.PatternWithDigitsAndDelimiterOption = new Option(value); } } + + /// + /// Used to track the state of VarString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarStringOption { get; private set; } /// /// Gets or Sets VarString /// [JsonPropertyName("string")] - public string VarString { get; set; } + public string VarString { get { return this. VarStringOption; } set { this.VarStringOption = new Option(value); } } + + /// + /// Used to track the state of UnsignedInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedIntegerOption { get; private set; } /// /// Gets or Sets UnsignedInteger /// [JsonPropertyName("unsigned_integer")] - public uint UnsignedInteger { get; set; } + public uint? UnsignedInteger { get { return this. UnsignedIntegerOption; } set { this.UnsignedIntegerOption = new Option(value); } } + + /// + /// Used to track the state of UnsignedLong + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnsignedLongOption { get; private set; } /// /// Gets or Sets UnsignedLong /// [JsonPropertyName("unsigned_long")] - public ulong UnsignedLong { get; set; } + public ulong? UnsignedLong { get { return this. UnsignedLongOption; } set { this.UnsignedLongOption = new Option(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -211,9 +317,11 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class FormatTest {\n"); - sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" VarByte: ").Append(VarByte).Append("\n"); sb.Append(" Date: ").Append(Date).Append("\n"); + sb.Append(" Number: ").Append(Number).Append("\n"); + sb.Append(" Password: ").Append(Password).Append("\n"); + sb.Append(" Binary: ").Append(Binary).Append("\n"); sb.Append(" DateTime: ").Append(DateTime).Append("\n"); sb.Append(" VarDecimal: ").Append(VarDecimal).Append("\n"); sb.Append(" VarDouble: ").Append(VarDouble).Append("\n"); @@ -221,8 +329,6 @@ public override string ToString() sb.Append(" Int32: ").Append(Int32).Append("\n"); sb.Append(" Int64: ").Append(Int64).Append("\n"); sb.Append(" Integer: ").Append(Integer).Append("\n"); - sb.Append(" Number: ").Append(Number).Append("\n"); - sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" PatternWithBackslash: ").Append(PatternWithBackslash).Append("\n"); sb.Append(" PatternWithDigits: ").Append(PatternWithDigits).Append("\n"); sb.Append(" PatternWithDigitsAndDelimiter: ").Append(PatternWithDigitsAndDelimiter).Append("\n"); @@ -242,122 +348,126 @@ public override string ToString() /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) { + // Number (decimal) maximum + if (this.Number > (decimal)543.2) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); + } + + // Number (decimal) minimum + if (this.Number < (decimal)32.1) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); + } + + // Password (string) maxLength + if (this.Password != null && this.Password.Length > 64) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); + } + + // Password (string) minLength + if (this.Password != null && this.Password.Length < 10) + { + yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); + } + // VarDouble (double) maximum - if (this.VarDouble > (double)123.4) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value > (double)123.4) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value less than or equal to 123.4.", new [] { "VarDouble" }); } // VarDouble (double) minimum - if (this.VarDouble < (double)67.8) + if (this.VarDoubleOption.IsSet && this.VarDoubleOption.Value < (double)67.8) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarDouble, must be a value greater than or equal to 67.8.", new [] { "VarDouble" }); } // VarFloat (float) maximum - if (this.VarFloat > (float)987.6) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value > (float)987.6) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value less than or equal to 987.6.", new [] { "VarFloat" }); } // VarFloat (float) minimum - if (this.VarFloat < (float)54.3) + if (this.VarFloatOption.IsSet && this.VarFloatOption.Value < (float)54.3) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarFloat, must be a value greater than or equal to 54.3.", new [] { "VarFloat" }); } // Int32 (int) maximum - if (this.Int32 > (int)200) + if (this.Int32Option.IsSet && this.Int32Option.Value > (int)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value less than or equal to 200.", new [] { "Int32" }); } // Int32 (int) minimum - if (this.Int32 < (int)20) + if (this.Int32Option.IsSet && this.Int32Option.Value < (int)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Int32, must be a value greater than or equal to 20.", new [] { "Int32" }); } // Integer (int) maximum - if (this.Integer > (int)100) + if (this.IntegerOption.IsSet && this.IntegerOption.Value > (int)100) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value less than or equal to 100.", new [] { "Integer" }); } // Integer (int) minimum - if (this.Integer < (int)10) + if (this.IntegerOption.IsSet && this.IntegerOption.Value < (int)10) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Integer, must be a value greater than or equal to 10.", new [] { "Integer" }); } - // Number (decimal) maximum - if (this.Number > (decimal)543.2) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value less than or equal to 543.2.", new [] { "Number" }); - } - - // Number (decimal) minimum - if (this.Number < (decimal)32.1) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Number, must be a value greater than or equal to 32.1.", new [] { "Number" }); - } - - // Password (string) maxLength - if (this.Password != null && this.Password.Length > 64) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be less than 64.", new [] { "Password" }); - } - - // Password (string) minLength - if (this.Password != null && this.Password.Length < 10) - { - yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for Password, length must be greater than 10.", new [] { "Password" }); - } - - if (this.PatternWithBackslash != null) { + if (this.PatternWithBackslashOption.Value != null) { // PatternWithBackslash (string) pattern Regex regexPatternWithBackslash = new Regex(@"^(([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))$", RegexOptions.CultureInvariant); - if (!regexPatternWithBackslash.Match(this.PatternWithBackslash).Success) + + if (this.PatternWithBackslashOption.Value != null &&!regexPatternWithBackslash.Match(this.PatternWithBackslashOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithBackslash, must match a pattern of " + regexPatternWithBackslash, new [] { "PatternWithBackslash" }); } } - if (this.PatternWithDigits != null) { + if (this.PatternWithDigitsOption.Value != null) { // PatternWithDigits (string) pattern Regex regexPatternWithDigits = new Regex(@"^\d{10}$", RegexOptions.CultureInvariant); - if (!regexPatternWithDigits.Match(this.PatternWithDigits).Success) + + if (this.PatternWithDigitsOption.Value != null &&!regexPatternWithDigits.Match(this.PatternWithDigitsOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigits, must match a pattern of " + regexPatternWithDigits, new [] { "PatternWithDigits" }); } } - if (this.PatternWithDigitsAndDelimiter != null) { + if (this.PatternWithDigitsAndDelimiterOption.Value != null) { // PatternWithDigitsAndDelimiter (string) pattern Regex regexPatternWithDigitsAndDelimiter = new Regex(@"^image_\d{1,3}$", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiter).Success) + + if (this.PatternWithDigitsAndDelimiterOption.Value != null &&!regexPatternWithDigitsAndDelimiter.Match(this.PatternWithDigitsAndDelimiterOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for PatternWithDigitsAndDelimiter, must match a pattern of " + regexPatternWithDigitsAndDelimiter, new [] { "PatternWithDigitsAndDelimiter" }); } } - if (this.VarString != null) { + if (this.VarStringOption.Value != null) { // VarString (string) pattern Regex regexVarString = new Regex(@"[a-z]", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase); - if (!regexVarString.Match(this.VarString).Success) + + if (this.VarStringOption.Value != null &&!regexVarString.Match(this.VarStringOption.Value).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for VarString, must match a pattern of " + regexVarString, new [] { "VarString" }); } } // UnsignedInteger (uint) maximum - if (this.UnsignedInteger > (uint)200) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value > (uint)200) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value less than or equal to 200.", new [] { "UnsignedInteger" }); } // UnsignedInteger (uint) minimum - if (this.UnsignedInteger < (uint)20) + if (this.UnsignedIntegerOption.IsSet && this.UnsignedIntegerOption.Value < (uint)20) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UnsignedInteger, must be a value greater than or equal to 20.", new [] { "UnsignedInteger" }); } @@ -398,25 +508,25 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - System.IO.Stream binary = default; - byte[] varByte = default; - DateTime? date = default; - DateTime? dateTime = default; - decimal? varDecimal = default; - double? varDouble = default; - float? varFloat = default; - int? int32 = default; - long? int64 = default; - int? integer = default; - decimal? number = default; - string password = default; - string patternWithBackslash = default; - string patternWithDigits = default; - string patternWithDigitsAndDelimiter = default; - string varString = default; - uint? unsignedInteger = default; - ulong? unsignedLong = default; - Guid? uuid = default; + Option varByte = default; + Option date = default; + Option number = default; + Option password = default; + Option binary = default; + Option dateTime = default; + Option varDecimal = default; + Option varDouble = default; + Option varFloat = default; + Option int32 = default; + Option int64 = default; + Option integer = default; + Option patternWithBackslash = default; + Option patternWithDigits = default; + Option patternWithDigitsAndDelimiter = default; + Option varString = default; + Option unsignedInteger = default; + Option unsignedLong = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -433,76 +543,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo switch (localVarJsonPropertyName) { - case "binary": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - binary = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; case "byte": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varByte = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varByte = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "date": if (utf8JsonReader.TokenType != JsonTokenType.Null) - date = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + date = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "number": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + number = new Option(utf8JsonReader.GetDecimal()); + break; + case "password": + password = new Option(utf8JsonReader.GetString()); + break; + case "binary": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + binary = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "decimal": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDecimal = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + varDecimal = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "double": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varDouble = utf8JsonReader.GetDouble(); + varDouble = new Option(utf8JsonReader.GetDouble()); break; case "float": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varFloat = (float)utf8JsonReader.GetDouble(); + varFloat = new Option((float)utf8JsonReader.GetDouble()); break; case "int32": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int32 = utf8JsonReader.GetInt32(); + int32 = new Option(utf8JsonReader.GetInt32()); break; case "int64": if (utf8JsonReader.TokenType != JsonTokenType.Null) - int64 = utf8JsonReader.GetInt64(); + int64 = new Option(utf8JsonReader.GetInt64()); break; case "integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integer = utf8JsonReader.GetInt32(); - break; - case "number": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - number = utf8JsonReader.GetDecimal(); - break; - case "password": - password = utf8JsonReader.GetString(); + integer = new Option(utf8JsonReader.GetInt32()); break; case "pattern_with_backslash": - patternWithBackslash = utf8JsonReader.GetString(); + patternWithBackslash = new Option(utf8JsonReader.GetString()); break; case "pattern_with_digits": - patternWithDigits = utf8JsonReader.GetString(); + patternWithDigits = new Option(utf8JsonReader.GetString()); break; case "pattern_with_digits_and_delimiter": - patternWithDigitsAndDelimiter = utf8JsonReader.GetString(); + patternWithDigitsAndDelimiter = new Option(utf8JsonReader.GetString()); break; case "string": - varString = utf8JsonReader.GetString(); + varString = new Option(utf8JsonReader.GetString()); break; case "unsigned_integer": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedInteger = utf8JsonReader.GetUInt32(); + unsignedInteger = new Option(utf8JsonReader.GetUInt32()); break; case "unsigned_long": if (utf8JsonReader.TokenType != JsonTokenType.Null) - unsignedLong = utf8JsonReader.GetUInt64(); + unsignedLong = new Option(utf8JsonReader.GetUInt64()); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -510,64 +620,76 @@ public override FormatTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (binary == null) - throw new ArgumentNullException(nameof(binary), "Property is required for class FormatTest."); + if (!varByte.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(varByte)); + + if (!date.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(date)); + + if (!number.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(number)); + + if (!password.IsSet) + throw new ArgumentException("Property is required for class FormatTest.", nameof(password)); - if (varByte == null) - throw new ArgumentNullException(nameof(varByte), "Property is required for class FormatTest."); + if (varByte.IsSet && varByte.Value == null) + throw new ArgumentNullException(nameof(varByte), "Property is not nullable for class FormatTest."); - if (date == null) - throw new ArgumentNullException(nameof(date), "Property is required for class FormatTest."); + if (date.IsSet && date.Value == null) + throw new ArgumentNullException(nameof(date), "Property is not nullable for class FormatTest."); - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class FormatTest."); + if (number.IsSet && number.Value == null) + throw new ArgumentNullException(nameof(number), "Property is not nullable for class FormatTest."); - if (varDecimal == null) - throw new ArgumentNullException(nameof(varDecimal), "Property is required for class FormatTest."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class FormatTest."); - if (varDouble == null) - throw new ArgumentNullException(nameof(varDouble), "Property is required for class FormatTest."); + if (binary.IsSet && binary.Value == null) + throw new ArgumentNullException(nameof(binary), "Property is not nullable for class FormatTest."); - if (varFloat == null) - throw new ArgumentNullException(nameof(varFloat), "Property is required for class FormatTest."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class FormatTest."); - if (int32 == null) - throw new ArgumentNullException(nameof(int32), "Property is required for class FormatTest."); + if (varDecimal.IsSet && varDecimal.Value == null) + throw new ArgumentNullException(nameof(varDecimal), "Property is not nullable for class FormatTest."); - if (int64 == null) - throw new ArgumentNullException(nameof(int64), "Property is required for class FormatTest."); + if (varDouble.IsSet && varDouble.Value == null) + throw new ArgumentNullException(nameof(varDouble), "Property is not nullable for class FormatTest."); - if (integer == null) - throw new ArgumentNullException(nameof(integer), "Property is required for class FormatTest."); + if (varFloat.IsSet && varFloat.Value == null) + throw new ArgumentNullException(nameof(varFloat), "Property is not nullable for class FormatTest."); - if (number == null) - throw new ArgumentNullException(nameof(number), "Property is required for class FormatTest."); + if (int32.IsSet && int32.Value == null) + throw new ArgumentNullException(nameof(int32), "Property is not nullable for class FormatTest."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class FormatTest."); + if (int64.IsSet && int64.Value == null) + throw new ArgumentNullException(nameof(int64), "Property is not nullable for class FormatTest."); - if (patternWithBackslash == null) - throw new ArgumentNullException(nameof(patternWithBackslash), "Property is required for class FormatTest."); + if (integer.IsSet && integer.Value == null) + throw new ArgumentNullException(nameof(integer), "Property is not nullable for class FormatTest."); - if (patternWithDigits == null) - throw new ArgumentNullException(nameof(patternWithDigits), "Property is required for class FormatTest."); + if (patternWithBackslash.IsSet && patternWithBackslash.Value == null) + throw new ArgumentNullException(nameof(patternWithBackslash), "Property is not nullable for class FormatTest."); - if (patternWithDigitsAndDelimiter == null) - throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + if (patternWithDigits.IsSet && patternWithDigits.Value == null) + throw new ArgumentNullException(nameof(patternWithDigits), "Property is not nullable for class FormatTest."); - if (varString == null) - throw new ArgumentNullException(nameof(varString), "Property is required for class FormatTest."); + if (patternWithDigitsAndDelimiter.IsSet && patternWithDigitsAndDelimiter.Value == null) + throw new ArgumentNullException(nameof(patternWithDigitsAndDelimiter), "Property is not nullable for class FormatTest."); - if (unsignedInteger == null) - throw new ArgumentNullException(nameof(unsignedInteger), "Property is required for class FormatTest."); + if (varString.IsSet && varString.Value == null) + throw new ArgumentNullException(nameof(varString), "Property is not nullable for class FormatTest."); - if (unsignedLong == null) - throw new ArgumentNullException(nameof(unsignedLong), "Property is required for class FormatTest."); + if (unsignedInteger.IsSet && unsignedInteger.Value == null) + throw new ArgumentNullException(nameof(unsignedInteger), "Property is not nullable for class FormatTest."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class FormatTest."); + if (unsignedLong.IsSet && unsignedLong.Value == null) + throw new ArgumentNullException(nameof(unsignedLong), "Property is not nullable for class FormatTest."); - return new FormatTest(binary, varByte, date.Value, dateTime.Value, varDecimal.Value, varDouble.Value, varFloat.Value, int32.Value, int64.Value, integer.Value, number.Value, password, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger.Value, unsignedLong.Value, uuid.Value); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class FormatTest."); + + return new FormatTest(varByte.Value, date.Value.Value, number.Value.Value, password.Value, binary, dateTime, varDecimal, varDouble, varFloat, int32, int64, integer, patternWithBackslash, patternWithDigits, patternWithDigitsAndDelimiter, varString, unsignedInteger, unsignedLong, uuid); } /// @@ -594,28 +716,83 @@ public override void Write(Utf8JsonWriter writer, FormatTest formatTest, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, FormatTest formatTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("binary"); - JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + if (formatTest.VarByte == null) + throw new ArgumentNullException(nameof(formatTest.VarByte), "Property is required for class FormatTest."); + + if (formatTest.Password == null) + throw new ArgumentNullException(nameof(formatTest.Password), "Property is required for class FormatTest."); + + if (formatTest.BinaryOption.IsSet && formatTest.Binary == null) + throw new ArgumentNullException(nameof(formatTest.Binary), "Property is required for class FormatTest."); + + if (formatTest.PatternWithBackslashOption.IsSet && formatTest.PatternWithBackslash == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithBackslash), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsOption.IsSet && formatTest.PatternWithDigits == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigits), "Property is required for class FormatTest."); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet && formatTest.PatternWithDigitsAndDelimiter == null) + throw new ArgumentNullException(nameof(formatTest.PatternWithDigitsAndDelimiter), "Property is required for class FormatTest."); + + if (formatTest.VarStringOption.IsSet && formatTest.VarString == null) + throw new ArgumentNullException(nameof(formatTest.VarString), "Property is required for class FormatTest."); + writer.WritePropertyName("byte"); JsonSerializer.Serialize(writer, formatTest.VarByte, jsonSerializerOptions); writer.WriteString("date", formatTest.Date.ToString(DateFormat)); - writer.WriteString("dateTime", formatTest.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("decimal"); - JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); - writer.WriteNumber("double", formatTest.VarDouble); - writer.WriteNumber("float", formatTest.VarFloat); - writer.WriteNumber("int32", formatTest.Int32); - writer.WriteNumber("int64", formatTest.Int64); - writer.WriteNumber("integer", formatTest.Integer); + writer.WriteNumber("number", formatTest.Number); + writer.WriteString("password", formatTest.Password); - writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); - writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); - writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); - writer.WriteString("string", formatTest.VarString); - writer.WriteNumber("unsigned_integer", formatTest.UnsignedInteger); - writer.WriteNumber("unsigned_long", formatTest.UnsignedLong); - writer.WriteString("uuid", formatTest.Uuid); + + if (formatTest.BinaryOption.IsSet) + { + writer.WritePropertyName("binary"); + JsonSerializer.Serialize(writer, formatTest.Binary, jsonSerializerOptions); + } + if (formatTest.DateTimeOption.IsSet) + writer.WriteString("dateTime", formatTest.DateTimeOption.Value.Value.ToString(DateTimeFormat)); + + if (formatTest.VarDecimalOption.IsSet) + { + writer.WritePropertyName("decimal"); + JsonSerializer.Serialize(writer, formatTest.VarDecimal, jsonSerializerOptions); + } + if (formatTest.VarDoubleOption.IsSet) + writer.WriteNumber("double", formatTest.VarDoubleOption.Value.Value); + + if (formatTest.VarFloatOption.IsSet) + writer.WriteNumber("float", formatTest.VarFloatOption.Value.Value); + + if (formatTest.Int32Option.IsSet) + writer.WriteNumber("int32", formatTest.Int32Option.Value.Value); + + if (formatTest.Int64Option.IsSet) + writer.WriteNumber("int64", formatTest.Int64Option.Value.Value); + + if (formatTest.IntegerOption.IsSet) + writer.WriteNumber("integer", formatTest.IntegerOption.Value.Value); + + if (formatTest.PatternWithBackslashOption.IsSet) + writer.WriteString("pattern_with_backslash", formatTest.PatternWithBackslash); + + if (formatTest.PatternWithDigitsOption.IsSet) + writer.WriteString("pattern_with_digits", formatTest.PatternWithDigits); + + if (formatTest.PatternWithDigitsAndDelimiterOption.IsSet) + writer.WriteString("pattern_with_digits_and_delimiter", formatTest.PatternWithDigitsAndDelimiter); + + if (formatTest.VarStringOption.IsSet) + writer.WriteString("string", formatTest.VarString); + + if (formatTest.UnsignedIntegerOption.IsSet) + writer.WriteNumber("unsigned_integer", formatTest.UnsignedIntegerOption.Value.Value); + + if (formatTest.UnsignedLongOption.IsSet) + writer.WriteNumber("unsigned_long", formatTest.UnsignedLongOption.Value.Value); + + if (formatTest.UuidOption.IsSet) + writer.WriteString("uuid", formatTest.UuidOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs index 2e05ffb958a4..efc98a08e71c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Fruit.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,10 +34,10 @@ public partial class Fruit : IValidatableObject /// /// /// color - public Fruit(Apple apple, string color) + public Fruit(Apple apple, Option color = default) { Apple = apple; - Color = color; + ColorOption = color; OnCreated(); } @@ -45,10 +46,10 @@ public Fruit(Apple apple, string color) /// /// /// color - public Fruit(Banana banana, string color) + public Fruit(Banana banana, Option color = default) { Banana = banana; - Color = color; + ColorOption = color; OnCreated(); } @@ -64,11 +65,18 @@ public Fruit(Banana banana, string color) /// public Banana Banana { get; set; } + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } + /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -116,7 +124,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string color = default; + Option color = default; Apple apple = default; Banana banana = default; @@ -156,7 +164,7 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -164,8 +172,8 @@ public override Fruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class Fruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class Fruit."); if (apple != null) return new Fruit(apple, color); @@ -200,7 +208,11 @@ public override void Write(Utf8JsonWriter writer, Fruit fruit, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Fruit fruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", fruit.Color); + if (fruit.ColorOption.IsSet && fruit.Color == null) + throw new ArgumentNullException(nameof(fruit.Color), "Property is required for class Fruit."); + + if (fruit.ColorOption.IsSet) + writer.WriteString("color", fruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs index aa26d3600c05..75652a1b436e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/FruitReq.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs index 3c2d1ecefc94..b9f6c12dea7a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GmFruit.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,31 +35,52 @@ public partial class GmFruit : IValidatableObject /// /// /// color - public GmFruit(Apple apple, Banana banana, string color) + public GmFruit(Option apple, Option banana, Option color = default) { - Apple = apple; - Banana = banana; - Color = color; + AppleOption = apple; + BananaOption = banana; + ColorOption = color; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Apple + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AppleOption { get; private set; } + /// /// Gets or Sets Apple /// - public Apple Apple { get; set; } + public Apple Apple { get { return this.AppleOption; } set { this.AppleOption = new Option(value); } } + + /// + /// Used to track the state of Banana + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BananaOption { get; private set; } /// /// Gets or Sets Banana /// - public Banana Banana { get; set; } + public Banana Banana { get { return this.BananaOption; } set { this.BananaOption = new Option(value); } } + + /// + /// Used to track the state of Color + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ColorOption { get; private set; } /// /// Gets or Sets Color /// [JsonPropertyName("color")] - public string Color { get; set; } + public string Color { get { return this. ColorOption; } set { this.ColorOption = new Option(value); } } /// /// Returns the string presentation of the object @@ -106,7 +128,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string color = default; + Option color = default; Apple apple = default; Banana banana = default; @@ -146,7 +168,7 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve switch (localVarJsonPropertyName) { case "color": - color = utf8JsonReader.GetString(); + color = new Option(utf8JsonReader.GetString()); break; default: break; @@ -154,10 +176,17 @@ public override GmFruit Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (color == null) - throw new ArgumentNullException(nameof(color), "Property is required for class GmFruit."); + if (color.IsSet && color.Value == null) + throw new ArgumentNullException(nameof(color), "Property is not nullable for class GmFruit."); - return new GmFruit(apple, banana, color); + Option appleParsedValue = apple == null + ? default + : new Option(apple); + Option bananaParsedValue = banana == null + ? default + : new Option(banana); + + return new GmFruit(appleParsedValue, bananaParsedValue, color); } /// @@ -171,16 +200,16 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize { writer.WriteStartObject(); - if (gmFruit.Apple != null) + if (gmFruit.AppleOption.IsSet && gmFruit.AppleOption.Value != null) { - AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Apple.GetType())); - AppleJsonConverter.WriteProperties(ref writer, gmFruit.Apple, jsonSerializerOptions); + AppleJsonConverter AppleJsonConverter = (AppleJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.AppleOption.Value.GetType())); + AppleJsonConverter.WriteProperties(ref writer, gmFruit.AppleOption.Value, jsonSerializerOptions); } - if (gmFruit.Banana != null) + if (gmFruit.BananaOption.IsSet && gmFruit.BananaOption.Value != null) { - BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.Banana.GetType())); - BananaJsonConverter.WriteProperties(ref writer, gmFruit.Banana, jsonSerializerOptions); + BananaJsonConverter BananaJsonConverter = (BananaJsonConverter) jsonSerializerOptions.Converters.First(c => c.CanConvert(gmFruit.BananaOption.Value.GetType())); + BananaJsonConverter.WriteProperties(ref writer, gmFruit.BananaOption.Value, jsonSerializerOptions); } WriteProperties(ref writer, gmFruit, jsonSerializerOptions); @@ -196,7 +225,11 @@ public override void Write(Utf8JsonWriter writer, GmFruit gmFruit, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, GmFruit gmFruit, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("color", gmFruit.Color); + if (gmFruit.ColorOption.IsSet && gmFruit.Color == null) + throw new ArgumentNullException(nameof(gmFruit.Color), "Property is required for class GmFruit."); + + if (gmFruit.ColorOption.IsSet) + writer.WriteString("color", gmFruit.Color); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs index 7ae4662ed8d4..6b7d7ae8da68 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/GrandparentAnimal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -110,7 +111,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -128,7 +129,7 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -136,10 +137,13 @@ public override GrandparentAnimal Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class GrandparentAnimal."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class GrandparentAnimal.", nameof(petType)); - return new GrandparentAnimal(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class GrandparentAnimal."); + + return new GrandparentAnimal(petType.Value); } /// @@ -166,6 +170,9 @@ public override void Write(Utf8JsonWriter writer, GrandparentAnimal grandparentA /// public void WriteProperties(ref Utf8JsonWriter writer, GrandparentAnimal grandparentAnimal, JsonSerializerOptions jsonSerializerOptions) { + if (grandparentAnimal.PetType == null) + throw new ArgumentNullException(nameof(grandparentAnimal.PetType), "Property is required for class GrandparentAnimal."); + writer.WriteString("pet_type", grandparentAnimal.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs index 31360d73f754..9652b767d130 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HasOnlyReadOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class HasOnlyReadOnly : IEquatable, IValidatable /// bar /// foo [JsonConstructor] - internal HasOnlyReadOnly(string bar, string foo) + internal HasOnlyReadOnly(Option bar = default, Option foo = default) { - Bar = bar; - Foo = foo; + BarOption = bar; + FooOption = foo; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Foo + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FooOption { get; } /// /// Gets or Sets Foo /// [JsonPropertyName("foo")] - public string Foo { get; } + public string Foo { get { return this. FooOption; } } /// /// Gets or Sets additional properties @@ -105,8 +120,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); - hashCode = (hashCode * 59) + Foo.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + + if (Foo != null) + hashCode = (hashCode * 59) + Foo.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -146,8 +165,8 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; - string foo = default; + Option bar = default; + Option foo = default; while (utf8JsonReader.Read()) { @@ -165,10 +184,10 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; case "foo": - foo = utf8JsonReader.GetString(); + foo = new Option(utf8JsonReader.GetString()); break; default: break; @@ -176,11 +195,11 @@ public override HasOnlyReadOnly Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class HasOnlyReadOnly."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class HasOnlyReadOnly."); - if (foo == null) - throw new ArgumentNullException(nameof(foo), "Property is required for class HasOnlyReadOnly."); + if (foo.IsSet && foo.Value == null) + throw new ArgumentNullException(nameof(foo), "Property is not nullable for class HasOnlyReadOnly."); return new HasOnlyReadOnly(bar, foo); } @@ -209,8 +228,17 @@ public override void Write(Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnl /// public void WriteProperties(ref Utf8JsonWriter writer, HasOnlyReadOnly hasOnlyReadOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", hasOnlyReadOnly.Bar); - writer.WriteString("foo", hasOnlyReadOnly.Foo); + if (hasOnlyReadOnly.BarOption.IsSet && hasOnlyReadOnly.Bar == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Bar), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.FooOption.IsSet && hasOnlyReadOnly.Foo == null) + throw new ArgumentNullException(nameof(hasOnlyReadOnly.Foo), "Property is required for class HasOnlyReadOnly."); + + if (hasOnlyReadOnly.BarOption.IsSet) + writer.WriteString("bar", hasOnlyReadOnly.Bar); + + if (hasOnlyReadOnly.FooOption.IsSet) + writer.WriteString("foo", hasOnlyReadOnly.Foo); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs index 8355d97fa097..568712d2708a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/HealthCheckResult.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class HealthCheckResult : IValidatableObject /// /// nullableMessage [JsonConstructor] - public HealthCheckResult(string nullableMessage = default) + public HealthCheckResult(Option nullableMessage = default) { - NullableMessage = nullableMessage; + NullableMessageOption = nullableMessage; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of NullableMessage + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NullableMessageOption { get; private set; } + /// /// Gets or Sets NullableMessage /// [JsonPropertyName("NullableMessage")] - public string NullableMessage { get; set; } + public string NullableMessage { get { return this. NullableMessageOption; } set { this.NullableMessageOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string nullableMessage = default; + Option nullableMessage = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override HealthCheckResult Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "NullableMessage": - nullableMessage = utf8JsonReader.GetString(); + nullableMessage = new Option(utf8JsonReader.GetString()); break; default: break; @@ -153,7 +161,11 @@ public override void Write(Utf8JsonWriter writer, HealthCheckResult healthCheckR /// public void WriteProperties(ref Utf8JsonWriter writer, HealthCheckResult healthCheckResult, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + if (healthCheckResult.NullableMessageOption.IsSet) + if (healthCheckResult.NullableMessageOption.Value != null) + writer.WriteString("NullableMessage", healthCheckResult.NullableMessage); + else + writer.WriteNull("NullableMessage"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs index 0355613042f2..3f4aa3229c4e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/IsoscelesTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -102,8 +103,8 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -121,10 +122,10 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -132,13 +133,19 @@ public override IsoscelesTriangle Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class IsoscelesTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class IsoscelesTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class IsoscelesTriangle.", nameof(triangleType)); - return new IsoscelesTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class IsoscelesTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class IsoscelesTriangle."); + + return new IsoscelesTriangle(shapeType.Value, triangleType.Value); } /// @@ -165,7 +172,14 @@ public override void Write(Utf8JsonWriter writer, IsoscelesTriangle isoscelesTri /// public void WriteProperties(ref Utf8JsonWriter writer, IsoscelesTriangle isoscelesTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (isoscelesTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.ShapeType), "Property is required for class IsoscelesTriangle."); + + if (isoscelesTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(isoscelesTriangle.TriangleType), "Property is required for class IsoscelesTriangle."); + writer.WriteString("shapeType", isoscelesTriangle.ShapeType); + writer.WriteString("triangleType", isoscelesTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs index 42b0c9cb2cf1..f21994c35234 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/List.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class List : IValidatableObject /// /// var123List [JsonConstructor] - public List(string var123List) + public List(Option var123List = default) { - Var123List = var123List; + Var123ListOption = var123List; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Var123List + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123ListOption { get; private set; } + /// /// Gets or Sets Var123List /// [JsonPropertyName("123-list")] - public string Var123List { get; set; } + public string Var123List { get { return this. Var123ListOption; } set { this.Var123ListOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string var123List = default; + Option var123List = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "123-list": - var123List = utf8JsonReader.GetString(); + var123List = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override List Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (var123List == null) - throw new ArgumentNullException(nameof(var123List), "Property is required for class List."); + if (var123List.IsSet && var123List.Value == null) + throw new ArgumentNullException(nameof(var123List), "Property is not nullable for class List."); return new List(var123List); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, List list, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, List list, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("123-list", list.Var123List); + if (list.Var123ListOption.IsSet && list.Var123List == null) + throw new ArgumentNullException(nameof(list.Var123List), "Property is required for class List."); + + if (list.Var123ListOption.IsSet) + writer.WriteString("123-list", list.Var123List); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs index 0ad8832af885..cfc824d8f5a6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/LiteralStringClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class LiteralStringClass : IValidatableObject /// escapedLiteralString (default to "C:\\Users\\username") /// unescapedLiteralString (default to "C:\Users\username") [JsonConstructor] - public LiteralStringClass(string escapedLiteralString = @"C:\\Users\\username", string unescapedLiteralString = @"C:\Users\username") + public LiteralStringClass(Option escapedLiteralString = default, Option unescapedLiteralString = default) { - EscapedLiteralString = escapedLiteralString; - UnescapedLiteralString = unescapedLiteralString; + EscapedLiteralStringOption = escapedLiteralString; + UnescapedLiteralStringOption = unescapedLiteralString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of EscapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EscapedLiteralStringOption { get; private set; } + /// /// Gets or Sets EscapedLiteralString /// [JsonPropertyName("escapedLiteralString")] - public string EscapedLiteralString { get; set; } + public string EscapedLiteralString { get { return this. EscapedLiteralStringOption; } set { this.EscapedLiteralStringOption = new Option(value); } } + + /// + /// Used to track the state of UnescapedLiteralString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UnescapedLiteralStringOption { get; private set; } /// /// Gets or Sets UnescapedLiteralString /// [JsonPropertyName("unescapedLiteralString")] - public string UnescapedLiteralString { get; set; } + public string UnescapedLiteralString { get { return this. UnescapedLiteralStringOption; } set { this.UnescapedLiteralStringOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string escapedLiteralString = default; - string unescapedLiteralString = default; + Option escapedLiteralString = default; + Option unescapedLiteralString = default; while (utf8JsonReader.Read()) { @@ -128,10 +143,10 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "escapedLiteralString": - escapedLiteralString = utf8JsonReader.GetString(); + escapedLiteralString = new Option(utf8JsonReader.GetString()); break; case "unescapedLiteralString": - unescapedLiteralString = utf8JsonReader.GetString(); + unescapedLiteralString = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,11 +154,11 @@ public override LiteralStringClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (escapedLiteralString == null) - throw new ArgumentNullException(nameof(escapedLiteralString), "Property is required for class LiteralStringClass."); + if (escapedLiteralString.IsSet && escapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(escapedLiteralString), "Property is not nullable for class LiteralStringClass."); - if (unescapedLiteralString == null) - throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is required for class LiteralStringClass."); + if (unescapedLiteralString.IsSet && unescapedLiteralString.Value == null) + throw new ArgumentNullException(nameof(unescapedLiteralString), "Property is not nullable for class LiteralStringClass."); return new LiteralStringClass(escapedLiteralString, unescapedLiteralString); } @@ -172,8 +187,17 @@ public override void Write(Utf8JsonWriter writer, LiteralStringClass literalStri /// public void WriteProperties(ref Utf8JsonWriter writer, LiteralStringClass literalStringClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); - writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); + if (literalStringClass.EscapedLiteralStringOption.IsSet && literalStringClass.EscapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.EscapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet && literalStringClass.UnescapedLiteralString == null) + throw new ArgumentNullException(nameof(literalStringClass.UnescapedLiteralString), "Property is required for class LiteralStringClass."); + + if (literalStringClass.EscapedLiteralStringOption.IsSet) + writer.WriteString("escapedLiteralString", literalStringClass.EscapedLiteralString); + + if (literalStringClass.UnescapedLiteralStringOption.IsSet) + writer.WriteString("unescapedLiteralString", literalStringClass.UnescapedLiteralString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs index 92011ad0e1d9..1ea0d944f050 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Mammal.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -150,7 +151,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; Pig pig = null; Whale whale = null; @@ -207,7 +208,7 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -215,17 +216,20 @@ public override Mammal Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Mammal."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Mammal.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Mammal."); if (pig != null) - return new Mammal(pig, className); + return new Mammal(pig, className.Value); if (whale != null) - return new Mammal(whale, className); + return new Mammal(whale, className.Value); if (zebra != null) - return new Mammal(zebra, className); + return new Mammal(zebra, className.Value); throw new JsonException(); } @@ -269,6 +273,9 @@ public override void Write(Utf8JsonWriter writer, Mammal mammal, JsonSerializerO /// public void WriteProperties(ref Utf8JsonWriter writer, Mammal mammal, JsonSerializerOptions jsonSerializerOptions) { + if (mammal.ClassName == null) + throw new ArgumentNullException(nameof(mammal.ClassName), "Property is required for class Mammal."); + writer.WriteString("className", mammal.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs index c99356fbf3a8..b620db4b59dc 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MapTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,12 +37,12 @@ public partial class MapTest : IValidatableObject /// mapMapOfString /// mapOfEnumString [JsonConstructor] - public MapTest(Dictionary directMap, Dictionary indirectMap, Dictionary> mapMapOfString, Dictionary mapOfEnumString) + public MapTest(Option> directMap = default, Option> indirectMap = default, Option>> mapMapOfString = default, Option> mapOfEnumString = default) { - DirectMap = directMap; - IndirectMap = indirectMap; - MapMapOfString = mapMapOfString; - MapOfEnumString = mapOfEnumString; + DirectMapOption = directMap; + IndirectMapOption = indirectMap; + MapMapOfStringOption = mapMapOfString; + MapOfEnumStringOption = mapOfEnumString; OnCreated(); } @@ -113,29 +114,57 @@ public static string InnerEnumToJsonValue(InnerEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of DirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> DirectMapOption { get; private set; } + /// /// Gets or Sets DirectMap /// [JsonPropertyName("direct_map")] - public Dictionary DirectMap { get; set; } + public Dictionary DirectMap { get { return this. DirectMapOption; } set { this.DirectMapOption = new Option>(value); } } + + /// + /// Used to track the state of IndirectMap + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> IndirectMapOption { get; private set; } /// /// Gets or Sets IndirectMap /// [JsonPropertyName("indirect_map")] - public Dictionary IndirectMap { get; set; } + public Dictionary IndirectMap { get { return this. IndirectMapOption; } set { this.IndirectMapOption = new Option>(value); } } + + /// + /// Used to track the state of MapMapOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option>> MapMapOfStringOption { get; private set; } /// /// Gets or Sets MapMapOfString /// [JsonPropertyName("map_map_of_string")] - public Dictionary> MapMapOfString { get; set; } + public Dictionary> MapMapOfString { get { return this. MapMapOfStringOption; } set { this.MapMapOfStringOption = new Option>>(value); } } + + /// + /// Used to track the state of MapOfEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapOfEnumStringOption { get; private set; } /// /// Gets or Sets MapOfEnumString /// [JsonPropertyName("map_of_enum_string")] - public Dictionary MapOfEnumString { get; set; } + public Dictionary MapOfEnumString { get { return this. MapOfEnumStringOption; } set { this.MapOfEnumStringOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -193,10 +222,10 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Dictionary directMap = default; - Dictionary indirectMap = default; - Dictionary> mapMapOfString = default; - Dictionary mapOfEnumString = default; + Option> directMap = default; + Option> indirectMap = default; + Option>> mapMapOfString = default; + Option> mapOfEnumString = default; while (utf8JsonReader.Read()) { @@ -215,19 +244,19 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve { case "direct_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - directMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + directMap = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "indirect_map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - indirectMap = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + indirectMap = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_map_of_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapMapOfString = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + mapMapOfString = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "map_of_enum_string": if (utf8JsonReader.TokenType != JsonTokenType.Null) - mapOfEnumString = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + mapOfEnumString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -235,17 +264,17 @@ public override MapTest Read(ref Utf8JsonReader utf8JsonReader, Type typeToConve } } - if (directMap == null) - throw new ArgumentNullException(nameof(directMap), "Property is required for class MapTest."); + if (directMap.IsSet && directMap.Value == null) + throw new ArgumentNullException(nameof(directMap), "Property is not nullable for class MapTest."); - if (indirectMap == null) - throw new ArgumentNullException(nameof(indirectMap), "Property is required for class MapTest."); + if (indirectMap.IsSet && indirectMap.Value == null) + throw new ArgumentNullException(nameof(indirectMap), "Property is not nullable for class MapTest."); - if (mapMapOfString == null) - throw new ArgumentNullException(nameof(mapMapOfString), "Property is required for class MapTest."); + if (mapMapOfString.IsSet && mapMapOfString.Value == null) + throw new ArgumentNullException(nameof(mapMapOfString), "Property is not nullable for class MapTest."); - if (mapOfEnumString == null) - throw new ArgumentNullException(nameof(mapOfEnumString), "Property is required for class MapTest."); + if (mapOfEnumString.IsSet && mapOfEnumString.Value == null) + throw new ArgumentNullException(nameof(mapOfEnumString), "Property is not nullable for class MapTest."); return new MapTest(directMap, indirectMap, mapMapOfString, mapOfEnumString); } @@ -274,14 +303,38 @@ public override void Write(Utf8JsonWriter writer, MapTest mapTest, JsonSerialize /// public void WriteProperties(ref Utf8JsonWriter writer, MapTest mapTest, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("direct_map"); - JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); - writer.WritePropertyName("indirect_map"); - JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); - writer.WritePropertyName("map_map_of_string"); - JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); - writer.WritePropertyName("map_of_enum_string"); - JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + if (mapTest.DirectMapOption.IsSet && mapTest.DirectMap == null) + throw new ArgumentNullException(nameof(mapTest.DirectMap), "Property is required for class MapTest."); + + if (mapTest.IndirectMapOption.IsSet && mapTest.IndirectMap == null) + throw new ArgumentNullException(nameof(mapTest.IndirectMap), "Property is required for class MapTest."); + + if (mapTest.MapMapOfStringOption.IsSet && mapTest.MapMapOfString == null) + throw new ArgumentNullException(nameof(mapTest.MapMapOfString), "Property is required for class MapTest."); + + if (mapTest.MapOfEnumStringOption.IsSet && mapTest.MapOfEnumString == null) + throw new ArgumentNullException(nameof(mapTest.MapOfEnumString), "Property is required for class MapTest."); + + if (mapTest.DirectMapOption.IsSet) + { + writer.WritePropertyName("direct_map"); + JsonSerializer.Serialize(writer, mapTest.DirectMap, jsonSerializerOptions); + } + if (mapTest.IndirectMapOption.IsSet) + { + writer.WritePropertyName("indirect_map"); + JsonSerializer.Serialize(writer, mapTest.IndirectMap, jsonSerializerOptions); + } + if (mapTest.MapMapOfStringOption.IsSet) + { + writer.WritePropertyName("map_map_of_string"); + JsonSerializer.Serialize(writer, mapTest.MapMapOfString, jsonSerializerOptions); + } + if (mapTest.MapOfEnumStringOption.IsSet) + { + writer.WritePropertyName("map_of_enum_string"); + JsonSerializer.Serialize(writer, mapTest.MapOfEnumString, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs index 0ed70f02c2db..b75b184b9ad2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/MixedPropertiesAndAdditionalPropertiesClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,40 +37,68 @@ public partial class MixedPropertiesAndAdditionalPropertiesClass : IValidatableO /// uuid /// uuidWithPattern [JsonConstructor] - public MixedPropertiesAndAdditionalPropertiesClass(DateTime dateTime, Dictionary map, Guid uuid, Guid uuidWithPattern) + public MixedPropertiesAndAdditionalPropertiesClass(Option dateTime = default, Option> map = default, Option uuid = default, Option uuidWithPattern = default) { - DateTime = dateTime; - Map = map; - Uuid = uuid; - UuidWithPattern = uuidWithPattern; + DateTimeOption = dateTime; + MapOption = map; + UuidOption = uuid; + UuidWithPatternOption = uuidWithPattern; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of DateTime + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DateTimeOption { get; private set; } + /// /// Gets or Sets DateTime /// [JsonPropertyName("dateTime")] - public DateTime DateTime { get; set; } + public DateTime? DateTime { get { return this. DateTimeOption; } set { this.DateTimeOption = new Option(value); } } + + /// + /// Used to track the state of Map + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> MapOption { get; private set; } /// /// Gets or Sets Map /// [JsonPropertyName("map")] - public Dictionary Map { get; set; } + public Dictionary Map { get { return this. MapOption; } set { this.MapOption = new Option>(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public Guid Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new Option(value); } } + + /// + /// Used to track the state of UuidWithPattern + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidWithPatternOption { get; private set; } /// /// Gets or Sets UuidWithPattern /// [JsonPropertyName("uuid_with_pattern")] - public Guid UuidWithPattern { get; set; } + public Guid? UuidWithPattern { get { return this. UuidWithPatternOption; } set { this.UuidWithPatternOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -103,7 +132,8 @@ public override string ToString() { // UuidWithPattern (Guid) pattern Regex regexUuidWithPattern = new Regex(@"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}", RegexOptions.CultureInvariant); - if (!regexUuidWithPattern.Match(this.UuidWithPattern.ToString()).Success) + + if (this.UuidWithPatternOption.Value != null &&!regexUuidWithPattern.Match(this.UuidWithPatternOption.Value.ToString()).Success) { yield return new System.ComponentModel.DataAnnotations.ValidationResult("Invalid value for UuidWithPattern, must match a pattern of " + regexUuidWithPattern, new [] { "UuidWithPattern" }); } @@ -138,10 +168,10 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea JsonTokenType startingTokenType = utf8JsonReader.TokenType; - DateTime? dateTime = default; - Dictionary map = default; - Guid? uuid = default; - Guid? uuidWithPattern = default; + Option dateTime = default; + Option> map = default; + Option uuid = default; + Option uuidWithPattern = default; while (utf8JsonReader.Read()) { @@ -160,19 +190,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea { case "dateTime": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateTime = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateTime = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "map": if (utf8JsonReader.TokenType != JsonTokenType.Null) - map = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + map = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; case "uuid_with_pattern": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuidWithPattern = utf8JsonReader.GetGuid(); + uuidWithPattern = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -180,19 +210,19 @@ public override MixedPropertiesAndAdditionalPropertiesClass Read(ref Utf8JsonRea } } - if (dateTime == null) - throw new ArgumentNullException(nameof(dateTime), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (dateTime.IsSet && dateTime.Value == null) + throw new ArgumentNullException(nameof(dateTime), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (map == null) - throw new ArgumentNullException(nameof(map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (map.IsSet && map.Value == null) + throw new ArgumentNullException(nameof(map), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - if (uuidWithPattern == null) - throw new ArgumentNullException(nameof(uuidWithPattern), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + if (uuidWithPattern.IsSet && uuidWithPattern.Value == null) + throw new ArgumentNullException(nameof(uuidWithPattern), "Property is not nullable for class MixedPropertiesAndAdditionalPropertiesClass."); - return new MixedPropertiesAndAdditionalPropertiesClass(dateTime.Value, map, uuid.Value, uuidWithPattern.Value); + return new MixedPropertiesAndAdditionalPropertiesClass(dateTime, map, uuid, uuidWithPattern); } /// @@ -219,11 +249,22 @@ public override void Write(Utf8JsonWriter writer, MixedPropertiesAndAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTime.ToString(DateTimeFormat)); - writer.WritePropertyName("map"); - JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); - writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.Uuid); - writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPattern); + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet && mixedPropertiesAndAdditionalPropertiesClass.Map == null) + throw new ArgumentNullException(nameof(mixedPropertiesAndAdditionalPropertiesClass.Map), "Property is required for class MixedPropertiesAndAdditionalPropertiesClass."); + + if (mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.IsSet) + writer.WriteString("dateTime", mixedPropertiesAndAdditionalPropertiesClass.DateTimeOption.Value.Value.ToString(DateTimeFormat)); + + if (mixedPropertiesAndAdditionalPropertiesClass.MapOption.IsSet) + { + writer.WritePropertyName("map"); + JsonSerializer.Serialize(writer, mixedPropertiesAndAdditionalPropertiesClass.Map, jsonSerializerOptions); + } + if (mixedPropertiesAndAdditionalPropertiesClass.UuidOption.IsSet) + writer.WriteString("uuid", mixedPropertiesAndAdditionalPropertiesClass.UuidOption.Value.Value); + + if (mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.IsSet) + writer.WriteString("uuid_with_pattern", mixedPropertiesAndAdditionalPropertiesClass.UuidWithPatternOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs index 7969b9ae04ed..ba4afe20a018 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Model200Response.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class Model200Response : IValidatableObject /// varClass /// name [JsonConstructor] - public Model200Response(string varClass, int name) + public Model200Response(Option varClass = default, Option name = default) { - VarClass = varClass; - Name = name; + VarClassOption = varClass; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClass + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClassOption { get; private set; } + /// /// Gets or Sets VarClass /// [JsonPropertyName("class")] - public string VarClass { get; set; } + public string VarClass { get { return this. VarClassOption; } set { this.VarClassOption = new Option(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public int Name { get; set; } + public int? Name { get { return this. NameOption; } set { this.NameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClass = default; - int? name = default; + Option varClass = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "class": - varClass = utf8JsonReader.GetString(); + varClass = new Option(utf8JsonReader.GetString()); break; case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - name = utf8JsonReader.GetInt32(); + name = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -140,13 +155,13 @@ public override Model200Response Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varClass == null) - throw new ArgumentNullException(nameof(varClass), "Property is required for class Model200Response."); + if (varClass.IsSet && varClass.Value == null) + throw new ArgumentNullException(nameof(varClass), "Property is not nullable for class Model200Response."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Model200Response."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Model200Response."); - return new Model200Response(varClass, name.Value); + return new Model200Response(varClass, name); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, Model200Response model200Respo /// public void WriteProperties(ref Utf8JsonWriter writer, Model200Response model200Response, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("class", model200Response.VarClass); - writer.WriteNumber("name", model200Response.Name); + if (model200Response.VarClassOption.IsSet && model200Response.VarClass == null) + throw new ArgumentNullException(nameof(model200Response.VarClass), "Property is required for class Model200Response."); + + if (model200Response.VarClassOption.IsSet) + writer.WriteString("class", model200Response.VarClass); + + if (model200Response.NameOption.IsSet) + writer.WriteNumber("name", model200Response.NameOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs index 810a6a01b8e9..2830a1d51350 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ModelClient.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class ModelClient : IValidatableObject /// /// varClient [JsonConstructor] - public ModelClient(string varClient) + public ModelClient(Option varClient = default) { - VarClient = varClient; + VarClientOption = varClient; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarClient + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarClientOption { get; private set; } + /// /// Gets or Sets VarClient /// [JsonPropertyName("client")] - public string VarClient { get; set; } + public string VarClient { get { return this. VarClientOption; } set { this.VarClientOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varClient = default; + Option varClient = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "client": - varClient = utf8JsonReader.GetString(); + varClient = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override ModelClient Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (varClient == null) - throw new ArgumentNullException(nameof(varClient), "Property is required for class ModelClient."); + if (varClient.IsSet && varClient.Value == null) + throw new ArgumentNullException(nameof(varClient), "Property is not nullable for class ModelClient."); return new ModelClient(varClient); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, ModelClient modelClient, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ModelClient modelClient, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("client", modelClient.VarClient); + if (modelClient.VarClientOption.IsSet && modelClient.VarClient == null) + throw new ArgumentNullException(nameof(modelClient.VarClient), "Property is required for class ModelClient."); + + if (modelClient.VarClientOption.IsSet) + writer.WriteString("client", modelClient.VarClient); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs index edcb6b3403c7..7403eda73f2c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Name.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,12 +37,12 @@ public partial class Name : IEquatable, IValidatableObject /// snakeCase /// var123Number [JsonConstructor] - public Name(int varName, string property, int snakeCase, int var123Number) + public Name(int varName, Option property = default, Option snakeCase = default, Option var123Number = default) { VarName = varName; - Property = property; - SnakeCase = snakeCase; - Var123Number = var123Number; + PropertyOption = property; + SnakeCaseOption = snakeCase; + Var123NumberOption = var123Number; OnCreated(); } @@ -53,23 +54,44 @@ public Name(int varName, string property, int snakeCase, int var123Number) [JsonPropertyName("name")] public int VarName { get; set; } + /// + /// Used to track the state of Property + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PropertyOption { get; private set; } + /// /// Gets or Sets Property /// [JsonPropertyName("property")] - public string Property { get; set; } + public string Property { get { return this. PropertyOption; } set { this.PropertyOption = new Option(value); } } + + /// + /// Used to track the state of SnakeCase + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SnakeCaseOption { get; } /// /// Gets or Sets SnakeCase /// [JsonPropertyName("snake_case")] - public int SnakeCase { get; } + public int? SnakeCase { get { return this. SnakeCaseOption; } } + + /// + /// Used to track the state of Var123Number + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option Var123NumberOption { get; } /// /// Gets or Sets Var123Number /// [JsonPropertyName("123Number")] - public int Var123Number { get; } + public int? Var123Number { get { return this. Var123NumberOption; } } /// /// Gets or Sets additional properties @@ -123,8 +145,12 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); - hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + if (SnakeCase != null) + hashCode = (hashCode * 59) + SnakeCase.GetHashCode(); + + if (Var123Number != null) + hashCode = (hashCode * 59) + Var123Number.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -164,10 +190,10 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varName = default; - string property = default; - int? snakeCase = default; - int? var123Number = default; + Option varName = default; + Option property = default; + Option snakeCase = default; + Option var123Number = default; while (utf8JsonReader.Read()) { @@ -186,18 +212,18 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "name": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varName = utf8JsonReader.GetInt32(); + varName = new Option(utf8JsonReader.GetInt32()); break; case "property": - property = utf8JsonReader.GetString(); + property = new Option(utf8JsonReader.GetString()); break; case "snake_case": if (utf8JsonReader.TokenType != JsonTokenType.Null) - snakeCase = utf8JsonReader.GetInt32(); + snakeCase = new Option(utf8JsonReader.GetInt32()); break; case "123Number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - var123Number = utf8JsonReader.GetInt32(); + var123Number = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -205,19 +231,22 @@ public override Name Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (varName == null) - throw new ArgumentNullException(nameof(varName), "Property is required for class Name."); + if (!varName.IsSet) + throw new ArgumentException("Property is required for class Name.", nameof(varName)); + + if (varName.IsSet && varName.Value == null) + throw new ArgumentNullException(nameof(varName), "Property is not nullable for class Name."); - if (property == null) - throw new ArgumentNullException(nameof(property), "Property is required for class Name."); + if (property.IsSet && property.Value == null) + throw new ArgumentNullException(nameof(property), "Property is not nullable for class Name."); - if (snakeCase == null) - throw new ArgumentNullException(nameof(snakeCase), "Property is required for class Name."); + if (snakeCase.IsSet && snakeCase.Value == null) + throw new ArgumentNullException(nameof(snakeCase), "Property is not nullable for class Name."); - if (var123Number == null) - throw new ArgumentNullException(nameof(var123Number), "Property is required for class Name."); + if (var123Number.IsSet && var123Number.Value == null) + throw new ArgumentNullException(nameof(var123Number), "Property is not nullable for class Name."); - return new Name(varName.Value, property, snakeCase.Value, var123Number.Value); + return new Name(varName.Value.Value, property, snakeCase, var123Number); } /// @@ -244,10 +273,19 @@ public override void Write(Utf8JsonWriter writer, Name name, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, Name name, JsonSerializerOptions jsonSerializerOptions) { + if (name.PropertyOption.IsSet && name.Property == null) + throw new ArgumentNullException(nameof(name.Property), "Property is required for class Name."); + writer.WriteNumber("name", name.VarName); - writer.WriteString("property", name.Property); - writer.WriteNumber("snake_case", name.SnakeCase); - writer.WriteNumber("123Number", name.Var123Number); + + if (name.PropertyOption.IsSet) + writer.WriteString("property", name.Property); + + if (name.SnakeCaseOption.IsSet) + writer.WriteNumber("snake_case", name.SnakeCaseOption.Value.Value); + + if (name.Var123NumberOption.IsSet) + writer.WriteNumber("123Number", name.Var123NumberOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs index 83ab7f40b1e8..cd1516104e35 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NotificationtestGetElementsV1ResponseMPayload.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List> aObjVariableobject = default; - int? pkiNotificationtestID = default; + Option>> aObjVariableobject = default; + Option pkiNotificationtestID = default; while (utf8JsonReader.Read()) { @@ -129,11 +130,11 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR { case "a_objVariableobject": if (utf8JsonReader.TokenType != JsonTokenType.Null) - aObjVariableobject = JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions); + aObjVariableobject = new Option>>(JsonSerializer.Deserialize>>(ref utf8JsonReader, jsonSerializerOptions)); break; case "pkiNotificationtestID": if (utf8JsonReader.TokenType != JsonTokenType.Null) - pkiNotificationtestID = utf8JsonReader.GetInt32(); + pkiNotificationtestID = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -141,13 +142,19 @@ public override NotificationtestGetElementsV1ResponseMPayload Read(ref Utf8JsonR } } - if (aObjVariableobject == null) - throw new ArgumentNullException(nameof(aObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!aObjVariableobject.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(aObjVariableobject)); - if (pkiNotificationtestID == null) - throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + if (!pkiNotificationtestID.IsSet) + throw new ArgumentException("Property is required for class NotificationtestGetElementsV1ResponseMPayload.", nameof(pkiNotificationtestID)); - return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject, pkiNotificationtestID.Value); + if (aObjVariableobject.IsSet && aObjVariableobject.Value == null) + throw new ArgumentNullException(nameof(aObjVariableobject), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + if (pkiNotificationtestID.IsSet && pkiNotificationtestID.Value == null) + throw new ArgumentNullException(nameof(pkiNotificationtestID), "Property is not nullable for class NotificationtestGetElementsV1ResponseMPayload."); + + return new NotificationtestGetElementsV1ResponseMPayload(aObjVariableobject.Value, pkiNotificationtestID.Value.Value); } /// @@ -174,6 +181,9 @@ public override void Write(Utf8JsonWriter writer, NotificationtestGetElementsV1R /// public void WriteProperties(ref Utf8JsonWriter writer, NotificationtestGetElementsV1ResponseMPayload notificationtestGetElementsV1ResponseMPayload, JsonSerializerOptions jsonSerializerOptions) { + if (notificationtestGetElementsV1ResponseMPayload.AObjVariableobject == null) + throw new ArgumentNullException(nameof(notificationtestGetElementsV1ResponseMPayload.AObjVariableobject), "Property is required for class NotificationtestGetElementsV1ResponseMPayload."); + writer.WritePropertyName("a_objVariableobject"); JsonSerializer.Serialize(writer, notificationtestGetElementsV1ResponseMPayload.AObjVariableobject, jsonSerializerOptions); writer.WriteNumber("pkiNotificationtestID", notificationtestGetElementsV1ResponseMPayload.PkiNotificationtestID); diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs index 5d9de18c4a36..bbd8904bfc82 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -20,20 +20,20 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// NullableClass /// - public partial class NullableClass : Dictionary, IValidatableObject + public partial class NullableClass : IValidatableObject { /// /// Initializes a new instance of the class. /// - /// arrayItemsNullable - /// objectItemsNullable /// arrayAndItemsNullableProp + /// arrayItemsNullable /// arrayNullableProp /// booleanProp /// dateProp @@ -41,99 +41,184 @@ public partial class NullableClass : Dictionary, IValidatableObj /// integerProp /// numberProp /// objectAndItemsNullableProp + /// objectItemsNullable /// objectNullableProp /// stringProp [JsonConstructor] - public NullableClass(List arrayItemsNullable, Dictionary objectItemsNullable, List arrayAndItemsNullableProp = default, List arrayNullableProp = default, bool? booleanProp = default, DateTime? dateProp = default, DateTime? datetimeProp = default, int? integerProp = default, decimal? numberProp = default, Dictionary objectAndItemsNullableProp = default, Dictionary objectNullableProp = default, string stringProp = default) : base() + public NullableClass(Option> arrayAndItemsNullableProp = default, Option> arrayItemsNullable = default, Option> arrayNullableProp = default, Option booleanProp = default, Option dateProp = default, Option datetimeProp = default, Option integerProp = default, Option numberProp = default, Option> objectAndItemsNullableProp = default, Option> objectItemsNullable = default, Option> objectNullableProp = default, Option stringProp = default) { - ArrayItemsNullable = arrayItemsNullable; - ObjectItemsNullable = objectItemsNullable; - ArrayAndItemsNullableProp = arrayAndItemsNullableProp; - ArrayNullableProp = arrayNullableProp; - BooleanProp = booleanProp; - DateProp = dateProp; - DatetimeProp = datetimeProp; - IntegerProp = integerProp; - NumberProp = numberProp; - ObjectAndItemsNullableProp = objectAndItemsNullableProp; - ObjectNullableProp = objectNullableProp; - StringProp = stringProp; + ArrayAndItemsNullablePropOption = arrayAndItemsNullableProp; + ArrayItemsNullableOption = arrayItemsNullable; + ArrayNullablePropOption = arrayNullableProp; + BooleanPropOption = booleanProp; + DatePropOption = dateProp; + DatetimePropOption = datetimeProp; + IntegerPropOption = integerProp; + NumberPropOption = numberProp; + ObjectAndItemsNullablePropOption = objectAndItemsNullableProp; + ObjectItemsNullableOption = objectItemsNullable; + ObjectNullablePropOption = objectNullableProp; + StringPropOption = stringProp; OnCreated(); } partial void OnCreated(); /// - /// Gets or Sets ArrayItemsNullable + /// Used to track the state of ArrayAndItemsNullableProp /// - [JsonPropertyName("array_items_nullable")] - public List ArrayItemsNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayAndItemsNullablePropOption { get; private set; } /// - /// Gets or Sets ObjectItemsNullable + /// Gets or Sets ArrayAndItemsNullableProp /// - [JsonPropertyName("object_items_nullable")] - public Dictionary ObjectItemsNullable { get; set; } + [JsonPropertyName("array_and_items_nullable_prop")] + public List ArrayAndItemsNullableProp { get { return this. ArrayAndItemsNullablePropOption; } set { this.ArrayAndItemsNullablePropOption = new Option>(value); } } /// - /// Gets or Sets ArrayAndItemsNullableProp + /// Used to track the state of ArrayItemsNullable /// - [JsonPropertyName("array_and_items_nullable_prop")] - public List ArrayAndItemsNullableProp { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ArrayItemsNullable + /// + [JsonPropertyName("array_items_nullable")] + public List ArrayItemsNullable { get { return this. ArrayItemsNullableOption; } set { this.ArrayItemsNullableOption = new Option>(value); } } + + /// + /// Used to track the state of ArrayNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ArrayNullablePropOption { get; private set; } /// /// Gets or Sets ArrayNullableProp /// [JsonPropertyName("array_nullable_prop")] - public List ArrayNullableProp { get; set; } + public List ArrayNullableProp { get { return this. ArrayNullablePropOption; } set { this.ArrayNullablePropOption = new Option>(value); } } + + /// + /// Used to track the state of BooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BooleanPropOption { get; private set; } /// /// Gets or Sets BooleanProp /// [JsonPropertyName("boolean_prop")] - public bool? BooleanProp { get; set; } + public bool? BooleanProp { get { return this. BooleanPropOption; } set { this.BooleanPropOption = new Option(value); } } + + /// + /// Used to track the state of DateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatePropOption { get; private set; } /// /// Gets or Sets DateProp /// [JsonPropertyName("date_prop")] - public DateTime? DateProp { get; set; } + public DateTime? DateProp { get { return this. DatePropOption; } set { this.DatePropOption = new Option(value); } } + + /// + /// Used to track the state of DatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DatetimePropOption { get; private set; } /// /// Gets or Sets DatetimeProp /// [JsonPropertyName("datetime_prop")] - public DateTime? DatetimeProp { get; set; } + public DateTime? DatetimeProp { get { return this. DatetimePropOption; } set { this.DatetimePropOption = new Option(value); } } + + /// + /// Used to track the state of IntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IntegerPropOption { get; private set; } /// /// Gets or Sets IntegerProp /// [JsonPropertyName("integer_prop")] - public int? IntegerProp { get; set; } + public int? IntegerProp { get { return this. IntegerPropOption; } set { this.IntegerPropOption = new Option(value); } } + + /// + /// Used to track the state of NumberProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NumberPropOption { get; private set; } /// /// Gets or Sets NumberProp /// [JsonPropertyName("number_prop")] - public decimal? NumberProp { get; set; } + public decimal? NumberProp { get { return this. NumberPropOption; } set { this.NumberPropOption = new Option(value); } } + + /// + /// Used to track the state of ObjectAndItemsNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectAndItemsNullablePropOption { get; private set; } /// /// Gets or Sets ObjectAndItemsNullableProp /// [JsonPropertyName("object_and_items_nullable_prop")] - public Dictionary ObjectAndItemsNullableProp { get; set; } + public Dictionary ObjectAndItemsNullableProp { get { return this. ObjectAndItemsNullablePropOption; } set { this.ObjectAndItemsNullablePropOption = new Option>(value); } } + + /// + /// Used to track the state of ObjectItemsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectItemsNullableOption { get; private set; } + + /// + /// Gets or Sets ObjectItemsNullable + /// + [JsonPropertyName("object_items_nullable")] + public Dictionary ObjectItemsNullable { get { return this. ObjectItemsNullableOption; } set { this.ObjectItemsNullableOption = new Option>(value); } } + + /// + /// Used to track the state of ObjectNullableProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> ObjectNullablePropOption { get; private set; } /// /// Gets or Sets ObjectNullableProp /// [JsonPropertyName("object_nullable_prop")] - public Dictionary ObjectNullableProp { get; set; } + public Dictionary ObjectNullableProp { get { return this. ObjectNullablePropOption; } set { this.ObjectNullablePropOption = new Option>(value); } } + + /// + /// Used to track the state of StringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StringPropOption { get; private set; } /// /// Gets or Sets StringProp /// [JsonPropertyName("string_prop")] - public string StringProp { get; set; } + public string StringProp { get { return this. StringPropOption; } set { this.StringPropOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -149,10 +234,8 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); - sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); - sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ArrayAndItemsNullableProp: ").Append(ArrayAndItemsNullableProp).Append("\n"); + sb.Append(" ArrayItemsNullable: ").Append(ArrayItemsNullable).Append("\n"); sb.Append(" ArrayNullableProp: ").Append(ArrayNullableProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); sb.Append(" DateProp: ").Append(DateProp).Append("\n"); @@ -160,6 +243,7 @@ public override string ToString() sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" ObjectAndItemsNullableProp: ").Append(ObjectAndItemsNullableProp).Append("\n"); + sb.Append(" ObjectItemsNullable: ").Append(ObjectItemsNullable).Append("\n"); sb.Append(" ObjectNullableProp: ").Append(ObjectNullableProp).Append("\n"); sb.Append(" StringProp: ").Append(StringProp).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -173,16 +257,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -220,18 +294,18 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List arrayItemsNullable = default; - Dictionary objectItemsNullable = default; - List arrayAndItemsNullableProp = default; - List arrayNullableProp = default; - bool? booleanProp = default; - DateTime? dateProp = default; - DateTime? datetimeProp = default; - int? integerProp = default; - decimal? numberProp = default; - Dictionary objectAndItemsNullableProp = default; - Dictionary objectNullableProp = default; - string stringProp = default; + Option> arrayAndItemsNullableProp = default; + Option> arrayItemsNullable = default; + Option> arrayNullableProp = default; + Option booleanProp = default; + Option dateProp = default; + Option datetimeProp = default; + Option integerProp = default; + Option numberProp = default; + Option> objectAndItemsNullableProp = default; + Option> objectItemsNullable = default; + Option> objectNullableProp = default; + Option stringProp = default; while (utf8JsonReader.Read()) { @@ -248,52 +322,52 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { - case "array_items_nullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); - break; - case "object_items_nullable": + case "array_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectItemsNullable = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayAndItemsNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "array_and_items_nullable_prop": + case "array_items_nullable": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayItemsNullable = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "array_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - arrayNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + arrayNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "boolean_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - booleanProp = utf8JsonReader.GetBoolean(); + booleanProp = new Option(utf8JsonReader.GetBoolean()); break; case "date_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - dateProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + dateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "datetime_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - datetimeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + datetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "integer_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - integerProp = utf8JsonReader.GetInt32(); + integerProp = new Option(utf8JsonReader.GetInt32()); break; case "number_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - numberProp = utf8JsonReader.GetDecimal(); + numberProp = new Option(utf8JsonReader.GetDecimal()); break; case "object_and_items_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectAndItemsNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectAndItemsNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "object_items_nullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectItemsNullable = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "object_nullable_prop": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectNullableProp = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + objectNullableProp = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "string_prop": - stringProp = utf8JsonReader.GetString(); + stringProp = new Option(utf8JsonReader.GetString()); break; default: break; @@ -301,13 +375,13 @@ public override NullableClass Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (arrayItemsNullable == null) - throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is required for class NullableClass."); + if (arrayItemsNullable.IsSet && arrayItemsNullable.Value == null) + throw new ArgumentNullException(nameof(arrayItemsNullable), "Property is not nullable for class NullableClass."); - if (objectItemsNullable == null) - throw new ArgumentNullException(nameof(objectItemsNullable), "Property is required for class NullableClass."); + if (objectItemsNullable.IsSet && objectItemsNullable.Value == null) + throw new ArgumentNullException(nameof(objectItemsNullable), "Property is not nullable for class NullableClass."); - return new NullableClass(arrayItemsNullable, objectItemsNullable, arrayAndItemsNullableProp, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectNullableProp, stringProp); + return new NullableClass(arrayAndItemsNullableProp, arrayItemsNullable, arrayNullableProp, booleanProp, dateProp, datetimeProp, integerProp, numberProp, objectAndItemsNullableProp, objectItemsNullable, objectNullableProp, stringProp); } /// @@ -334,45 +408,89 @@ public override void Write(Utf8JsonWriter writer, NullableClass nullableClass, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableClass nullableClass, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("array_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("object_items_nullable"); - JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); - writer.WritePropertyName("array_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("array_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); - - if (nullableClass.BooleanProp != null) - writer.WriteBoolean("boolean_prop", nullableClass.BooleanProp.Value); - else - writer.WriteNull("boolean_prop"); - - if (nullableClass.DateProp != null) - writer.WriteString("date_prop", nullableClass.DateProp.Value.ToString(DatePropFormat)); - else - writer.WriteNull("date_prop"); - - if (nullableClass.DatetimeProp != null) - writer.WriteString("datetime_prop", nullableClass.DatetimeProp.Value.ToString(DatetimePropFormat)); - else - writer.WriteNull("datetime_prop"); - - if (nullableClass.IntegerProp != null) - writer.WriteNumber("integer_prop", nullableClass.IntegerProp.Value); - else - writer.WriteNull("integer_prop"); - - if (nullableClass.NumberProp != null) - writer.WriteNumber("number_prop", nullableClass.NumberProp.Value); - else - writer.WriteNull("number_prop"); - - writer.WritePropertyName("object_and_items_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); - writer.WritePropertyName("object_nullable_prop"); - JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); - writer.WriteString("string_prop", nullableClass.StringProp); + if (nullableClass.ArrayItemsNullableOption.IsSet && nullableClass.ArrayItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ArrayItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ObjectItemsNullableOption.IsSet && nullableClass.ObjectItemsNullable == null) + throw new ArgumentNullException(nameof(nullableClass.ObjectItemsNullable), "Property is required for class NullableClass."); + + if (nullableClass.ArrayAndItemsNullablePropOption.IsSet) + if (nullableClass.ArrayAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("array_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_and_items_nullable_prop"); + if (nullableClass.ArrayItemsNullableOption.IsSet) + { + writer.WritePropertyName("array_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ArrayItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ArrayNullablePropOption.IsSet) + if (nullableClass.ArrayNullablePropOption.Value != null) + { + writer.WritePropertyName("array_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ArrayNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("array_nullable_prop"); + if (nullableClass.BooleanPropOption.IsSet) + if (nullableClass.BooleanPropOption.Value != null) + writer.WriteBoolean("boolean_prop", nullableClass.BooleanPropOption.Value.Value); + else + writer.WriteNull("boolean_prop"); + + if (nullableClass.DatePropOption.IsSet) + if (nullableClass.DatePropOption.Value != null) + writer.WriteString("date_prop", nullableClass.DatePropOption.Value.Value.ToString(DatePropFormat)); + else + writer.WriteNull("date_prop"); + + if (nullableClass.DatetimePropOption.IsSet) + if (nullableClass.DatetimePropOption.Value != null) + writer.WriteString("datetime_prop", nullableClass.DatetimePropOption.Value.Value.ToString(DatetimePropFormat)); + else + writer.WriteNull("datetime_prop"); + + if (nullableClass.IntegerPropOption.IsSet) + if (nullableClass.IntegerPropOption.Value != null) + writer.WriteNumber("integer_prop", nullableClass.IntegerPropOption.Value.Value); + else + writer.WriteNull("integer_prop"); + + if (nullableClass.NumberPropOption.IsSet) + if (nullableClass.NumberPropOption.Value != null) + writer.WriteNumber("number_prop", nullableClass.NumberPropOption.Value.Value); + else + writer.WriteNull("number_prop"); + + if (nullableClass.ObjectAndItemsNullablePropOption.IsSet) + if (nullableClass.ObjectAndItemsNullablePropOption.Value != null) + { + writer.WritePropertyName("object_and_items_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectAndItemsNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_and_items_nullable_prop"); + if (nullableClass.ObjectItemsNullableOption.IsSet) + { + writer.WritePropertyName("object_items_nullable"); + JsonSerializer.Serialize(writer, nullableClass.ObjectItemsNullable, jsonSerializerOptions); + } + if (nullableClass.ObjectNullablePropOption.IsSet) + if (nullableClass.ObjectNullablePropOption.Value != null) + { + writer.WritePropertyName("object_nullable_prop"); + JsonSerializer.Serialize(writer, nullableClass.ObjectNullableProp, jsonSerializerOptions); + } + else + writer.WriteNull("object_nullable_prop"); + if (nullableClass.StringPropOption.IsSet) + if (nullableClass.StringPropOption.Value != null) + writer.WriteString("string_prop", nullableClass.StringProp); + else + writer.WriteNull("string_prop"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs index 684109acd50f..415b5b58a977 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableGuidClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,20 +34,27 @@ public partial class NullableGuidClass : IValidatableObject /// /// uuid [JsonConstructor] - public NullableGuidClass(Guid? uuid = default) + public NullableGuidClass(Option uuid = default) { - Uuid = uuid; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } + /// /// Gets or Sets Uuid /// /// 72f98069-206d-4f12-9f12-3d1e525a8e84 [JsonPropertyName("uuid")] - public Guid? Uuid { get; set; } + public Guid? Uuid { get { return this. UuidOption; } set { this.UuidOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -101,7 +109,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Guid? uuid = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -120,7 +128,7 @@ public override NullableGuidClass Read(ref Utf8JsonReader utf8JsonReader, Type t { case "uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - uuid = utf8JsonReader.GetGuid(); + uuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -155,11 +163,11 @@ public override void Write(Utf8JsonWriter writer, NullableGuidClass nullableGuid /// public void WriteProperties(ref Utf8JsonWriter writer, NullableGuidClass nullableGuidClass, JsonSerializerOptions jsonSerializerOptions) { - - if (nullableGuidClass.Uuid == null) - writer.WriteNull("uuid"); - else - writer.WriteString("uuid", nullableGuidClass.Uuid.Value); + if (nullableGuidClass.UuidOption.IsSet) + if (nullableGuidClass.UuidOption.Value != null) + writer.WriteString("uuid", nullableGuidClass.UuidOption.Value.Value); + else + writer.WriteNull("uuid"); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs index a44c950b81bb..1e38640c8af9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NullableShape.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override NullableShape Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class NullableShape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class NullableShape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class NullableShape."); if (quadrilateral != null) - return new NullableShape(quadrilateral, shapeType); + return new NullableShape(quadrilateral, shapeType.Value); if (triangle != null) - return new NullableShape(triangle, shapeType); + return new NullableShape(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, NullableShape nullableShape, J /// public void WriteProperties(ref Utf8JsonWriter writer, NullableShape nullableShape, JsonSerializerOptions jsonSerializerOptions) { + if (nullableShape.ShapeType == null) + throw new ArgumentNullException(nameof(nullableShape.ShapeType), "Property is required for class NullableShape."); + writer.WriteString("shapeType", nullableShape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs index 3f3cbf4c5059..dff14aaba024 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/NumberOnly.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class NumberOnly : IValidatableObject /// /// justNumber [JsonConstructor] - public NumberOnly(decimal justNumber) + public NumberOnly(Option justNumber = default) { - JustNumber = justNumber; + JustNumberOption = justNumber; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of JustNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option JustNumberOption { get; private set; } + /// /// Gets or Sets JustNumber /// [JsonPropertyName("JustNumber")] - public decimal JustNumber { get; set; } + public decimal? JustNumber { get { return this. JustNumberOption; } set { this.JustNumberOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo JsonTokenType startingTokenType = utf8JsonReader.TokenType; - decimal? justNumber = default; + Option justNumber = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo { case "JustNumber": if (utf8JsonReader.TokenType != JsonTokenType.Null) - justNumber = utf8JsonReader.GetDecimal(); + justNumber = new Option(utf8JsonReader.GetDecimal()); break; default: break; @@ -127,10 +135,10 @@ public override NumberOnly Read(ref Utf8JsonReader utf8JsonReader, Type typeToCo } } - if (justNumber == null) - throw new ArgumentNullException(nameof(justNumber), "Property is required for class NumberOnly."); + if (justNumber.IsSet && justNumber.Value == null) + throw new ArgumentNullException(nameof(justNumber), "Property is not nullable for class NumberOnly."); - return new NumberOnly(justNumber.Value); + return new NumberOnly(justNumber); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, NumberOnly numberOnly, JsonSer /// public void WriteProperties(ref Utf8JsonWriter writer, NumberOnly numberOnly, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("JustNumber", numberOnly.JustNumber); + if (numberOnly.JustNumberOption.IsSet) + writer.WriteNumber("JustNumber", numberOnly.JustNumberOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs index 57a1614f29f4..a11aee11212b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ObjectWithDeprecatedFields.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -36,43 +37,71 @@ public partial class ObjectWithDeprecatedFields : IValidatableObject /// id /// uuid [JsonConstructor] - public ObjectWithDeprecatedFields(List bars, DeprecatedObject deprecatedRef, decimal id, string uuid) + public ObjectWithDeprecatedFields(Option> bars = default, Option deprecatedRef = default, Option id = default, Option uuid = default) { - Bars = bars; - DeprecatedRef = deprecatedRef; - Id = id; - Uuid = uuid; + BarsOption = bars; + DeprecatedRefOption = deprecatedRef; + IdOption = id; + UuidOption = uuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bars + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> BarsOption { get; private set; } + /// /// Gets or Sets Bars /// [JsonPropertyName("bars")] [Obsolete] - public List Bars { get; set; } + public List Bars { get { return this. BarsOption; } set { this.BarsOption = new Option>(value); } } + + /// + /// Used to track the state of DeprecatedRef + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option DeprecatedRefOption { get; private set; } /// /// Gets or Sets DeprecatedRef /// [JsonPropertyName("deprecatedRef")] [Obsolete] - public DeprecatedObject DeprecatedRef { get; set; } + public DeprecatedObject DeprecatedRef { get { return this. DeprecatedRefOption; } set { this.DeprecatedRefOption = new Option(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] [Obsolete] - public decimal Id { get; set; } + public decimal? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } + + /// + /// Used to track the state of Uuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UuidOption { get; private set; } /// /// Gets or Sets Uuid /// [JsonPropertyName("uuid")] - public string Uuid { get; set; } + public string Uuid { get { return this. UuidOption; } set { this.UuidOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -130,10 +159,10 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List bars = default; - DeprecatedObject deprecatedRef = default; - decimal? id = default; - string uuid = default; + Option> bars = default; + Option deprecatedRef = default; + Option id = default; + Option uuid = default; while (utf8JsonReader.Read()) { @@ -152,18 +181,18 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade { case "bars": if (utf8JsonReader.TokenType != JsonTokenType.Null) - bars = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + bars = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; case "deprecatedRef": if (utf8JsonReader.TokenType != JsonTokenType.Null) - deprecatedRef = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + deprecatedRef = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetDecimal(); + id = new Option(utf8JsonReader.GetDecimal()); break; case "uuid": - uuid = utf8JsonReader.GetString(); + uuid = new Option(utf8JsonReader.GetString()); break; default: break; @@ -171,19 +200,19 @@ public override ObjectWithDeprecatedFields Read(ref Utf8JsonReader utf8JsonReade } } - if (bars == null) - throw new ArgumentNullException(nameof(bars), "Property is required for class ObjectWithDeprecatedFields."); + if (bars.IsSet && bars.Value == null) + throw new ArgumentNullException(nameof(bars), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (deprecatedRef == null) - throw new ArgumentNullException(nameof(deprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + if (deprecatedRef.IsSet && deprecatedRef.Value == null) + throw new ArgumentNullException(nameof(deprecatedRef), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class ObjectWithDeprecatedFields."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class ObjectWithDeprecatedFields."); - if (uuid == null) - throw new ArgumentNullException(nameof(uuid), "Property is required for class ObjectWithDeprecatedFields."); + if (uuid.IsSet && uuid.Value == null) + throw new ArgumentNullException(nameof(uuid), "Property is not nullable for class ObjectWithDeprecatedFields."); - return new ObjectWithDeprecatedFields(bars, deprecatedRef, id.Value, uuid); + return new ObjectWithDeprecatedFields(bars, deprecatedRef, id, uuid); } /// @@ -210,12 +239,30 @@ public override void Write(Utf8JsonWriter writer, ObjectWithDeprecatedFields obj /// public void WriteProperties(ref Utf8JsonWriter writer, ObjectWithDeprecatedFields objectWithDeprecatedFields, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("bars"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); - writer.WritePropertyName("deprecatedRef"); - JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); - writer.WriteNumber("id", objectWithDeprecatedFields.Id); - writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); + if (objectWithDeprecatedFields.BarsOption.IsSet && objectWithDeprecatedFields.Bars == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Bars), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet && objectWithDeprecatedFields.DeprecatedRef == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.DeprecatedRef), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.UuidOption.IsSet && objectWithDeprecatedFields.Uuid == null) + throw new ArgumentNullException(nameof(objectWithDeprecatedFields.Uuid), "Property is required for class ObjectWithDeprecatedFields."); + + if (objectWithDeprecatedFields.BarsOption.IsSet) + { + writer.WritePropertyName("bars"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.Bars, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.DeprecatedRefOption.IsSet) + { + writer.WritePropertyName("deprecatedRef"); + JsonSerializer.Serialize(writer, objectWithDeprecatedFields.DeprecatedRef, jsonSerializerOptions); + } + if (objectWithDeprecatedFields.IdOption.IsSet) + writer.WriteNumber("id", objectWithDeprecatedFields.IdOption.Value.Value); + + if (objectWithDeprecatedFields.UuidOption.IsSet) + writer.WriteString("uuid", objectWithDeprecatedFields.Uuid); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OneOfString.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OneOfString.cs index 91dd67631614..660604e3ef17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OneOfString.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OneOfString.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs index 13afecfac3f6..afab71d723cb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Order.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,21 +32,21 @@ public partial class Order : IValidatableObject /// /// Initializes a new instance of the class. /// + /// complete (default to false) /// id /// petId /// quantity /// shipDate /// Order Status - /// complete (default to false) [JsonConstructor] - public Order(long id, long petId, int quantity, DateTime shipDate, StatusEnum status, bool complete = false) + public Order(Option complete = default, Option id = default, Option petId = default, Option quantity = default, Option shipDate = default, Option status = default) { - Id = id; - PetId = petId; - Quantity = quantity; - ShipDate = shipDate; - Status = status; - Complete = complete; + CompleteOption = complete; + IdOption = id; + PetIdOption = petId; + QuantityOption = quantity; + ShipDateOption = shipDate; + StatusOption = status; OnCreated(); } @@ -118,7 +119,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Placed) return "placed"; @@ -132,43 +133,85 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// Order Status /// /// Order Status [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new Option(value); } } + + /// + /// Used to track the state of Complete + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CompleteOption { get; private set; } + + /// + /// Gets or Sets Complete + /// + [JsonPropertyName("complete")] + public bool? Complete { get { return this. CompleteOption; } set { this.CompleteOption = new Option(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } + + /// + /// Used to track the state of PetId + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PetIdOption { get; private set; } /// /// Gets or Sets PetId /// [JsonPropertyName("petId")] - public long PetId { get; set; } + public long? PetId { get { return this. PetIdOption; } set { this.PetIdOption = new Option(value); } } + + /// + /// Used to track the state of Quantity + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option QuantityOption { get; private set; } /// /// Gets or Sets Quantity /// [JsonPropertyName("quantity")] - public int Quantity { get; set; } + public int? Quantity { get { return this. QuantityOption; } set { this.QuantityOption = new Option(value); } } /// - /// Gets or Sets ShipDate + /// Used to track the state of ShipDate /// - /// 2020-02-02T20:20:20.000222Z - [JsonPropertyName("shipDate")] - public DateTime ShipDate { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ShipDateOption { get; private set; } /// - /// Gets or Sets Complete + /// Gets or Sets ShipDate /// - [JsonPropertyName("complete")] - public bool Complete { get; set; } + /// 2020-02-02T20:20:20.000222Z + [JsonPropertyName("shipDate")] + public DateTime? ShipDate { get { return this. ShipDateOption; } set { this.ShipDateOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -184,12 +227,12 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Order {\n"); + sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" PetId: ").Append(PetId).Append("\n"); sb.Append(" Quantity: ").Append(Quantity).Append("\n"); sb.Append(" ShipDate: ").Append(ShipDate).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); - sb.Append(" Complete: ").Append(Complete).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -233,12 +276,12 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - long? petId = default; - int? quantity = default; - DateTime? shipDate = default; - Order.StatusEnum? status = default; - bool? complete = default; + Option complete = default; + Option id = default; + Option petId = default; + Option quantity = default; + Option shipDate = default; + Option status = default; while (utf8JsonReader.Read()) { @@ -255,31 +298,30 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { + case "complete": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + complete = new Option(utf8JsonReader.GetBoolean()); + break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "petId": if (utf8JsonReader.TokenType != JsonTokenType.Null) - petId = utf8JsonReader.GetInt64(); + petId = new Option(utf8JsonReader.GetInt64()); break; case "quantity": if (utf8JsonReader.TokenType != JsonTokenType.Null) - quantity = utf8JsonReader.GetInt32(); + quantity = new Option(utf8JsonReader.GetInt32()); break; case "shipDate": if (utf8JsonReader.TokenType != JsonTokenType.Null) - shipDate = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + shipDate = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "status": string statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Order.StatusEnumFromStringOrDefault(statusRawValue); - break; - case "complete": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - complete = utf8JsonReader.GetBoolean(); + if (statusRawValue != null) + status = new Option(Order.StatusEnumFromStringOrDefault(statusRawValue)); break; default: break; @@ -287,25 +329,25 @@ public override Order Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Order."); + if (complete.IsSet && complete.Value == null) + throw new ArgumentNullException(nameof(complete), "Property is not nullable for class Order."); - if (petId == null) - throw new ArgumentNullException(nameof(petId), "Property is required for class Order."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Order."); - if (quantity == null) - throw new ArgumentNullException(nameof(quantity), "Property is required for class Order."); + if (petId.IsSet && petId.Value == null) + throw new ArgumentNullException(nameof(petId), "Property is not nullable for class Order."); - if (shipDate == null) - throw new ArgumentNullException(nameof(shipDate), "Property is required for class Order."); + if (quantity.IsSet && quantity.Value == null) + throw new ArgumentNullException(nameof(quantity), "Property is not nullable for class Order."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Order."); + if (shipDate.IsSet && shipDate.Value == null) + throw new ArgumentNullException(nameof(shipDate), "Property is not nullable for class Order."); - if (complete == null) - throw new ArgumentNullException(nameof(complete), "Property is required for class Order."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Order."); - return new Order(id.Value, petId.Value, quantity.Value, shipDate.Value, status.Value, complete.Value); + return new Order(complete, id, petId, quantity, shipDate, status); } /// @@ -332,18 +374,23 @@ public override void Write(Utf8JsonWriter writer, Order order, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Order order, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", order.Id); - writer.WriteNumber("petId", order.PetId); - writer.WriteNumber("quantity", order.Quantity); - writer.WriteString("shipDate", order.ShipDate.ToString(ShipDateFormat)); - - var statusRawValue = Order.StatusEnumToJsonValue(order.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WriteBoolean("complete", order.Complete); + if (order.CompleteOption.IsSet) + writer.WriteBoolean("complete", order.CompleteOption.Value.Value); + + if (order.IdOption.IsSet) + writer.WriteNumber("id", order.IdOption.Value.Value); + + if (order.PetIdOption.IsSet) + writer.WriteNumber("petId", order.PetIdOption.Value.Value); + + if (order.QuantityOption.IsSet) + writer.WriteNumber("quantity", order.QuantityOption.Value.Value); + + if (order.ShipDateOption.IsSet) + writer.WriteString("shipDate", order.ShipDateOption.Value.Value.ToString(ShipDateFormat)); + + var statusRawValue = Order.StatusEnumToJsonValue(order.StatusOption.Value.Value); + writer.WriteString("status", statusRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs index c37883db124b..42665b8a066c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterComposite.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,33 +36,54 @@ public partial class OuterComposite : IValidatableObject /// myNumber /// myString [JsonConstructor] - public OuterComposite(bool myBoolean, decimal myNumber, string myString) + public OuterComposite(Option myBoolean = default, Option myNumber = default, Option myString = default) { - MyBoolean = myBoolean; - MyNumber = myNumber; - MyString = myString; + MyBooleanOption = myBoolean; + MyNumberOption = myNumber; + MyStringOption = myString; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of MyBoolean + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyBooleanOption { get; private set; } + /// /// Gets or Sets MyBoolean /// [JsonPropertyName("my_boolean")] - public bool MyBoolean { get; set; } + public bool? MyBoolean { get { return this. MyBooleanOption; } set { this.MyBooleanOption = new Option(value); } } + + /// + /// Used to track the state of MyNumber + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyNumberOption { get; private set; } /// /// Gets or Sets MyNumber /// [JsonPropertyName("my_number")] - public decimal MyNumber { get; set; } + public decimal? MyNumber { get { return this. MyNumberOption; } set { this.MyNumberOption = new Option(value); } } + + /// + /// Used to track the state of MyString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option MyStringOption { get; private set; } /// /// Gets or Sets MyString /// [JsonPropertyName("my_string")] - public string MyString { get; set; } + public string MyString { get { return this. MyStringOption; } set { this.MyStringOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -118,9 +140,9 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - bool? myBoolean = default; - decimal? myNumber = default; - string myString = default; + Option myBoolean = default; + Option myNumber = default; + Option myString = default; while (utf8JsonReader.Read()) { @@ -139,14 +161,14 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type { case "my_boolean": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myBoolean = utf8JsonReader.GetBoolean(); + myBoolean = new Option(utf8JsonReader.GetBoolean()); break; case "my_number": if (utf8JsonReader.TokenType != JsonTokenType.Null) - myNumber = utf8JsonReader.GetDecimal(); + myNumber = new Option(utf8JsonReader.GetDecimal()); break; case "my_string": - myString = utf8JsonReader.GetString(); + myString = new Option(utf8JsonReader.GetString()); break; default: break; @@ -154,16 +176,16 @@ public override OuterComposite Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (myBoolean == null) - throw new ArgumentNullException(nameof(myBoolean), "Property is required for class OuterComposite."); + if (myBoolean.IsSet && myBoolean.Value == null) + throw new ArgumentNullException(nameof(myBoolean), "Property is not nullable for class OuterComposite."); - if (myNumber == null) - throw new ArgumentNullException(nameof(myNumber), "Property is required for class OuterComposite."); + if (myNumber.IsSet && myNumber.Value == null) + throw new ArgumentNullException(nameof(myNumber), "Property is not nullable for class OuterComposite."); - if (myString == null) - throw new ArgumentNullException(nameof(myString), "Property is required for class OuterComposite."); + if (myString.IsSet && myString.Value == null) + throw new ArgumentNullException(nameof(myString), "Property is not nullable for class OuterComposite."); - return new OuterComposite(myBoolean.Value, myNumber.Value, myString); + return new OuterComposite(myBoolean, myNumber, myString); } /// @@ -190,9 +212,17 @@ public override void Write(Utf8JsonWriter writer, OuterComposite outerComposite, /// public void WriteProperties(ref Utf8JsonWriter writer, OuterComposite outerComposite, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteBoolean("my_boolean", outerComposite.MyBoolean); - writer.WriteNumber("my_number", outerComposite.MyNumber); - writer.WriteString("my_string", outerComposite.MyString); + if (outerComposite.MyStringOption.IsSet && outerComposite.MyString == null) + throw new ArgumentNullException(nameof(outerComposite.MyString), "Property is required for class OuterComposite."); + + if (outerComposite.MyBooleanOption.IsSet) + writer.WriteBoolean("my_boolean", outerComposite.MyBooleanOption.Value.Value); + + if (outerComposite.MyNumberOption.IsSet) + writer.WriteNumber("my_number", outerComposite.MyNumberOption.Value.Value); + + if (outerComposite.MyStringOption.IsSet) + writer.WriteString("my_string", outerComposite.MyString); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs index a4ec335bb386..47bb6793c6ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index 7c67db5ddca3..136fb4c54c4e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs index 84ea65297ab0..2ed4f18a657e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumInteger.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs index 983d194a1998..c6a470cc64d1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumIntegerDefaultValue.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs index 51d8bee407e0..a2e789f2edef 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/OuterEnumTest.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs index eb0129c6ce0f..c451e1a8991b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ParentPet.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -76,7 +77,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string petType = default; + Option petType = default; while (utf8JsonReader.Read()) { @@ -94,7 +95,7 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon switch (localVarJsonPropertyName) { case "pet_type": - petType = utf8JsonReader.GetString(); + petType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -102,10 +103,13 @@ public override ParentPet Read(ref Utf8JsonReader utf8JsonReader, Type typeToCon } } - if (petType == null) - throw new ArgumentNullException(nameof(petType), "Property is required for class ParentPet."); + if (!petType.IsSet) + throw new ArgumentException("Property is required for class ParentPet.", nameof(petType)); - return new ParentPet(petType); + if (petType.IsSet && petType.Value == null) + throw new ArgumentNullException(nameof(petType), "Property is not nullable for class ParentPet."); + + return new ParentPet(petType.Value); } /// @@ -132,6 +136,9 @@ public override void Write(Utf8JsonWriter writer, ParentPet parentPet, JsonSeria /// public void WriteProperties(ref Utf8JsonWriter writer, ParentPet parentPet, JsonSerializerOptions jsonSerializerOptions) { + if (parentPet.PetType == null) + throw new ArgumentNullException(nameof(parentPet.PetType), "Property is required for class ParentPet."); + writer.WriteString("pet_type", parentPet.PetType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs index aa380014a324..59c2707e1100 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pet.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,21 +32,21 @@ public partial class Pet : IValidatableObject /// /// Initializes a new instance of the class. /// - /// category - /// id /// name /// photoUrls + /// category + /// id /// pet status in the store /// tags [JsonConstructor] - public Pet(Category category, long id, string name, List photoUrls, StatusEnum status, List tags) + public Pet(string name, List photoUrls, Option category = default, Option id = default, Option status = default, Option> tags = default) { - Category = category; - Id = id; Name = name; PhotoUrls = photoUrls; - Status = status; - Tags = tags; + CategoryOption = category; + IdOption = id; + StatusOption = status; + TagsOption = tags; OnCreated(); } @@ -118,7 +119,7 @@ public static StatusEnum StatusEnumFromString(string value) /// /// /// - public static string StatusEnumToJsonValue(StatusEnum value) + public static string StatusEnumToJsonValue(StatusEnum? value) { if (value == StatusEnum.Available) return "available"; @@ -132,43 +133,71 @@ public static string StatusEnumToJsonValue(StatusEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Status + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option StatusOption { get; private set; } + /// /// pet status in the store /// /// pet status in the store [JsonPropertyName("status")] - public StatusEnum Status { get; set; } + public StatusEnum? Status { get { return this.StatusOption; } set { this.StatusOption = new Option(value); } } + + /// + /// Gets or Sets Name + /// + /// doggie + [JsonPropertyName("name")] + public string Name { get; set; } + + /// + /// Gets or Sets PhotoUrls + /// + [JsonPropertyName("photoUrls")] + public List PhotoUrls { get; set; } + + /// + /// Used to track the state of Category + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option CategoryOption { get; private set; } /// /// Gets or Sets Category /// [JsonPropertyName("category")] - public Category Category { get; set; } + public Category Category { get { return this. CategoryOption; } set { this.CategoryOption = new Option(value); } } /// - /// Gets or Sets Id + /// Used to track the state of Id /// - [JsonPropertyName("id")] - public long Id { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// - /// Gets or Sets Name + /// Gets or Sets Id /// - /// doggie - [JsonPropertyName("name")] - public string Name { get; set; } + [JsonPropertyName("id")] + public long? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } /// - /// Gets or Sets PhotoUrls + /// Used to track the state of Tags /// - [JsonPropertyName("photoUrls")] - public List PhotoUrls { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> TagsOption { get; private set; } /// /// Gets or Sets Tags /// [JsonPropertyName("tags")] - public List Tags { get; set; } + public List Tags { get { return this. TagsOption; } set { this.TagsOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -184,10 +213,10 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Pet {\n"); - sb.Append(" Category: ").Append(Category).Append("\n"); - sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" PhotoUrls: ").Append(PhotoUrls).Append("\n"); + sb.Append(" Category: ").Append(Category).Append("\n"); + sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" Status: ").Append(Status).Append("\n"); sb.Append(" Tags: ").Append(Tags).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -228,12 +257,12 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - Category category = default; - long? id = default; - string name = default; - List photoUrls = default; - Pet.StatusEnum? status = default; - List tags = default; + Option name = default; + Option> photoUrls = default; + Option category = default; + Option id = default; + Option status = default; + Option> tags = default; while (utf8JsonReader.Read()) { @@ -250,30 +279,29 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { - case "category": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - category = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + case "name": + name = new Option(utf8JsonReader.GetString()); break; - case "id": + case "photoUrls": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + photoUrls = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; - case "name": - name = utf8JsonReader.GetString(); + case "category": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + category = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; - case "photoUrls": + case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - photoUrls = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + id = new Option(utf8JsonReader.GetInt64()); break; case "status": string statusRawValue = utf8JsonReader.GetString(); - status = statusRawValue == null - ? null - : Pet.StatusEnumFromStringOrDefault(statusRawValue); + if (statusRawValue != null) + status = new Option(Pet.StatusEnumFromStringOrDefault(statusRawValue)); break; case "tags": if (utf8JsonReader.TokenType != JsonTokenType.Null) - tags = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + tags = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -281,25 +309,31 @@ public override Pet Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (category == null) - throw new ArgumentNullException(nameof(category), "Property is required for class Pet."); + if (!name.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(name)); + + if (!photoUrls.IsSet) + throw new ArgumentException("Property is required for class Pet.", nameof(photoUrls)); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Pet."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Pet."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Pet."); + if (photoUrls.IsSet && photoUrls.Value == null) + throw new ArgumentNullException(nameof(photoUrls), "Property is not nullable for class Pet."); - if (photoUrls == null) - throw new ArgumentNullException(nameof(photoUrls), "Property is required for class Pet."); + if (category.IsSet && category.Value == null) + throw new ArgumentNullException(nameof(category), "Property is not nullable for class Pet."); - if (status == null) - throw new ArgumentNullException(nameof(status), "Property is required for class Pet."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Pet."); - if (tags == null) - throw new ArgumentNullException(nameof(tags), "Property is required for class Pet."); + if (status.IsSet && status.Value == null) + throw new ArgumentNullException(nameof(status), "Property is not nullable for class Pet."); - return new Pet(category, id.Value, name, photoUrls, status.Value, tags); + if (tags.IsSet && tags.Value == null) + throw new ArgumentNullException(nameof(tags), "Property is not nullable for class Pet."); + + return new Pet(name.Value, photoUrls.Value, category, id, status, tags); } /// @@ -326,21 +360,37 @@ public override void Write(Utf8JsonWriter writer, Pet pet, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pet pet, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("category"); - JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); - writer.WriteNumber("id", pet.Id); + if (pet.Name == null) + throw new ArgumentNullException(nameof(pet.Name), "Property is required for class Pet."); + + if (pet.PhotoUrls == null) + throw new ArgumentNullException(nameof(pet.PhotoUrls), "Property is required for class Pet."); + + if (pet.CategoryOption.IsSet && pet.Category == null) + throw new ArgumentNullException(nameof(pet.Category), "Property is required for class Pet."); + + if (pet.TagsOption.IsSet && pet.Tags == null) + throw new ArgumentNullException(nameof(pet.Tags), "Property is required for class Pet."); + writer.WriteString("name", pet.Name); + writer.WritePropertyName("photoUrls"); JsonSerializer.Serialize(writer, pet.PhotoUrls, jsonSerializerOptions); + if (pet.CategoryOption.IsSet) + { + writer.WritePropertyName("category"); + JsonSerializer.Serialize(writer, pet.Category, jsonSerializerOptions); + } + if (pet.IdOption.IsSet) + writer.WriteNumber("id", pet.IdOption.Value.Value); - var statusRawValue = Pet.StatusEnumToJsonValue(pet.Status); - if (statusRawValue != null) - writer.WriteString("status", statusRawValue); - else - writer.WriteNull("status"); - - writer.WritePropertyName("tags"); - JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + var statusRawValue = Pet.StatusEnumToJsonValue(pet.StatusOption.Value.Value); + writer.WriteString("status", statusRawValue); + if (pet.TagsOption.IsSet) + { + writer.WritePropertyName("tags"); + JsonSerializer.Serialize(writer, pet.Tags, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs index 8185d643e794..d3bbeb8ff326 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Pig.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; + Option className = default; BasquePig basquePig = null; DanishPig danishPig = null; @@ -184,7 +185,7 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Pig Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Pig."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Pig.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Pig."); if (basquePig != null) - return new Pig(basquePig, className); + return new Pig(basquePig, className.Value); if (danishPig != null) - return new Pig(danishPig, className); + return new Pig(danishPig, className.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Pig pig, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Pig pig, JsonSerializerOptions jsonSerializerOptions) { + if (pig.ClassName == null) + throw new ArgumentNullException(nameof(pig.ClassName), "Property is required for class Pig."); + writer.WriteString("className", pig.ClassName); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs index 3a89a8716e07..2c2227a22512 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/PolymorphicProperty.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs index 65f7b8b4536f..3f4034a17713 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Quadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; + Option quadrilateralType = default; ComplexQuadrilateral complexQuadrilateral = null; SimpleQuadrilateral simpleQuadrilateral = null; @@ -184,7 +185,7 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Quadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class Quadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class Quadrilateral.", nameof(quadrilateralType)); + + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class Quadrilateral."); if (complexQuadrilateral != null) - return new Quadrilateral(complexQuadrilateral, quadrilateralType); + return new Quadrilateral(complexQuadrilateral, quadrilateralType.Value); if (simpleQuadrilateral != null) - return new Quadrilateral(simpleQuadrilateral, quadrilateralType); + return new Quadrilateral(simpleQuadrilateral, quadrilateralType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Quadrilateral quadrilateral, J /// public void WriteProperties(ref Utf8JsonWriter writer, Quadrilateral quadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateral.QuadrilateralType), "Property is required for class Quadrilateral."); + writer.WriteString("quadrilateralType", quadrilateral.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs index c329eed3266b..75b7e516cfca 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/QuadrilateralInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; + Option quadrilateralType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override QuadrilateralInterface Read(ref Utf8JsonReader utf8JsonReader, T } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class QuadrilateralInterface."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class QuadrilateralInterface.", nameof(quadrilateralType)); - return new QuadrilateralInterface(quadrilateralType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class QuadrilateralInterface."); + + return new QuadrilateralInterface(quadrilateralType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, QuadrilateralInterface quadril /// public void WriteProperties(ref Utf8JsonWriter writer, QuadrilateralInterface quadrilateralInterface, JsonSerializerOptions jsonSerializerOptions) { + if (quadrilateralInterface.QuadrilateralType == null) + throw new ArgumentNullException(nameof(quadrilateralInterface.QuadrilateralType), "Property is required for class QuadrilateralInterface."); + writer.WriteString("quadrilateralType", quadrilateralInterface.QuadrilateralType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs index 2c8b4fff43d6..d5b7e21838df 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ReadOnlyFirst.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class ReadOnlyFirst : IEquatable, IValidatableObje /// bar /// baz [JsonConstructor] - public ReadOnlyFirst(string bar, string baz) + public ReadOnlyFirst(Option bar = default, Option baz = default) { - Bar = bar; - Baz = baz; + BarOption = bar; + BazOption = baz; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Bar + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BarOption { get; } + /// /// Gets or Sets Bar /// [JsonPropertyName("bar")] - public string Bar { get; } + public string Bar { get { return this. BarOption; } } + + /// + /// Used to track the state of Baz + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option BazOption { get; private set; } /// /// Gets or Sets Baz /// [JsonPropertyName("baz")] - public string Baz { get; set; } + public string Baz { get { return this. BazOption; } set { this.BazOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -105,7 +120,9 @@ public override int GetHashCode() unchecked // Overflow is fine, just wrap { int hashCode = 41; - hashCode = (hashCode * 59) + Bar.GetHashCode(); + if (Bar != null) + hashCode = (hashCode * 59) + Bar.GetHashCode(); + hashCode = (hashCode * 59) + AdditionalProperties.GetHashCode(); return hashCode; @@ -145,8 +162,8 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string bar = default; - string baz = default; + Option bar = default; + Option baz = default; while (utf8JsonReader.Read()) { @@ -164,10 +181,10 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT switch (localVarJsonPropertyName) { case "bar": - bar = utf8JsonReader.GetString(); + bar = new Option(utf8JsonReader.GetString()); break; case "baz": - baz = utf8JsonReader.GetString(); + baz = new Option(utf8JsonReader.GetString()); break; default: break; @@ -175,11 +192,11 @@ public override ReadOnlyFirst Read(ref Utf8JsonReader utf8JsonReader, Type typeT } } - if (bar == null) - throw new ArgumentNullException(nameof(bar), "Property is required for class ReadOnlyFirst."); + if (bar.IsSet && bar.Value == null) + throw new ArgumentNullException(nameof(bar), "Property is not nullable for class ReadOnlyFirst."); - if (baz == null) - throw new ArgumentNullException(nameof(baz), "Property is required for class ReadOnlyFirst."); + if (baz.IsSet && baz.Value == null) + throw new ArgumentNullException(nameof(baz), "Property is not nullable for class ReadOnlyFirst."); return new ReadOnlyFirst(bar, baz); } @@ -208,8 +225,17 @@ public override void Write(Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, J /// public void WriteProperties(ref Utf8JsonWriter writer, ReadOnlyFirst readOnlyFirst, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("bar", readOnlyFirst.Bar); - writer.WriteString("baz", readOnlyFirst.Baz); + if (readOnlyFirst.BarOption.IsSet && readOnlyFirst.Bar == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Bar), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BazOption.IsSet && readOnlyFirst.Baz == null) + throw new ArgumentNullException(nameof(readOnlyFirst.Baz), "Property is required for class ReadOnlyFirst."); + + if (readOnlyFirst.BarOption.IsSet) + writer.WriteString("bar", readOnlyFirst.Bar); + + if (readOnlyFirst.BazOption.IsSet) + writer.WriteString("baz", readOnlyFirst.Baz); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..483b3a96a212 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,2378 @@ +// +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Text; +using System.Text.RegularExpressions; +using System.Text.Json; +using System.Text.Json.Serialization; +using System.ComponentModel.DataAnnotations; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + public partial class RequiredClass : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// requiredNotNullableDateProp + /// requiredNotnullableArrayOfString + /// requiredNotnullableBooleanProp + /// requiredNotnullableDatetimeProp + /// requiredNotnullableEnumInteger + /// requiredNotnullableEnumIntegerOnly + /// requiredNotnullableEnumString + /// requiredNotnullableOuterEnumDefaultValue + /// requiredNotnullableStringProp + /// requiredNotnullableUuid + /// requiredNotnullableintegerProp + /// requiredNullableArrayOfString + /// requiredNullableBooleanProp + /// requiredNullableDateProp + /// requiredNullableDatetimeProp + /// requiredNullableEnumInteger + /// requiredNullableEnumIntegerOnly + /// requiredNullableEnumString + /// requiredNullableIntegerProp + /// requiredNullableOuterEnumDefaultValue + /// requiredNullableStringProp + /// requiredNullableUuid + /// notRequiredNotnullableDateProp + /// notRequiredNotnullableintegerProp + /// notRequiredNullableDateProp + /// notRequiredNullableIntegerProp + /// notrequiredNotnullableArrayOfString + /// notrequiredNotnullableBooleanProp + /// notrequiredNotnullableDatetimeProp + /// notrequiredNotnullableEnumInteger + /// notrequiredNotnullableEnumIntegerOnly + /// notrequiredNotnullableEnumString + /// notrequiredNotnullableOuterEnumDefaultValue + /// notrequiredNotnullableStringProp + /// notrequiredNotnullableUuid + /// notrequiredNullableArrayOfString + /// notrequiredNullableBooleanProp + /// notrequiredNullableDatetimeProp + /// notrequiredNullableEnumInteger + /// notrequiredNullableEnumIntegerOnly + /// notrequiredNullableEnumString + /// notrequiredNullableOuterEnumDefaultValue + /// notrequiredNullableStringProp + /// notrequiredNullableUuid + [JsonConstructor] + public RequiredClass(DateTime requiredNotNullableDateProp, List requiredNotnullableArrayOfString, bool requiredNotnullableBooleanProp, DateTime requiredNotnullableDatetimeProp, RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger, RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly, RequiredNotnullableEnumStringEnum requiredNotnullableEnumString, OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue, string requiredNotnullableStringProp, Guid requiredNotnullableUuid, int requiredNotnullableintegerProp, List requiredNullableArrayOfString = default, bool? requiredNullableBooleanProp = default, DateTime? requiredNullableDateProp = default, DateTime? requiredNullableDatetimeProp = default, RequiredNullableEnumIntegerEnum? requiredNullableEnumInteger = default, RequiredNullableEnumIntegerOnlyEnum? requiredNullableEnumIntegerOnly = default, RequiredNullableEnumStringEnum? requiredNullableEnumString = default, int? requiredNullableIntegerProp = default, OuterEnumDefaultValue? requiredNullableOuterEnumDefaultValue = default, string requiredNullableStringProp = default, Guid? requiredNullableUuid = default, Option notRequiredNotnullableDateProp = default, Option notRequiredNotnullableintegerProp = default, Option notRequiredNullableDateProp = default, Option notRequiredNullableIntegerProp = default, Option> notrequiredNotnullableArrayOfString = default, Option notrequiredNotnullableBooleanProp = default, Option notrequiredNotnullableDatetimeProp = default, Option notrequiredNotnullableEnumInteger = default, Option notrequiredNotnullableEnumIntegerOnly = default, Option notrequiredNotnullableEnumString = default, Option notrequiredNotnullableOuterEnumDefaultValue = default, Option notrequiredNotnullableStringProp = default, Option notrequiredNotnullableUuid = default, Option> notrequiredNullableArrayOfString = default, Option notrequiredNullableBooleanProp = default, Option notrequiredNullableDatetimeProp = default, Option notrequiredNullableEnumInteger = default, Option notrequiredNullableEnumIntegerOnly = default, Option notrequiredNullableEnumString = default, Option notrequiredNullableOuterEnumDefaultValue = default, Option notrequiredNullableStringProp = default, Option notrequiredNullableUuid = default) + { + RequiredNotNullableDateProp = requiredNotNullableDateProp; + RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + RequiredNotnullableEnumString = requiredNotnullableEnumString; + RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + RequiredNotnullableStringProp = requiredNotnullableStringProp; + RequiredNotnullableUuid = requiredNotnullableUuid; + RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + RequiredNullableArrayOfString = requiredNullableArrayOfString; + RequiredNullableBooleanProp = requiredNullableBooleanProp; + RequiredNullableDateProp = requiredNullableDateProp; + RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + RequiredNullableEnumInteger = requiredNullableEnumInteger; + RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + RequiredNullableEnumString = requiredNullableEnumString; + RequiredNullableIntegerProp = requiredNullableIntegerProp; + RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + RequiredNullableStringProp = requiredNullableStringProp; + RequiredNullableUuid = requiredNullableUuid; + NotRequiredNotnullableDatePropOption = notRequiredNotnullableDateProp; + NotRequiredNotnullableintegerPropOption = notRequiredNotnullableintegerProp; + NotRequiredNullableDatePropOption = notRequiredNullableDateProp; + NotRequiredNullableIntegerPropOption = notRequiredNullableIntegerProp; + NotrequiredNotnullableArrayOfStringOption = notrequiredNotnullableArrayOfString; + NotrequiredNotnullableBooleanPropOption = notrequiredNotnullableBooleanProp; + NotrequiredNotnullableDatetimePropOption = notrequiredNotnullableDatetimeProp; + NotrequiredNotnullableEnumIntegerOption = notrequiredNotnullableEnumInteger; + NotrequiredNotnullableEnumIntegerOnlyOption = notrequiredNotnullableEnumIntegerOnly; + NotrequiredNotnullableEnumStringOption = notrequiredNotnullableEnumString; + NotrequiredNotnullableOuterEnumDefaultValueOption = notrequiredNotnullableOuterEnumDefaultValue; + NotrequiredNotnullableStringPropOption = notrequiredNotnullableStringProp; + NotrequiredNotnullableUuidOption = notrequiredNotnullableUuid; + NotrequiredNullableArrayOfStringOption = notrequiredNullableArrayOfString; + NotrequiredNullableBooleanPropOption = notrequiredNullableBooleanProp; + NotrequiredNullableDatetimePropOption = notrequiredNullableDatetimeProp; + NotrequiredNullableEnumIntegerOption = notrequiredNullableEnumInteger; + NotrequiredNullableEnumIntegerOnlyOption = notrequiredNullableEnumIntegerOnly; + NotrequiredNullableEnumStringOption = notrequiredNullableEnumString; + NotrequiredNullableOuterEnumDefaultValueOption = notrequiredNullableOuterEnumDefaultValue; + NotrequiredNullableStringPropOption = notrequiredNullableStringProp; + NotrequiredNullableUuidOption = notrequiredNullableUuid; + OnCreated(); + } + + partial void OnCreated(); + + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerEnum? RequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerEnumToJsonValue(RequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [JsonPropertyName("required_notnullable_enum_integer")] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumIntegerOnlyEnum? RequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(RequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("required_notnullable_enum_integer_only")] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNotnullableEnumString + /// + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNotnullableEnumStringEnum RequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNotnullableEnumStringEnum? RequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNotnullableEnumStringEnumToJsonValue(RequiredNotnullableEnumStringEnum value) + { + if (value == RequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [JsonPropertyName("required_notnullable_enum_string")] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerEnum RequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerEnum? RequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return RequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerEnumToJsonValue(RequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [JsonPropertyName("required_nullable_enum_integer")] + public RequiredNullableEnumIntegerEnum? RequiredNullableEnumInteger { get; set; } + + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return RequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int RequiredNullableEnumIntegerOnlyEnumToJsonValue(RequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("required_nullable_enum_integer_only")] + public RequiredNullableEnumIntegerOnlyEnum? RequiredNullableEnumIntegerOnly { get; set; } + + /// + /// Defines RequiredNullableEnumString + /// + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static RequiredNullableEnumStringEnum RequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type RequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static RequiredNullableEnumStringEnum? RequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return RequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return RequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return RequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return RequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return RequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return RequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return RequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string RequiredNullableEnumStringEnumToJsonValue(RequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == RequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == RequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == RequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == RequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == RequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == RequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == RequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [JsonPropertyName("required_nullable_enum_string")] + public RequiredNullableEnumStringEnum? RequiredNullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("required_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum NotrequiredNotnullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNotnullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerEnumToJsonValue(NotrequiredNotnullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [JsonPropertyName("notrequired_notnullable_enum_integer")] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get { return this.NotrequiredNotnullableEnumIntegerOption; } set { this.NotrequiredNotnullableEnumIntegerOption = new Option(value); } } + + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum NotrequiredNotnullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNotnullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNotnullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_notnullable_enum_integer_only")] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get { return this.NotrequiredNotnullableEnumIntegerOnlyOption; } set { this.NotrequiredNotnullableEnumIntegerOnlyOption = new Option(value); } } + + /// + /// Defines NotrequiredNotnullableEnumString + /// + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum NotrequiredNotnullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNotnullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNotnullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNotnullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNotnullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNotnullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNotnullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNotnullableEnumStringEnumToJsonValue(NotrequiredNotnullableEnumStringEnum? value) + { + if (value == NotrequiredNotnullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNotnullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNotnullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNotnullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNotnullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNotnullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [JsonPropertyName("notrequired_notnullable_enum_string")] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get { return this.NotrequiredNotnullableEnumStringOption; } set { this.NotrequiredNotnullableEnumStringOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_notnullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get { return this.NotrequiredNotnullableOuterEnumDefaultValueOption; } set { this.NotrequiredNotnullableOuterEnumDefaultValueOption = new Option(value); } } + + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum NotrequiredNullableEnumIntegerEnumFromString(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumIntegerEnumFromStringOrDefault(string value) + { + if (value.Equals((1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_1; + + if (value.Equals((-1).ToString())) + return NotrequiredNullableEnumIntegerEnum.NUMBER_MINUS_1; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerEnumToJsonValue(NotrequiredNullableEnumIntegerEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumInteger + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [JsonPropertyName("notrequired_nullable_enum_integer")] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get { return this.NotrequiredNullableEnumIntegerOption; } set { this.NotrequiredNullableEnumIntegerOption = new Option(value); } } + + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum NotrequiredNullableEnumIntegerOnlyEnumFromString(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumIntegerOnlyEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnlyEnumFromStringOrDefault(string value) + { + if (value.Equals((2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_2; + + if (value.Equals((-2).ToString())) + return NotrequiredNullableEnumIntegerOnlyEnum.NUMBER_MINUS_2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + public static int NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(NotrequiredNullableEnumIntegerOnlyEnum value) + { + return (int) value; + } + + /// + /// Used to track the state of NotrequiredNullableEnumIntegerOnly + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumIntegerOnlyOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [JsonPropertyName("notrequired_nullable_enum_integer_only")] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get { return this.NotrequiredNullableEnumIntegerOnlyOption; } set { this.NotrequiredNullableEnumIntegerOnlyOption = new Option(value); } } + + /// + /// Defines NotrequiredNullableEnumString + /// + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + Lower = 2, + + /// + /// Enum Empty for value: + /// + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + Duplicatevalue2 = 8 + } + + /// + /// Returns a + /// + /// + /// + /// + public static NotrequiredNullableEnumStringEnum NotrequiredNullableEnumStringEnumFromString(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + throw new NotImplementedException($"Could not convert value to type NotrequiredNullableEnumStringEnum: '{value}'"); + } + + /// + /// Returns a + /// + /// + /// + public static NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumStringEnumFromStringOrDefault(string value) + { + if (value.Equals("UPPER")) + return NotrequiredNullableEnumStringEnum.UPPER; + + if (value.Equals("lower")) + return NotrequiredNullableEnumStringEnum.Lower; + + if (value.Equals("")) + return NotrequiredNullableEnumStringEnum.Empty; + + if (value.Equals("Value\twith tab")) + return NotrequiredNullableEnumStringEnum.ValuewithTab; + + if (value.Equals("Value with \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithQuote; + + if (value.Equals("Value with escaped \" quote")) + return NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote; + + if (value.Equals("Duplicate\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue; + + if (value.Equals("Duplicate\r\nvalue")) + return NotrequiredNullableEnumStringEnum.Duplicatevalue2; + + return null; + } + + /// + /// Converts the to the json value + /// + /// + /// + /// + public static string NotrequiredNullableEnumStringEnumToJsonValue(NotrequiredNullableEnumStringEnum? value) + { + if (value == null) + return null; + + if (value == NotrequiredNullableEnumStringEnum.UPPER) + return "UPPER"; + + if (value == NotrequiredNullableEnumStringEnum.Lower) + return "lower"; + + if (value == NotrequiredNullableEnumStringEnum.Empty) + return ""; + + if (value == NotrequiredNullableEnumStringEnum.ValuewithTab) + return "Value\twith tab"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithQuote) + return "Value with \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.ValueWithEscapedQuote) + return "Value with escaped \" quote"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue) + return "Duplicate\nvalue"; + + if (value == NotrequiredNullableEnumStringEnum.Duplicatevalue2) + return "Duplicate\r\nvalue"; + + throw new NotImplementedException($"Value could not be handled: '{value}'"); + } + + /// + /// Used to track the state of NotrequiredNullableEnumString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableEnumStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [JsonPropertyName("notrequired_nullable_enum_string")] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get { return this.NotrequiredNullableEnumStringOption; } set { this.NotrequiredNullableEnumStringOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNullableOuterEnumDefaultValue + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableOuterEnumDefaultValueOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [JsonPropertyName("notrequired_nullable_outerEnumDefaultValue")] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get { return this.NotrequiredNullableOuterEnumDefaultValueOption; } set { this.NotrequiredNullableOuterEnumDefaultValueOption = new Option(value); } } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [JsonPropertyName("required_not_nullable_date_prop")] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [JsonPropertyName("required_notnullable_array_of_string")] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [JsonPropertyName("required_notnullable_boolean_prop")] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [JsonPropertyName("required_notnullable_datetime_prop")] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [JsonPropertyName("required_notnullable_string_prop")] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_notnullable_uuid")] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [JsonPropertyName("required_notnullableinteger_prop")] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [JsonPropertyName("required_nullable_array_of_string")] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [JsonPropertyName("required_nullable_boolean_prop")] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [JsonPropertyName("required_nullable_date_prop")] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [JsonPropertyName("required_nullable_datetime_prop")] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [JsonPropertyName("required_nullable_integer_prop")] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [JsonPropertyName("required_nullable_string_prop")] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("required_nullable_uuid")] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Used to track the state of NotRequiredNotnullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [JsonPropertyName("not_required_notnullable_date_prop")] + public DateTime? NotRequiredNotnullableDateProp { get { return this. NotRequiredNotnullableDatePropOption; } set { this.NotRequiredNotnullableDatePropOption = new Option(value); } } + + /// + /// Used to track the state of NotRequiredNotnullableintegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNotnullableintegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [JsonPropertyName("not_required_notnullableinteger_prop")] + public int? NotRequiredNotnullableintegerProp { get { return this. NotRequiredNotnullableintegerPropOption; } set { this.NotRequiredNotnullableintegerPropOption = new Option(value); } } + + /// + /// Used to track the state of NotRequiredNullableDateProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableDatePropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [JsonPropertyName("not_required_nullable_date_prop")] + public DateTime? NotRequiredNullableDateProp { get { return this. NotRequiredNullableDatePropOption; } set { this.NotRequiredNullableDatePropOption = new Option(value); } } + + /// + /// Used to track the state of NotRequiredNullableIntegerProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotRequiredNullableIntegerPropOption { get; private set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [JsonPropertyName("not_required_nullable_integer_prop")] + public int? NotRequiredNullableIntegerProp { get { return this. NotRequiredNullableIntegerPropOption; } set { this.NotRequiredNullableIntegerPropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> NotrequiredNotnullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [JsonPropertyName("notrequired_notnullable_array_of_string")] + public List NotrequiredNotnullableArrayOfString { get { return this. NotrequiredNotnullableArrayOfStringOption; } set { this.NotrequiredNotnullableArrayOfStringOption = new Option>(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [JsonPropertyName("notrequired_notnullable_boolean_prop")] + public bool? NotrequiredNotnullableBooleanProp { get { return this. NotrequiredNotnullableBooleanPropOption; } set { this.NotrequiredNotnullableBooleanPropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [JsonPropertyName("notrequired_notnullable_datetime_prop")] + public DateTime? NotrequiredNotnullableDatetimeProp { get { return this. NotrequiredNotnullableDatetimePropOption; } set { this.NotrequiredNotnullableDatetimePropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [JsonPropertyName("notrequired_notnullable_string_prop")] + public string NotrequiredNotnullableStringProp { get { return this. NotrequiredNotnullableStringPropOption; } set { this.NotrequiredNotnullableStringPropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNotnullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNotnullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_notnullable_uuid")] + public Guid? NotrequiredNotnullableUuid { get { return this. NotrequiredNotnullableUuidOption; } set { this.NotrequiredNotnullableUuidOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNullableArrayOfString + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> NotrequiredNullableArrayOfStringOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [JsonPropertyName("notrequired_nullable_array_of_string")] + public List NotrequiredNullableArrayOfString { get { return this. NotrequiredNullableArrayOfStringOption; } set { this.NotrequiredNullableArrayOfStringOption = new Option>(value); } } + + /// + /// Used to track the state of NotrequiredNullableBooleanProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableBooleanPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [JsonPropertyName("notrequired_nullable_boolean_prop")] + public bool? NotrequiredNullableBooleanProp { get { return this. NotrequiredNullableBooleanPropOption; } set { this.NotrequiredNullableBooleanPropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNullableDatetimeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableDatetimePropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [JsonPropertyName("notrequired_nullable_datetime_prop")] + public DateTime? NotrequiredNullableDatetimeProp { get { return this. NotrequiredNullableDatetimePropOption; } set { this.NotrequiredNullableDatetimePropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNullableStringProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableStringPropOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [JsonPropertyName("notrequired_nullable_string_prop")] + public string NotrequiredNullableStringProp { get { return this. NotrequiredNullableStringPropOption; } set { this.NotrequiredNullableStringPropOption = new Option(value); } } + + /// + /// Used to track the state of NotrequiredNullableUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NotrequiredNullableUuidOption { get; private set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [JsonPropertyName("notrequired_nullable_uuid")] + public Guid? NotrequiredNullableUuid { get { return this. NotrequiredNullableUuidOption; } set { this.NotrequiredNullableUuidOption = new Option(value); } } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public Dictionary AdditionalProperties { get; } = new Dictionary(); + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + + /// + /// A Json converter for type + /// + public class RequiredClassJsonConverter : JsonConverter + { + /// + /// The format to use to serialize RequiredNotNullableDateProp + /// + public static string RequiredNotNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNotnullableDatetimeProp + /// + public static string RequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize RequiredNullableDateProp + /// + public static string RequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize RequiredNullableDatetimeProp + /// + public static string RequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotRequiredNotnullableDateProp + /// + public static string NotRequiredNotnullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotRequiredNullableDateProp + /// + public static string NotRequiredNullableDatePropFormat { get; set; } = "yyyy'-'MM'-'dd"; + + /// + /// The format to use to serialize NotrequiredNotnullableDatetimeProp + /// + public static string NotrequiredNotnullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// The format to use to serialize NotrequiredNullableDatetimeProp + /// + public static string NotrequiredNullableDatetimePropFormat { get; set; } = "yyyy'-'MM'-'dd'T'HH':'mm':'ss'.'fffffffK"; + + /// + /// Deserializes json to + /// + /// + /// + /// + /// + /// + public override RequiredClass Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonSerializerOptions jsonSerializerOptions) + { + int currentDepth = utf8JsonReader.CurrentDepth; + + if (utf8JsonReader.TokenType != JsonTokenType.StartObject && utf8JsonReader.TokenType != JsonTokenType.StartArray) + throw new JsonException(); + + JsonTokenType startingTokenType = utf8JsonReader.TokenType; + + Option requiredNotNullableDateProp = default; + Option> requiredNotnullableArrayOfString = default; + Option requiredNotnullableBooleanProp = default; + Option requiredNotnullableDatetimeProp = default; + Option requiredNotnullableEnumInteger = default; + Option requiredNotnullableEnumIntegerOnly = default; + Option requiredNotnullableEnumString = default; + Option requiredNotnullableOuterEnumDefaultValue = default; + Option requiredNotnullableStringProp = default; + Option requiredNotnullableUuid = default; + Option requiredNotnullableintegerProp = default; + Option> requiredNullableArrayOfString = default; + Option requiredNullableBooleanProp = default; + Option requiredNullableDateProp = default; + Option requiredNullableDatetimeProp = default; + Option requiredNullableEnumInteger = default; + Option requiredNullableEnumIntegerOnly = default; + Option requiredNullableEnumString = default; + Option requiredNullableIntegerProp = default; + Option requiredNullableOuterEnumDefaultValue = default; + Option requiredNullableStringProp = default; + Option requiredNullableUuid = default; + Option notRequiredNotnullableDateProp = default; + Option notRequiredNotnullableintegerProp = default; + Option notRequiredNullableDateProp = default; + Option notRequiredNullableIntegerProp = default; + Option> notrequiredNotnullableArrayOfString = default; + Option notrequiredNotnullableBooleanProp = default; + Option notrequiredNotnullableDatetimeProp = default; + Option notrequiredNotnullableEnumInteger = default; + Option notrequiredNotnullableEnumIntegerOnly = default; + Option notrequiredNotnullableEnumString = default; + Option notrequiredNotnullableOuterEnumDefaultValue = default; + Option notrequiredNotnullableStringProp = default; + Option notrequiredNotnullableUuid = default; + Option> notrequiredNullableArrayOfString = default; + Option notrequiredNullableBooleanProp = default; + Option notrequiredNullableDatetimeProp = default; + Option notrequiredNullableEnumInteger = default; + Option notrequiredNullableEnumIntegerOnly = default; + Option notrequiredNullableEnumString = default; + Option notrequiredNullableOuterEnumDefaultValue = default; + Option notrequiredNullableStringProp = default; + Option notrequiredNullableUuid = default; + + while (utf8JsonReader.Read()) + { + if (startingTokenType == JsonTokenType.StartObject && utf8JsonReader.TokenType == JsonTokenType.EndObject && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (startingTokenType == JsonTokenType.StartArray && utf8JsonReader.TokenType == JsonTokenType.EndArray && currentDepth == utf8JsonReader.CurrentDepth) + break; + + if (utf8JsonReader.TokenType == JsonTokenType.PropertyName && currentDepth == utf8JsonReader.CurrentDepth - 1) + { + string localVarJsonPropertyName = utf8JsonReader.GetString(); + utf8JsonReader.Read(); + + switch (localVarJsonPropertyName) + { + case "required_not_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumInteger = new Option((RequiredClass.RequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableEnumIntegerOnly = new Option((RequiredClass.RequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_notnullable_enum_string": + string requiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableEnumStringRawValue != null) + requiredNotnullableEnumString = new Option(RequiredClass.RequiredNotnullableEnumStringEnumFromStringOrDefault(requiredNotnullableEnumStringRawValue)); + break; + case "required_notnullable_outerEnumDefaultValue": + string requiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNotnullableOuterEnumDefaultValueRawValue != null) + requiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "required_notnullable_string_prop": + requiredNotnullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "required_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumInteger = new Option((RequiredClass.RequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableEnumIntegerOnly = new Option((RequiredClass.RequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "required_nullable_enum_string": + string requiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (requiredNullableEnumStringRawValue != null) + requiredNullableEnumString = new Option(RequiredClass.RequiredNullableEnumStringEnumFromStringOrDefault(requiredNullableEnumStringRawValue)); + break; + case "required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "required_nullable_outerEnumDefaultValue": + string requiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + requiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(requiredNullableOuterEnumDefaultValueRawValue)); + break; + case "required_nullable_string_prop": + requiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "required_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + requiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "not_required_notnullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_notnullableinteger_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNotnullableintegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "not_required_nullable_date_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableDateProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "not_required_nullable_integer_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notRequiredNullableIntegerProp = new Option(utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_notnullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_notnullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumInteger = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_notnullable_enum_string": + string notrequiredNotnullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableEnumStringRawValue != null) + notrequiredNotnullableEnumString = new Option(RequiredClass.NotrequiredNotnullableEnumStringEnumFromStringOrDefault(notrequiredNotnullableEnumStringRawValue)); + break; + case "notrequired_notnullable_outerEnumDefaultValue": + string notrequiredNotnullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNotnullableOuterEnumDefaultValueRawValue != null) + notrequiredNotnullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNotnullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_notnullable_string_prop": + notrequiredNotnullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_notnullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNotnullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + case "notrequired_nullable_array_of_string": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableArrayOfString = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_boolean_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableBooleanProp = new Option(utf8JsonReader.GetBoolean()); + break; + case "notrequired_nullable_datetime_prop": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableDatetimeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "notrequired_nullable_enum_integer": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumInteger = new Option((RequiredClass.NotrequiredNullableEnumIntegerEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_integer_only": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableEnumIntegerOnly = new Option((RequiredClass.NotrequiredNullableEnumIntegerOnlyEnum)utf8JsonReader.GetInt32()); + break; + case "notrequired_nullable_enum_string": + string notrequiredNullableEnumStringRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableEnumStringRawValue != null) + notrequiredNullableEnumString = new Option(RequiredClass.NotrequiredNullableEnumStringEnumFromStringOrDefault(notrequiredNullableEnumStringRawValue)); + break; + case "notrequired_nullable_outerEnumDefaultValue": + string notrequiredNullableOuterEnumDefaultValueRawValue = utf8JsonReader.GetString(); + if (notrequiredNullableOuterEnumDefaultValueRawValue != null) + notrequiredNullableOuterEnumDefaultValue = new Option(OuterEnumDefaultValueValueConverter.FromStringOrDefault(notrequiredNullableOuterEnumDefaultValueRawValue)); + break; + case "notrequired_nullable_string_prop": + notrequiredNullableStringProp = new Option(utf8JsonReader.GetString()); + break; + case "notrequired_nullable_uuid": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + notrequiredNullableUuid = new Option(utf8JsonReader.GetGuid()); + break; + default: + break; + } + } + } + + if (!requiredNotNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotNullableDateProp)); + + if (!requiredNotnullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableArrayOfString)); + + if (!requiredNotnullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableBooleanProp)); + + if (!requiredNotnullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableDatetimeProp)); + + if (!requiredNotnullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumInteger)); + + if (!requiredNotnullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumIntegerOnly)); + + if (!requiredNotnullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableEnumString)); + + if (!requiredNotnullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableOuterEnumDefaultValue)); + + if (!requiredNotnullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableStringProp)); + + if (!requiredNotnullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableUuid)); + + if (!requiredNotnullableintegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNotnullableintegerProp)); + + if (!requiredNullableArrayOfString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableArrayOfString)); + + if (!requiredNullableBooleanProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableBooleanProp)); + + if (!requiredNullableDateProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDateProp)); + + if (!requiredNullableDatetimeProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableDatetimeProp)); + + if (!requiredNullableEnumInteger.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumInteger)); + + if (!requiredNullableEnumIntegerOnly.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumIntegerOnly)); + + if (!requiredNullableEnumString.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableEnumString)); + + if (!requiredNullableIntegerProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableIntegerProp)); + + if (!requiredNullableOuterEnumDefaultValue.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableOuterEnumDefaultValue)); + + if (!requiredNullableStringProp.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableStringProp)); + + if (!requiredNullableUuid.IsSet) + throw new ArgumentException("Property is required for class RequiredClass.", nameof(requiredNullableUuid)); + + if (requiredNotNullableDateProp.IsSet && requiredNotNullableDateProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotNullableDateProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableArrayOfString.IsSet && requiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableBooleanProp.IsSet && requiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableDatetimeProp.IsSet && requiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumInteger.IsSet && requiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumIntegerOnly.IsSet && requiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableEnumString.IsSet && requiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableOuterEnumDefaultValue.IsSet && requiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableStringProp.IsSet && requiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableUuid.IsSet && requiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + if (requiredNotnullableintegerProp.IsSet && requiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(requiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableDateProp.IsSet && notRequiredNotnullableDateProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableDateProp), "Property is not nullable for class RequiredClass."); + + if (notRequiredNotnullableintegerProp.IsSet && notRequiredNotnullableintegerProp.Value == null) + throw new ArgumentNullException(nameof(notRequiredNotnullableintegerProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableArrayOfString.IsSet && notrequiredNotnullableArrayOfString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableArrayOfString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableBooleanProp.IsSet && notrequiredNotnullableBooleanProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableBooleanProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableDatetimeProp.IsSet && notrequiredNotnullableDatetimeProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableDatetimeProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumInteger.IsSet && notrequiredNotnullableEnumInteger.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumInteger), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumIntegerOnly.IsSet && notrequiredNotnullableEnumIntegerOnly.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumIntegerOnly), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableEnumString.IsSet && notrequiredNotnullableEnumString.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableEnumString), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableOuterEnumDefaultValue.IsSet && notrequiredNotnullableOuterEnumDefaultValue.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableOuterEnumDefaultValue), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableStringProp.IsSet && notrequiredNotnullableStringProp.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableStringProp), "Property is not nullable for class RequiredClass."); + + if (notrequiredNotnullableUuid.IsSet && notrequiredNotnullableUuid.Value == null) + throw new ArgumentNullException(nameof(notrequiredNotnullableUuid), "Property is not nullable for class RequiredClass."); + + return new RequiredClass(requiredNotNullableDateProp.Value.Value, requiredNotnullableArrayOfString.Value, requiredNotnullableBooleanProp.Value.Value, requiredNotnullableDatetimeProp.Value.Value, requiredNotnullableEnumInteger.Value.Value, requiredNotnullableEnumIntegerOnly.Value.Value, requiredNotnullableEnumString.Value.Value, requiredNotnullableOuterEnumDefaultValue.Value.Value, requiredNotnullableStringProp.Value, requiredNotnullableUuid.Value.Value, requiredNotnullableintegerProp.Value.Value, requiredNullableArrayOfString.Value, requiredNullableBooleanProp.Value, requiredNullableDateProp.Value, requiredNullableDatetimeProp.Value, requiredNullableEnumInteger.Value, requiredNullableEnumIntegerOnly.Value, requiredNullableEnumString.Value, requiredNullableIntegerProp.Value, requiredNullableOuterEnumDefaultValue.Value, requiredNullableStringProp.Value, requiredNullableUuid.Value, notRequiredNotnullableDateProp, notRequiredNotnullableintegerProp, notRequiredNullableDateProp, notRequiredNullableIntegerProp, notrequiredNotnullableArrayOfString, notrequiredNotnullableBooleanProp, notrequiredNotnullableDatetimeProp, notrequiredNotnullableEnumInteger, notrequiredNotnullableEnumIntegerOnly, notrequiredNotnullableEnumString, notrequiredNotnullableOuterEnumDefaultValue, notrequiredNotnullableStringProp, notrequiredNotnullableUuid, notrequiredNullableArrayOfString, notrequiredNullableBooleanProp, notrequiredNullableDatetimeProp, notrequiredNullableEnumInteger, notrequiredNullableEnumIntegerOnly, notrequiredNullableEnumString, notrequiredNullableOuterEnumDefaultValue, notrequiredNullableStringProp, notrequiredNullableUuid); + } + + /// + /// Serializes a + /// + /// + /// + /// + /// + public override void Write(Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + writer.WriteStartObject(); + + WriteProperties(ref writer, requiredClass, jsonSerializerOptions); + writer.WriteEndObject(); + } + + /// + /// Serializes the properties of + /// + /// + /// + /// + /// + public void WriteProperties(ref Utf8JsonWriter writer, RequiredClass requiredClass, JsonSerializerOptions jsonSerializerOptions) + { + if (requiredClass.RequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.RequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.RequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet && requiredClass.NotrequiredNotnullableArrayOfString == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableArrayOfString), "Property is required for class RequiredClass."); + + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet && requiredClass.NotrequiredNotnullableStringProp == null) + throw new ArgumentNullException(nameof(requiredClass.NotrequiredNotnullableStringProp), "Property is required for class RequiredClass."); + + writer.WriteString("required_not_nullable_date_prop", requiredClass.RequiredNotNullableDateProp.ToString(RequiredNotNullableDatePropFormat)); + + writer.WritePropertyName("required_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNotnullableArrayOfString, jsonSerializerOptions); + writer.WriteBoolean("required_notnullable_boolean_prop", requiredClass.RequiredNotnullableBooleanProp); + + writer.WriteString("required_notnullable_datetime_prop", requiredClass.RequiredNotnullableDatetimeProp.ToString(RequiredNotnullableDatetimePropFormat)); + + writer.WriteNumber("required_notnullable_enum_integer", RequiredClass.RequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNotnullableEnumInteger)); + + writer.WriteNumber("required_notnullable_enum_integer_only", RequiredClass.RequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNotnullableEnumIntegerOnly)); + + var requiredNotnullableEnumStringRawValue = RequiredClass.RequiredNotnullableEnumStringEnumToJsonValue(requiredClass.RequiredNotnullableEnumString); + writer.WriteString("required_notnullable_enum_string", requiredNotnullableEnumStringRawValue); + var requiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNotnullableOuterEnumDefaultValue); + writer.WriteString("required_notnullable_outerEnumDefaultValue", requiredNotnullableOuterEnumDefaultValueRawValue); + + writer.WriteString("required_notnullable_string_prop", requiredClass.RequiredNotnullableStringProp); + + writer.WriteString("required_notnullable_uuid", requiredClass.RequiredNotnullableUuid); + + writer.WriteNumber("required_notnullableinteger_prop", requiredClass.RequiredNotnullableintegerProp); + + if (requiredClass.RequiredNullableArrayOfString != null) + { + writer.WritePropertyName("required_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.RequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("required_nullable_array_of_string"); + if (requiredClass.RequiredNullableBooleanProp != null) + writer.WriteBoolean("required_nullable_boolean_prop", requiredClass.RequiredNullableBooleanProp.Value); + else + writer.WriteNull("required_nullable_boolean_prop"); + + if (requiredClass.RequiredNullableDateProp != null) + writer.WriteString("required_nullable_date_prop", requiredClass.RequiredNullableDateProp.Value.ToString(RequiredNullableDatePropFormat)); + else + writer.WriteNull("required_nullable_date_prop"); + + if (requiredClass.RequiredNullableDatetimeProp != null) + writer.WriteString("required_nullable_datetime_prop", requiredClass.RequiredNullableDatetimeProp.Value.ToString(RequiredNullableDatetimePropFormat)); + else + writer.WriteNull("required_nullable_datetime_prop"); + + if (requiredClass.RequiredNullableEnumInteger != null) + writer.WriteNumber("required_nullable_enum_integer", RequiredClass.RequiredNullableEnumIntegerEnumToJsonValue(requiredClass.RequiredNullableEnumInteger.Value)); + else + writer.WriteNull("required_nullable_enum_integer"); + + if (requiredClass.RequiredNullableEnumIntegerOnly != null) + writer.WriteNumber("required_nullable_enum_integer_only", RequiredClass.RequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.RequiredNullableEnumIntegerOnly.Value)); + else + writer.WriteNull("required_nullable_enum_integer_only"); + + var requiredNullableEnumStringRawValue = RequiredClass.RequiredNullableEnumStringEnumToJsonValue(requiredClass.RequiredNullableEnumString.Value); + if (requiredNullableEnumStringRawValue != null) + writer.WriteString("required_nullable_enum_string", requiredNullableEnumStringRawValue); + else + writer.WriteNull("required_nullable_enum_string"); + + if (requiredClass.RequiredNullableIntegerProp != null) + writer.WriteNumber("required_nullable_integer_prop", requiredClass.RequiredNullableIntegerProp.Value); + else + writer.WriteNull("required_nullable_integer_prop"); + + if (requiredClass.RequiredNullableOuterEnumDefaultValue == null) + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + else + { + var requiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.RequiredNullableOuterEnumDefaultValue.Value); + if (requiredNullableOuterEnumDefaultValueRawValue != null) + writer.WriteString("required_nullable_outerEnumDefaultValue", requiredNullableOuterEnumDefaultValueRawValue); + else + writer.WriteNull("required_nullable_outerEnumDefaultValue"); + } + + if (requiredClass.RequiredNullableStringProp != null) + writer.WriteString("required_nullable_string_prop", requiredClass.RequiredNullableStringProp); + else + writer.WriteNull("required_nullable_string_prop"); + + if (requiredClass.RequiredNullableUuid != null) + writer.WriteString("required_nullable_uuid", requiredClass.RequiredNullableUuid.Value); + else + writer.WriteNull("required_nullable_uuid"); + + if (requiredClass.NotRequiredNotnullableDatePropOption.IsSet) + writer.WriteString("not_required_notnullable_date_prop", requiredClass.NotRequiredNotnullableDatePropOption.Value.Value.ToString(NotRequiredNotnullableDatePropFormat)); + + if (requiredClass.NotRequiredNotnullableintegerPropOption.IsSet) + writer.WriteNumber("not_required_notnullableinteger_prop", requiredClass.NotRequiredNotnullableintegerPropOption.Value.Value); + + if (requiredClass.NotRequiredNullableDatePropOption.IsSet) + if (requiredClass.NotRequiredNullableDatePropOption.Value != null) + writer.WriteString("not_required_nullable_date_prop", requiredClass.NotRequiredNullableDatePropOption.Value.Value.ToString(NotRequiredNullableDatePropFormat)); + else + writer.WriteNull("not_required_nullable_date_prop"); + + if (requiredClass.NotRequiredNullableIntegerPropOption.IsSet) + if (requiredClass.NotRequiredNullableIntegerPropOption.Value != null) + writer.WriteNumber("not_required_nullable_integer_prop", requiredClass.NotRequiredNullableIntegerPropOption.Value.Value); + else + writer.WriteNull("not_required_nullable_integer_prop"); + + if (requiredClass.NotrequiredNotnullableArrayOfStringOption.IsSet) + { + writer.WritePropertyName("notrequired_notnullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNotnullableArrayOfString, jsonSerializerOptions); + } + if (requiredClass.NotrequiredNotnullableBooleanPropOption.IsSet) + writer.WriteBoolean("notrequired_notnullable_boolean_prop", requiredClass.NotrequiredNotnullableBooleanPropOption.Value.Value); + + if (requiredClass.NotrequiredNotnullableDatetimePropOption.IsSet) + writer.WriteString("notrequired_notnullable_datetime_prop", requiredClass.NotrequiredNotnullableDatetimePropOption.Value.Value.ToString(NotrequiredNotnullableDatetimePropFormat)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer", RequiredClass.NotrequiredNotnullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOption.Value.Value)); + + if (requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.IsSet) + writer.WriteNumber("notrequired_notnullable_enum_integer_only", RequiredClass.NotrequiredNotnullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumIntegerOnlyOption.Value.Value)); + + var notrequiredNotnullableEnumStringRawValue = RequiredClass.NotrequiredNotnullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNotnullableEnumStringOption.Value.Value); + writer.WriteString("notrequired_notnullable_enum_string", notrequiredNotnullableEnumStringRawValue); + if (requiredClass.NotrequiredNotnullableOuterEnumDefaultValueOption.IsSet) + { + var notrequiredNotnullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNotnullableOuterEnumDefaultValue.Value); + writer.WriteString("notrequired_notnullable_outerEnumDefaultValue", notrequiredNotnullableOuterEnumDefaultValueRawValue); + } + if (requiredClass.NotrequiredNotnullableStringPropOption.IsSet) + writer.WriteString("notrequired_notnullable_string_prop", requiredClass.NotrequiredNotnullableStringProp); + + if (requiredClass.NotrequiredNotnullableUuidOption.IsSet) + writer.WriteString("notrequired_notnullable_uuid", requiredClass.NotrequiredNotnullableUuidOption.Value.Value); + + if (requiredClass.NotrequiredNullableArrayOfStringOption.IsSet) + if (requiredClass.NotrequiredNullableArrayOfStringOption.Value != null) + { + writer.WritePropertyName("notrequired_nullable_array_of_string"); + JsonSerializer.Serialize(writer, requiredClass.NotrequiredNullableArrayOfString, jsonSerializerOptions); + } + else + writer.WriteNull("notrequired_nullable_array_of_string"); + if (requiredClass.NotrequiredNullableBooleanPropOption.IsSet) + if (requiredClass.NotrequiredNullableBooleanPropOption.Value != null) + writer.WriteBoolean("notrequired_nullable_boolean_prop", requiredClass.NotrequiredNullableBooleanPropOption.Value.Value); + else + writer.WriteNull("notrequired_nullable_boolean_prop"); + + if (requiredClass.NotrequiredNullableDatetimePropOption.IsSet) + if (requiredClass.NotrequiredNullableDatetimePropOption.Value != null) + writer.WriteString("notrequired_nullable_datetime_prop", requiredClass.NotrequiredNullableDatetimePropOption.Value.Value.ToString(NotrequiredNullableDatetimePropFormat)); + else + writer.WriteNull("notrequired_nullable_datetime_prop"); + + if (requiredClass.NotrequiredNullableEnumIntegerOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer", RequiredClass.NotrequiredNullableEnumIntegerEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOption.Value.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer"); + + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.IsSet) + if (requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value != null) + writer.WriteNumber("notrequired_nullable_enum_integer_only", RequiredClass.NotrequiredNullableEnumIntegerOnlyEnumToJsonValue(requiredClass.NotrequiredNullableEnumIntegerOnlyOption.Value.Value)); + else + writer.WriteNull("notrequired_nullable_enum_integer_only"); + + var notrequiredNullableEnumStringRawValue = RequiredClass.NotrequiredNullableEnumStringEnumToJsonValue(requiredClass.NotrequiredNullableEnumStringOption.Value.Value); + if (notrequiredNullableEnumStringRawValue != null) + writer.WriteString("notrequired_nullable_enum_string", notrequiredNullableEnumStringRawValue); + else + writer.WriteNull("notrequired_nullable_enum_string"); + + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.IsSet) + if (requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value != null) + { + var notrequiredNullableOuterEnumDefaultValueRawValue = OuterEnumDefaultValueValueConverter.ToJsonValue(requiredClass.NotrequiredNullableOuterEnumDefaultValueOption.Value.Value); + writer.WriteString("notrequired_nullable_outerEnumDefaultValue", notrequiredNullableOuterEnumDefaultValueRawValue); + } + else + writer.WriteNull("notrequired_nullable_outerEnumDefaultValue"); + if (requiredClass.NotrequiredNullableStringPropOption.IsSet) + if (requiredClass.NotrequiredNullableStringPropOption.Value != null) + writer.WriteString("notrequired_nullable_string_prop", requiredClass.NotrequiredNullableStringProp); + else + writer.WriteNull("notrequired_nullable_string_prop"); + + if (requiredClass.NotrequiredNullableUuidOption.IsSet) + if (requiredClass.NotrequiredNullableUuidOption.Value != null) + writer.WriteString("notrequired_nullable_uuid", requiredClass.NotrequiredNullableUuidOption.Value.Value); + else + writer.WriteNull("notrequired_nullable_uuid"); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs index 86e7223ee957..7ef17db222ff 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Return.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class Return : IValidatableObject /// /// varReturn [JsonConstructor] - public Return(int varReturn) + public Return(Option varReturn = default) { - VarReturn = varReturn; + VarReturnOption = varReturn; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarReturn + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarReturnOption { get; private set; } + /// /// Gets or Sets VarReturn /// [JsonPropertyName("return")] - public int VarReturn { get; set; } + public int? VarReturn { get { return this. VarReturnOption; } set { this.VarReturnOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver JsonTokenType startingTokenType = utf8JsonReader.TokenType; - int? varReturn = default; + Option varReturn = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver { case "return": if (utf8JsonReader.TokenType != JsonTokenType.Null) - varReturn = utf8JsonReader.GetInt32(); + varReturn = new Option(utf8JsonReader.GetInt32()); break; default: break; @@ -127,10 +135,10 @@ public override Return Read(ref Utf8JsonReader utf8JsonReader, Type typeToConver } } - if (varReturn == null) - throw new ArgumentNullException(nameof(varReturn), "Property is required for class Return."); + if (varReturn.IsSet && varReturn.Value == null) + throw new ArgumentNullException(nameof(varReturn), "Property is not nullable for class Return."); - return new Return(varReturn.Value); + return new Return(varReturn); } /// @@ -157,7 +165,8 @@ public override void Write(Utf8JsonWriter writer, Return varReturn, JsonSerializ /// public void WriteProperties(ref Utf8JsonWriter writer, Return varReturn, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("return", varReturn.VarReturn); + if (varReturn.VarReturnOption.IsSet) + writer.WriteNumber("return", varReturn.VarReturnOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs index 86effcebe7ae..f7435144367e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHash.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class RolesReportsHash : IValidatableObject /// role /// roleUuid [JsonConstructor] - public RolesReportsHash(RolesReportsHashRole role, Guid roleUuid) + public RolesReportsHash(Option role = default, Option roleUuid = default) { - Role = role; - RoleUuid = roleUuid; + RoleOption = role; + RoleUuidOption = roleUuid; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Role + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleOption { get; private set; } + /// /// Gets or Sets Role /// [JsonPropertyName("role")] - public RolesReportsHashRole Role { get; set; } + public RolesReportsHashRole Role { get { return this. RoleOption; } set { this.RoleOption = new Option(value); } } + + /// + /// Used to track the state of RoleUuid + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option RoleUuidOption { get; private set; } /// /// Gets or Sets RoleUuid /// [JsonPropertyName("role_uuid")] - public Guid RoleUuid { get; set; } + public Guid? RoleUuid { get { return this. RoleUuidOption; } set { this.RoleUuidOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - RolesReportsHashRole role = default; - Guid? roleUuid = default; + Option role = default; + Option roleUuid = default; while (utf8JsonReader.Read()) { @@ -129,11 +144,11 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty { case "role": if (utf8JsonReader.TokenType != JsonTokenType.Null) - role = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + role = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "role_uuid": if (utf8JsonReader.TokenType != JsonTokenType.Null) - roleUuid = utf8JsonReader.GetGuid(); + roleUuid = new Option(utf8JsonReader.GetGuid()); break; default: break; @@ -141,13 +156,13 @@ public override RolesReportsHash Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (role == null) - throw new ArgumentNullException(nameof(role), "Property is required for class RolesReportsHash."); + if (role.IsSet && role.Value == null) + throw new ArgumentNullException(nameof(role), "Property is not nullable for class RolesReportsHash."); - if (roleUuid == null) - throw new ArgumentNullException(nameof(roleUuid), "Property is required for class RolesReportsHash."); + if (roleUuid.IsSet && roleUuid.Value == null) + throw new ArgumentNullException(nameof(roleUuid), "Property is not nullable for class RolesReportsHash."); - return new RolesReportsHash(role, roleUuid.Value); + return new RolesReportsHash(role, roleUuid); } /// @@ -174,9 +189,16 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHash rolesReportsH /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHash rolesReportsHash, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("role"); - JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); - writer.WriteString("role_uuid", rolesReportsHash.RoleUuid); + if (rolesReportsHash.RoleOption.IsSet && rolesReportsHash.Role == null) + throw new ArgumentNullException(nameof(rolesReportsHash.Role), "Property is required for class RolesReportsHash."); + + if (rolesReportsHash.RoleOption.IsSet) + { + writer.WritePropertyName("role"); + JsonSerializer.Serialize(writer, rolesReportsHash.Role, jsonSerializerOptions); + } + if (rolesReportsHash.RoleUuidOption.IsSet) + writer.WriteString("role_uuid", rolesReportsHash.RoleUuidOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs index c7002b77b2e1..4a29f6ec7b16 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/RolesReportsHashRole.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class RolesReportsHashRole : IValidatableObject /// /// name [JsonConstructor] - public RolesReportsHashRole(string name) + public RolesReportsHashRole(Option name = default) { - Name = name; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } + /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string name = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ switch (localVarJsonPropertyName) { case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override RolesReportsHashRole Read(ref Utf8JsonReader utf8JsonReader, Typ } } - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class RolesReportsHashRole."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class RolesReportsHashRole."); return new RolesReportsHashRole(name); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, RolesReportsHashRole rolesRepo /// public void WriteProperties(ref Utf8JsonWriter writer, RolesReportsHashRole rolesReportsHashRole, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("name", rolesReportsHashRole.Name); + if (rolesReportsHashRole.NameOption.IsSet && rolesReportsHashRole.Name == null) + throw new ArgumentNullException(nameof(rolesReportsHashRole.Name), "Property is required for class RolesReportsHashRole."); + + if (rolesReportsHashRole.NameOption.IsSet) + writer.WriteString("name", rolesReportsHashRole.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs index 4151ead57dfb..52a8e0d69c60 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ScaleneTriangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; - string triangleType = default; + Option shapeType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override ScaleneTriangle Read(ref Utf8JsonReader utf8JsonReader, Type typ } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ScaleneTriangle."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(shapeType)); - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class ScaleneTriangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class ScaleneTriangle.", nameof(triangleType)); - return new ScaleneTriangle(shapeType, triangleType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ScaleneTriangle."); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class ScaleneTriangle."); + + return new ScaleneTriangle(shapeType.Value, triangleType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, ScaleneTriangle scaleneTriangl /// public void WriteProperties(ref Utf8JsonWriter writer, ScaleneTriangle scaleneTriangle, JsonSerializerOptions jsonSerializerOptions) { + if (scaleneTriangle.ShapeType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.ShapeType), "Property is required for class ScaleneTriangle."); + + if (scaleneTriangle.TriangleType == null) + throw new ArgumentNullException(nameof(scaleneTriangle.TriangleType), "Property is required for class ScaleneTriangle."); + writer.WriteString("shapeType", scaleneTriangle.ShapeType); + writer.WriteString("triangleType", scaleneTriangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs index dae0ef02f966..575069f242e0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Shape.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override Shape Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class Shape."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class Shape.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class Shape."); if (quadrilateral != null) - return new Shape(quadrilateral, shapeType); + return new Shape(quadrilateral, shapeType.Value); if (triangle != null) - return new Shape(triangle, shapeType); + return new Shape(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, Shape shape, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Shape shape, JsonSerializerOptions jsonSerializerOptions) { + if (shape.ShapeType == null) + throw new ArgumentNullException(nameof(shape.ShapeType), "Property is required for class Shape."); + writer.WriteString("shapeType", shape.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs index de32fa535aec..5bd364cc6a41 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override ShapeInterface Read(ref Utf8JsonReader utf8JsonReader, Type type } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeInterface."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeInterface.", nameof(shapeType)); - return new ShapeInterface(shapeType); + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeInterface."); + + return new ShapeInterface(shapeType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, ShapeInterface shapeInterface, /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeInterface shapeInterface, JsonSerializerOptions jsonSerializerOptions) { + if (shapeInterface.ShapeType == null) + throw new ArgumentNullException(nameof(shapeInterface.ShapeType), "Property is required for class ShapeInterface."); + writer.WriteString("shapeType", shapeInterface.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs index 955461e12024..a26dab034230 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ShapeOrNull.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -133,7 +134,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string shapeType = default; + Option shapeType = default; Quadrilateral quadrilateral = null; Triangle triangle = null; @@ -184,7 +185,7 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC switch (localVarJsonPropertyName) { case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -192,14 +193,17 @@ public override ShapeOrNull Read(ref Utf8JsonReader utf8JsonReader, Type typeToC } } - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class ShapeOrNull."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class ShapeOrNull.", nameof(shapeType)); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class ShapeOrNull."); if (quadrilateral != null) - return new ShapeOrNull(quadrilateral, shapeType); + return new ShapeOrNull(quadrilateral, shapeType.Value); if (triangle != null) - return new ShapeOrNull(triangle, shapeType); + return new ShapeOrNull(triangle, shapeType.Value); throw new JsonException(); } @@ -238,6 +242,9 @@ public override void Write(Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonS /// public void WriteProperties(ref Utf8JsonWriter writer, ShapeOrNull shapeOrNull, JsonSerializerOptions jsonSerializerOptions) { + if (shapeOrNull.ShapeType == null) + throw new ArgumentNullException(nameof(shapeOrNull.ShapeType), "Property is required for class ShapeOrNull."); + writer.WriteString("shapeType", shapeOrNull.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs index 7f0b8a306f80..a00a87e2efa5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SimpleQuadrilateral.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -109,8 +110,8 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string quadrilateralType = default; - string shapeType = default; + Option quadrilateralType = default; + Option shapeType = default; while (utf8JsonReader.Read()) { @@ -128,10 +129,10 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type switch (localVarJsonPropertyName) { case "quadrilateralType": - quadrilateralType = utf8JsonReader.GetString(); + quadrilateralType = new Option(utf8JsonReader.GetString()); break; case "shapeType": - shapeType = utf8JsonReader.GetString(); + shapeType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -139,13 +140,19 @@ public override SimpleQuadrilateral Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (quadrilateralType == null) - throw new ArgumentNullException(nameof(quadrilateralType), "Property is required for class SimpleQuadrilateral."); + if (!quadrilateralType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(quadrilateralType)); - if (shapeType == null) - throw new ArgumentNullException(nameof(shapeType), "Property is required for class SimpleQuadrilateral."); + if (!shapeType.IsSet) + throw new ArgumentException("Property is required for class SimpleQuadrilateral.", nameof(shapeType)); - return new SimpleQuadrilateral(quadrilateralType, shapeType); + if (quadrilateralType.IsSet && quadrilateralType.Value == null) + throw new ArgumentNullException(nameof(quadrilateralType), "Property is not nullable for class SimpleQuadrilateral."); + + if (shapeType.IsSet && shapeType.Value == null) + throw new ArgumentNullException(nameof(shapeType), "Property is not nullable for class SimpleQuadrilateral."); + + return new SimpleQuadrilateral(quadrilateralType.Value, shapeType.Value); } /// @@ -172,7 +179,14 @@ public override void Write(Utf8JsonWriter writer, SimpleQuadrilateral simpleQuad /// public void WriteProperties(ref Utf8JsonWriter writer, SimpleQuadrilateral simpleQuadrilateral, JsonSerializerOptions jsonSerializerOptions) { + if (simpleQuadrilateral.QuadrilateralType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.QuadrilateralType), "Property is required for class SimpleQuadrilateral."); + + if (simpleQuadrilateral.ShapeType == null) + throw new ArgumentNullException(nameof(simpleQuadrilateral.ShapeType), "Property is required for class SimpleQuadrilateral."); + writer.WriteString("quadrilateralType", simpleQuadrilateral.QuadrilateralType); + writer.WriteString("shapeType", simpleQuadrilateral.ShapeType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs index 8328ad3ee121..81bfc146662c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/SpecialModelName.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class SpecialModelName : IValidatableObject /// varSpecialModelName /// specialPropertyName [JsonConstructor] - public SpecialModelName(string varSpecialModelName, long specialPropertyName) + public SpecialModelName(Option varSpecialModelName = default, Option specialPropertyName = default) { - VarSpecialModelName = varSpecialModelName; - SpecialPropertyName = specialPropertyName; + VarSpecialModelNameOption = varSpecialModelName; + SpecialPropertyNameOption = specialPropertyName; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of VarSpecialModelName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option VarSpecialModelNameOption { get; private set; } + /// /// Gets or Sets VarSpecialModelName /// [JsonPropertyName("_special_model.name_")] - public string VarSpecialModelName { get; set; } + public string VarSpecialModelName { get { return this. VarSpecialModelNameOption; } set { this.VarSpecialModelNameOption = new Option(value); } } + + /// + /// Used to track the state of SpecialPropertyName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SpecialPropertyNameOption { get; private set; } /// /// Gets or Sets SpecialPropertyName /// [JsonPropertyName("$special[property.name]")] - public long SpecialPropertyName { get; set; } + public long? SpecialPropertyName { get { return this. SpecialPropertyNameOption; } set { this.SpecialPropertyNameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string varSpecialModelName = default; - long? specialPropertyName = default; + Option varSpecialModelName = default; + Option specialPropertyName = default; while (utf8JsonReader.Read()) { @@ -128,11 +143,11 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty switch (localVarJsonPropertyName) { case "_special_model.name_": - varSpecialModelName = utf8JsonReader.GetString(); + varSpecialModelName = new Option(utf8JsonReader.GetString()); break; case "$special[property.name]": if (utf8JsonReader.TokenType != JsonTokenType.Null) - specialPropertyName = utf8JsonReader.GetInt64(); + specialPropertyName = new Option(utf8JsonReader.GetInt64()); break; default: break; @@ -140,13 +155,13 @@ public override SpecialModelName Read(ref Utf8JsonReader utf8JsonReader, Type ty } } - if (varSpecialModelName == null) - throw new ArgumentNullException(nameof(varSpecialModelName), "Property is required for class SpecialModelName."); + if (varSpecialModelName.IsSet && varSpecialModelName.Value == null) + throw new ArgumentNullException(nameof(varSpecialModelName), "Property is not nullable for class SpecialModelName."); - if (specialPropertyName == null) - throw new ArgumentNullException(nameof(specialPropertyName), "Property is required for class SpecialModelName."); + if (specialPropertyName.IsSet && specialPropertyName.Value == null) + throw new ArgumentNullException(nameof(specialPropertyName), "Property is not nullable for class SpecialModelName."); - return new SpecialModelName(varSpecialModelName, specialPropertyName.Value); + return new SpecialModelName(varSpecialModelName, specialPropertyName); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, SpecialModelName specialModelN /// public void WriteProperties(ref Utf8JsonWriter writer, SpecialModelName specialModelName, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); - writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyName); + if (specialModelName.VarSpecialModelNameOption.IsSet && specialModelName.VarSpecialModelName == null) + throw new ArgumentNullException(nameof(specialModelName.VarSpecialModelName), "Property is required for class SpecialModelName."); + + if (specialModelName.VarSpecialModelNameOption.IsSet) + writer.WriteString("_special_model.name_", specialModelName.VarSpecialModelName); + + if (specialModelName.SpecialPropertyNameOption.IsSet) + writer.WriteNumber("$special[property.name]", specialModelName.SpecialPropertyNameOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs index 6524d75edcf5..4f4891d049f1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Tag.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -34,26 +35,40 @@ public partial class Tag : IValidatableObject /// id /// name [JsonConstructor] - public Tag(long id, string name) + public Tag(Option id = default, Option name = default) { - Id = id; - Name = name; + IdOption = id; + NameOption = name; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } + /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } + + /// + /// Used to track the state of Name + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option NameOption { get; private set; } /// /// Gets or Sets Name /// [JsonPropertyName("name")] - public string Name { get; set; } + public string Name { get { return this. NameOption; } set { this.NameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -109,8 +124,8 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - long? id = default; - string name = default; + Option id = default; + Option name = default; while (utf8JsonReader.Read()) { @@ -129,10 +144,10 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, { case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "name": - name = utf8JsonReader.GetString(); + name = new Option(utf8JsonReader.GetString()); break; default: break; @@ -140,13 +155,13 @@ public override Tag Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class Tag."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class Tag."); - if (name == null) - throw new ArgumentNullException(nameof(name), "Property is required for class Tag."); + if (name.IsSet && name.Value == null) + throw new ArgumentNullException(nameof(name), "Property is not nullable for class Tag."); - return new Tag(id.Value, name); + return new Tag(id, name); } /// @@ -173,8 +188,14 @@ public override void Write(Utf8JsonWriter writer, Tag tag, JsonSerializerOptions /// public void WriteProperties(ref Utf8JsonWriter writer, Tag tag, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteNumber("id", tag.Id); - writer.WriteString("name", tag.Name); + if (tag.NameOption.IsSet && tag.Name == null) + throw new ArgumentNullException(nameof(tag.Name), "Property is required for class Tag."); + + if (tag.IdOption.IsSet) + writer.WriteNumber("id", tag.IdOption.Value.Value); + + if (tag.NameOption.IsSet) + writer.WriteString("name", tag.Name); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs index b2e110e79f67..47a94630b7d8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordList.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class TestCollectionEndingWithWordList : IValidatableObject /// /// value [JsonConstructor] - public TestCollectionEndingWithWordList(string value) + public TestCollectionEndingWithWordList(Option value = default) { - Value = value; + ValueOption = value; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of Value + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ValueOption { get; private set; } + /// /// Gets or Sets Value /// [JsonPropertyName("value")] - public string Value { get; set; } + public string Value { get { return this. ValueOption; } set { this.ValueOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string value = default; + Option value = default; while (utf8JsonReader.Read()) { @@ -118,7 +126,7 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso switch (localVarJsonPropertyName) { case "value": - value = utf8JsonReader.GetString(); + value = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,8 +134,8 @@ public override TestCollectionEndingWithWordList Read(ref Utf8JsonReader utf8Jso } } - if (value == null) - throw new ArgumentNullException(nameof(value), "Property is required for class TestCollectionEndingWithWordList."); + if (value.IsSet && value.Value == null) + throw new ArgumentNullException(nameof(value), "Property is not nullable for class TestCollectionEndingWithWordList."); return new TestCollectionEndingWithWordList(value); } @@ -156,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordList testCollectionEndingWithWordList, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("value", testCollectionEndingWithWordList.Value); + if (testCollectionEndingWithWordList.ValueOption.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList.Value), "Property is required for class TestCollectionEndingWithWordList."); + + if (testCollectionEndingWithWordList.ValueOption.IsSet) + writer.WriteString("value", testCollectionEndingWithWordList.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs index 8753edfd9f35..d1b0714cb3c6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestCollectionEndingWithWordListObject.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,19 +34,26 @@ public partial class TestCollectionEndingWithWordListObject : IValidatableObject /// /// testCollectionEndingWithWordList [JsonConstructor] - public TestCollectionEndingWithWordListObject(List testCollectionEndingWithWordList) + public TestCollectionEndingWithWordListObject(Option> testCollectionEndingWithWordList = default) { - TestCollectionEndingWithWordList = testCollectionEndingWithWordList; + TestCollectionEndingWithWordListOption = testCollectionEndingWithWordList; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of TestCollectionEndingWithWordList + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option> TestCollectionEndingWithWordListOption { get; private set; } + /// /// Gets or Sets TestCollectionEndingWithWordList /// [JsonPropertyName("TestCollectionEndingWithWordList")] - public List TestCollectionEndingWithWordList { get; set; } + public List TestCollectionEndingWithWordList { get { return this. TestCollectionEndingWithWordListOption; } set { this.TestCollectionEndingWithWordListOption = new Option>(value); } } /// /// Gets or Sets additional properties @@ -100,7 +108,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u JsonTokenType startingTokenType = utf8JsonReader.TokenType; - List testCollectionEndingWithWordList = default; + Option> testCollectionEndingWithWordList = default; while (utf8JsonReader.Read()) { @@ -119,7 +127,7 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u { case "TestCollectionEndingWithWordList": if (utf8JsonReader.TokenType != JsonTokenType.Null) - testCollectionEndingWithWordList = JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions); + testCollectionEndingWithWordList = new Option>(JsonSerializer.Deserialize>(ref utf8JsonReader, jsonSerializerOptions)); break; default: break; @@ -127,8 +135,8 @@ public override TestCollectionEndingWithWordListObject Read(ref Utf8JsonReader u } } - if (testCollectionEndingWithWordList == null) - throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + if (testCollectionEndingWithWordList.IsSet && testCollectionEndingWithWordList.Value == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordList), "Property is not nullable for class TestCollectionEndingWithWordListObject."); return new TestCollectionEndingWithWordListObject(testCollectionEndingWithWordList); } @@ -157,8 +165,14 @@ public override void Write(Utf8JsonWriter writer, TestCollectionEndingWithWordLi /// public void WriteProperties(ref Utf8JsonWriter writer, TestCollectionEndingWithWordListObject testCollectionEndingWithWordListObject, JsonSerializerOptions jsonSerializerOptions) { - writer.WritePropertyName("TestCollectionEndingWithWordList"); - JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet && testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList == null) + throw new ArgumentNullException(nameof(testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList), "Property is required for class TestCollectionEndingWithWordListObject."); + + if (testCollectionEndingWithWordListObject.TestCollectionEndingWithWordListOption.IsSet) + { + writer.WritePropertyName("TestCollectionEndingWithWordList"); + JsonSerializer.Serialize(writer, testCollectionEndingWithWordListObject.TestCollectionEndingWithWordList, jsonSerializerOptions); + } } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index 139e92b4c6a8..68d1acab3ec3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -20,32 +20,40 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// TestInlineFreeformAdditionalPropertiesRequest /// - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty [JsonConstructor] - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty) : base() + public TestInlineFreeformAdditionalPropertiesRequest(Option someProperty = default) { - SomeProperty = someProperty; + SomePropertyOption = someProperty; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of SomeProperty + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option SomePropertyOption { get; private set; } + /// /// Gets or Sets SomeProperty /// [JsonPropertyName("someProperty")] - public string SomeProperty { get; set; } + public string SomeProperty { get { return this. SomePropertyOption; } set { this.SomePropertyOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -61,7 +69,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -74,16 +81,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -111,7 +108,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string someProperty = default; + Option someProperty = default; while (utf8JsonReader.Read()) { @@ -129,7 +126,7 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR switch (localVarJsonPropertyName) { case "someProperty": - someProperty = utf8JsonReader.GetString(); + someProperty = new Option(utf8JsonReader.GetString()); break; default: break; @@ -137,8 +134,8 @@ public override TestInlineFreeformAdditionalPropertiesRequest Read(ref Utf8JsonR } } - if (someProperty == null) - throw new ArgumentNullException(nameof(someProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + if (someProperty.IsSet && someProperty.Value == null) + throw new ArgumentNullException(nameof(someProperty), "Property is not nullable for class TestInlineFreeformAdditionalPropertiesRequest."); return new TestInlineFreeformAdditionalPropertiesRequest(someProperty); } @@ -167,7 +164,11 @@ public override void Write(Utf8JsonWriter writer, TestInlineFreeformAdditionalPr /// public void WriteProperties(ref Utf8JsonWriter writer, TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet && testInlineFreeformAdditionalPropertiesRequest.SomeProperty == null) + throw new ArgumentNullException(nameof(testInlineFreeformAdditionalPropertiesRequest.SomeProperty), "Property is required for class TestInlineFreeformAdditionalPropertiesRequest."); + + if (testInlineFreeformAdditionalPropertiesRequest.SomePropertyOption.IsSet) + writer.WriteString("someProperty", testInlineFreeformAdditionalPropertiesRequest.SomeProperty); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs index 814316961f91..737124e080b3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Triangle.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -150,7 +151,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string triangleType = default; + Option triangleType = default; EquilateralTriangle equilateralTriangle = null; IsoscelesTriangle isoscelesTriangle = null; @@ -207,7 +208,7 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -215,17 +216,20 @@ public override Triangle Read(ref Utf8JsonReader utf8JsonReader, Type typeToConv } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class Triangle."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class Triangle.", nameof(triangleType)); + + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class Triangle."); if (equilateralTriangle != null) - return new Triangle(equilateralTriangle, triangleType); + return new Triangle(equilateralTriangle, triangleType.Value); if (isoscelesTriangle != null) - return new Triangle(isoscelesTriangle, triangleType); + return new Triangle(isoscelesTriangle, triangleType.Value); if (scaleneTriangle != null) - return new Triangle(scaleneTriangle, triangleType); + return new Triangle(scaleneTriangle, triangleType.Value); throw new JsonException(); } @@ -269,6 +273,9 @@ public override void Write(Utf8JsonWriter writer, Triangle triangle, JsonSeriali /// public void WriteProperties(ref Utf8JsonWriter writer, Triangle triangle, JsonSerializerOptions jsonSerializerOptions) { + if (triangle.TriangleType == null) + throw new ArgumentNullException(nameof(triangle.TriangleType), "Property is required for class Triangle."); + writer.WriteString("triangleType", triangle.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs index 6bd1e4303a70..270c598de618 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/TriangleInterface.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -100,7 +101,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string triangleType = default; + Option triangleType = default; while (utf8JsonReader.Read()) { @@ -118,7 +119,7 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t switch (localVarJsonPropertyName) { case "triangleType": - triangleType = utf8JsonReader.GetString(); + triangleType = new Option(utf8JsonReader.GetString()); break; default: break; @@ -126,10 +127,13 @@ public override TriangleInterface Read(ref Utf8JsonReader utf8JsonReader, Type t } } - if (triangleType == null) - throw new ArgumentNullException(nameof(triangleType), "Property is required for class TriangleInterface."); + if (!triangleType.IsSet) + throw new ArgumentException("Property is required for class TriangleInterface.", nameof(triangleType)); - return new TriangleInterface(triangleType); + if (triangleType.IsSet && triangleType.Value == null) + throw new ArgumentNullException(nameof(triangleType), "Property is not nullable for class TriangleInterface."); + + return new TriangleInterface(triangleType.Value); } /// @@ -156,6 +160,9 @@ public override void Write(Utf8JsonWriter writer, TriangleInterface triangleInte /// public void WriteProperties(ref Utf8JsonWriter writer, TriangleInterface triangleInterface, JsonSerializerOptions jsonSerializerOptions) { + if (triangleInterface.TriangleType == null) + throw new ArgumentNullException(nameof(triangleInterface.TriangleType), "Property is required for class TriangleInterface."); + writer.WriteString("triangleType", triangleInterface.TriangleType); } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs index ea527b94ec08..8c8eb5c8434b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/User.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -31,114 +32,198 @@ public partial class User : IValidatableObject /// /// Initializes a new instance of the class. /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. /// email /// firstName /// id /// lastName /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. /// password /// phone /// User Status /// username - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. [JsonConstructor] - public User(string email, string firstName, long id, string lastName, Object objectWithNoDeclaredProps, string password, string phone, int userStatus, string username, Object anyTypeProp = default, Object anyTypePropNullable = default, Object objectWithNoDeclaredPropsNullable = default) + public User(Option anyTypeProp = default, Option anyTypePropNullable = default, Option email = default, Option firstName = default, Option id = default, Option lastName = default, Option objectWithNoDeclaredProps = default, Option objectWithNoDeclaredPropsNullable = default, Option password = default, Option phone = default, Option userStatus = default, Option username = default) { - Email = email; - FirstName = firstName; - Id = id; - LastName = lastName; - ObjectWithNoDeclaredProps = objectWithNoDeclaredProps; - Password = password; - Phone = phone; - UserStatus = userStatus; - Username = username; - AnyTypeProp = anyTypeProp; - AnyTypePropNullable = anyTypePropNullable; - ObjectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; + AnyTypePropOption = anyTypeProp; + AnyTypePropNullableOption = anyTypePropNullable; + EmailOption = email; + FirstNameOption = firstName; + IdOption = id; + LastNameOption = lastName; + ObjectWithNoDeclaredPropsOption = objectWithNoDeclaredProps; + ObjectWithNoDeclaredPropsNullableOption = objectWithNoDeclaredPropsNullable; + PasswordOption = password; + PhoneOption = phone; + UserStatusOption = userStatus; + UsernameOption = username; OnCreated(); } partial void OnCreated(); + /// + /// Used to track the state of AnyTypeProp + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + [JsonPropertyName("anyTypeProp")] + public Object AnyTypeProp { get { return this. AnyTypePropOption; } set { this.AnyTypePropOption = new Option(value); } } + + /// + /// Used to track the state of AnyTypePropNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option AnyTypePropNullableOption { get; private set; } + + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// + /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + [JsonPropertyName("anyTypePropNullable")] + public Object AnyTypePropNullable { get { return this. AnyTypePropNullableOption; } set { this.AnyTypePropNullableOption = new Option(value); } } + + /// + /// Used to track the state of Email + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option EmailOption { get; private set; } + /// /// Gets or Sets Email /// [JsonPropertyName("email")] - public string Email { get; set; } + public string Email { get { return this. EmailOption; } set { this.EmailOption = new Option(value); } } + + /// + /// Used to track the state of FirstName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option FirstNameOption { get; private set; } /// /// Gets or Sets FirstName /// [JsonPropertyName("firstName")] - public string FirstName { get; set; } + public string FirstName { get { return this. FirstNameOption; } set { this.FirstNameOption = new Option(value); } } + + /// + /// Used to track the state of Id + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option IdOption { get; private set; } /// /// Gets or Sets Id /// [JsonPropertyName("id")] - public long Id { get; set; } + public long? Id { get { return this. IdOption; } set { this.IdOption = new Option(value); } } + + /// + /// Used to track the state of LastName + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option LastNameOption { get; private set; } /// /// Gets or Sets LastName /// [JsonPropertyName("lastName")] - public string LastName { get; set; } + public string LastName { get { return this. LastNameOption; } set { this.LastNameOption = new Option(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredProps + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsOption { get; private set; } /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. /// /// test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. [JsonPropertyName("objectWithNoDeclaredProps")] - public Object ObjectWithNoDeclaredProps { get; set; } + public Object ObjectWithNoDeclaredProps { get { return this. ObjectWithNoDeclaredPropsOption; } set { this.ObjectWithNoDeclaredPropsOption = new Option(value); } } + + /// + /// Used to track the state of ObjectWithNoDeclaredPropsNullable + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ObjectWithNoDeclaredPropsNullableOption { get; private set; } + + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// + /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + [JsonPropertyName("objectWithNoDeclaredPropsNullable")] + public Object ObjectWithNoDeclaredPropsNullable { get { return this. ObjectWithNoDeclaredPropsNullableOption; } set { this.ObjectWithNoDeclaredPropsNullableOption = new Option(value); } } + + /// + /// Used to track the state of Password + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PasswordOption { get; private set; } /// /// Gets or Sets Password /// [JsonPropertyName("password")] - public string Password { get; set; } + public string Password { get { return this. PasswordOption; } set { this.PasswordOption = new Option(value); } } /// - /// Gets or Sets Phone + /// Used to track the state of Phone /// - [JsonPropertyName("phone")] - public string Phone { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option PhoneOption { get; private set; } /// - /// User Status + /// Gets or Sets Phone /// - /// User Status - [JsonPropertyName("userStatus")] - public int UserStatus { get; set; } + [JsonPropertyName("phone")] + public string Phone { get { return this. PhoneOption; } set { this.PhoneOption = new Option(value); } } /// - /// Gets or Sets Username + /// Used to track the state of UserStatus /// - [JsonPropertyName("username")] - public string Username { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UserStatusOption { get; private set; } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 + /// User Status /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 - [JsonPropertyName("anyTypeProp")] - public Object AnyTypeProp { get; set; } + /// User Status + [JsonPropertyName("userStatus")] + public int? UserStatus { get { return this. UserStatusOption; } set { this.UserStatusOption = new Option(value); } } /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. + /// Used to track the state of Username /// - /// test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. - [JsonPropertyName("anyTypePropNullable")] - public Object AnyTypePropNullable { get; set; } + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option UsernameOption { get; private set; } /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. + /// Gets or Sets Username /// - /// test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. - [JsonPropertyName("objectWithNoDeclaredPropsNullable")] - public Object ObjectWithNoDeclaredPropsNullable { get; set; } + [JsonPropertyName("username")] + public string Username { get { return this. UsernameOption; } set { this.UsernameOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -154,18 +239,18 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class User {\n"); + sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); + sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); sb.Append(" Email: ").Append(Email).Append("\n"); sb.Append(" FirstName: ").Append(FirstName).Append("\n"); sb.Append(" Id: ").Append(Id).Append("\n"); sb.Append(" LastName: ").Append(LastName).Append("\n"); sb.Append(" ObjectWithNoDeclaredProps: ").Append(ObjectWithNoDeclaredProps).Append("\n"); + sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" Password: ").Append(Password).Append("\n"); sb.Append(" Phone: ").Append(Phone).Append("\n"); sb.Append(" UserStatus: ").Append(UserStatus).Append("\n"); sb.Append(" Username: ").Append(Username).Append("\n"); - sb.Append(" AnyTypeProp: ").Append(AnyTypeProp).Append("\n"); - sb.Append(" AnyTypePropNullable: ").Append(AnyTypePropNullable).Append("\n"); - sb.Append(" ObjectWithNoDeclaredPropsNullable: ").Append(ObjectWithNoDeclaredPropsNullable).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); @@ -204,18 +289,18 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string email = default; - string firstName = default; - long? id = default; - string lastName = default; - Object objectWithNoDeclaredProps = default; - string password = default; - string phone = default; - int? userStatus = default; - string username = default; - Object anyTypeProp = default; - Object anyTypePropNullable = default; - Object objectWithNoDeclaredPropsNullable = default; + Option anyTypeProp = default; + Option anyTypePropNullable = default; + Option email = default; + Option firstName = default; + Option id = default; + Option lastName = default; + Option objectWithNoDeclaredProps = default; + Option objectWithNoDeclaredPropsNullable = default; + Option password = default; + Option phone = default; + Option userStatus = default; + Option username = default; while (utf8JsonReader.Read()) { @@ -232,47 +317,47 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, switch (localVarJsonPropertyName) { + case "anyTypeProp": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypeProp = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "anyTypePropNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + anyTypePropNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; case "email": - email = utf8JsonReader.GetString(); + email = new Option(utf8JsonReader.GetString()); break; case "firstName": - firstName = utf8JsonReader.GetString(); + firstName = new Option(utf8JsonReader.GetString()); break; case "id": if (utf8JsonReader.TokenType != JsonTokenType.Null) - id = utf8JsonReader.GetInt64(); + id = new Option(utf8JsonReader.GetInt64()); break; case "lastName": - lastName = utf8JsonReader.GetString(); + lastName = new Option(utf8JsonReader.GetString()); break; case "objectWithNoDeclaredProps": if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredProps = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + objectWithNoDeclaredProps = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); + break; + case "objectWithNoDeclaredPropsNullable": + if (utf8JsonReader.TokenType != JsonTokenType.Null) + objectWithNoDeclaredPropsNullable = new Option(JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions)); break; case "password": - password = utf8JsonReader.GetString(); + password = new Option(utf8JsonReader.GetString()); break; case "phone": - phone = utf8JsonReader.GetString(); + phone = new Option(utf8JsonReader.GetString()); break; case "userStatus": if (utf8JsonReader.TokenType != JsonTokenType.Null) - userStatus = utf8JsonReader.GetInt32(); + userStatus = new Option(utf8JsonReader.GetInt32()); break; case "username": - username = utf8JsonReader.GetString(); - break; - case "anyTypeProp": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypeProp = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "anyTypePropNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - anyTypePropNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); - break; - case "objectWithNoDeclaredPropsNullable": - if (utf8JsonReader.TokenType != JsonTokenType.Null) - objectWithNoDeclaredPropsNullable = JsonSerializer.Deserialize(ref utf8JsonReader, jsonSerializerOptions); + username = new Option(utf8JsonReader.GetString()); break; default: break; @@ -280,34 +365,34 @@ public override User Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert, } } - if (email == null) - throw new ArgumentNullException(nameof(email), "Property is required for class User."); + if (email.IsSet && email.Value == null) + throw new ArgumentNullException(nameof(email), "Property is not nullable for class User."); - if (firstName == null) - throw new ArgumentNullException(nameof(firstName), "Property is required for class User."); + if (firstName.IsSet && firstName.Value == null) + throw new ArgumentNullException(nameof(firstName), "Property is not nullable for class User."); - if (id == null) - throw new ArgumentNullException(nameof(id), "Property is required for class User."); + if (id.IsSet && id.Value == null) + throw new ArgumentNullException(nameof(id), "Property is not nullable for class User."); - if (lastName == null) - throw new ArgumentNullException(nameof(lastName), "Property is required for class User."); + if (lastName.IsSet && lastName.Value == null) + throw new ArgumentNullException(nameof(lastName), "Property is not nullable for class User."); - if (objectWithNoDeclaredProps == null) - throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is required for class User."); + if (objectWithNoDeclaredProps.IsSet && objectWithNoDeclaredProps.Value == null) + throw new ArgumentNullException(nameof(objectWithNoDeclaredProps), "Property is not nullable for class User."); - if (password == null) - throw new ArgumentNullException(nameof(password), "Property is required for class User."); + if (password.IsSet && password.Value == null) + throw new ArgumentNullException(nameof(password), "Property is not nullable for class User."); - if (phone == null) - throw new ArgumentNullException(nameof(phone), "Property is required for class User."); + if (phone.IsSet && phone.Value == null) + throw new ArgumentNullException(nameof(phone), "Property is not nullable for class User."); - if (userStatus == null) - throw new ArgumentNullException(nameof(userStatus), "Property is required for class User."); + if (userStatus.IsSet && userStatus.Value == null) + throw new ArgumentNullException(nameof(userStatus), "Property is not nullable for class User."); - if (username == null) - throw new ArgumentNullException(nameof(username), "Property is required for class User."); + if (username.IsSet && username.Value == null) + throw new ArgumentNullException(nameof(username), "Property is not nullable for class User."); - return new User(email, firstName, id.Value, lastName, objectWithNoDeclaredProps, password, phone, userStatus.Value, username, anyTypeProp, anyTypePropNullable, objectWithNoDeclaredPropsNullable); + return new User(anyTypeProp, anyTypePropNullable, email, firstName, id, lastName, objectWithNoDeclaredProps, objectWithNoDeclaredPropsNullable, password, phone, userStatus, username); } /// @@ -334,22 +419,79 @@ public override void Write(Utf8JsonWriter writer, User user, JsonSerializerOptio /// public void WriteProperties(ref Utf8JsonWriter writer, User user, JsonSerializerOptions jsonSerializerOptions) { - writer.WriteString("email", user.Email); - writer.WriteString("firstName", user.FirstName); - writer.WriteNumber("id", user.Id); - writer.WriteString("lastName", user.LastName); - writer.WritePropertyName("objectWithNoDeclaredProps"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); - writer.WriteString("password", user.Password); - writer.WriteString("phone", user.Phone); - writer.WriteNumber("userStatus", user.UserStatus); - writer.WriteString("username", user.Username); - writer.WritePropertyName("anyTypeProp"); - JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); - writer.WritePropertyName("anyTypePropNullable"); - JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); - writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); - JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + if (user.EmailOption.IsSet && user.Email == null) + throw new ArgumentNullException(nameof(user.Email), "Property is required for class User."); + + if (user.FirstNameOption.IsSet && user.FirstName == null) + throw new ArgumentNullException(nameof(user.FirstName), "Property is required for class User."); + + if (user.LastNameOption.IsSet && user.LastName == null) + throw new ArgumentNullException(nameof(user.LastName), "Property is required for class User."); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet && user.ObjectWithNoDeclaredProps == null) + throw new ArgumentNullException(nameof(user.ObjectWithNoDeclaredProps), "Property is required for class User."); + + if (user.PasswordOption.IsSet && user.Password == null) + throw new ArgumentNullException(nameof(user.Password), "Property is required for class User."); + + if (user.PhoneOption.IsSet && user.Phone == null) + throw new ArgumentNullException(nameof(user.Phone), "Property is required for class User."); + + if (user.UsernameOption.IsSet && user.Username == null) + throw new ArgumentNullException(nameof(user.Username), "Property is required for class User."); + + if (user.AnyTypePropOption.IsSet) + if (user.AnyTypePropOption.Value != null) + { + writer.WritePropertyName("anyTypeProp"); + JsonSerializer.Serialize(writer, user.AnyTypeProp, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypeProp"); + if (user.AnyTypePropNullableOption.IsSet) + if (user.AnyTypePropNullableOption.Value != null) + { + writer.WritePropertyName("anyTypePropNullable"); + JsonSerializer.Serialize(writer, user.AnyTypePropNullable, jsonSerializerOptions); + } + else + writer.WriteNull("anyTypePropNullable"); + if (user.EmailOption.IsSet) + writer.WriteString("email", user.Email); + + if (user.FirstNameOption.IsSet) + writer.WriteString("firstName", user.FirstName); + + if (user.IdOption.IsSet) + writer.WriteNumber("id", user.IdOption.Value.Value); + + if (user.LastNameOption.IsSet) + writer.WriteString("lastName", user.LastName); + + if (user.ObjectWithNoDeclaredPropsOption.IsSet) + { + writer.WritePropertyName("objectWithNoDeclaredProps"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredProps, jsonSerializerOptions); + } + if (user.ObjectWithNoDeclaredPropsNullableOption.IsSet) + if (user.ObjectWithNoDeclaredPropsNullableOption.Value != null) + { + writer.WritePropertyName("objectWithNoDeclaredPropsNullable"); + JsonSerializer.Serialize(writer, user.ObjectWithNoDeclaredPropsNullable, jsonSerializerOptions); + } + else + writer.WriteNull("objectWithNoDeclaredPropsNullable"); + if (user.PasswordOption.IsSet) + writer.WriteString("password", user.Password); + + if (user.PhoneOption.IsSet) + writer.WriteString("phone", user.Phone); + + if (user.UserStatusOption.IsSet) + writer.WriteNumber("userStatus", user.UserStatusOption.Value.Value); + + if (user.UsernameOption.IsSet) + writer.WriteString("username", user.Username); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs index e633a5c92cf5..de887038530b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Whale.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -35,11 +36,11 @@ public partial class Whale : IValidatableObject /// hasBaleen /// hasTeeth [JsonConstructor] - public Whale(string className, bool hasBaleen, bool hasTeeth) + public Whale(string className, Option hasBaleen = default, Option hasTeeth = default) { ClassName = className; - HasBaleen = hasBaleen; - HasTeeth = hasTeeth; + HasBaleenOption = hasBaleen; + HasTeethOption = hasTeeth; OnCreated(); } @@ -51,17 +52,31 @@ public Whale(string className, bool hasBaleen, bool hasTeeth) [JsonPropertyName("className")] public string ClassName { get; set; } + /// + /// Used to track the state of HasBaleen + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasBaleenOption { get; private set; } + /// /// Gets or Sets HasBaleen /// [JsonPropertyName("hasBaleen")] - public bool HasBaleen { get; set; } + public bool? HasBaleen { get { return this. HasBaleenOption; } set { this.HasBaleenOption = new Option(value); } } + + /// + /// Used to track the state of HasTeeth + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option HasTeethOption { get; private set; } /// /// Gets or Sets HasTeeth /// [JsonPropertyName("hasTeeth")] - public bool HasTeeth { get; set; } + public bool? HasTeeth { get { return this. HasTeethOption; } set { this.HasTeethOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -118,9 +133,9 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - bool? hasBaleen = default; - bool? hasTeeth = default; + Option className = default; + Option hasBaleen = default; + Option hasTeeth = default; while (utf8JsonReader.Read()) { @@ -138,15 +153,15 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "hasBaleen": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasBaleen = utf8JsonReader.GetBoolean(); + hasBaleen = new Option(utf8JsonReader.GetBoolean()); break; case "hasTeeth": if (utf8JsonReader.TokenType != JsonTokenType.Null) - hasTeeth = utf8JsonReader.GetBoolean(); + hasTeeth = new Option(utf8JsonReader.GetBoolean()); break; default: break; @@ -154,16 +169,19 @@ public override Whale Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Whale."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Whale.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Whale."); - if (hasBaleen == null) - throw new ArgumentNullException(nameof(hasBaleen), "Property is required for class Whale."); + if (hasBaleen.IsSet && hasBaleen.Value == null) + throw new ArgumentNullException(nameof(hasBaleen), "Property is not nullable for class Whale."); - if (hasTeeth == null) - throw new ArgumentNullException(nameof(hasTeeth), "Property is required for class Whale."); + if (hasTeeth.IsSet && hasTeeth.Value == null) + throw new ArgumentNullException(nameof(hasTeeth), "Property is not nullable for class Whale."); - return new Whale(className, hasBaleen.Value, hasTeeth.Value); + return new Whale(className.Value, hasBaleen, hasTeeth); } /// @@ -190,9 +208,16 @@ public override void Write(Utf8JsonWriter writer, Whale whale, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Whale whale, JsonSerializerOptions jsonSerializerOptions) { + if (whale.ClassName == null) + throw new ArgumentNullException(nameof(whale.ClassName), "Property is required for class Whale."); + writer.WriteString("className", whale.ClassName); - writer.WriteBoolean("hasBaleen", whale.HasBaleen); - writer.WriteBoolean("hasTeeth", whale.HasTeeth); + + if (whale.HasBaleenOption.IsSet) + writer.WriteBoolean("hasBaleen", whale.HasBaleenOption.Value.Value); + + if (whale.HasTeethOption.IsSet) + writer.WriteBoolean("hasTeeth", whale.HasTeethOption.Value.Value); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs index 503c47228cdf..1c364c4be9e2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -20,13 +20,14 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { /// /// Zebra /// - public partial class Zebra : Dictionary, IValidatableObject + public partial class Zebra : IValidatableObject { /// /// Initializes a new instance of the class. @@ -34,10 +35,10 @@ public partial class Zebra : Dictionary, IValidatableObject /// className /// type [JsonConstructor] - public Zebra(string className, TypeEnum type) : base() + public Zebra(string className, Option type = default) { ClassName = className; - Type = type; + TypeOption = type; OnCreated(); } @@ -109,7 +110,7 @@ public static TypeEnum TypeEnumFromString(string value) /// /// /// - public static string TypeEnumToJsonValue(TypeEnum value) + public static string TypeEnumToJsonValue(TypeEnum? value) { if (value == TypeEnum.Plains) return "plains"; @@ -123,11 +124,18 @@ public static string TypeEnumToJsonValue(TypeEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of Type + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option TypeOption { get; private set; } + /// /// Gets or Sets Type /// [JsonPropertyName("type")] - public TypeEnum Type { get; set; } + public TypeEnum? Type { get { return this.TypeOption; } set { this.TypeOption = new Option(value); } } /// /// Gets or Sets ClassName @@ -149,7 +157,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString()?.Replace("\n", "\n ")).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -163,16 +170,6 @@ public override string ToString() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } @@ -200,8 +197,8 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert JsonTokenType startingTokenType = utf8JsonReader.TokenType; - string className = default; - Zebra.TypeEnum? type = default; + Option className = default; + Option type = default; while (utf8JsonReader.Read()) { @@ -219,13 +216,12 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert switch (localVarJsonPropertyName) { case "className": - className = utf8JsonReader.GetString(); + className = new Option(utf8JsonReader.GetString()); break; case "type": string typeRawValue = utf8JsonReader.GetString(); - type = typeRawValue == null - ? null - : Zebra.TypeEnumFromStringOrDefault(typeRawValue); + if (typeRawValue != null) + type = new Option(Zebra.TypeEnumFromStringOrDefault(typeRawValue)); break; default: break; @@ -233,13 +229,16 @@ public override Zebra Read(ref Utf8JsonReader utf8JsonReader, Type typeToConvert } } - if (className == null) - throw new ArgumentNullException(nameof(className), "Property is required for class Zebra."); + if (!className.IsSet) + throw new ArgumentException("Property is required for class Zebra.", nameof(className)); + + if (className.IsSet && className.Value == null) + throw new ArgumentNullException(nameof(className), "Property is not nullable for class Zebra."); - if (type == null) - throw new ArgumentNullException(nameof(type), "Property is required for class Zebra."); + if (type.IsSet && type.Value == null) + throw new ArgumentNullException(nameof(type), "Property is not nullable for class Zebra."); - return new Zebra(className, type.Value); + return new Zebra(className.Value, type); } /// @@ -266,13 +265,13 @@ public override void Write(Utf8JsonWriter writer, Zebra zebra, JsonSerializerOpt /// public void WriteProperties(ref Utf8JsonWriter writer, Zebra zebra, JsonSerializerOptions jsonSerializerOptions) { + if (zebra.ClassName == null) + throw new ArgumentNullException(nameof(zebra.ClassName), "Property is required for class Zebra."); + writer.WriteString("className", zebra.ClassName); - var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.Type); - if (typeRawValue != null) - writer.WriteString("type", typeRawValue); - else - writer.WriteNull("type"); + var typeRawValue = Zebra.TypeEnumToJsonValue(zebra.TypeOption.Value.Value); + writer.WriteString("type", typeRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs index 20e184f02b2b..34a044fb8b13 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnum.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs index c590ea6644ba..e7baeec052c5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Model/ZeroBasedEnumClass.cs @@ -20,6 +20,7 @@ using System.Text.Json.Serialization; using System.ComponentModel.DataAnnotations; using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; +using Org.OpenAPITools.Client; namespace Org.OpenAPITools.Model { @@ -33,9 +34,9 @@ public partial class ZeroBasedEnumClass : IValidatableObject /// /// zeroBasedEnum [JsonConstructor] - public ZeroBasedEnumClass(ZeroBasedEnumEnum zeroBasedEnum) + public ZeroBasedEnumClass(Option zeroBasedEnum = default) { - ZeroBasedEnum = zeroBasedEnum; + ZeroBasedEnumOption = zeroBasedEnum; OnCreated(); } @@ -96,7 +97,7 @@ public static ZeroBasedEnumEnum ZeroBasedEnumEnumFromString(string value) /// /// /// - public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) + public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum? value) { if (value == ZeroBasedEnumEnum.Unknown) return "unknown"; @@ -107,11 +108,18 @@ public static string ZeroBasedEnumEnumToJsonValue(ZeroBasedEnumEnum value) throw new NotImplementedException($"Value could not be handled: '{value}'"); } + /// + /// Used to track the state of ZeroBasedEnum + /// + [JsonIgnore] + [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] + public Option ZeroBasedEnumOption { get; private set; } + /// /// Gets or Sets ZeroBasedEnum /// [JsonPropertyName("ZeroBasedEnum")] - public ZeroBasedEnumEnum ZeroBasedEnum { get; set; } + public ZeroBasedEnumEnum? ZeroBasedEnum { get { return this.ZeroBasedEnumOption; } set { this.ZeroBasedEnumOption = new Option(value); } } /// /// Gets or Sets additional properties @@ -166,7 +174,7 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type JsonTokenType startingTokenType = utf8JsonReader.TokenType; - ZeroBasedEnumClass.ZeroBasedEnumEnum? zeroBasedEnum = default; + Option zeroBasedEnum = default; while (utf8JsonReader.Read()) { @@ -185,9 +193,8 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type { case "ZeroBasedEnum": string zeroBasedEnumRawValue = utf8JsonReader.GetString(); - zeroBasedEnum = zeroBasedEnumRawValue == null - ? null - : ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue); + if (zeroBasedEnumRawValue != null) + zeroBasedEnum = new Option(ZeroBasedEnumClass.ZeroBasedEnumEnumFromStringOrDefault(zeroBasedEnumRawValue)); break; default: break; @@ -195,10 +202,10 @@ public override ZeroBasedEnumClass Read(ref Utf8JsonReader utf8JsonReader, Type } } - if (zeroBasedEnum == null) - throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is required for class ZeroBasedEnumClass."); + if (zeroBasedEnum.IsSet && zeroBasedEnum.Value == null) + throw new ArgumentNullException(nameof(zeroBasedEnum), "Property is not nullable for class ZeroBasedEnumClass."); - return new ZeroBasedEnumClass(zeroBasedEnum.Value); + return new ZeroBasedEnumClass(zeroBasedEnum); } /// @@ -225,12 +232,8 @@ public override void Write(Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEn /// public void WriteProperties(ref Utf8JsonWriter writer, ZeroBasedEnumClass zeroBasedEnumClass, JsonSerializerOptions jsonSerializerOptions) { - - var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnum); - if (zeroBasedEnumRawValue != null) - writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); - else - writer.WriteNull("ZeroBasedEnum"); + var zeroBasedEnumRawValue = ZeroBasedEnumClass.ZeroBasedEnumEnumToJsonValue(zeroBasedEnumClass.ZeroBasedEnumOption.Value.Value); + writer.WriteString("ZeroBasedEnum", zeroBasedEnumRawValue); } } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 20173ba5ebcd..ab2ce35e262b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,10 +20,11 @@ - + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md index d90bb5761dd3..a957baa422a8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-generichost-netstandard2.0/src/Org.OpenAPITools/README.md @@ -69,42 +69,7 @@ namespace YourProject .ConfigureApi((context, options) => { // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); - options.AddTokens(token); - - // optionally choose the method the tokens will be provided with, default is RateLimitProvider - options.UseProvider, ApiKeyToken>(); - - // the type of token here depends on the api security specifications - ApiKeyToken token = new(""); + ApiKeyToken token = new("", ClientUtils.ApiKeyHeader.Authorization); options.AddTokens(token); // optionally choose the method the tokens will be provided with, default is RateLimitProvider diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/FILES index cfa6edb1db83..3079e1bed81a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -195,6 +196,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/README.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/README.md index 18aa6dd26bc4..f41927be64a0 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/README.md @@ -140,6 +140,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -246,6 +247,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-httpclient/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/FakeApi.md index bd9b0d42c221..ada65ec39650 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -571,6 +572,95 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using System.Net.Http; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes + HttpClient httpClient = new HttpClient(); + HttpClientHandler httpClientHandler = new HttpClientHandler(); + var apiInstance = new FakeApi(httpClient, config, httpClientHandler); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/PetApi.md index cf016f148d96..fbe6c1f5aa65 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/PetApi.md @@ -427,6 +427,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); // create instances of HttpClient, HttpClientHandler to be reused later with different Api classes HttpClient httpClient = new HttpClient(); @@ -483,7 +487,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/UserApi.md index a7cf3372a3a4..0e5c25a6eff8 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/docs/UserApi.md @@ -466,6 +466,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -560,7 +562,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs index 14104f06bee8..57774764f56c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -146,6 +146,24 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + void TestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody); + /// /// /// /// @@ -559,6 +577,29 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1715,6 +1756,119 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = requestBody; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = requestBody; + + + // make the HTTP request + + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs index ff5078724368..2d6e56f65c73 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Api/PetApi.cs @@ -1315,6 +1315,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1376,6 +1381,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs index f6e3372563a8..8ab66c3d5f69 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -94,14 +94,38 @@ public async Task Deserialize(HttpResponseMessage response) /// Object representation of the JSON string. internal async Task Deserialize(HttpResponseMessage response, Type type) { - IList headers = response.Headers.Select(x => x.Key + "=" + x.Value).ToList(); + IList headers = new List(); + // process response headers, e.g. Access-Control-Allow-Methods + foreach (var responseHeader in response.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + + // process response content headers, e.g. Content-Type + foreach (var responseHeader in response.Content.Headers) + { + headers.Add(responseHeader.Key + "=" + ClientUtils.ParameterToString(responseHeader.Value)); + } + // RFC 2183 & RFC 2616 + var fileNameRegex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$", RegexOptions.IgnoreCase); if (type == typeof(byte[])) // return byte array { return await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false); } else if (type == typeof(FileParameter)) { + if (headers != null) { + foreach (var header in headers) + { + var match = fileNameRegex.Match(header.ToString()); + if (match.Success) + { + string fileName = ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + return new FileParameter(fileName, await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); + } + } + } return new FileParameter(await response.Content.ReadAsStreamAsync().ConfigureAwait(false)); } @@ -114,10 +138,10 @@ internal async Task Deserialize(HttpResponseMessage response, Type type) var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) ? Path.GetTempPath() : _configuration.TempFolderPath; - var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in headers) { - var match = regex.Match(header.ToString()); + var match = fileNameRegex.Match(header.ToString()); if (match.Success) { string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..5e20b7408d46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs index f7d085a21cea..8b003f6b9af6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -52,17 +52,25 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; this.AdditionalProperties = new Dictionary(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs index f533b3bfc2eb..29446e5dc84f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Drawing.cs @@ -31,7 +31,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -40,7 +40,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -87,7 +87,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -101,7 +100,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -134,7 +133,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -165,16 +164,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs index 9f936ccbd880..bb695d4dfb2d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -31,7 +31,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -48,7 +48,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -152,7 +152,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -174,7 +173,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -207,7 +206,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -270,16 +269,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..919ae3fc0fe8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1043 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using FileParameter = Org.OpenAPITools.Client.FileParameter; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index 03f440cf19a2..db14de1df9c5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -31,13 +31,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -63,7 +63,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -74,7 +73,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -107,7 +106,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -126,16 +125,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs index d45445e174aa..ebb1e730433f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Model/Zebra.cs @@ -31,7 +31,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -77,7 +77,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -109,7 +109,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -121,7 +120,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -154,7 +153,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -174,16 +173,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj index c3a5ce9403ff..32a0e7090ce3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-httpclient/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,10 +20,10 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/FILES index ddeca89d213f..1e54de3472d2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -198,6 +199,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/README.md b/samples/client/petstore/csharp/OpenAPIClient-net47/README.md index 2a3e242fe88d..b77dcd24dfbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-net47/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/FakeApi.md index c8a21d2e25c6..1debc2b6564d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/PetApi.md index ad44daac69e1..220b1ae30105 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index 00220e121756..7d108b4e7df3 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs index 7282ba7821b9..ce37acaec65f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs index 22b4eeeea76e..7a34dc4fe192 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs index b9c53cd6b62b..b10e49166a65 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -562,7 +562,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..5e20b7408d46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs index eaeb0202a264..8e76f168a65e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/ChildCat.cs @@ -51,17 +51,25 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; this.AdditionalProperties = new Dictionary(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs index d5d633ed3b31..1d18a58b117a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -86,7 +86,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -100,7 +99,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -133,7 +132,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -164,16 +163,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs index 919ed331163d..5c7b13e9b783 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -151,7 +151,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -173,7 +172,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -206,7 +205,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -269,16 +268,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..90e0c44b40b8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1042 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index e668ef1fe4ea..c56b9e336517 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -62,7 +62,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -73,7 +72,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -106,7 +105,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -125,16 +124,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs index 193c3be7973b..58ec23be816e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -76,7 +76,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -108,7 +108,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,7 +119,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -153,7 +152,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -173,16 +172,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj index b6795e5e0ddc..673473e74a28 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net47/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/FILES index ddeca89d213f..1e54de3472d2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -198,6 +199,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/README.md b/samples/client/petstore/csharp/OpenAPIClient-net48/README.md index 2a3e242fe88d..b77dcd24dfbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-net48/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/FakeApi.md index c8a21d2e25c6..1debc2b6564d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/PetApi.md index ad44daac69e1..220b1ae30105 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index a522b7684ac7..d6af6b81ea78 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -8,9 +8,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs index 7282ba7821b9..ce37acaec65f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs index 22b4eeeea76e..7a34dc4fe192 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs index b9c53cd6b62b..b10e49166a65 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ApiClient.cs @@ -562,7 +562,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..5e20b7408d46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs index eaeb0202a264..8e76f168a65e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/ChildCat.cs @@ -51,17 +51,25 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; this.AdditionalProperties = new Dictionary(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs index d5d633ed3b31..1d18a58b117a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -86,7 +86,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -100,7 +99,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -133,7 +132,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -164,16 +163,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs index 919ed331163d..5c7b13e9b783 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -151,7 +151,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -173,7 +172,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -206,7 +205,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -269,16 +268,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..90e0c44b40b8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1042 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index e668ef1fe4ea..c56b9e336517 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -62,7 +62,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -73,7 +72,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -106,7 +105,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -125,16 +124,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs index 193c3be7973b..58ec23be816e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -76,7 +76,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -108,7 +108,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,7 +119,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -153,7 +152,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -173,16 +172,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 6b3163ef9ada..84e6c8e86ea6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net48/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/FILES index ddeca89d213f..1e54de3472d2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -198,6 +199,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/README.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/README.md index 2a3e242fe88d..b77dcd24dfbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-net5.0/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/DateOnlyClass.md index d0912d2ac415..8291b9cb6d78 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/DateOnlyClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/DateOnlyClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**DateOnlyProperty** | **DateTime** | | [optional] +**DateOnlyProperty** | **DateOnly** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FakeApi.md index 70d7da71e1c6..b939df0baf1c 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) @@ -810,7 +896,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = null, int? int32 = null, long? int64 = null, float? varFloat = null, string? varString = null, System.IO.Stream? binary = null, DateTime? date = null, DateTime? dateTime = null, string? password = null, string? callback = null) +> void TestEndpointParameters (decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = null, int? int32 = null, long? int64 = null, float? varFloat = null, string? varString = null, System.IO.Stream? binary = null, DateOnly? date = null, DateTime? dateTime = null, string? password = null, string? callback = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -847,7 +933,7 @@ namespace Example var varFloat = 3.4F; // float? | None (optional) var varString = "varString_example"; // string? | None (optional) var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream? | None (optional) - var date = DateTime.Parse("2013-10-20"); // DateTime? | None (optional) + var date = DateOnly.Parse("2013-10-20"); // DateOnly? | None (optional) var dateTime = DateTime.Parse(""2010-02-01T10:20:10.111110+01:00""); // DateTime? | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") var password = "password_example"; // string? | None (optional) var callback = "callback_example"; // string? | None (optional) @@ -899,7 +985,7 @@ catch (ApiException e) | **varFloat** | **float?** | None | [optional] | | **varString** | **string?** | None | [optional] | | **binary** | **System.IO.Stream?****System.IO.Stream?** | None | [optional] | -| **date** | **DateTime?** | None | [optional] | +| **date** | **DateOnly?** | None | [optional] | | **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | | **password** | **string?** | None | [optional] | | **callback** | **string?** | None | [optional] | diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FormatTest.md index 2d28c89fa309..1d09c0f37e47 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/FormatTest.md @@ -16,7 +16,7 @@ Name | Type | Description | Notes **VarString** | **string** | | [optional] **VarByte** | **byte[]** | | **Binary** | **System.IO.Stream** | | [optional] -**Date** | **DateTime** | | +**Date** | **DateOnly** | | **DateTime** | **DateTime** | | [optional] **Uuid** | **Guid** | | [optional] **Password** | **string** | | diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/NullableClass.md index 7bab4fa20ee9..67c1052fca9d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/NullableClass.md @@ -8,7 +8,7 @@ Name | Type | Description | Notes **NumberProp** | **decimal?** | | [optional] **BooleanProp** | **bool?** | | [optional] **StringProp** | **string** | | [optional] -**DateProp** | **DateTime?** | | [optional] +**DateProp** | **DateOnly** | | [optional] **DatetimeProp** | **DateTime?** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/PetApi.md index 7cadc180a75f..417e0ab80207 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/RequiredClass.md new file mode 100644 index 000000000000..685c1c51e031 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateOnly** | | +**RequiredNotNullableDateProp** | **DateOnly** | | +**NotRequiredNullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNotnullableDateProp** | **DateOnly** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj index ca4153189a50..3ddd6b44be59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -9,9 +9,9 @@ - - - + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs index afe118039335..785e887d37f9 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -248,7 +268,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// Index associated with the operation. /// - void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); + void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -273,7 +293,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// Index associated with the operation. /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); /// /// To test enum parameters /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -703,7 +748,7 @@ public interface IFakeApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -729,7 +774,7 @@ public interface IFakeApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// To test enum parameters /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// @@ -2304,7 +2491,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Index associated with the operation. /// - public void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) + public void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) { TestEndpointParametersWithHttpInfo(number, varDouble, patternWithoutDelimiter, varByte, integer, int32, int64, varFloat, varString, binary, date, dateTime, password, callback); } @@ -2329,7 +2516,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Index associated with the operation. /// ApiResponse of Object(void) - public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) @@ -2455,7 +2642,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await TestEndpointParametersWithHttpInfoAsync(number, varDouble, patternWithoutDelimiter, varByte, integer, int32, int64, varFloat, varString, binary, date, dateTime, password, callback, operationIndex, cancellationToken).ConfigureAwait(false); } @@ -2481,7 +2668,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs index cb1a5d8b24d1..f86ff3fb795e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs index b9c53cd6b62b..b10e49166a65 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ApiClient.cs @@ -562,7 +562,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..d5acb18947c2 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index d98d2815297d..0685800345a1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -349,8 +352,10 @@ private string GetRSASignature(byte[] stringToSign) /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) - throw new Exception("key file path does not exist."); + if (!File.Exists(KeyFilePath) && string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } var keyStr = KeyString; const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; @@ -446,6 +451,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs index eaeb0202a264..8e76f168a65e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/ChildCat.cs @@ -51,17 +51,25 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; this.AdditionalProperties = new Dictionary(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs index d618b5ba1100..6fcef7bd7049 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/DateOnlyClass.cs @@ -36,7 +36,7 @@ public partial class DateOnlyClass : IEquatable, IValidatableObje /// Initializes a new instance of the class. /// /// dateOnlyProperty. - public DateOnlyClass(DateTime dateOnlyProperty = default(DateTime)) + public DateOnlyClass(DateOnly dateOnlyProperty = default(DateOnly)) { this.DateOnlyProperty = dateOnlyProperty; this.AdditionalProperties = new Dictionary(); @@ -48,7 +48,7 @@ public partial class DateOnlyClass : IEquatable, IValidatableObje /// Fri Jul 21 00:00:00 UTC 2017 [DataMember(Name = "dateOnlyProperty", EmitDefaultValue = false)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime DateOnlyProperty { get; set; } + public DateOnly DateOnlyProperty { get; set; } /// /// Gets or Sets additional properties diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs index d5d633ed3b31..1d18a58b117a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -86,7 +86,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -100,7 +99,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -133,7 +132,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -164,16 +163,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs index 8a1f7d62fa27..e797509b92d5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/FormatTest.cs @@ -62,7 +62,7 @@ protected FormatTest() /// A string that is a 10 digit number. Can have leading zeros.. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. /// None. - public FormatTest(int integer = default(int), int int32 = default(int), uint unsignedInteger = default(uint), long int64 = default(long), ulong unsignedLong = default(ulong), decimal number = default(decimal), float varFloat = default(float), double varDouble = default(double), decimal varDecimal = default(decimal), string varString = default(string), byte[] varByte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string), string patternWithBackslash = default(string)) + public FormatTest(int integer = default(int), int int32 = default(int), uint unsignedInteger = default(uint), long int64 = default(long), ulong unsignedLong = default(ulong), decimal number = default(decimal), float varFloat = default(float), double varDouble = default(double), decimal varDecimal = default(decimal), string varString = default(string), byte[] varByte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateOnly date = default(DateOnly), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string), string patternWithBackslash = default(string)) { this.Number = number; // to ensure "varByte" is required (not null) @@ -71,6 +71,11 @@ protected FormatTest() throw new ArgumentNullException("varByte is a required property for FormatTest and cannot be null"); } this.VarByte = varByte; + // to ensure "date" is required (not null) + if (date == null) + { + throw new ArgumentNullException("date is a required property for FormatTest and cannot be null"); + } this.Date = date; // to ensure "password" is required (not null) if (password == null) @@ -174,7 +179,7 @@ protected FormatTest() /// Sun Feb 02 00:00:00 UTC 2020 [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime Date { get; set; } + public DateOnly Date { get; set; } /// /// Gets or Sets DateTime diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs index 919ed331163d..43fe8c921031 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateOnly dateProp = default(DateOnly), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -93,7 +93,7 @@ public partial class NullableClass : Dictionary, IEquatable [DataMember(Name = "date_prop", EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime? DateProp { get; set; } + public DateOnly DateProp { get; set; } /// /// Gets or Sets DatetimeProp @@ -151,7 +151,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -173,7 +172,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -206,7 +205,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -269,16 +268,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs index d95073253857..0bd55810cdf1 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Order.cs @@ -52,10 +52,10 @@ public enum StatusEnum Approved = 2, /// - /// Enum Delivered for value: delivered + /// Enum Shipped for value: delivered /// [EnumMember(Value = "delivered")] - Delivered = 3 + Shipped = 3 } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnum.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnum.cs index 59a9f8e3500a..7cacd79e3e6a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnum.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnum.cs @@ -45,10 +45,10 @@ public enum OuterEnum Approved = 2, /// - /// Enum Delivered for value: delivered + /// Enum Shipped for value: delivered /// [EnumMember(Value = "delivered")] - Delivered = 3 + Shipped = 3 } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs index 40e276b600eb..d6790731adb7 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/OuterEnumDefaultValue.cs @@ -45,10 +45,10 @@ public enum OuterEnumDefaultValue Approved = 2, /// - /// Enum Delivered for value: delivered + /// Enum Shipped for value: delivered /// [EnumMember(Value = "delivered")] - Delivered = 3 + Shipped = 3 } } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..a1c904a838fe --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1047 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateOnly requiredNullableDateProp = default(DateOnly), DateOnly requiredNotNullableDateProp = default(DateOnly), DateOnly notRequiredNullableDateProp = default(DateOnly), DateOnly notRequiredNotnullableDateProp = default(DateOnly), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + // to ensure "requiredNotNullableDateProp" is required (not null) + if (requiredNotNullableDateProp == null) + { + throw new ArgumentNullException("requiredNotNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index e668ef1fe4ea..c56b9e336517 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -62,7 +62,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -73,7 +72,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -106,7 +105,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -125,16 +124,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs index 193c3be7973b..58ec23be816e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -76,7 +76,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -108,7 +108,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,7 +119,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -153,7 +152,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -173,16 +172,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 8c0a21ddae8e..154b17942c57 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient-net5.0/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.gitignore b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.gitignore new file mode 100644 index 000000000000..1ee53850b84c --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.gitignore @@ -0,0 +1,362 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator-ignore b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/FILES new file mode 100644 index 000000000000..2a2fc5407057 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/FILES @@ -0,0 +1,29 @@ +.gitignore +Org.OpenAPITools.sln +README.md +api/openapi.yaml +appveyor.yml +docs/DefaultApi.md +docs/NowGet200Response.md +git_push.sh +src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj +src/Org.OpenAPITools/Api/DefaultApi.cs +src/Org.OpenAPITools/Client/ApiClient.cs +src/Org.OpenAPITools/Client/ApiException.cs +src/Org.OpenAPITools/Client/ApiResponse.cs +src/Org.OpenAPITools/Client/ClientUtils.cs +src/Org.OpenAPITools/Client/Configuration.cs +src/Org.OpenAPITools/Client/ExceptionFactory.cs +src/Org.OpenAPITools/Client/GlobalConfiguration.cs +src/Org.OpenAPITools/Client/HttpMethod.cs +src/Org.OpenAPITools/Client/IApiAccessor.cs +src/Org.OpenAPITools/Client/IAsynchronousClient.cs +src/Org.OpenAPITools/Client/IReadableConfiguration.cs +src/Org.OpenAPITools/Client/ISynchronousClient.cs +src/Org.OpenAPITools/Client/Multimap.cs +src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs +src/Org.OpenAPITools/Client/RequestOptions.cs +src/Org.OpenAPITools/Client/RetryConfiguration.cs +src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs +src/Org.OpenAPITools/Model/NowGet200Response.cs +src/Org.OpenAPITools/Org.OpenAPITools.csproj diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/Org.OpenAPITools.sln b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/Org.OpenAPITools.sln new file mode 100644 index 000000000000..ae868d9e2be0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/Org.OpenAPITools.sln @@ -0,0 +1,27 @@ +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio 2012 +VisualStudioVersion = 12.0.0.0 +MinimumVisualStudioVersion = 10.0.0.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools", "src\Org.OpenAPITools\Org.OpenAPITools.csproj", "{D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Org.OpenAPITools.Test", "src\Org.OpenAPITools.Test\Org.OpenAPITools.Test.csproj", "{19F1DEBC-DE5E-4517-8062-F000CD499087}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|Any CPU = Debug|Any CPU + Release|Any CPU = Release|Any CPU + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D0A67E81-4061-48EB-B4B8-C73BDF8B2D95}.Release|Any CPU.Build.0 = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Debug|Any CPU.Build.0 = Debug|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.ActiveCfg = Release|Any CPU + {19F1DEBC-DE5E-4517-8062-F000CD499087}.Release|Any CPU.Build.0 = Release|Any CPU + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection +EndGlobal \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/README.md b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/README.md new file mode 100644 index 000000000000..d4007cf506b4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/README.md @@ -0,0 +1,127 @@ +# Org.OpenAPITools - the C# library for the OpenAPI Dates + +Thic spec contains endpoints with dates in different formats + +This C# SDK is automatically generated by the [OpenAPI Generator](https://openapi-generator.tech) project: + +- API version: 1.0.0 +- SDK version: 1.0.0 +- Build package: org.openapitools.codegen.languages.CSharpClientCodegen + + +## Frameworks supported + + +## Dependencies + +- [RestSharp](https://www.nuget.org/packages/RestSharp) - 106.13.0 or later +- [Json.NET](https://www.nuget.org/packages/Newtonsoft.Json/) - 13.0.2 or later +- [JsonSubTypes](https://www.nuget.org/packages/JsonSubTypes/) - 1.8.0 or later +- [System.ComponentModel.Annotations](https://www.nuget.org/packages/System.ComponentModel.Annotations) - 5.0.0 or later + +The DLLs included in the package may not be the latest version. We recommend using [NuGet](https://docs.nuget.org/consume/installing-nuget) to obtain the latest version of the packages: +``` +Install-Package RestSharp +Install-Package Newtonsoft.Json +Install-Package JsonSubTypes +Install-Package System.ComponentModel.Annotations +``` + +NOTE: RestSharp versions greater than 105.1.0 have a bug which causes file uploads to fail. See [RestSharp#742](https://github.com/restsharp/RestSharp/issues/742). +NOTE: RestSharp for .Net Core creates a new socket for each api call, which can lead to a socket exhaustion problem. See [RestSharp#1406](https://github.com/restsharp/RestSharp/issues/1406). + + +## Installation +Run the following command to generate the DLL +- [Mac/Linux] `/bin/sh build.sh` +- [Windows] `build.bat` + +Then include the DLL (under the `bin` folder) in the C# project, and use the namespaces: +```csharp +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; +``` + +## Packaging + +A `.nuspec` is included with the project. You can follow the Nuget quickstart to [create](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#create-the-package) and [publish](https://docs.microsoft.com/en-us/nuget/quickstart/create-and-publish-a-package#publish-the-package) packages. + +This `.nuspec` uses placeholders from the `.csproj`, so build the `.csproj` directly: + +``` +nuget pack -Build -OutputDirectory out Org.OpenAPITools.csproj +``` + +Then, publish to a [local feed](https://docs.microsoft.com/en-us/nuget/hosting-packages/local-feeds) or [other host](https://docs.microsoft.com/en-us/nuget/hosting-packages/overview) and consume the new package via Nuget as usual. + + +## Usage + +To use the API client with a HTTP proxy, setup a `System.Net.WebProxy` +```csharp +Configuration c = new Configuration(); +System.Net.WebProxy webProxy = new System.Net.WebProxy("http://myProxyUrl:80/"); +webProxy.Credentials = System.Net.CredentialCache.DefaultCredentials; +c.Proxy = webProxy; +``` + + +## Getting Started + +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class Example + { + public static void Main() + { + + Configuration config = new Configuration(); + config.BasePath = "http://localhost"; + var apiInstance = new DefaultApi(config); + + try + { + NowGet200Response result = apiInstance.NowGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.NowGet: " + e.Message ); + Debug.Print("Status Code: "+ e.ErrorCode); + Debug.Print(e.StackTrace); + } + + } + } +} +``` + + +## Documentation for API Endpoints + +All URIs are relative to *http://localhost* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*DefaultApi* | [**NowGet**](docs/DefaultApi.md#nowget) | **GET** /now | + + + +## Documentation for Models + + - [Model.NowGet200Response](docs/NowGet200Response.md) + + + +## Documentation for Authorization + +Endpoints do not require authorization. + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/api/openapi.yaml new file mode 100644 index 000000000000..a84e041a00fa --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/api/openapi.yaml @@ -0,0 +1,35 @@ +openapi: 3.0.0 +info: + description: Thic spec contains endpoints with dates in different formats + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Dates + version: 1.0.0 +servers: +- url: / +paths: + /now: + get: + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/_now_get_200_response' + description: now dates +components: + schemas: + _now_get_200_response: + example: + today: 2000-01-23 + now: 2000-01-23T04:56:07.000+00:00 + properties: + today: + format: date + type: string + now: + format: date-time + type: string + type: object + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/appveyor.yml b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/appveyor.yml new file mode 100644 index 000000000000..f76f63cee506 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/appveyor.yml @@ -0,0 +1,9 @@ +# auto-generated by OpenAPI Generator (https://github.com/OpenAPITools/openapi-generator) +# +image: Visual Studio 2019 +clone_depth: 1 +build_script: +- dotnet build -c Release +- dotnet test -c Release +after_build: +- dotnet pack .\src\Org.OpenAPITools\Org.OpenAPITools.csproj -o ../../output -c Release --no-build diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/DefaultApi.md b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/DefaultApi.md new file mode 100644 index 000000000000..33e7748827e0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/DefaultApi.md @@ -0,0 +1,90 @@ +# Org.OpenAPITools.Api.DefaultApi + +All URIs are relative to *http://localhost* + +| Method | HTTP request | Description | +|--------|--------------|-------------| +| [**NowGet**](DefaultApi.md#nowget) | **GET** /now | | + + +# **NowGet** +> NowGet200Response NowGet () + + + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class NowGetExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://localhost"; + var apiInstance = new DefaultApi(config); + + try + { + NowGet200Response result = apiInstance.NowGet(); + Debug.WriteLine(result); + } + catch (ApiException e) + { + Debug.Print("Exception when calling DefaultApi.NowGet: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the NowGetWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + ApiResponse response = apiInstance.NowGetWithHttpInfo(); + Debug.Write("Status Code: " + response.StatusCode); + Debug.Write("Response Headers: " + response.Headers); + Debug.Write("Response Body: " + response.Data); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling DefaultApi.NowGetWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters +This endpoint does not need any parameter. +### Return type + +[**NowGet200Response**](NowGet200Response.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | now dates | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/NowGet200Response.md b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/NowGet200Response.md new file mode 100644 index 000000000000..932034b2af2d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/docs/NowGet200Response.md @@ -0,0 +1,11 @@ +# Org.OpenAPITools.Model.NowGet200Response + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Today** | **DateTime** | | [optional] +**Now** | **DateTime** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/git_push.sh b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs new file mode 100644 index 000000000000..5dfa62da67f4 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Api/DefaultApiTests.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using System; +using System.IO; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Reflection; +using RestSharp; +using Xunit; + +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Api; +// uncomment below to import models +//using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Test.Api +{ + /// + /// Class for testing DefaultApi + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the API endpoint. + /// + public class DefaultApiTests : IDisposable + { + private DefaultApi instance; + + public DefaultApiTests() + { + instance = new DefaultApi(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of DefaultApi + /// + [Fact] + public void InstanceTest() + { + // TODO uncomment below to test 'IsType' DefaultApi + //Assert.IsType(instance); + } + + /// + /// Test NowGet + /// + [Fact] + public void NowGetTest() + { + // TODO uncomment below to test the method and replace null with proper value + //var response = instance.NowGet(); + //Assert.IsType(response); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs new file mode 100644 index 000000000000..a91e45c60c8b --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Model/NowGet200ResponseTests.cs @@ -0,0 +1,75 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing NowGet200Response + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class NowGet200ResponseTests : IDisposable + { + // TODO uncomment below to declare an instance variable for NowGet200Response + //private NowGet200Response instance; + + public NowGet200ResponseTests() + { + // TODO uncomment below to create an instance of NowGet200Response + //instance = new NowGet200Response(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of NowGet200Response + /// + [Fact] + public void NowGet200ResponseInstanceTest() + { + // TODO uncomment below to test "IsType" NowGet200Response + //Assert.IsType(instance); + } + + /// + /// Test the property 'Today' + /// + [Fact] + public void TodayTest() + { + // TODO unit test for the property 'Today' + } + + /// + /// Test the property 'Now' + /// + [Fact] + public void NowTest() + { + // TODO unit test for the property 'Now' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj new file mode 100644 index 000000000000..3ddd6b44be59 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools.Test/Org.OpenAPITools.Test.csproj @@ -0,0 +1,20 @@ + + + + Org.OpenAPITools.Test + Org.OpenAPITools.Test + net7.0 + false + annotations + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs new file mode 100644 index 000000000000..cb394b92ba4a --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Api/DefaultApi.cs @@ -0,0 +1,326 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.Net; +using System.Net.Mime; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Org.OpenAPITools.Api +{ + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiSync : IApiAccessor + { + #region Synchronous Operations + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// NowGet200Response + NowGet200Response NowGet(int operationIndex = 0); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of NowGet200Response + ApiResponse NowGetWithHttpInfo(int operationIndex = 0); + #endregion Synchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApiAsync : IApiAccessor + { + #region Asynchronous Operations + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of NowGet200Response + System.Threading.Tasks.Task NowGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// + /// + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (NowGet200Response) + System.Threading.Tasks.Task> NowGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + #endregion Asynchronous Operations + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public interface IDefaultApi : IDefaultApiSync, IDefaultApiAsync + { + + } + + /// + /// Represents a collection of functions to interact with the API endpoints + /// + public partial class DefaultApi : IDefaultApi + { + private Org.OpenAPITools.Client.ExceptionFactory _exceptionFactory = (name, response) => null; + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi() : this((string)null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// + public DefaultApi(string basePath) + { + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + new Org.OpenAPITools.Client.Configuration { BasePath = basePath } + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using Configuration object + /// + /// An instance of Configuration + /// + public DefaultApi(Org.OpenAPITools.Client.Configuration configuration) + { + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Configuration = Org.OpenAPITools.Client.Configuration.MergeConfigurations( + Org.OpenAPITools.Client.GlobalConfiguration.Instance, + configuration + ); + this.Client = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + this.AsynchronousClient = new Org.OpenAPITools.Client.ApiClient(this.Configuration.BasePath); + ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// Initializes a new instance of the class + /// using a Configuration object and client instance. + /// + /// The client interface for synchronous API access. + /// The client interface for asynchronous API access. + /// The configuration object. + public DefaultApi(Org.OpenAPITools.Client.ISynchronousClient client, Org.OpenAPITools.Client.IAsynchronousClient asyncClient, Org.OpenAPITools.Client.IReadableConfiguration configuration) + { + if (client == null) throw new ArgumentNullException("client"); + if (asyncClient == null) throw new ArgumentNullException("asyncClient"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + this.Client = client; + this.AsynchronousClient = asyncClient; + this.Configuration = configuration; + this.ExceptionFactory = Org.OpenAPITools.Client.Configuration.DefaultExceptionFactory; + } + + /// + /// The client for accessing this underlying API asynchronously. + /// + public Org.OpenAPITools.Client.IAsynchronousClient AsynchronousClient { get; set; } + + /// + /// The client for accessing this underlying API synchronously. + /// + public Org.OpenAPITools.Client.ISynchronousClient Client { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + public string GetBasePath() + { + return this.Configuration.BasePath; + } + + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + public Org.OpenAPITools.Client.IReadableConfiguration Configuration { get; set; } + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + public Org.OpenAPITools.Client.ExceptionFactory ExceptionFactory + { + get + { + if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) + { + throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); + } + return _exceptionFactory; + } + set { _exceptionFactory = value; } + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// NowGet200Response + public NowGet200Response NowGet(int operationIndex = 0) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = NowGetWithHttpInfo(); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// ApiResponse of NowGet200Response + public Org.OpenAPITools.Client.ApiResponse NowGetWithHttpInfo(int operationIndex = 0) + { + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "DefaultApi.NowGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Get("/now", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("NowGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of NowGet200Response + public async System.Threading.Tasks.Task NowGetAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + Org.OpenAPITools.Client.ApiResponse localVarResponse = await NowGetWithHttpInfoAsync(operationIndex, cancellationToken).ConfigureAwait(false); + return localVarResponse.Data; + } + + /// + /// + /// + /// Thrown when fails to make API call + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse (NowGet200Response) + public async System.Threading.Tasks.Task> NowGetWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + }; + + // to determine the Accept header + string[] _accepts = new string[] { + "application/json" + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + + localVarRequestOptions.Operation = "DefaultApi.NowGet"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.GetAsync("/now", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("NowGet", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs new file mode 100644 index 000000000000..594bf890cb88 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiClient.cs @@ -0,0 +1,833 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Runtime.Serialization; +using System.Runtime.Serialization.Formatters; +using System.Text; +using System.Threading; +using System.Text.RegularExpressions; +using System.Threading.Tasks; +using System.Web; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; +using RestSharp; +using RestSharp.Serializers; +using RestSharpMethod = RestSharp.Method; +using Polly; + +namespace Org.OpenAPITools.Client +{ + /// + /// Allows RestSharp to Serialize/Deserialize JSON using our custom logic, but only when ContentType is JSON. + /// + internal class CustomJsonCodec : IRestSerializer, ISerializer, IDeserializer + { + private readonly IReadableConfiguration _configuration; + private readonly JsonSerializerSettings _serializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + public CustomJsonCodec(IReadableConfiguration configuration) + { + _configuration = configuration; + } + + public CustomJsonCodec(JsonSerializerSettings serializerSettings, IReadableConfiguration configuration) + { + _serializerSettings = serializerSettings; + _configuration = configuration; + } + + /// + /// Serialize the object into a JSON string. + /// + /// Object to be serialized. + /// A JSON string. + public string Serialize(object obj) + { + if (obj != null && obj is Org.OpenAPITools.Model.AbstractOpenAPISchema) + { + // the object to be serialized is an oneOf/anyOf schema + return ((Org.OpenAPITools.Model.AbstractOpenAPISchema)obj).ToJson(); + } + else + { + return JsonConvert.SerializeObject(obj, _serializerSettings); + } + } + + public string Serialize(Parameter bodyParameter) => Serialize(bodyParameter.Value); + + public T Deserialize(RestResponse response) + { + var result = (T)Deserialize(response, typeof(T)); + return result; + } + + /// + /// Deserialize the JSON string into a proper object. + /// + /// The HTTP response. + /// Object type. + /// Object representation of the JSON string. + internal object Deserialize(RestResponse response, Type type) + { + if (type == typeof(byte[])) // return byte array + { + return response.RawBytes; + } + + // TODO: ? if (type.IsAssignableFrom(typeof(Stream))) + if (type == typeof(Stream)) + { + var bytes = response.RawBytes; + if (response.Headers != null) + { + var filePath = string.IsNullOrEmpty(_configuration.TempFolderPath) + ? Path.GetTempPath() + : _configuration.TempFolderPath; + var regex = new Regex(@"Content-Disposition=.*filename=['""]?([^'""\s]+)['""]?$"); + foreach (var header in response.Headers) + { + var match = regex.Match(header.ToString()); + if (match.Success) + { + string fileName = filePath + ClientUtils.SanitizeFilename(match.Groups[1].Value.Replace("\"", "").Replace("'", "")); + File.WriteAllBytes(fileName, bytes); + return new FileStream(fileName, FileMode.Open); + } + } + } + var stream = new MemoryStream(bytes); + return stream; + } + + if (type.Name.StartsWith("System.Nullable`1[[System.DateTime")) // return a datetime object + { + return DateTime.Parse(response.Content, null, System.Globalization.DateTimeStyles.RoundtripKind); + } + + if (type == typeof(string) || type.Name.StartsWith("System.Nullable")) // return primitive type + { + return Convert.ChangeType(response.Content, type); + } + + // at this point, it must be a model (json) + try + { + return JsonConvert.DeserializeObject(response.Content, type, _serializerSettings); + } + catch (Exception e) + { + throw new ApiException(500, e.Message); + } + } + + public ISerializer Serializer => this; + public IDeserializer Deserializer => this; + + public string[] AcceptedContentTypes => RestSharp.ContentType.JsonAccept; + + public SupportsContentType SupportsContentType => contentType => + contentType.Value.EndsWith("json", StringComparison.InvariantCultureIgnoreCase) || + contentType.Value.EndsWith("javascript", StringComparison.InvariantCultureIgnoreCase); + + public ContentType ContentType { get; set; } = RestSharp.ContentType.Json; + + public DataFormat DataFormat => DataFormat.Json; + } + /// + /// Provides a default implementation of an Api client (both synchronous and asynchronous implementations), + /// encapsulating general REST accessor use cases. + /// + public partial class ApiClient : ISynchronousClient, IAsynchronousClient + { + private readonly string _baseUrl; + + /// + /// Specifies the settings on a object. + /// These settings can be adjusted to accommodate custom serialization rules. + /// + public JsonSerializerSettings SerializerSettings { get; set; } = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Allows for extending request processing for generated code. + /// + /// The RestSharp request object + partial void InterceptRequest(RestRequest request); + + /// + /// Allows for extending response processing for generated code. + /// + /// The RestSharp request object + /// The RestSharp response object + partial void InterceptResponse(RestRequest request, RestResponse response); + + /// + /// Initializes a new instance of the , defaulting to the global configurations' base url. + /// + public ApiClient() + { + _baseUrl = Org.OpenAPITools.Client.GlobalConfiguration.Instance.BasePath; + } + + /// + /// Initializes a new instance of the + /// + /// The target service's base path in URL format. + /// + public ApiClient(string basePath) + { + if (string.IsNullOrEmpty(basePath)) + throw new ArgumentException("basePath cannot be empty"); + + _baseUrl = basePath; + } + + /// + /// Constructs the RestSharp version of an http method + /// + /// Swagger Client Custom HttpMethod + /// RestSharp's HttpMethod instance. + /// + private RestSharpMethod Method(HttpMethod method) + { + RestSharpMethod other; + switch (method) + { + case HttpMethod.Get: + other = RestSharpMethod.Get; + break; + case HttpMethod.Post: + other = RestSharpMethod.Post; + break; + case HttpMethod.Put: + other = RestSharpMethod.Put; + break; + case HttpMethod.Delete: + other = RestSharpMethod.Delete; + break; + case HttpMethod.Head: + other = RestSharpMethod.Head; + break; + case HttpMethod.Options: + other = RestSharpMethod.Options; + break; + case HttpMethod.Patch: + other = RestSharpMethod.Patch; + break; + default: + throw new ArgumentOutOfRangeException("method", method, null); + } + + return other; + } + + /// + /// Provides all logic for constructing a new RestSharp . + /// At this point, all information for querying the service is known. Here, it is simply + /// mapped into the RestSharp request. + /// + /// The http verb. + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// [private] A new RestRequest instance. + /// + private RestRequest NewRequest( + HttpMethod method, + string path, + RequestOptions options, + IReadableConfiguration configuration) + { + if (path == null) throw new ArgumentNullException("path"); + if (options == null) throw new ArgumentNullException("options"); + if (configuration == null) throw new ArgumentNullException("configuration"); + + RestRequest request = new RestRequest(path, Method(method)); + + if (options.PathParameters != null) + { + foreach (var pathParam in options.PathParameters) + { + request.AddParameter(pathParam.Key, pathParam.Value, ParameterType.UrlSegment); + } + } + + if (options.QueryParameters != null) + { + foreach (var queryParam in options.QueryParameters) + { + foreach (var value in queryParam.Value) + { + request.AddQueryParameter(queryParam.Key, value); + } + } + } + + if (configuration.DefaultHeaders != null) + { + foreach (var headerParam in configuration.DefaultHeaders) + { + request.AddHeader(headerParam.Key, headerParam.Value); + } + } + + if (options.HeaderParameters != null) + { + foreach (var headerParam in options.HeaderParameters) + { + foreach (var value in headerParam.Value) + { + request.AddHeader(headerParam.Key, value); + } + } + } + + if (options.FormParameters != null) + { + foreach (var formParam in options.FormParameters) + { + request.AddParameter(formParam.Key, formParam.Value); + } + } + + if (options.Data != null) + { + if (options.Data is Stream stream) + { + var contentType = "application/octet-stream"; + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + contentType = contentTypes[0]; + } + + var bytes = ClientUtils.ReadAsBytes(stream); + request.AddParameter(contentType, bytes, ParameterType.RequestBody); + } + else + { + if (options.HeaderParameters != null) + { + var contentTypes = options.HeaderParameters["Content-Type"]; + if (contentTypes == null || contentTypes.Any(header => header.Contains("application/json"))) + { + request.RequestFormat = DataFormat.Json; + } + else + { + // TODO: Generated client user should add additional handlers. RestSharp only supports XML and JSON, with XML as default. + } + } + else + { + // Here, we'll assume JSON APIs are more common. XML can be forced by adding produces/consumes to openapi spec explicitly. + request.RequestFormat = DataFormat.Json; + } + + request.AddJsonBody(options.Data); + } + } + + if (options.FileParameters != null) + { + foreach (var fileParam in options.FileParameters) + { + foreach (var file in fileParam.Value) + { + var bytes = ClientUtils.ReadAsBytes(file); + var fileStream = file as FileStream; + if (fileStream != null) + request.AddFile(fileParam.Key, bytes, System.IO.Path.GetFileName(fileStream.Name)); + else + request.AddFile(fileParam.Key, bytes, "no_file_name_provided"); + } + } + } + + return request; + } + + private ApiResponse ToApiResponse(RestResponse response) + { + T result = response.Data; + string rawContent = response.Content; + + var transformed = new ApiResponse(response.StatusCode, new Multimap(), result, rawContent) + { + ErrorText = response.ErrorMessage, + Cookies = new List() + }; + + if (response.Headers != null) + { + foreach (var responseHeader in response.Headers) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.ContentHeaders != null) + { + foreach (var responseHeader in response.ContentHeaders) + { + transformed.Headers.Add(responseHeader.Name, ClientUtils.ParameterToString(responseHeader.Value)); + } + } + + if (response.Cookies != null) + { + foreach (var responseCookies in response.Cookies.Cast()) + { + transformed.Cookies.Add( + new Cookie( + responseCookies.Name, + responseCookies.Value, + responseCookies.Path, + responseCookies.Domain) + ); + } + } + + return transformed; + } + + private ApiResponse Exec(RestRequest request, RequestOptions options, IReadableConfiguration configuration) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var cookies = new CookieContainer(); + + if (options.Cookies != null && options.Cookies.Count > 0) + { + foreach (var cookie in options.Cookies) + { + cookies.Add(new Cookie(cookie.Name, cookie.Value)); + } + } + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + CookieContainer = cookies, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response; + if (RetryConfiguration.RetryPolicy != null) + { + var policy = RetryConfiguration.RetryPolicy; + var policyResult = policy.ExecuteAndCapture(() => client.Execute(request)); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = client.Execute(request); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + try + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + catch (Exception ex) + { + throw ex.InnerException != null ? ex.InnerException : ex; + } + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + else if (typeof(T).Name == "String") // for string response + { + response.Data = (T)(object)response.Content; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + private async Task> ExecAsync(RestRequest request, RequestOptions options, IReadableConfiguration configuration, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var baseUrl = configuration.GetOperationServerUrl(options.Operation, options.OperationIndex) ?? _baseUrl; + + var clientOptions = new RestClientOptions(baseUrl) + { + ClientCertificates = configuration.ClientCertificates, + MaxTimeout = configuration.Timeout, + Proxy = configuration.Proxy, + UserAgent = configuration.UserAgent, + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback + }; + + using (RestClient client = new RestClient(clientOptions, + configureSerialization: serializerConfig => serializerConfig.UseSerializer(() => new CustomJsonCodec(SerializerSettings, configuration)))) + { + InterceptRequest(request); + + RestResponse response; + if (RetryConfiguration.AsyncRetryPolicy != null) + { + var policy = RetryConfiguration.AsyncRetryPolicy; + var policyResult = await policy.ExecuteAndCaptureAsync((ct) => client.ExecuteAsync(request, ct), cancellationToken).ConfigureAwait(false); + response = (policyResult.Outcome == OutcomeType.Successful) ? client.Deserialize(policyResult.Result) : new RestResponse(request) + { + ErrorException = policyResult.FinalException + }; + } + else + { + response = await client.ExecuteAsync(request, cancellationToken).ConfigureAwait(false); + } + + // if the response type is oneOf/anyOf, call FromJSON to deserialize the data + if (typeof(Org.OpenAPITools.Model.AbstractOpenAPISchema).IsAssignableFrom(typeof(T))) + { + response.Data = (T) typeof(T).GetMethod("FromJson").Invoke(null, new object[] { response.Content }); + } + else if (typeof(T).Name == "Stream") // for binary response + { + response.Data = (T)(object)new MemoryStream(response.RawBytes); + } + else if (typeof(T).Name == "Byte[]") // for byte response + { + response.Data = (T)(object)response.RawBytes; + } + + InterceptResponse(request, response); + + var result = ToApiResponse(response); + if (response.ErrorMessage != null) + { + result.ErrorText = response.ErrorMessage; + } + + if (response.Cookies != null && response.Cookies.Count > 0) + { + if (result.Cookies == null) result.Cookies = new List(); + foreach (var restResponseCookie in response.Cookies.Cast()) + { + var cookie = new Cookie( + restResponseCookie.Name, + restResponseCookie.Value, + restResponseCookie.Path, + restResponseCookie.Domain + ) + { + Comment = restResponseCookie.Comment, + CommentUri = restResponseCookie.CommentUri, + Discard = restResponseCookie.Discard, + Expired = restResponseCookie.Expired, + Expires = restResponseCookie.Expires, + HttpOnly = restResponseCookie.HttpOnly, + Port = restResponseCookie.Port, + Secure = restResponseCookie.Secure, + Version = restResponseCookie.Version + }; + + result.Cookies.Add(cookie); + } + } + return result; + } + } + + #region IAsynchronousClient + /// + /// Make a HTTP GET request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Get, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP POST request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Post, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PUT request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Put, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP DELETE request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Delete, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP HEAD request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Head, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP OPTION request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Options, path, options, config), options, config, cancellationToken); + } + + /// + /// Make a HTTP PATCH request (async). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// Token that enables callers to cancel the request. + /// A Task containing ApiResponse + public Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var config = configuration ?? GlobalConfiguration.Instance; + return ExecAsync(NewRequest(HttpMethod.Patch, path, options, config), options, config, cancellationToken); + } + #endregion IAsynchronousClient + + #region ISynchronousClient + /// + /// Make a HTTP GET request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Get, path, options, config), options, config); + } + + /// + /// Make a HTTP POST request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Post, path, options, config), options, config); + } + + /// + /// Make a HTTP PUT request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Put, path, options, config), options, config); + } + + /// + /// Make a HTTP DELETE request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Delete, path, options, config), options, config); + } + + /// + /// Make a HTTP HEAD request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Head, path, options, config), options, config); + } + + /// + /// Make a HTTP OPTION request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Options, path, options, config), options, config); + } + + /// + /// Make a HTTP PATCH request (synchronous). + /// + /// The target path (or resource). + /// The additional request options. + /// A per-request configuration object. It is assumed that any merge with + /// GlobalConfiguration has been done before calling this method. + /// A Task containing ApiResponse + public ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null) + { + var config = configuration ?? GlobalConfiguration.Instance; + return Exec(NewRequest(HttpMethod.Patch, path, options, config), options, config); + } + #endregion ISynchronousClient + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs new file mode 100644 index 000000000000..64872847b838 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiException.cs @@ -0,0 +1,68 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// API Exception + /// + public class ApiException : Exception + { + /// + /// Gets or sets the error code (HTTP status code) + /// + /// The error code (HTTP status code). + public int ErrorCode { get; set; } + + /// + /// Gets or sets the error content (body json object) + /// + /// The error content (Http response body). + public object ErrorContent { get; private set; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; private set; } + + /// + /// Initializes a new instance of the class. + /// + public ApiException() { } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + public ApiException(int errorCode, string message) : base(message) + { + this.ErrorCode = errorCode; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Error message. + /// Error content. + /// HTTP Headers. + public ApiException(int errorCode, string message, object errorContent = null, Multimap headers = null) : base(message) + { + this.ErrorCode = errorCode; + this.ErrorContent = errorContent; + this.Headers = headers; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse.cs new file mode 100644 index 000000000000..62640a590495 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ApiResponse.cs @@ -0,0 +1,166 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// Provides a non-generic contract for the ApiResponse wrapper. + /// + public interface IApiResponse + { + /// + /// The data type of + /// + Type ResponseType { get; } + + /// + /// The content of this response + /// + Object Content { get; } + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + Multimap Headers { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + List Cookies { get; set; } + + /// + /// The raw content of this response + /// + string RawContent { get; } + } + + /// + /// API Response + /// + public class ApiResponse : IApiResponse + { + #region Properties + + /// + /// Gets or sets the status code (HTTP status code) + /// + /// The status code. + public HttpStatusCode StatusCode { get; } + + /// + /// Gets or sets the HTTP headers + /// + /// HTTP headers + public Multimap Headers { get; } + + /// + /// Gets or sets the data (parsed HTTP body) + /// + /// The data. + public T Data { get; } + + /// + /// Gets or sets any error text defined by the calling client. + /// + public string ErrorText { get; set; } + + /// + /// Gets or sets any cookies passed along on the response. + /// + public List Cookies { get; set; } + + /// + /// The content of this response + /// + public Type ResponseType + { + get { return typeof(T); } + } + + /// + /// The data type of + /// + public object Content + { + get { return Data; } + } + + /// + /// The raw content + /// + public string RawContent { get; } + + #endregion Properties + + #region Constructors + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data, string rawContent) + { + StatusCode = statusCode; + Headers = headers; + Data = data; + RawContent = rawContent; + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// HTTP headers. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, Multimap headers, T data) : this(statusCode, headers, data, null) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + /// Raw content. + public ApiResponse(HttpStatusCode statusCode, T data, string rawContent) : this(statusCode, null, data, rawContent) + { + } + + /// + /// Initializes a new instance of the class. + /// + /// HTTP status code. + /// Data (parsed HTTP body) + public ApiResponse(HttpStatusCode statusCode, T data) : this(statusCode, data, null) + { + } + + #endregion Constructors + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs new file mode 100644 index 000000000000..3cdbe0639296 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -0,0 +1,247 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Globalization; +using System.IO; +using System.Linq; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; + +namespace Org.OpenAPITools.Client +{ + /// + /// Utility functions providing some benefit to API client consumers. + /// + public static class ClientUtils + { + /// + /// Sanitize filename by removing the path + /// + /// Filename + /// Filename + public static string SanitizeFilename(string filename) + { + Match match = Regex.Match(filename, @".*[/\\](.*)$"); + return match.Success ? match.Groups[1].Value : filename; + } + + /// + /// Convert params to key/value pairs. + /// Use collectionFormat to properly format lists and collections. + /// + /// The swagger-supported collection format, one of: csv, tsv, ssv, pipes, multi + /// Key name. + /// Value object. + /// A multimap of keys with 1..n associated values. + public static Multimap ParameterToMultiMap(string collectionFormat, string name, object value) + { + var parameters = new Multimap(); + + if (value is ICollection collection && collectionFormat == "multi") + { + foreach (var item in collection) + { + parameters.Add(name, ParameterToString(item)); + } + } + else if (value is IDictionary dictionary) + { + if(collectionFormat == "deepObject") { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(name + "[" + entry.Key + "]", ParameterToString(entry.Value)); + } + } + else { + foreach (DictionaryEntry entry in dictionary) + { + parameters.Add(entry.Key.ToString(), ParameterToString(entry.Value)); + } + } + } + else + { + parameters.Add(name, ParameterToString(value)); + } + + return parameters; + } + + /// + /// If parameter is DateTime, output in a formatted string (default ISO 8601), customizable with Configuration.DateTime. + /// If parameter is a list, join the list with ",". + /// Otherwise just return the string. + /// + /// The parameter (header, path, query, form). + /// An optional configuration instance, providing formatting options used in processing. + /// Formatted string. + public static string ParameterToString(object obj, IReadableConfiguration configuration = null) + { + if (obj is DateTime dateTime) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTime.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is DateTimeOffset dateTimeOffset) + // Return a formatted date string - Can be customized with Configuration.DateTimeFormat + // Defaults to an ISO 8601, using the known as a Round-trip date/time pattern ("o") + // https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 + // For example: 2009-06-15T13:45:30.0000000 + return dateTimeOffset.ToString((configuration ?? GlobalConfiguration.Instance).DateTimeFormat); + if (obj is bool boolean) + return boolean ? "true" : "false"; + if (obj is ICollection collection) { + List entries = new List(); + foreach (var entry in collection) + entries.Add(ParameterToString(entry, configuration)); + return string.Join(",", entries); + } + if (obj is Enum && HasEnumMemberAttrValue(obj)) + return GetEnumMemberAttrValue(obj); + + return Convert.ToString(obj, CultureInfo.InvariantCulture); + } + + /// + /// Serializes the given object when not null. Otherwise return null. + /// + /// The object to serialize. + /// Serialized string. + public static string Serialize(object obj) + { + return obj != null ? Newtonsoft.Json.JsonConvert.SerializeObject(obj) : null; + } + + /// + /// Encode string in base64 format. + /// + /// string to be encoded. + /// Encoded string. + public static string Base64Encode(string text) + { + return Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(text)); + } + + /// + /// Convert stream to byte array + /// + /// Input stream to be converted + /// Byte array + public static byte[] ReadAsBytes(Stream inputStream) + { + using (var ms = new MemoryStream()) + { + inputStream.CopyTo(ms); + return ms.ToArray(); + } + } + + /// + /// Select the Content-Type header's value from the given content-type array: + /// if JSON type exists in the given array, use it; + /// otherwise use the first one defined in 'consumes' + /// + /// The Content-Type array to select from. + /// The Content-Type header to use. + public static string SelectHeaderContentType(string[] contentTypes) + { + if (contentTypes.Length == 0) + return null; + + foreach (var contentType in contentTypes) + { + if (IsJsonMime(contentType)) + return contentType; + } + + return contentTypes[0]; // use the first content type specified in 'consumes' + } + + /// + /// Select the Accept header's value from the given accepts array: + /// if JSON exists in the given array, use it; + /// otherwise use all of them (joining into a string) + /// + /// The accepts array to select from. + /// The Accept header to use. + public static string SelectHeaderAccept(string[] accepts) + { + if (accepts.Length == 0) + return null; + + if (accepts.Contains("application/json", StringComparer.OrdinalIgnoreCase)) + return "application/json"; + + return string.Join(",", accepts); + } + + /// + /// Provides a case-insensitive check that a provided content type is a known JSON-like content type. + /// + public static readonly Regex JsonRegex = new Regex("(?i)^(application/json|[^;/ \t]+/[^;/ \t]+[+]json)[ \t]*(;.*)?$"); + + /// + /// Check if the given MIME is a JSON MIME. + /// JSON MIME examples: + /// application/json + /// application/json; charset=UTF8 + /// APPLICATION/JSON + /// application/vnd.company+json + /// + /// MIME + /// Returns True if MIME type is json. + public static bool IsJsonMime(string mime) + { + if (string.IsNullOrWhiteSpace(mime)) return false; + + return JsonRegex.IsMatch(mime) || mime.Equals("application/json-patch+json"); + } + + /// + /// Is the Enum decorated with EnumMember Attribute + /// + /// + /// true if found + private static bool HasEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) return true; + return false; + } + + /// + /// Get the EnumMember value + /// + /// + /// EnumMember value as string otherwise null + private static string GetEnumMemberAttrValue(object enumVal) + { + if (enumVal == null) + throw new ArgumentNullException(nameof(enumVal)); + var enumType = enumVal.GetType(); + var memInfo = enumType.GetMember(enumVal.ToString() ?? throw new InvalidOperationException()); + var attr = memInfo.FirstOrDefault()?.GetCustomAttributes(false).OfType().FirstOrDefault(); + if (attr != null) + { + return attr.Value; + } + return null; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Configuration.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Configuration.cs new file mode 100644 index 000000000000..37ef82463978 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Configuration.cs @@ -0,0 +1,612 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Concurrent; +using System.Collections.Generic; +using System.IO; +using System.Linq; +using System.Net; +using System.Reflection; +using System.Security.Cryptography.X509Certificates; +using System.Text; +using System.Net.Http; +using System.Net.Security; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a set of configuration settings + /// + public class Configuration : IReadableConfiguration + { + #region Constants + + /// + /// Version of the package. + /// + /// Version of the package. + public const string Version = "1.0.0"; + + /// + /// Identifier for ISO 8601 DateTime Format + /// + /// See https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx#Anchor_8 for more information. + // ReSharper disable once InconsistentNaming + public const string ISO8601_DATETIME_FORMAT = "o"; + + #endregion Constants + + #region Static Members + + /// + /// Default creation of exceptions for a given method name and response object + /// + public static readonly ExceptionFactory DefaultExceptionFactory = (methodName, response) => + { + var status = (int)response.StatusCode; + if (status >= 400) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.RawContent), + response.RawContent, response.Headers); + } + if (status == 0) + { + return new ApiException(status, + string.Format("Error calling {0}: {1}", methodName, response.ErrorText), response.ErrorText); + } + return null; + }; + + #endregion Static Members + + #region Private Members + + /// + /// Defines the base path of the target API server. + /// Example: http://localhost:3000/v1/ + /// + private string _basePath; + + private bool _useDefaultCredentials = false; + + /// + /// Gets or sets the API key based on the authentication name. + /// This is the key and value comprising the "secret" for accessing an API. + /// + /// The API key. + private IDictionary _apiKey; + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// The prefix of the API key. + private IDictionary _apiKeyPrefix; + + private string _dateTimeFormat = ISO8601_DATETIME_FORMAT; + private string _tempFolderPath = Path.GetTempPath(); + + /// + /// Gets or sets the servers defined in the OpenAPI spec. + /// + /// The servers + private IList> _servers; + + /// + /// Gets or sets the operation servers defined in the OpenAPI spec. + /// + /// The operation servers + private IReadOnlyDictionary>> _operationServers; + + #endregion Private Members + + #region Constructors + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration() + { + Proxy = null; + UserAgent = WebUtility.UrlEncode("OpenAPI-Generator/1.0.0/csharp"); + BasePath = "http://localhost"; + DefaultHeaders = new ConcurrentDictionary(); + ApiKey = new ConcurrentDictionary(); + ApiKeyPrefix = new ConcurrentDictionary(); + Servers = new List>() + { + { + new Dictionary { + {"url", ""}, + {"description", "No description provided"}, + } + } + }; + OperationServers = new Dictionary>>() + { + }; + + // Setting Timeout has side effects (forces ApiClient creation). + Timeout = 100000; + } + + /// + /// Initializes a new instance of the class + /// + [System.Diagnostics.CodeAnalysis.SuppressMessage("ReSharper", "VirtualMemberCallInConstructor")] + public Configuration( + IDictionary defaultHeaders, + IDictionary apiKey, + IDictionary apiKeyPrefix, + string basePath = "http://localhost") : this() + { + if (string.IsNullOrWhiteSpace(basePath)) + throw new ArgumentException("The provided basePath is invalid.", "basePath"); + if (defaultHeaders == null) + throw new ArgumentNullException("defaultHeaders"); + if (apiKey == null) + throw new ArgumentNullException("apiKey"); + if (apiKeyPrefix == null) + throw new ArgumentNullException("apiKeyPrefix"); + + BasePath = basePath; + + foreach (var keyValuePair in defaultHeaders) + { + DefaultHeaders.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKey) + { + ApiKey.Add(keyValuePair); + } + + foreach (var keyValuePair in apiKeyPrefix) + { + ApiKeyPrefix.Add(keyValuePair); + } + } + + #endregion Constructors + + #region Properties + + /// + /// Gets or sets the base path for API access. + /// + public virtual string BasePath + { + get { return _basePath; } + set { _basePath = value; } + } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + public virtual bool UseDefaultCredentials + { + get { return _useDefaultCredentials; } + set { _useDefaultCredentials = value; } + } + + /// + /// Gets or sets the default header. + /// + [Obsolete("Use DefaultHeaders instead.")] + public virtual IDictionary DefaultHeader + { + get + { + return DefaultHeaders; + } + set + { + DefaultHeaders = value; + } + } + + /// + /// Gets or sets the default headers. + /// + public virtual IDictionary DefaultHeaders { get; set; } + + /// + /// Gets or sets the HTTP timeout (milliseconds) of ApiClient. Default to 100000 milliseconds. + /// + public virtual int Timeout { get; set; } + + /// + /// Gets or sets the proxy + /// + /// Proxy. + public virtual WebProxy Proxy { get; set; } + + /// + /// Gets or sets the HTTP user agent. + /// + /// Http user agent. + public virtual string UserAgent { get; set; } + + /// + /// Gets or sets the username (HTTP basic authentication). + /// + /// The username. + public virtual string Username { get; set; } + + /// + /// Gets or sets the password (HTTP basic authentication). + /// + /// The password. + public virtual string Password { get; set; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + public string GetApiKeyWithPrefix(string apiKeyIdentifier) + { + string apiKeyValue; + ApiKey.TryGetValue(apiKeyIdentifier, out apiKeyValue); + string apiKeyPrefix; + if (ApiKeyPrefix.TryGetValue(apiKeyIdentifier, out apiKeyPrefix)) + { + return apiKeyPrefix + " " + apiKeyValue; + } + + return apiKeyValue; + } + + /// + /// Gets or sets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + public X509CertificateCollection ClientCertificates { get; set; } + + /// + /// Gets or sets the access token for OAuth2 authentication. + /// + /// This helper property simplifies code generation. + /// + /// The access token. + public virtual string AccessToken { get; set; } + + /// + /// Gets or sets the temporary folder path to store the files downloaded from the server. + /// + /// Folder path. + public virtual string TempFolderPath + { + get { return _tempFolderPath; } + + set + { + if (string.IsNullOrEmpty(value)) + { + _tempFolderPath = Path.GetTempPath(); + return; + } + + // create the directory if it does not exist + if (!Directory.Exists(value)) + { + Directory.CreateDirectory(value); + } + + // check if the path contains directory separator at the end + if (value[value.Length - 1] == Path.DirectorySeparatorChar) + { + _tempFolderPath = value; + } + else + { + _tempFolderPath = value + Path.DirectorySeparatorChar; + } + } + } + + /// + /// Gets or sets the date time format used when serializing in the ApiClient + /// By default, it's set to ISO 8601 - "o", for others see: + /// https://msdn.microsoft.com/en-us/library/az4se3k1(v=vs.110).aspx + /// and https://msdn.microsoft.com/en-us/library/8kb3ddd4(v=vs.110).aspx + /// No validation is done to ensure that the string you're providing is valid + /// + /// The DateTimeFormat string + public virtual string DateTimeFormat + { + get { return _dateTimeFormat; } + set + { + if (string.IsNullOrEmpty(value)) + { + // Never allow a blank or null string, go back to the default + _dateTimeFormat = ISO8601_DATETIME_FORMAT; + return; + } + + // Caution, no validation when you choose date time format other than ISO 8601 + // Take a look at the above links + _dateTimeFormat = value; + } + } + + /// + /// Gets or sets the prefix (e.g. Token) of the API key based on the authentication name. + /// + /// Whatever you set here will be prepended to the value defined in AddApiKey. + /// + /// An example invocation here might be: + /// + /// ApiKeyPrefix["Authorization"] = "Bearer"; + /// + /// … where ApiKey["Authorization"] would then be used to set the value of your bearer token. + /// + /// + /// OAuth2 workflows should set tokens via AccessToken. + /// + /// + /// The prefix of the API key. + public virtual IDictionary ApiKeyPrefix + { + get { return _apiKeyPrefix; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKeyPrefix collection may not be null."); + } + _apiKeyPrefix = value; + } + } + + /// + /// Gets or sets the API key based on the authentication name. + /// + /// The API key. + public virtual IDictionary ApiKey + { + get { return _apiKey; } + set + { + if (value == null) + { + throw new InvalidOperationException("ApiKey collection may not be null."); + } + _apiKey = value; + } + } + + /// + /// Gets or sets the servers. + /// + /// The servers. + public virtual IList> Servers + { + get { return _servers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Servers may not be null."); + } + _servers = value; + } + } + + /// + /// Gets or sets the operation servers. + /// + /// The operation servers. + public virtual IReadOnlyDictionary>> OperationServers + { + get { return _operationServers; } + set + { + if (value == null) + { + throw new InvalidOperationException("Operation servers may not be null."); + } + _operationServers = value; + } + } + + /// + /// Returns URL based on server settings without providing values + /// for the variables + /// + /// Array index of the server settings. + /// The server URL. + public string GetServerUrl(int index) + { + return GetServerUrl(Servers, index, null); + } + + /// + /// Returns URL based on server settings. + /// + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + public string GetServerUrl(int index, Dictionary inputVariables) + { + return GetServerUrl(Servers, index, inputVariables); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index) + { + return GetOperationServerUrl(operation, index, null); + } + + /// + /// Returns URL based on operation server settings. + /// + /// Operation associated with the request path. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The operation server URL. + public string GetOperationServerUrl(string operation, int index, Dictionary inputVariables) + { + if (operation != null && OperationServers.TryGetValue(operation, out var operationServer)) + { + return GetServerUrl(operationServer, index, inputVariables); + } + + return null; + } + + /// + /// Returns URL based on server settings. + /// + /// Dictionary of server settings. + /// Array index of the server settings. + /// Dictionary of the variables and the corresponding values. + /// The server URL. + private string GetServerUrl(IList> servers, int index, Dictionary inputVariables) + { + if (index < 0 || index >= servers.Count) + { + throw new InvalidOperationException($"Invalid index {index} when selecting the server. Must be less than {servers.Count}."); + } + + if (inputVariables == null) + { + inputVariables = new Dictionary(); + } + + IReadOnlyDictionary server = servers[index]; + string url = (string)server["url"]; + + if (server.ContainsKey("variables")) + { + // go through each variable and assign a value + foreach (KeyValuePair variable in (IReadOnlyDictionary)server["variables"]) + { + + IReadOnlyDictionary serverVariables = (IReadOnlyDictionary)(variable.Value); + + if (inputVariables.ContainsKey(variable.Key)) + { + if (((List)serverVariables["enum_values"]).Contains(inputVariables[variable.Key])) + { + url = url.Replace("{" + variable.Key + "}", inputVariables[variable.Key]); + } + else + { + throw new InvalidOperationException($"The variable `{variable.Key}` in the server URL has invalid value #{inputVariables[variable.Key]}. Must be {(List)serverVariables["enum_values"]}"); + } + } + else + { + // use default value + url = url.Replace("{" + variable.Key + "}", (string)serverVariables["default_value"]); + } + } + } + + return url; + } + + /// + /// Gets and Sets the RemoteCertificateValidationCallback + /// + public RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; set; } + + #endregion Properties + + #region Methods + + /// + /// Returns a string with essential information for debugging. + /// + public static string ToDebugReport() + { + string report = "C# SDK (Org.OpenAPITools) Debug Report:\n"; + report += " OS: " + System.Environment.OSVersion + "\n"; + report += " .NET Framework Version: " + System.Environment.Version + "\n"; + report += " Version of the API: 1.0.0\n"; + report += " SDK Package Version: 1.0.0\n"; + + return report; + } + + /// + /// Add Api Key Header. + /// + /// Api Key name. + /// Api Key value. + /// + public void AddApiKey(string key, string value) + { + ApiKey[key] = value; + } + + /// + /// Sets the API key prefix. + /// + /// Api Key name. + /// Api Key value. + public void AddApiKeyPrefix(string key, string value) + { + ApiKeyPrefix[key] = value; + } + + #endregion Methods + + #region Static Members + /// + /// Merge configurations. + /// + /// First configuration. + /// Second configuration. + /// Merged configuration. + public static IReadableConfiguration MergeConfigurations(IReadableConfiguration first, IReadableConfiguration second) + { + if (second == null) return first ?? GlobalConfiguration.Instance; + + Dictionary apiKey = first.ApiKey.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary apiKeyPrefix = first.ApiKeyPrefix.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + Dictionary defaultHeaders = first.DefaultHeaders.ToDictionary(kvp => kvp.Key, kvp => kvp.Value); + + foreach (var kvp in second.ApiKey) apiKey[kvp.Key] = kvp.Value; + foreach (var kvp in second.ApiKeyPrefix) apiKeyPrefix[kvp.Key] = kvp.Value; + foreach (var kvp in second.DefaultHeaders) defaultHeaders[kvp.Key] = kvp.Value; + + var config = new Configuration + { + ApiKey = apiKey, + ApiKeyPrefix = apiKeyPrefix, + DefaultHeaders = defaultHeaders, + BasePath = second.BasePath ?? first.BasePath, + Timeout = second.Timeout, + Proxy = second.Proxy ?? first.Proxy, + UserAgent = second.UserAgent ?? first.UserAgent, + Username = second.Username ?? first.Username, + Password = second.Password ?? first.Password, + AccessToken = second.AccessToken ?? first.AccessToken, + TempFolderPath = second.TempFolderPath ?? first.TempFolderPath, + DateTimeFormat = second.DateTimeFormat ?? first.DateTimeFormat, + ClientCertificates = second.ClientCertificates ?? first.ClientCertificates, + UseDefaultCredentials = second.UseDefaultCredentials, + RemoteCertificateValidationCallback = second.RemoteCertificateValidationCallback ?? first.RemoteCertificateValidationCallback, + }; + return config; + } + #endregion Static Members + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionFactory.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionFactory.cs new file mode 100644 index 000000000000..12d2e18f66e7 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ExceptionFactory.cs @@ -0,0 +1,22 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// A delegate to ExceptionFactory method + /// + /// Method name + /// Response + /// Exceptions + public delegate Exception ExceptionFactory(string methodName, IApiResponse response); +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/GlobalConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/GlobalConfiguration.cs new file mode 100644 index 000000000000..c0351acf1211 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/GlobalConfiguration.cs @@ -0,0 +1,67 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// provides a compile-time extension point for globally configuring + /// API Clients. + /// + /// + /// A customized implementation via partial class may reside in another file and may + /// be excluded from automatic generation via a .openapi-generator-ignore file. + /// + public partial class GlobalConfiguration : Configuration + { + #region Private Members + + private static readonly object GlobalConfigSync = new { }; + private static IReadableConfiguration _globalConfiguration; + + #endregion Private Members + + #region Constructors + + /// + private GlobalConfiguration() + { + } + + /// + public GlobalConfiguration(IDictionary defaultHeader, IDictionary apiKey, IDictionary apiKeyPrefix, string basePath = "http://localhost:3000/api") : base(defaultHeader, apiKey, apiKeyPrefix, basePath) + { + } + + static GlobalConfiguration() + { + Instance = new GlobalConfiguration(); + } + + #endregion Constructors + + /// + /// Gets or sets the default Configuration. + /// + /// Configuration. + public static IReadableConfiguration Instance + { + get { return _globalConfiguration; } + set + { + lock (GlobalConfigSync) + { + _globalConfiguration = value; + } + } + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HttpMethod.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HttpMethod.cs new file mode 100644 index 000000000000..e06a7dbd6cc2 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/HttpMethod.cs @@ -0,0 +1,33 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +namespace Org.OpenAPITools.Client +{ + /// + /// Http methods supported by swagger + /// + public enum HttpMethod + { + /// HTTP GET request. + Get, + /// HTTP POST request. + Post, + /// HTTP PUT request. + Put, + /// HTTP DELETE request. + Delete, + /// HTTP HEAD request. + Head, + /// HTTP OPTIONS request. + Options, + /// HTTP PATCH request. + Patch + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IApiAccessor.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IApiAccessor.cs new file mode 100644 index 000000000000..e31d64e704a9 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IApiAccessor.cs @@ -0,0 +1,37 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents configuration aspects required to interact with the API endpoints. + /// + public interface IApiAccessor + { + /// + /// Gets or sets the configuration object + /// + /// An instance of the Configuration + IReadableConfiguration Configuration { get; set; } + + /// + /// Gets the base path of the API client. + /// + /// The base path + string GetBasePath(); + + /// + /// Provides a factory method hook for the creation of exceptions. + /// + ExceptionFactory ExceptionFactory { get; set; } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IAsynchronousClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IAsynchronousClient.cs new file mode 100644 index 000000000000..b1c5178bca68 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IAsynchronousClient.cs @@ -0,0 +1,100 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Threading.Tasks; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Asynchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface IAsynchronousClient + { + /// + /// Executes a non-blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> GetAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PostAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PutAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> DeleteAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> HeadAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> OptionsAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// Executes a non-blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// Cancellation Token to cancel the request. + /// The return type. + /// A task eventually representing the response data, decorated with + Task> PatchAsync(string path, RequestOptions options, IReadableConfiguration configuration = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IReadableConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IReadableConfiguration.cs new file mode 100644 index 000000000000..b5ffbc06997d --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/IReadableConfiguration.cs @@ -0,0 +1,141 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.Net; +using System.Net.Security; +using System.Security.Cryptography.X509Certificates; + +namespace Org.OpenAPITools.Client +{ + /// + /// Represents a readable-only configuration contract. + /// + public interface IReadableConfiguration + { + /// + /// Gets the access token. + /// + /// Access token. + string AccessToken { get; } + + /// + /// Gets the API key. + /// + /// API key. + IDictionary ApiKey { get; } + + /// + /// Gets the API key prefix. + /// + /// API key prefix. + IDictionary ApiKeyPrefix { get; } + + /// + /// Gets the base path. + /// + /// Base path. + string BasePath { get; } + + /// + /// Gets the date time format. + /// + /// Date time format. + string DateTimeFormat { get; } + + /// + /// Gets the default header. + /// + /// Default header. + [Obsolete("Use DefaultHeaders instead.")] + IDictionary DefaultHeader { get; } + + /// + /// Gets the default headers. + /// + /// Default headers. + IDictionary DefaultHeaders { get; } + + /// + /// Gets the temp folder path. + /// + /// Temp folder path. + string TempFolderPath { get; } + + /// + /// Gets the HTTP connection timeout (in milliseconds) + /// + /// HTTP connection timeout. + int Timeout { get; } + + /// + /// Gets the proxy. + /// + /// Proxy. + WebProxy Proxy { get; } + + /// + /// Gets the user agent. + /// + /// User agent. + string UserAgent { get; } + + /// + /// Gets the username. + /// + /// Username. + string Username { get; } + + /// + /// Gets the password. + /// + /// Password. + string Password { get; } + + /// + /// Determine whether or not the "default credentials" (e.g. the user account under which the current process is running) will be sent along to the server. The default is false. + /// + bool UseDefaultCredentials { get; } + + /// + /// Get the servers associated with the operation. + /// + /// Operation servers. + IReadOnlyDictionary>> OperationServers { get; } + + /// + /// Gets the API key with prefix. + /// + /// API key identifier (authentication scheme). + /// API key with prefix. + string GetApiKeyWithPrefix(string apiKeyIdentifier); + + /// + /// Gets the Operation server url at the provided index. + /// + /// Operation server name. + /// Index of the operation server settings. + /// + string GetOperationServerUrl(string operation, int index); + + /// + /// Gets certificate collection to be sent with requests. + /// + /// X509 Certificate collection. + X509CertificateCollection ClientCertificates { get; } + + /// + /// Callback function for handling the validation of remote certificates. Useful for certificate pinning and + /// overriding certificate errors in the scope of a request. + /// + RemoteCertificateValidationCallback RemoteCertificateValidationCallback { get; } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ISynchronousClient.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ISynchronousClient.cs new file mode 100644 index 000000000000..965cec3b0432 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/ISynchronousClient.cs @@ -0,0 +1,93 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.IO; + +namespace Org.OpenAPITools.Client +{ + /// + /// Contract for Synchronous RESTful API interactions. + /// + /// This interface allows consumers to provide a custom API accessor client. + /// + public interface ISynchronousClient + { + /// + /// Executes a blocking call to some using the GET http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Get(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the POST http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Post(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PUT http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Put(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the DELETE http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Delete(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the HEAD http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Head(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the OPTIONS http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Options(string path, RequestOptions options, IReadableConfiguration configuration = null); + + /// + /// Executes a blocking call to some using the PATCH http verb. + /// + /// The relative path to invoke. + /// The request parameters to pass along to the client. + /// Per-request configurable settings. + /// The return type. + /// The response data, decorated with + ApiResponse Patch(string path, RequestOptions options, IReadableConfiguration configuration = null); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Multimap.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Multimap.cs new file mode 100644 index 000000000000..b3fdf6b71a30 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/Multimap.cs @@ -0,0 +1,295 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; + +namespace Org.OpenAPITools.Client +{ + /// + /// A dictionary in which one key has many associated values. + /// + /// The type of the key + /// The type of the value associated with the key. + public class Multimap : IDictionary> + { + #region Private Fields + + private readonly Dictionary> _dictionary; + + #endregion Private Fields + + #region Constructors + + /// + /// Empty Constructor. + /// + public Multimap() + { + _dictionary = new Dictionary>(); + } + + /// + /// Constructor with comparer. + /// + /// + public Multimap(IEqualityComparer comparer) + { + _dictionary = new Dictionary>(comparer); + } + + #endregion Constructors + + #region Enumerators + + /// + /// To get the enumerator. + /// + /// Enumerator + public IEnumerator>> GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + /// + /// To get the enumerator. + /// + /// Enumerator + IEnumerator IEnumerable.GetEnumerator() + { + return _dictionary.GetEnumerator(); + } + + #endregion Enumerators + + #region Public Members + /// + /// Add values to Multimap + /// + /// Key value pair + public void Add(KeyValuePair> item) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + + /// + /// Add Multimap to Multimap + /// + /// Multimap + public void Add(Multimap multimap) + { + foreach (var item in multimap) + { + if (!TryAdd(item.Key, item.Value)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + + /// + /// Clear Multimap + /// + public void Clear() + { + _dictionary.Clear(); + } + + /// + /// Determines whether Multimap contains the specified item. + /// + /// Key value pair + /// Method needs to be implemented + /// true if the Multimap contains the item; otherwise, false. + public bool Contains(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Copy items of the Multimap to an array, + /// starting at a particular array index. + /// + /// The array that is the destination of the items copied + /// from Multimap. The array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + /// Method needs to be implemented + public void CopyTo(KeyValuePair>[] array, int arrayIndex) + { + throw new NotImplementedException(); + } + + /// + /// Removes the specified item from the Multimap. + /// + /// Key value pair + /// true if the item is successfully removed; otherwise, false. + /// Method needs to be implemented + public bool Remove(KeyValuePair> item) + { + throw new NotImplementedException(); + } + + /// + /// Gets the number of items contained in the Multimap. + /// + public int Count => _dictionary.Count; + + /// + /// Gets a value indicating whether the Multimap is read-only. + /// + public bool IsReadOnly => false; + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add the value to Multimap. + public void Add(TKey key, IList value) + { + if (value != null && value.Count > 0) + { + if (_dictionary.TryGetValue(key, out var list)) + { + foreach (var k in value) list.Add(k); + } + else + { + list = new List(value); + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add values to Multimap."); + } + } + } + + /// + /// Determines whether the Multimap contains an item with the specified key. + /// + /// The key to locate in the Multimap. + /// true if the Multimap contains an item with + /// the key; otherwise, false. + public bool ContainsKey(TKey key) + { + return _dictionary.ContainsKey(key); + } + + /// + /// Removes item with the specified key from the Multimap. + /// + /// The key to locate in the Multimap. + /// true if the item is successfully removed; otherwise, false. + public bool Remove(TKey key) + { + return TryRemove(key, out var _); + } + + /// + /// Gets the value associated with the specified key. + /// + /// The key whose value to get. + /// When this method returns, the value associated with the specified key, if the + /// key is found; otherwise, the default value for the type of the value parameter. + /// This parameter is passed uninitialized. + /// true if the object that implements Multimap contains + /// an item with the specified key; otherwise, false. + public bool TryGetValue(TKey key, out IList value) + { + return _dictionary.TryGetValue(key, out value); + } + + /// + /// Gets or sets the item with the specified key. + /// + /// The key of the item to get or set. + /// The value of the specified key. + public IList this[TKey key] + { + get => _dictionary[key]; + set => _dictionary[key] = value; + } + + /// + /// Gets a System.Collections.Generic.ICollection containing the keys of the Multimap. + /// + public ICollection Keys => _dictionary.Keys; + + /// + /// Gets a System.Collections.Generic.ICollection containing the values of the Multimap. + /// + public ICollection> Values => _dictionary.Values; + + /// + /// Copy the items of the Multimap to an System.Array, + /// starting at a particular System.Array index. + /// + /// The one-dimensional System.Array that is the destination of the items copied + /// from Multimap. The System.Array must have zero-based indexing. + /// The zero-based index in array at which copying begins. + public void CopyTo(Array array, int index) + { + ((ICollection)_dictionary).CopyTo(array, index); + } + + /// + /// Adds an item with the provided key and value to the Multimap. + /// + /// The object to use as the key of the item to add. + /// The object to use as the value of the item to add. + /// Thrown when couldn't add value to Multimap. + public void Add(TKey key, TValue value) + { + if (value != null) + { + if (_dictionary.TryGetValue(key, out var list)) + { + list.Add(value); + } + else + { + list = new List { value }; + if (!TryAdd(key, list)) + throw new InvalidOperationException("Could not add value to Multimap."); + } + } + } + + #endregion Public Members + + #region Private Members + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryRemove(TKey key, out IList value) + { + _dictionary.TryGetValue(key, out value); + return _dictionary.Remove(key); + } + + /** + * Helper method to encapsulate generator differences between dictionary types. + */ + private bool TryAdd(TKey key, IList value) + { + try + { + _dictionary.Add(key, value); + } + catch (ArgumentException) + { + return false; + } + + return true; + } + #endregion Private Members + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs new file mode 100644 index 000000000000..b56476476ac6 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/OpenAPIDateConverter.cs @@ -0,0 +1,29 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + +using Newtonsoft.Json.Converters; + +namespace Org.OpenAPITools.Client +{ + /// + /// Formatter for 'date' openapi formats ss defined by full-date - RFC3339 + /// see https://github.com/OAI/OpenAPI-Specification/blob/master/versions/3.0.0.md#data-types + /// + public class OpenAPIDateConverter : IsoDateTimeConverter + { + /// + /// Initializes a new instance of the class. + /// + public OpenAPIDateConverter() + { + // full-date = date-fullyear "-" date-month "-" date-mday + DateTimeFormat = "yyyy-MM-dd"; + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RequestOptions.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RequestOptions.cs new file mode 100644 index 000000000000..2f65f902cff1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RequestOptions.cs @@ -0,0 +1,84 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections.Generic; +using System.IO; +using System.Net; + +namespace Org.OpenAPITools.Client +{ + /// + /// A container for generalized request inputs. This type allows consumers to extend the request functionality + /// by abstracting away from the default (built-in) request framework (e.g. RestSharp). + /// + public class RequestOptions + { + /// + /// Parameters to be bound to path parts of the Request's URL + /// + public Dictionary PathParameters { get; set; } + + /// + /// Query parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap QueryParameters { get; set; } + + /// + /// Header parameters to be applied to the request. + /// Keys may have 1 or more values associated. + /// + public Multimap HeaderParameters { get; set; } + + /// + /// Form parameters to be sent along with the request. + /// + public Dictionary FormParameters { get; set; } + + /// + /// File parameters to be sent along with the request. + /// + public Multimap FileParameters { get; set; } + + /// + /// Cookies to be sent along with the request. + /// + public List Cookies { get; set; } + + /// + /// Operation associated with the request path. + /// + public string Operation { get; set; } + + /// + /// Index associated with the operation. + /// + public int OperationIndex { get; set; } + + /// + /// Any data associated with a request body. + /// + public Object Data { get; set; } + + /// + /// Constructs a new instance of + /// + public RequestOptions() + { + PathParameters = new Dictionary(); + QueryParameters = new Multimap(); + HeaderParameters = new Multimap(); + FormParameters = new Dictionary(); + FileParameters = new Multimap(); + Cookies = new List(); + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RetryConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RetryConfiguration.cs new file mode 100644 index 000000000000..ca42aee633b5 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Client/RetryConfiguration.cs @@ -0,0 +1,31 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Polly; +using RestSharp; + +namespace Org.OpenAPITools.Client +{ + /// + /// Configuration class to set the polly retry policies to be applied to the requests. + /// + public static class RetryConfiguration + { + /// + /// Retry policy + /// + public static Policy RetryPolicy { get; set; } + + /// + /// Async retry policy + /// + public static AsyncPolicy AsyncRetryPolicy { get; set; } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs new file mode 100644 index 000000000000..16a2db7a38aa --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/AbstractOpenAPISchema.cs @@ -0,0 +1,76 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using Newtonsoft.Json; +using Newtonsoft.Json.Serialization; + +namespace Org.OpenAPITools.Model +{ + /// + /// Abstract base class for oneOf, anyOf schemas in the OpenAPI specification + /// + public abstract partial class AbstractOpenAPISchema + { + /// + /// Custom JSON serializer + /// + static public readonly JsonSerializerSettings SerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Error, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Custom JSON serializer for objects with additional properties + /// + static public readonly JsonSerializerSettings AdditionalPropertiesSerializerSettings = new JsonSerializerSettings + { + // OpenAPI generated types generally hide default constructors. + ConstructorHandling = ConstructorHandling.AllowNonPublicDefaultConstructor, + MissingMemberHandling = MissingMemberHandling.Ignore, + ContractResolver = new DefaultContractResolver + { + NamingStrategy = new CamelCaseNamingStrategy + { + OverrideSpecifiedNames = false + } + } + }; + + /// + /// Gets or Sets the actual instance + /// + public abstract Object ActualInstance { get; set; } + + /// + /// Gets or Sets IsNullable to indicate whether the instance is nullable + /// + public bool IsNullable { get; protected set; } + + /// + /// Gets or Sets the schema type, which can be either `oneOf` or `anyOf` + /// + public string SchemaType { get; protected set; } + + /// + /// Converts the instance into JSON string. + /// + public abstract string ToJson(); + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs new file mode 100644 index 000000000000..08559efc7704 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Model/NowGet200Response.cs @@ -0,0 +1,92 @@ +/* + * OpenAPI Dates + * + * Thic spec contains endpoints with dates in different formats + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Model +{ + /// + /// NowGet200Response + /// + [DataContract(Name = "_now_get_200_response")] + public partial class NowGet200Response : IValidatableObject + { + /// + /// Initializes a new instance of the class. + /// + /// today. + /// now. + public NowGet200Response(DateTime today = default(DateTime), DateTime now = default(DateTime)) + { + this.Today = today; + this.Now = now; + } + + /// + /// Gets or Sets Today + /// + [DataMember(Name = "today", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime Today { get; set; } + + /// + /// Gets or Sets Now + /// + [DataMember(Name = "now", EmitDefaultValue = false)] + public DateTime Now { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class NowGet200Response {\n"); + sb.Append(" Today: ").Append(Today).Append("\n"); + sb.Append(" Now: ").Append(Now).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj new file mode 100644 index 000000000000..721eade2ad16 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-net7.0-useDateTimeForDate/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -0,0 +1,36 @@ + + + + false + net7.0 + Org.OpenAPITools + Org.OpenAPITools + Library + OpenAPI + OpenAPI + OpenAPI Library + A library generated from a OpenAPI doc + No Copyright + Org.OpenAPITools + 1.0.0 + bin\$(Configuration)\$(TargetFramework)\Org.OpenAPITools.xml + https://github.com/GIT_USER_ID/GIT_REPO_ID.git + git + Minor update + annotations + + + + + + + + + + + + + + + + diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/FILES index b6dffff4f19f..b73f11d50f17 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/FILES @@ -75,6 +75,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -194,6 +195,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/README.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/README.md index dcfb29678186..06c969e72fed 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/README.md @@ -101,6 +101,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -207,6 +208,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](Quadrilateral.md) - [Model.QuadrilateralInterface](QuadrilateralInterface.md) - [Model.ReadOnlyFirst](ReadOnlyFirst.md) + - [Model.RequiredClass](RequiredClass.md) - [Model.Return](Return.md) - [Model.RolesReportsHash](RolesReportsHash.md) - [Model.RolesReportsHashRole](RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/FakeApi.md index c8a21d2e25c6..1debc2b6564d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/PetApi.md index ad44daac69e1..220b1ae30105 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..24f5e2325d28 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,410 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; +using NUnit.Framework; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Test] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Test] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Test] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Test] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Test] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Test] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Test] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Test] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Test] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Test] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Test] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Test] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Test] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Test] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Test] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Test] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Test] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Test] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Test] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Test] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Test] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Test] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Test] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Test] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Test] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Test] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Test] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Test] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Test] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Test] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Test] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Test] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Test] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Test] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Test] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Test] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Test] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + /// + /// Test the property 'RequiredNullableUuid' + /// + [Test] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Test] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Test] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Test] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Test] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Test] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Test] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Test] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/FakeApi.cs index fa822317a0b2..293a89f3b781 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/FakeApi.cs @@ -145,6 +145,24 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + void TestAdditionalPropertiesReference(Dictionary requestBody); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody); + /// /// /// /// @@ -558,6 +576,29 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1711,6 +1752,130 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = requestBody; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + var task = TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, cancellationToken); +#if UNITY_EDITOR || !UNITY_WEBGL + await task.ConfigureAwait(false); +#else + await task; +#endif + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + + localVarRequestOptions.Data = requestBody; + + + // make the HTTP request + + var task = this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken); + +#if UNITY_EDITOR || !UNITY_WEBGL + var localVarResponse = await task.ConfigureAwait(false); +#else + var localVarResponse = await task; +#endif + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) throw _exception; + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/PetApi.cs index 4e9580620b48..e775e38390a6 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Api/PetApi.cs @@ -1289,6 +1289,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1355,6 +1360,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/ChildCat.cs index cdcba31d446d..939b710f34bb 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/ChildCat.cs @@ -47,17 +47,22 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() { } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs index 9bfd0ce588da..f9e91a2fb86b 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Drawing.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable + public partial class Drawing : IEquatable { /// /// Initializes a new instance of the class. @@ -37,7 +37,7 @@ public partial class Drawing : Dictionary, IEquatable /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -84,7 +84,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -98,7 +97,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -124,22 +123,22 @@ public bool Equals(Drawing input) { return false; } - return base.Equals(input) && + return ( this.MainShape == input.MainShape || (this.MainShape != null && this.MainShape.Equals(input.MainShape)) - ) && base.Equals(input) && + ) && ( this.ShapeOrNull == input.ShapeOrNull || (this.ShapeOrNull != null && this.ShapeOrNull.Equals(input.ShapeOrNull)) - ) && base.Equals(input) && + ) && ( this.NullableShape == input.NullableShape || (this.NullableShape != null && this.NullableShape.Equals(input.NullableShape)) - ) && base.Equals(input) && + ) && ( this.Shapes == input.Shapes || this.Shapes != null && @@ -157,7 +156,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs index 699f0c7881d8..43e095493285 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/NullableClass.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable + public partial class NullableClass : IEquatable { /// /// Initializes a new instance of the class. @@ -45,7 +45,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -149,7 +149,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -171,7 +170,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -197,67 +196,67 @@ public bool Equals(NullableClass input) { return false; } - return base.Equals(input) && + return ( this.IntegerProp == input.IntegerProp || (this.IntegerProp != null && this.IntegerProp.Equals(input.IntegerProp)) - ) && base.Equals(input) && + ) && ( this.NumberProp == input.NumberProp || (this.NumberProp != null && this.NumberProp.Equals(input.NumberProp)) - ) && base.Equals(input) && + ) && ( this.BooleanProp == input.BooleanProp || (this.BooleanProp != null && this.BooleanProp.Equals(input.BooleanProp)) - ) && base.Equals(input) && + ) && ( this.StringProp == input.StringProp || (this.StringProp != null && this.StringProp.Equals(input.StringProp)) - ) && base.Equals(input) && + ) && ( this.DateProp == input.DateProp || (this.DateProp != null && this.DateProp.Equals(input.DateProp)) - ) && base.Equals(input) && + ) && ( this.DatetimeProp == input.DatetimeProp || (this.DatetimeProp != null && this.DatetimeProp.Equals(input.DatetimeProp)) - ) && base.Equals(input) && + ) && ( this.ArrayNullableProp == input.ArrayNullableProp || this.ArrayNullableProp != null && input.ArrayNullableProp != null && this.ArrayNullableProp.SequenceEqual(input.ArrayNullableProp) - ) && base.Equals(input) && + ) && ( this.ArrayAndItemsNullableProp == input.ArrayAndItemsNullableProp || this.ArrayAndItemsNullableProp != null && input.ArrayAndItemsNullableProp != null && this.ArrayAndItemsNullableProp.SequenceEqual(input.ArrayAndItemsNullableProp) - ) && base.Equals(input) && + ) && ( this.ArrayItemsNullable == input.ArrayItemsNullable || this.ArrayItemsNullable != null && input.ArrayItemsNullable != null && this.ArrayItemsNullable.SequenceEqual(input.ArrayItemsNullable) - ) && base.Equals(input) && + ) && ( this.ObjectNullableProp == input.ObjectNullableProp || this.ObjectNullableProp != null && input.ObjectNullableProp != null && this.ObjectNullableProp.SequenceEqual(input.ObjectNullableProp) - ) && base.Equals(input) && + ) && ( this.ObjectAndItemsNullableProp == input.ObjectAndItemsNullableProp || this.ObjectAndItemsNullableProp != null && input.ObjectAndItemsNullableProp != null && this.ObjectAndItemsNullableProp.SequenceEqual(input.ObjectAndItemsNullableProp) - ) && base.Equals(input) && + ) && ( this.ObjectItemsNullable == input.ObjectItemsNullable || this.ObjectItemsNullable != null && @@ -275,7 +274,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..eb89d56999fc --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1224 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() { } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return this.Equals(input as RequiredClass); + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + if (input == null) + { + return false; + } + return + ( + this.RequiredNullableIntegerProp == input.RequiredNullableIntegerProp || + (this.RequiredNullableIntegerProp != null && + this.RequiredNullableIntegerProp.Equals(input.RequiredNullableIntegerProp)) + ) && + ( + this.RequiredNotnullableintegerProp == input.RequiredNotnullableintegerProp || + this.RequiredNotnullableintegerProp.Equals(input.RequiredNotnullableintegerProp) + ) && + ( + this.NotRequiredNullableIntegerProp == input.NotRequiredNullableIntegerProp || + (this.NotRequiredNullableIntegerProp != null && + this.NotRequiredNullableIntegerProp.Equals(input.NotRequiredNullableIntegerProp)) + ) && + ( + this.NotRequiredNotnullableintegerProp == input.NotRequiredNotnullableintegerProp || + this.NotRequiredNotnullableintegerProp.Equals(input.NotRequiredNotnullableintegerProp) + ) && + ( + this.RequiredNullableStringProp == input.RequiredNullableStringProp || + (this.RequiredNullableStringProp != null && + this.RequiredNullableStringProp.Equals(input.RequiredNullableStringProp)) + ) && + ( + this.RequiredNotnullableStringProp == input.RequiredNotnullableStringProp || + (this.RequiredNotnullableStringProp != null && + this.RequiredNotnullableStringProp.Equals(input.RequiredNotnullableStringProp)) + ) && + ( + this.NotrequiredNullableStringProp == input.NotrequiredNullableStringProp || + (this.NotrequiredNullableStringProp != null && + this.NotrequiredNullableStringProp.Equals(input.NotrequiredNullableStringProp)) + ) && + ( + this.NotrequiredNotnullableStringProp == input.NotrequiredNotnullableStringProp || + (this.NotrequiredNotnullableStringProp != null && + this.NotrequiredNotnullableStringProp.Equals(input.NotrequiredNotnullableStringProp)) + ) && + ( + this.RequiredNullableBooleanProp == input.RequiredNullableBooleanProp || + (this.RequiredNullableBooleanProp != null && + this.RequiredNullableBooleanProp.Equals(input.RequiredNullableBooleanProp)) + ) && + ( + this.RequiredNotnullableBooleanProp == input.RequiredNotnullableBooleanProp || + this.RequiredNotnullableBooleanProp.Equals(input.RequiredNotnullableBooleanProp) + ) && + ( + this.NotrequiredNullableBooleanProp == input.NotrequiredNullableBooleanProp || + (this.NotrequiredNullableBooleanProp != null && + this.NotrequiredNullableBooleanProp.Equals(input.NotrequiredNullableBooleanProp)) + ) && + ( + this.NotrequiredNotnullableBooleanProp == input.NotrequiredNotnullableBooleanProp || + this.NotrequiredNotnullableBooleanProp.Equals(input.NotrequiredNotnullableBooleanProp) + ) && + ( + this.RequiredNullableDateProp == input.RequiredNullableDateProp || + (this.RequiredNullableDateProp != null && + this.RequiredNullableDateProp.Equals(input.RequiredNullableDateProp)) + ) && + ( + this.RequiredNotNullableDateProp == input.RequiredNotNullableDateProp || + (this.RequiredNotNullableDateProp != null && + this.RequiredNotNullableDateProp.Equals(input.RequiredNotNullableDateProp)) + ) && + ( + this.NotRequiredNullableDateProp == input.NotRequiredNullableDateProp || + (this.NotRequiredNullableDateProp != null && + this.NotRequiredNullableDateProp.Equals(input.NotRequiredNullableDateProp)) + ) && + ( + this.NotRequiredNotnullableDateProp == input.NotRequiredNotnullableDateProp || + (this.NotRequiredNotnullableDateProp != null && + this.NotRequiredNotnullableDateProp.Equals(input.NotRequiredNotnullableDateProp)) + ) && + ( + this.RequiredNotnullableDatetimeProp == input.RequiredNotnullableDatetimeProp || + (this.RequiredNotnullableDatetimeProp != null && + this.RequiredNotnullableDatetimeProp.Equals(input.RequiredNotnullableDatetimeProp)) + ) && + ( + this.RequiredNullableDatetimeProp == input.RequiredNullableDatetimeProp || + (this.RequiredNullableDatetimeProp != null && + this.RequiredNullableDatetimeProp.Equals(input.RequiredNullableDatetimeProp)) + ) && + ( + this.NotrequiredNullableDatetimeProp == input.NotrequiredNullableDatetimeProp || + (this.NotrequiredNullableDatetimeProp != null && + this.NotrequiredNullableDatetimeProp.Equals(input.NotrequiredNullableDatetimeProp)) + ) && + ( + this.NotrequiredNotnullableDatetimeProp == input.NotrequiredNotnullableDatetimeProp || + (this.NotrequiredNotnullableDatetimeProp != null && + this.NotrequiredNotnullableDatetimeProp.Equals(input.NotrequiredNotnullableDatetimeProp)) + ) && + ( + this.RequiredNullableEnumInteger == input.RequiredNullableEnumInteger || + this.RequiredNullableEnumInteger.Equals(input.RequiredNullableEnumInteger) + ) && + ( + this.RequiredNotnullableEnumInteger == input.RequiredNotnullableEnumInteger || + this.RequiredNotnullableEnumInteger.Equals(input.RequiredNotnullableEnumInteger) + ) && + ( + this.NotrequiredNullableEnumInteger == input.NotrequiredNullableEnumInteger || + this.NotrequiredNullableEnumInteger.Equals(input.NotrequiredNullableEnumInteger) + ) && + ( + this.NotrequiredNotnullableEnumInteger == input.NotrequiredNotnullableEnumInteger || + this.NotrequiredNotnullableEnumInteger.Equals(input.NotrequiredNotnullableEnumInteger) + ) && + ( + this.RequiredNullableEnumIntegerOnly == input.RequiredNullableEnumIntegerOnly || + this.RequiredNullableEnumIntegerOnly.Equals(input.RequiredNullableEnumIntegerOnly) + ) && + ( + this.RequiredNotnullableEnumIntegerOnly == input.RequiredNotnullableEnumIntegerOnly || + this.RequiredNotnullableEnumIntegerOnly.Equals(input.RequiredNotnullableEnumIntegerOnly) + ) && + ( + this.NotrequiredNullableEnumIntegerOnly == input.NotrequiredNullableEnumIntegerOnly || + this.NotrequiredNullableEnumIntegerOnly.Equals(input.NotrequiredNullableEnumIntegerOnly) + ) && + ( + this.NotrequiredNotnullableEnumIntegerOnly == input.NotrequiredNotnullableEnumIntegerOnly || + this.NotrequiredNotnullableEnumIntegerOnly.Equals(input.NotrequiredNotnullableEnumIntegerOnly) + ) && + ( + this.RequiredNotnullableEnumString == input.RequiredNotnullableEnumString || + this.RequiredNotnullableEnumString.Equals(input.RequiredNotnullableEnumString) + ) && + ( + this.RequiredNullableEnumString == input.RequiredNullableEnumString || + this.RequiredNullableEnumString.Equals(input.RequiredNullableEnumString) + ) && + ( + this.NotrequiredNullableEnumString == input.NotrequiredNullableEnumString || + this.NotrequiredNullableEnumString.Equals(input.NotrequiredNullableEnumString) + ) && + ( + this.NotrequiredNotnullableEnumString == input.NotrequiredNotnullableEnumString || + this.NotrequiredNotnullableEnumString.Equals(input.NotrequiredNotnullableEnumString) + ) && + ( + this.RequiredNullableOuterEnumDefaultValue == input.RequiredNullableOuterEnumDefaultValue || + this.RequiredNullableOuterEnumDefaultValue.Equals(input.RequiredNullableOuterEnumDefaultValue) + ) && + ( + this.RequiredNotnullableOuterEnumDefaultValue == input.RequiredNotnullableOuterEnumDefaultValue || + this.RequiredNotnullableOuterEnumDefaultValue.Equals(input.RequiredNotnullableOuterEnumDefaultValue) + ) && + ( + this.NotrequiredNullableOuterEnumDefaultValue == input.NotrequiredNullableOuterEnumDefaultValue || + this.NotrequiredNullableOuterEnumDefaultValue.Equals(input.NotrequiredNullableOuterEnumDefaultValue) + ) && + ( + this.NotrequiredNotnullableOuterEnumDefaultValue == input.NotrequiredNotnullableOuterEnumDefaultValue || + this.NotrequiredNotnullableOuterEnumDefaultValue.Equals(input.NotrequiredNotnullableOuterEnumDefaultValue) + ) && + ( + this.RequiredNullableUuid == input.RequiredNullableUuid || + (this.RequiredNullableUuid != null && + this.RequiredNullableUuid.Equals(input.RequiredNullableUuid)) + ) && + ( + this.RequiredNotnullableUuid == input.RequiredNotnullableUuid || + (this.RequiredNotnullableUuid != null && + this.RequiredNotnullableUuid.Equals(input.RequiredNotnullableUuid)) + ) && + ( + this.NotrequiredNullableUuid == input.NotrequiredNullableUuid || + (this.NotrequiredNullableUuid != null && + this.NotrequiredNullableUuid.Equals(input.NotrequiredNullableUuid)) + ) && + ( + this.NotrequiredNotnullableUuid == input.NotrequiredNotnullableUuid || + (this.NotrequiredNotnullableUuid != null && + this.NotrequiredNotnullableUuid.Equals(input.NotrequiredNotnullableUuid)) + ) && + ( + this.RequiredNullableArrayOfString == input.RequiredNullableArrayOfString || + this.RequiredNullableArrayOfString != null && + input.RequiredNullableArrayOfString != null && + this.RequiredNullableArrayOfString.SequenceEqual(input.RequiredNullableArrayOfString) + ) && + ( + this.RequiredNotnullableArrayOfString == input.RequiredNotnullableArrayOfString || + this.RequiredNotnullableArrayOfString != null && + input.RequiredNotnullableArrayOfString != null && + this.RequiredNotnullableArrayOfString.SequenceEqual(input.RequiredNotnullableArrayOfString) + ) && + ( + this.NotrequiredNullableArrayOfString == input.NotrequiredNullableArrayOfString || + this.NotrequiredNullableArrayOfString != null && + input.NotrequiredNullableArrayOfString != null && + this.NotrequiredNullableArrayOfString.SequenceEqual(input.NotrequiredNullableArrayOfString) + ) && + ( + this.NotrequiredNotnullableArrayOfString == input.NotrequiredNotnullableArrayOfString || + this.NotrequiredNotnullableArrayOfString != null && + input.NotrequiredNotnullableArrayOfString != null && + this.NotrequiredNotnullableArrayOfString.SequenceEqual(input.NotrequiredNotnullableArrayOfString) + ); + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + return hashCode; + } + } + + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index f4048c333a2b..b64d51277036 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -28,13 +28,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -60,7 +60,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -71,7 +70,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -97,7 +96,7 @@ public bool Equals(TestInlineFreeformAdditionalPropertiesRequest input) { return false; } - return base.Equals(input) && + return ( this.SomeProperty == input.SomeProperty || (this.SomeProperty != null && @@ -114,7 +113,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); diff --git a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Zebra.cs index c4a9ab74efe3..e08246f7a4a5 100644 --- a/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient-unityWebRequest/src/Org.OpenAPITools/Model/Zebra.cs @@ -28,7 +28,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable + public partial class Zebra : IEquatable { /// /// Defines Type @@ -74,7 +74,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -106,7 +106,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -118,7 +117,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -144,11 +143,11 @@ public bool Equals(Zebra input) { return false; } - return base.Equals(input) && + return ( this.Type == input.Type || this.Type.Equals(input.Type) - ) && base.Equals(input) && + ) && ( this.ClassName == input.ClassName || (this.ClassName != null && @@ -165,7 +164,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { diff --git a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/FILES index f69e6ba1aba7..0af518f942ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -197,6 +198,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClient/README.md b/samples/client/petstore/csharp/OpenAPIClient/README.md index af827f28641e..1670f76c1a89 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/README.md +++ b/samples/client/petstore/csharp/OpenAPIClient/README.md @@ -115,6 +115,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -221,6 +222,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClient/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClient/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClient/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md index c8a21d2e25c6..1debc2b6564d 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClient/docs/PetApi.md index ad44daac69e1..220b1ae30105 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClient/docs/RequiredClass.md new file mode 100644 index 000000000000..07b6f018f6c1 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateTime?** | | +**RequiredNotNullableDateProp** | **DateTime** | | +**NotRequiredNullableDateProp** | **DateTime?** | | [optional] +**NotRequiredNotnullableDateProp** | **DateTime** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClient/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClient/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClient/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs index 7282ba7821b9..ce37acaec65f 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs index 22b4eeeea76e..7a34dc4fe192 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs index cb5abc941b1c..3c0762f55399 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ApiClient.cs @@ -561,7 +561,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..5e20b7408d46 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index 7c8668488ee2..256f338e1817 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -412,6 +415,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs index eaeb0202a264..8e76f168a65e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/ChildCat.cs @@ -51,17 +51,25 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() + { + this.AdditionalProperties = new Dictionary(); + } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; this.AdditionalProperties = new Dictionary(); } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs index d5d633ed3b31..1d18a58b117a 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -86,7 +86,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -100,7 +99,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -133,7 +132,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -164,16 +163,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs index 919ed331163d..5c7b13e9b783 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -151,7 +151,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -173,7 +172,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -206,7 +205,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -269,16 +268,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..90e0c44b40b8 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1042 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() + { + this.AdditionalProperties = new Dictionary(); + } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateTime? requiredNullableDateProp = default(DateTime?), DateTime requiredNotNullableDateProp = default(DateTime), DateTime? notRequiredNullableDateProp = default(DateTime?), DateTime notRequiredNotnullableDateProp = default(DateTime), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + this.AdditionalProperties = new Dictionary(); + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime? NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateTime NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets additional properties + /// + [JsonExtensionData] + public IDictionary AdditionalProperties { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.AdditionalProperties != null) + { + hashCode = (hashCode * 59) + this.AdditionalProperties.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index e668ef1fe4ea..c56b9e336517 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -62,7 +62,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -73,7 +72,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -106,7 +105,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -125,16 +124,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs index 193c3be7973b..58ec23be816e 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -76,7 +76,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -108,7 +108,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,7 +119,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -153,7 +152,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -173,16 +172,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj index c040fee79765..6064f45f6dd4 100644 --- a/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClient/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/FILES b/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/FILES index f69e6ba1aba7..0af518f942ac 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/FILES +++ b/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/FILES @@ -77,6 +77,7 @@ docs/PolymorphicProperty.md docs/Quadrilateral.md docs/QuadrilateralInterface.md docs/ReadOnlyFirst.md +docs/RequiredClass.md docs/Return.md docs/RolesReportsHash.md docs/RolesReportsHashRole.md @@ -197,6 +198,7 @@ src/Org.OpenAPITools/Model/PolymorphicProperty.cs src/Org.OpenAPITools/Model/Quadrilateral.cs src/Org.OpenAPITools/Model/QuadrilateralInterface.cs src/Org.OpenAPITools/Model/ReadOnlyFirst.cs +src/Org.OpenAPITools/Model/RequiredClass.cs src/Org.OpenAPITools/Model/Return.cs src/Org.OpenAPITools/Model/RolesReportsHash.cs src/Org.OpenAPITools/Model/RolesReportsHashRole.cs diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClientCore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/README.md b/samples/client/petstore/csharp/OpenAPIClientCore/README.md index 2a3e242fe88d..b77dcd24dfbf 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/README.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**FakeOuterNumberSerialize**](docs/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**FakeOuterStringSerialize**](docs/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**GetArrayOfEnums**](docs/FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**TestAdditionalPropertiesReference**](docs/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**TestBodyWithFileSchema**](docs/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**TestBodyWithQueryParams**](docs/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**TestClientModel**](docs/FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model @@ -233,6 +234,7 @@ Class | Method | HTTP request | Description - [Model.Quadrilateral](docs/Quadrilateral.md) - [Model.QuadrilateralInterface](docs/QuadrilateralInterface.md) - [Model.ReadOnlyFirst](docs/ReadOnlyFirst.md) + - [Model.RequiredClass](docs/RequiredClass.md) - [Model.Return](docs/Return.md) - [Model.RolesReportsHash](docs/RolesReportsHash.md) - [Model.RolesReportsHashRole](docs/RolesReportsHashRole.md) diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/api/openapi.yaml b/samples/client/petstore/csharp/OpenAPIClientCore/api/openapi.yaml index f6eeaf555f13..c03f1e44116a 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/api/openapi.yaml +++ b/samples/client/petstore/csharp/OpenAPIClientCore/api/openapi.yaml @@ -262,6 +262,7 @@ paths: description: Pet not found security: - api_key: [] + - api_key_query: [] summary: Find pet by ID tags: - pet @@ -499,6 +500,14 @@ paths: type: string description: successful operation headers: + Set-Cookie: + description: Cookie authentication key for use with the `api_key` apiKey + authentication. + explode: false + schema: + example: AUTH_KEY=abcde12345; Path=/; HttpOnly + type: string + style: simple X-Rate-Limit: description: calls per hour allowed by the user explode: false @@ -575,6 +584,14 @@ paths: description: Invalid username supplied "404": description: User not found + "598": + description: Not a real HTTP status code + "599": + content: + application/json: + schema: + $ref: '#/components/schemas/User' + description: Not a real HTTP status code with a return object summary: Get user by user name tags: - user @@ -924,6 +941,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1885,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1946,6 +1984,264 @@ components: nullable: true type: string type: object + RequiredClass: + properties: + required_nullable_integer_prop: + nullable: true + type: integer + required_notnullableinteger_prop: + nullable: false + type: integer + not_required_nullable_integer_prop: + nullable: true + type: integer + not_required_notnullableinteger_prop: + nullable: false + type: integer + required_nullable_string_prop: + nullable: true + type: string + required_notnullable_string_prop: + nullable: false + type: string + notrequired_nullable_string_prop: + nullable: true + type: string + notrequired_notnullable_string_prop: + nullable: false + type: string + required_nullable_boolean_prop: + nullable: true + type: boolean + required_notnullable_boolean_prop: + nullable: false + type: boolean + notrequired_nullable_boolean_prop: + nullable: true + type: boolean + notrequired_notnullable_boolean_prop: + nullable: false + type: boolean + required_nullable_date_prop: + format: date + nullable: true + type: string + required_not_nullable_date_prop: + format: date + nullable: false + type: string + not_required_nullable_date_prop: + format: date + nullable: true + type: string + not_required_notnullable_date_prop: + format: date + nullable: false + type: string + required_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_nullable_datetime_prop: + format: date-time + nullable: true + type: string + notrequired_notnullable_datetime_prop: + format: date-time + nullable: false + type: string + required_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + required_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + notrequired_nullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: true + type: integer + notrequired_notnullable_enum_integer: + enum: + - 1 + - -1 + format: int32 + nullable: false + type: integer + required_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + required_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + notrequired_nullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: true + type: integer + notrequired_notnullable_enum_integer_only: + enum: + - 2 + - -2 + nullable: false + type: integer + required_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_nullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: true + type: string + notrequired_notnullable_enum_string: + enum: + - UPPER + - lower + - "" + - "Value\twith tab" + - Value with " quote + - Value with escaped \" quote + - |- + Duplicate + value + - "Duplicate\r\nvalue" + nullable: false + type: string + required_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + required_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + notrequired_nullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: true + notrequired_notnullable_outerEnumDefaultValue: + allOf: + - $ref: '#/components/schemas/OuterEnumDefaultValue' + nullable: false + required_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + required_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + notrequired_nullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: true + type: string + notrequired_notnullable_uuid: + example: 72f98069-206d-4f12-9f12-3d1e525a8e84 + format: uuid + nullable: false + type: string + required_nullable_array_of_string: + items: + type: string + nullable: true + type: array + required_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + notrequired_nullable_array_of_string: + items: + type: string + nullable: true + type: array + notrequired_notnullable_array_of_string: + items: + type: string + nullable: false + type: array + required: + - required_not_nullable_date_prop + - required_notnullable_array_of_string + - required_notnullable_boolean_prop + - required_notnullable_datetime_prop + - required_notnullable_enum_integer + - required_notnullable_enum_integer_only + - required_notnullable_enum_string + - required_notnullable_outerEnumDefaultValue + - required_notnullable_string_prop + - required_notnullable_uuid + - required_notnullableinteger_prop + - required_nullable_array_of_string + - required_nullable_boolean_prop + - required_nullable_date_prop + - required_nullable_datetime_prop + - required_nullable_enum_integer + - required_nullable_enum_integer_only + - required_nullable_enum_string + - required_nullable_integer_prop + - required_nullable_outerEnumDefaultValue + - required_nullable_string_prop + - required_nullable_uuid + type: object NullableClass: additionalProperties: nullable: true @@ -2233,6 +2529,8 @@ components: - ChildCat type: string x-enum-as-string: true + required: + - pet_type type: object ArrayOfEnums: items: diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/ChildCat.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/ChildCat.md index 072ad05b36d2..8ce6449e5f22 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/ChildCat.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/ChildCat.md @@ -5,7 +5,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **Name** | **string** | | [optional] -**PetType** | **string** | | [optional] [default to PetTypeEnum.ChildCat] +**PetType** | **string** | | [default to PetTypeEnum.ChildCat] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/DateOnlyClass.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/DateOnlyClass.md index d0912d2ac415..8291b9cb6d78 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/DateOnlyClass.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/DateOnlyClass.md @@ -4,7 +4,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**DateOnlyProperty** | **DateTime** | | [optional] +**DateOnlyProperty** | **DateOnly** | | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/FakeApi.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/FakeApi.md index 70d7da71e1c6..b939df0baf1c 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/FakeApi.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**FakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | | | [**FakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | | | [**GetArrayOfEnums**](FakeApi.md#getarrayofenums) | **GET** /fake/array-of-enums | Array of Enums | +| [**TestAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**TestBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | | | [**TestBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | | | [**TestClientModel**](FakeApi.md#testclientmodel) | **PATCH** /fake | To test \"client\" model | @@ -547,6 +548,91 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **TestAdditionalPropertiesReference** +> void TestAdditionalPropertiesReference (Dictionary requestBody) + +test referenced additionalProperties + +### Example +```csharp +using System.Collections.Generic; +using System.Diagnostics; +using Org.OpenAPITools.Api; +using Org.OpenAPITools.Client; +using Org.OpenAPITools.Model; + +namespace Example +{ + public class TestAdditionalPropertiesReferenceExample + { + public static void Main() + { + Configuration config = new Configuration(); + config.BasePath = "http://petstore.swagger.io:80/v2"; + var apiInstance = new FakeApi(config); + var requestBody = new Dictionary(); // Dictionary | request body + + try + { + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReference(requestBody); + } + catch (ApiException e) + { + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReference: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); + } + } + } +} +``` + +#### Using the TestAdditionalPropertiesReferenceWithHttpInfo variant +This returns an ApiResponse object which contains the response data, status code and headers. + +```csharp +try +{ + // test referenced additionalProperties + apiInstance.TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); +} +catch (ApiException e) +{ + Debug.Print("Exception when calling FakeApi.TestAdditionalPropertiesReferenceWithHttpInfo: " + e.Message); + Debug.Print("Status Code: " + e.ErrorCode); + Debug.Print(e.StackTrace); +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------|------|-------------|-------| +| **requestBody** | [**Dictionary<string, Object>**](Object.md) | request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **TestBodyWithFileSchema** > void TestBodyWithFileSchema (FileSchemaTestClass fileSchemaTestClass) @@ -810,7 +896,7 @@ No authorization required # **TestEndpointParameters** -> void TestEndpointParameters (decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = null, int? int32 = null, long? int64 = null, float? varFloat = null, string? varString = null, System.IO.Stream? binary = null, DateTime? date = null, DateTime? dateTime = null, string? password = null, string? callback = null) +> void TestEndpointParameters (decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = null, int? int32 = null, long? int64 = null, float? varFloat = null, string? varString = null, System.IO.Stream? binary = null, DateOnly? date = null, DateTime? dateTime = null, string? password = null, string? callback = null) Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -847,7 +933,7 @@ namespace Example var varFloat = 3.4F; // float? | None (optional) var varString = "varString_example"; // string? | None (optional) var binary = new System.IO.MemoryStream(System.IO.File.ReadAllBytes("/path/to/file.txt")); // System.IO.Stream? | None (optional) - var date = DateTime.Parse("2013-10-20"); // DateTime? | None (optional) + var date = DateOnly.Parse("2013-10-20"); // DateOnly? | None (optional) var dateTime = DateTime.Parse(""2010-02-01T10:20:10.111110+01:00""); // DateTime? | None (optional) (default to "2010-02-01T10:20:10.111110+01:00") var password = "password_example"; // string? | None (optional) var callback = "callback_example"; // string? | None (optional) @@ -899,7 +985,7 @@ catch (ApiException e) | **varFloat** | **float?** | None | [optional] | | **varString** | **string?** | None | [optional] | | **binary** | **System.IO.Stream?****System.IO.Stream?** | None | [optional] | -| **date** | **DateTime?** | None | [optional] | +| **date** | **DateOnly?** | None | [optional] | | **dateTime** | **DateTime?** | None | [optional] [default to "2010-02-01T10:20:10.111110+01:00"] | | **password** | **string?** | None | [optional] | | **callback** | **string?** | None | [optional] | diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/FormatTest.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/FormatTest.md index 2d28c89fa309..1d09c0f37e47 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/FormatTest.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/FormatTest.md @@ -16,7 +16,7 @@ Name | Type | Description | Notes **VarString** | **string** | | [optional] **VarByte** | **byte[]** | | **Binary** | **System.IO.Stream** | | [optional] -**Date** | **DateTime** | | +**Date** | **DateOnly** | | **DateTime** | **DateTime** | | [optional] **Uuid** | **Guid** | | [optional] **Password** | **string** | | diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/NullableClass.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/NullableClass.md index 7bab4fa20ee9..67c1052fca9d 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/NullableClass.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/NullableClass.md @@ -8,7 +8,7 @@ Name | Type | Description | Notes **NumberProp** | **decimal?** | | [optional] **BooleanProp** | **bool?** | | [optional] **StringProp** | **string** | | [optional] -**DateProp** | **DateTime?** | | [optional] +**DateProp** | **DateOnly** | | [optional] **DatetimeProp** | **DateTime?** | | [optional] **ArrayNullableProp** | **List<Object>** | | [optional] **ArrayAndItemsNullableProp** | **List<Object>** | | [optional] diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/PetApi.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/PetApi.md index 7cadc180a75f..417e0ab80207 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/PetApi.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/PetApi.md @@ -410,6 +410,10 @@ namespace Example config.AddApiKey("api_key", "YOUR_API_KEY"); // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed // config.AddApiKeyPrefix("api_key", "Bearer"); + // Configure API key authorization: api_key_query + config.AddApiKey("api_key_query", "YOUR_API_KEY"); + // Uncomment below to setup prefix (e.g. Bearer) for API key, if needed + // config.AddApiKeyPrefix("api_key_query", "Bearer"); var apiInstance = new PetApi(config); var petId = 789L; // long | ID of pet to return @@ -463,7 +467,7 @@ catch (ApiException e) ### Authorization -[api_key](../README.md#api_key) +[api_key](../README.md#api_key), [api_key_query](../README.md#api_key_query) ### HTTP request headers diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/RequiredClass.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/RequiredClass.md new file mode 100644 index 000000000000..685c1c51e031 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/RequiredClass.md @@ -0,0 +1,53 @@ +# Org.OpenAPITools.Model.RequiredClass + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**RequiredNullableIntegerProp** | **int?** | | +**RequiredNotnullableintegerProp** | **int** | | +**NotRequiredNullableIntegerProp** | **int?** | | [optional] +**NotRequiredNotnullableintegerProp** | **int** | | [optional] +**RequiredNullableStringProp** | **string** | | +**RequiredNotnullableStringProp** | **string** | | +**NotrequiredNullableStringProp** | **string** | | [optional] +**NotrequiredNotnullableStringProp** | **string** | | [optional] +**RequiredNullableBooleanProp** | **bool?** | | +**RequiredNotnullableBooleanProp** | **bool** | | +**NotrequiredNullableBooleanProp** | **bool?** | | [optional] +**NotrequiredNotnullableBooleanProp** | **bool** | | [optional] +**RequiredNullableDateProp** | **DateOnly** | | +**RequiredNotNullableDateProp** | **DateOnly** | | +**NotRequiredNullableDateProp** | **DateOnly** | | [optional] +**NotRequiredNotnullableDateProp** | **DateOnly** | | [optional] +**RequiredNotnullableDatetimeProp** | **DateTime** | | +**RequiredNullableDatetimeProp** | **DateTime?** | | +**NotrequiredNullableDatetimeProp** | **DateTime?** | | [optional] +**NotrequiredNotnullableDatetimeProp** | **DateTime** | | [optional] +**RequiredNullableEnumInteger** | **int?** | | +**RequiredNotnullableEnumInteger** | **int** | | +**NotrequiredNullableEnumInteger** | **int?** | | [optional] +**NotrequiredNotnullableEnumInteger** | **int** | | [optional] +**RequiredNullableEnumIntegerOnly** | **int?** | | +**RequiredNotnullableEnumIntegerOnly** | **int** | | +**NotrequiredNullableEnumIntegerOnly** | **int?** | | [optional] +**NotrequiredNotnullableEnumIntegerOnly** | **int** | | [optional] +**RequiredNotnullableEnumString** | **string** | | +**RequiredNullableEnumString** | **string** | | +**NotrequiredNullableEnumString** | **string** | | [optional] +**NotrequiredNotnullableEnumString** | **string** | | [optional] +**RequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**RequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | +**NotrequiredNullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**NotrequiredNotnullableOuterEnumDefaultValue** | **OuterEnumDefaultValue** | | [optional] +**RequiredNullableUuid** | **Guid?** | | +**RequiredNotnullableUuid** | **Guid** | | +**NotrequiredNullableUuid** | **Guid?** | | [optional] +**NotrequiredNotnullableUuid** | **Guid** | | [optional] +**RequiredNullableArrayOfString** | **List<string>** | | +**RequiredNotnullableArrayOfString** | **List<string>** | | +**NotrequiredNullableArrayOfString** | **List<string>** | | [optional] +**NotrequiredNotnullableArrayOfString** | **List<string>** | | [optional] + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/docs/UserApi.md b/samples/client/petstore/csharp/OpenAPIClientCore/docs/UserApi.md index adb1d8d3fec2..7b8439c45411 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/docs/UserApi.md +++ b/samples/client/petstore/csharp/OpenAPIClientCore/docs/UserApi.md @@ -446,6 +446,8 @@ No authorization required | **200** | successful operation | - | | **400** | Invalid username supplied | - | | **404** | User not found | - | +| **598** | Not a real HTTP status code | - | +| **599** | Not a real HTTP status code with a return object | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) @@ -536,7 +538,7 @@ No authorization required ### HTTP response details | Status code | Description | Response headers | |-------------|-------------|------------------| -| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | | **400** | Invalid username/password supplied | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs new file mode 100644 index 000000000000..17de04feade0 --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools.Test/Model/RequiredClassTests.cs @@ -0,0 +1,453 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using Xunit; + +using System; +using System.Linq; +using System.IO; +using System.Collections.Generic; +using Org.OpenAPITools.Model; +using Org.OpenAPITools.Client; +using System.Reflection; +using Newtonsoft.Json; + +namespace Org.OpenAPITools.Test.Model +{ + /// + /// Class for testing RequiredClass + /// + /// + /// This file is automatically generated by OpenAPI Generator (https://openapi-generator.tech). + /// Please update the test case below to test the model. + /// + public class RequiredClassTests : IDisposable + { + // TODO uncomment below to declare an instance variable for RequiredClass + //private RequiredClass instance; + + public RequiredClassTests() + { + // TODO uncomment below to create an instance of RequiredClass + //instance = new RequiredClass(); + } + + public void Dispose() + { + // Cleanup when everything is done. + } + + /// + /// Test an instance of RequiredClass + /// + [Fact] + public void RequiredClassInstanceTest() + { + // TODO uncomment below to test "IsType" RequiredClass + //Assert.IsType(instance); + } + + /// + /// Test the property 'RequiredNullableIntegerProp' + /// + [Fact] + public void RequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'RequiredNullableIntegerProp' + } + + /// + /// Test the property 'RequiredNotnullableintegerProp' + /// + [Fact] + public void RequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'RequiredNotnullableintegerProp' + } + + /// + /// Test the property 'NotRequiredNullableIntegerProp' + /// + [Fact] + public void NotRequiredNullableIntegerPropTest() + { + // TODO unit test for the property 'NotRequiredNullableIntegerProp' + } + + /// + /// Test the property 'NotRequiredNotnullableintegerProp' + /// + [Fact] + public void NotRequiredNotnullableintegerPropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableintegerProp' + } + + /// + /// Test the property 'RequiredNullableStringProp' + /// + [Fact] + public void RequiredNullableStringPropTest() + { + // TODO unit test for the property 'RequiredNullableStringProp' + } + + /// + /// Test the property 'RequiredNotnullableStringProp' + /// + [Fact] + public void RequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'RequiredNotnullableStringProp' + } + + /// + /// Test the property 'NotrequiredNullableStringProp' + /// + [Fact] + public void NotrequiredNullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNullableStringProp' + } + + /// + /// Test the property 'NotrequiredNotnullableStringProp' + /// + [Fact] + public void NotrequiredNotnullableStringPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableStringProp' + } + + /// + /// Test the property 'RequiredNullableBooleanProp' + /// + [Fact] + public void RequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNullableBooleanProp' + } + + /// + /// Test the property 'RequiredNotnullableBooleanProp' + /// + [Fact] + public void RequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'RequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNullableBooleanProp' + /// + [Fact] + public void NotrequiredNullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNullableBooleanProp' + } + + /// + /// Test the property 'NotrequiredNotnullableBooleanProp' + /// + [Fact] + public void NotrequiredNotnullableBooleanPropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableBooleanProp' + } + + /// + /// Test the property 'RequiredNullableDateProp' + /// + [Fact] + public void RequiredNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNullableDateProp' + } + + /// + /// Test the property 'RequiredNotNullableDateProp' + /// + [Fact] + public void RequiredNotNullableDatePropTest() + { + // TODO unit test for the property 'RequiredNotNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNullableDateProp' + /// + [Fact] + public void NotRequiredNullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNullableDateProp' + } + + /// + /// Test the property 'NotRequiredNotnullableDateProp' + /// + [Fact] + public void NotRequiredNotnullableDatePropTest() + { + // TODO unit test for the property 'NotRequiredNotnullableDateProp' + } + + /// + /// Test the property 'RequiredNotnullableDatetimeProp' + /// + [Fact] + public void RequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableDatetimeProp' + /// + [Fact] + public void RequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'RequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNullableDatetimeProp' + /// + [Fact] + public void NotrequiredNullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNullableDatetimeProp' + } + + /// + /// Test the property 'NotrequiredNotnullableDatetimeProp' + /// + [Fact] + public void NotrequiredNotnullableDatetimePropTest() + { + // TODO unit test for the property 'NotrequiredNotnullableDatetimeProp' + } + + /// + /// Test the property 'RequiredNullableEnumInteger' + /// + [Fact] + public void RequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNullableEnumInteger' + } + + /// + /// Test the property 'RequiredNotnullableEnumInteger' + /// + [Fact] + public void RequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNullableEnumInteger' + /// + [Fact] + public void NotrequiredNullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumInteger' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumInteger' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumInteger' + } + + /// + /// Test the property 'RequiredNullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void RequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumIntegerOnly' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumIntegerOnly' + /// + [Fact] + public void NotrequiredNotnullableEnumIntegerOnlyTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumIntegerOnly' + } + + /// + /// Test the property 'RequiredNotnullableEnumString' + /// + [Fact] + public void RequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableEnumString' + /// + [Fact] + public void RequiredNullableEnumStringTest() + { + // TODO unit test for the property 'RequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNullableEnumString' + /// + [Fact] + public void NotrequiredNullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNullableEnumString' + } + + /// + /// Test the property 'NotrequiredNotnullableEnumString' + /// + [Fact] + public void NotrequiredNotnullableEnumStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableEnumString' + } + + /// + /// Test the property 'RequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void RequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'RequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'NotrequiredNotnullableOuterEnumDefaultValue' + /// + [Fact] + public void NotrequiredNotnullableOuterEnumDefaultValueTest() + { + // TODO unit test for the property 'NotrequiredNotnullableOuterEnumDefaultValue' + } + + /// + /// Test the property 'RequiredNullableUuid' + /// + [Fact] + public void RequiredNullableUuidTest() + { + // TODO unit test for the property 'RequiredNullableUuid' + } + + /// + /// Test the property 'RequiredNotnullableUuid' + /// + [Fact] + public void RequiredNotnullableUuidTest() + { + // TODO unit test for the property 'RequiredNotnullableUuid' + } + + /// + /// Test the property 'NotrequiredNullableUuid' + /// + [Fact] + public void NotrequiredNullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNullableUuid' + } + + /// + /// Test the property 'NotrequiredNotnullableUuid' + /// + [Fact] + public void NotrequiredNotnullableUuidTest() + { + // TODO unit test for the property 'NotrequiredNotnullableUuid' + } + + /// + /// Test the property 'RequiredNullableArrayOfString' + /// + [Fact] + public void RequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNullableArrayOfString' + } + + /// + /// Test the property 'RequiredNotnullableArrayOfString' + /// + [Fact] + public void RequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'RequiredNotnullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNullableArrayOfString' + /// + [Fact] + public void NotrequiredNullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNullableArrayOfString' + } + + /// + /// Test the property 'NotrequiredNotnullableArrayOfString' + /// + [Fact] + public void NotrequiredNotnullableArrayOfStringTest() + { + // TODO unit test for the property 'NotrequiredNotnullableArrayOfString' + } + } +} diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs index afe118039335..785e887d37f9 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/FakeApi.cs @@ -158,6 +158,26 @@ public interface IFakeApiSync : IApiAccessor /// ApiResponse of List<OuterEnum> ApiResponse> GetArrayOfEnumsWithHttpInfo(int operationIndex = 0); /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0); + /// /// /// /// @@ -248,7 +268,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// Index associated with the operation. /// - void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); + void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -273,7 +293,7 @@ public interface IFakeApiSync : IApiAccessor /// None (optional) /// Index associated with the operation. /// ApiResponse of Object(void) - ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); + ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0); /// /// To test enum parameters /// @@ -603,6 +623,31 @@ public interface IFakeApiAsync : IApiAccessor /// Task of ApiResponse (List<OuterEnum>) System.Threading.Tasks.Task>> GetArrayOfEnumsWithHttpInfoAsync(int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + + /// + /// test referenced additionalProperties + /// + /// + /// + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + /// /// /// /// @@ -703,7 +748,7 @@ public interface IFakeApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of void - System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -729,7 +774,7 @@ public interface IFakeApiAsync : IApiAccessor /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse - System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); + System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)); /// /// To test enum parameters /// @@ -1836,6 +1881,148 @@ public Org.OpenAPITools.Client.ApiResponse> GetArrayOfEnumsWithH return localVarResponse; } + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// + public void TestAdditionalPropertiesReference(Dictionary requestBody, int operationIndex = 0) + { + TestAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// ApiResponse of Object(void) + public Org.OpenAPITools.Client.ApiResponse TestAdditionalPropertiesReferenceWithHttpInfo(Dictionary requestBody, int operationIndex = 0) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = this.Client.Post("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration); + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of void + public async System.Threading.Tasks.Task TestAdditionalPropertiesReferenceAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + await TestAdditionalPropertiesReferenceWithHttpInfoAsync(requestBody, operationIndex, cancellationToken).ConfigureAwait(false); + } + + /// + /// test referenced additionalProperties + /// + /// Thrown when fails to make API call + /// request body + /// Index associated with the operation. + /// Cancellation Token to cancel the request. + /// Task of ApiResponse + public async System.Threading.Tasks.Task> TestAdditionalPropertiesReferenceWithHttpInfoAsync(Dictionary requestBody, int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + { + // verify the required parameter 'requestBody' is set + if (requestBody == null) + { + throw new Org.OpenAPITools.Client.ApiException(400, "Missing required parameter 'requestBody' when calling FakeApi->TestAdditionalPropertiesReference"); + } + + + Org.OpenAPITools.Client.RequestOptions localVarRequestOptions = new Org.OpenAPITools.Client.RequestOptions(); + + string[] _contentTypes = new string[] { + "application/json" + }; + + // to determine the Accept header + string[] _accepts = new string[] { + }; + + var localVarContentType = Org.OpenAPITools.Client.ClientUtils.SelectHeaderContentType(_contentTypes); + if (localVarContentType != null) + { + localVarRequestOptions.HeaderParameters.Add("Content-Type", localVarContentType); + } + + var localVarAccept = Org.OpenAPITools.Client.ClientUtils.SelectHeaderAccept(_accepts); + if (localVarAccept != null) + { + localVarRequestOptions.HeaderParameters.Add("Accept", localVarAccept); + } + + localVarRequestOptions.Data = requestBody; + + localVarRequestOptions.Operation = "FakeApi.TestAdditionalPropertiesReference"; + localVarRequestOptions.OperationIndex = operationIndex; + + + // make the HTTP request + var localVarResponse = await this.AsynchronousClient.PostAsync("/fake/additionalProperties-reference", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); + + if (this.ExceptionFactory != null) + { + Exception _exception = this.ExceptionFactory("TestAdditionalPropertiesReference", localVarResponse); + if (_exception != null) + { + throw _exception; + } + } + + return localVarResponse; + } + /// /// For this test, the body for this request much reference a schema named `File`. /// @@ -2304,7 +2491,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Index associated with the operation. /// - public void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) + public void TestEndpointParameters(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) { TestEndpointParametersWithHttpInfo(number, varDouble, patternWithoutDelimiter, varByte, integer, int32, int64, varFloat, varString, binary, date, dateTime, password, callback); } @@ -2329,7 +2516,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// None (optional) /// Index associated with the operation. /// ApiResponse of Object(void) - public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) + public Org.OpenAPITools.Client.ApiResponse TestEndpointParametersWithHttpInfo(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) @@ -2455,7 +2642,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of void - public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task TestEndpointParametersAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { await TestEndpointParametersWithHttpInfoAsync(number, varDouble, patternWithoutDelimiter, varByte, integer, int32, int64, varFloat, varString, binary, date, dateTime, password, callback, operationIndex, cancellationToken).ConfigureAwait(false); } @@ -2481,7 +2668,7 @@ public Org.OpenAPITools.Client.ApiResponse TestClientModelWithHttpI /// Index associated with the operation. /// Cancellation Token to cancel the request. /// Task of ApiResponse - public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateTime? date = default(DateTime?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) + public async System.Threading.Tasks.Task> TestEndpointParametersWithHttpInfoAsync(decimal number, double varDouble, string patternWithoutDelimiter, byte[] varByte, int? integer = default(int?), int? int32 = default(int?), long? int64 = default(long?), float? varFloat = default(float?), string? varString = default(string?), System.IO.Stream? binary = default(System.IO.Stream?), DateOnly? date = default(DateOnly?), DateTime? dateTime = default(DateTime?), string? password = default(string?), string? callback = default(string?), int operationIndex = 0, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // verify the required parameter 'patternWithoutDelimiter' is set if (patternWithoutDelimiter == null) diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs index cb1a5d8b24d1..f86ff3fb795e 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Api/PetApi.cs @@ -1461,6 +1461,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = this.Client.Get("/pet/{petId}", localVarRequestOptions, this.Configuration); @@ -1534,6 +1539,11 @@ public Org.OpenAPITools.Client.ApiResponse GetPetByIdWithHttpInfo(long petI { localVarRequestOptions.HeaderParameters.Add("api_key", this.Configuration.GetApiKeyWithPrefix("api_key")); } + // authentication (api_key_query) required + if (!string.IsNullOrEmpty(this.Configuration.GetApiKeyWithPrefix("api_key_query"))) + { + localVarRequestOptions.QueryParameters.Add(Org.OpenAPITools.Client.ClientUtils.ParameterToMultiMap("", "api_key_query", this.Configuration.GetApiKeyWithPrefix("api_key_query"))); + } // make the HTTP request var localVarResponse = await this.AsynchronousClient.GetAsync("/pet/{petId}", localVarRequestOptions, this.Configuration, cancellationToken).ConfigureAwait(false); diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs index b9c53cd6b62b..b10e49166a65 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ApiClient.cs @@ -562,7 +562,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs index 8e33ee2d9b5b..d5acb18947c2 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs index d98d2815297d..0685800345a1 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Client/HttpSigningConfiguration.cs @@ -110,14 +110,13 @@ internal Dictionary GetHttpSignedHeader(string basePath,string m const string HEADER_AUTHORIZATION = "Authorization"; //Read the api key from the file - if(string.IsNullOrEmpty(this.KeyString)) + if(File.Exists(KeyFilePath)) { this.KeyString = ReadApiKeyFromFile(KeyFilePath); } - - if(string.IsNullOrEmpty(KeyString)) + else if(string.IsNullOrEmpty(KeyString)) { - throw new Exception("No API key has been provided."); + throw new Exception("No API key has been provided. Supply it using either KeyFilePath or KeyString"); } //Hash table to store singed headers @@ -325,6 +324,10 @@ private int GetUnixTime(DateTime date2) private string GetRSASignature(byte[] stringToSign) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } RSA rsa = GetRSAProviderFromPemFile(KeyString, KeyPassPhrase); if (SigningAlgorithm == "RSASSA-PSS") { @@ -349,8 +352,10 @@ private string GetRSASignature(byte[] stringToSign) /// ECDSA signature private string GetECDSASignature(byte[] dataToSign) { - if (!File.Exists(KeyFilePath)) - throw new Exception("key file path does not exist."); + if (!File.Exists(KeyFilePath) && string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } var keyStr = KeyString; const string ecKeyHeader = "-----BEGIN EC PRIVATE KEY-----"; @@ -446,6 +451,11 @@ private byte[] ConvertToECDSAANS1Format(byte[] signedBytes) private RSACryptoServiceProvider GetRSAProviderFromPemFile(string keyString, SecureString keyPassPhrase = null) { + if (string.IsNullOrEmpty(KeyString)) + { + throw new Exception("No API key has been provided."); + } + const string pempubheader = "-----BEGIN PUBLIC KEY-----"; const string pempubfooter = "-----END PUBLIC KEY-----"; bool isPrivateKeyFile = true; diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs index 06722c456583..fcfcb93317e9 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/ChildCat.cs @@ -51,17 +51,22 @@ public enum PetTypeEnum /// /// Gets or Sets PetType /// - [DataMember(Name = "pet_type", EmitDefaultValue = false)] - public PetTypeEnum? PetType { get; set; } + [DataMember(Name = "pet_type", IsRequired = true, EmitDefaultValue = true)] + public PetTypeEnum PetType { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected ChildCat() { } /// /// Initializes a new instance of the class. /// /// name. - /// petType (default to PetTypeEnum.ChildCat). - public ChildCat(string name = default(string), PetTypeEnum? petType = PetTypeEnum.ChildCat) : base() + /// petType (required) (default to PetTypeEnum.ChildCat). + public ChildCat(string name = default(string), PetTypeEnum petType = PetTypeEnum.ChildCat) : base() { - this.Name = name; this.PetType = petType; + this.Name = name; } /// diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/DateOnlyClass.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/DateOnlyClass.cs index 3382d11be96d..4b9ee8fe482f 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/DateOnlyClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/DateOnlyClass.cs @@ -36,7 +36,7 @@ public partial class DateOnlyClass : IEquatable, IValidatableObje /// Initializes a new instance of the class. /// /// dateOnlyProperty. - public DateOnlyClass(DateTime dateOnlyProperty = default(DateTime)) + public DateOnlyClass(DateOnly dateOnlyProperty = default(DateOnly)) { this.DateOnlyProperty = dateOnlyProperty; } @@ -47,7 +47,7 @@ public partial class DateOnlyClass : IEquatable, IValidatableObje /// Fri Jul 21 00:00:00 UTC 2017 [DataMember(Name = "dateOnlyProperty", EmitDefaultValue = false)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime DateOnlyProperty { get; set; } + public DateOnly DateOnlyProperty { get; set; } /// /// Returns the string presentation of the object diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs index d5d633ed3b31..1d18a58b117a 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Drawing.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Drawing /// [DataContract(Name = "Drawing")] - public partial class Drawing : Dictionary, IEquatable, IValidatableObject + public partial class Drawing : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -39,7 +39,7 @@ public partial class Drawing : Dictionary, IEquatable, I /// shapeOrNull. /// nullableShape. /// shapes. - public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) : base() + public Drawing(Shape mainShape = default(Shape), ShapeOrNull shapeOrNull = default(ShapeOrNull), NullableShape nullableShape = default(NullableShape), List shapes = default(List)) { this.MainShape = mainShape; this.ShapeOrNull = shapeOrNull; @@ -86,7 +86,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Drawing {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" MainShape: ").Append(MainShape).Append("\n"); sb.Append(" ShapeOrNull: ").Append(ShapeOrNull).Append("\n"); sb.Append(" NullableShape: ").Append(NullableShape).Append("\n"); @@ -100,7 +99,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -133,7 +132,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.MainShape != null) { hashCode = (hashCode * 59) + this.MainShape.GetHashCode(); @@ -164,16 +163,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs index d5e9e3c94d41..082635330ade 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/FormatTest.cs @@ -59,7 +59,7 @@ protected FormatTest() { } /// A string that is a 10 digit number. Can have leading zeros.. /// A string starting with 'image_' (case insensitive) and one to three digits following i.e. Image_01.. /// None. - public FormatTest(int integer = default(int), int int32 = default(int), uint unsignedInteger = default(uint), long int64 = default(long), ulong unsignedLong = default(ulong), decimal number = default(decimal), float varFloat = default(float), double varDouble = default(double), decimal varDecimal = default(decimal), string varString = default(string), byte[] varByte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateTime date = default(DateTime), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string), string patternWithBackslash = default(string)) + public FormatTest(int integer = default(int), int int32 = default(int), uint unsignedInteger = default(uint), long int64 = default(long), ulong unsignedLong = default(ulong), decimal number = default(decimal), float varFloat = default(float), double varDouble = default(double), decimal varDecimal = default(decimal), string varString = default(string), byte[] varByte = default(byte[]), System.IO.Stream binary = default(System.IO.Stream), DateOnly date = default(DateOnly), DateTime dateTime = default(DateTime), Guid uuid = default(Guid), string password = default(string), string patternWithDigits = default(string), string patternWithDigitsAndDelimiter = default(string), string patternWithBackslash = default(string)) { this.Number = number; // to ensure "varByte" is required (not null) @@ -68,6 +68,11 @@ protected FormatTest() { } throw new ArgumentNullException("varByte is a required property for FormatTest and cannot be null"); } this.VarByte = varByte; + // to ensure "date" is required (not null) + if (date == null) + { + throw new ArgumentNullException("date is a required property for FormatTest and cannot be null"); + } this.Date = date; // to ensure "password" is required (not null) if (password == null) @@ -170,7 +175,7 @@ protected FormatTest() { } /// Sun Feb 02 00:00:00 UTC 2020 [DataMember(Name = "date", IsRequired = true, EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime Date { get; set; } + public DateOnly Date { get; set; } /// /// Gets or Sets DateTime diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs index 919ed331163d..43fe8c921031 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/NullableClass.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// NullableClass /// [DataContract(Name = "NullableClass")] - public partial class NullableClass : Dictionary, IEquatable, IValidatableObject + public partial class NullableClass : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. @@ -47,7 +47,7 @@ public partial class NullableClass : Dictionary, IEquatableobjectNullableProp. /// objectAndItemsNullableProp. /// objectItemsNullable. - public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateTime? dateProp = default(DateTime?), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) : base() + public NullableClass(int? integerProp = default(int?), decimal? numberProp = default(decimal?), bool? booleanProp = default(bool?), string stringProp = default(string), DateOnly dateProp = default(DateOnly), DateTime? datetimeProp = default(DateTime?), List arrayNullableProp = default(List), List arrayAndItemsNullableProp = default(List), List arrayItemsNullable = default(List), Dictionary objectNullableProp = default(Dictionary), Dictionary objectAndItemsNullableProp = default(Dictionary), Dictionary objectItemsNullable = default(Dictionary)) { this.IntegerProp = integerProp; this.NumberProp = numberProp; @@ -93,7 +93,7 @@ public partial class NullableClass : Dictionary, IEquatable [DataMember(Name = "date_prop", EmitDefaultValue = true)] [JsonConverter(typeof(OpenAPIDateConverter))] - public DateTime? DateProp { get; set; } + public DateOnly DateProp { get; set; } /// /// Gets or Sets DatetimeProp @@ -151,7 +151,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class NullableClass {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" IntegerProp: ").Append(IntegerProp).Append("\n"); sb.Append(" NumberProp: ").Append(NumberProp).Append("\n"); sb.Append(" BooleanProp: ").Append(BooleanProp).Append("\n"); @@ -173,7 +172,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -206,7 +205,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.IntegerProp != null) { hashCode = (hashCode * 59) + this.IntegerProp.GetHashCode(); @@ -269,16 +268,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/RequiredClass.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/RequiredClass.cs new file mode 100644 index 000000000000..93e4c273108f --- /dev/null +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/RequiredClass.cs @@ -0,0 +1,1032 @@ +/* + * OpenAPI Petstore + * + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * Generated by: https://github.com/openapitools/openapi-generator.git + */ + + +using System; +using System.Collections; +using System.Collections.Generic; +using System.Collections.ObjectModel; +using System.Linq; +using System.IO; +using System.Runtime.Serialization; +using System.Text; +using System.Text.RegularExpressions; +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using Newtonsoft.Json.Linq; +using System.ComponentModel.DataAnnotations; +using OpenAPIDateConverter = Org.OpenAPITools.Client.OpenAPIDateConverter; +using OpenAPIClientUtils = Org.OpenAPITools.Client.ClientUtils; + +namespace Org.OpenAPITools.Model +{ + /// + /// RequiredClass + /// + [DataContract(Name = "RequiredClass")] + public partial class RequiredClass : IEquatable, IValidatableObject + { + /// + /// Defines RequiredNullableEnumInteger + /// + public enum RequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNullableEnumInteger + /// + [DataMember(Name = "required_nullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerEnum RequiredNullableEnumInteger { get; set; } + /// + /// Defines RequiredNotnullableEnumInteger + /// + public enum RequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumInteger + /// + [DataMember(Name = "required_notnullable_enum_integer", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerEnum RequiredNotnullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNullableEnumInteger + /// + public enum NotrequiredNullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumInteger + /// + [DataMember(Name = "notrequired_nullable_enum_integer", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerEnum? NotrequiredNullableEnumInteger { get; set; } + /// + /// Defines NotrequiredNotnullableEnumInteger + /// + public enum NotrequiredNotnullableEnumIntegerEnum + { + /// + /// Enum NUMBER_1 for value: 1 + /// + NUMBER_1 = 1, + + /// + /// Enum NUMBER_MINUS_1 for value: -1 + /// + NUMBER_MINUS_1 = -1 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumInteger + /// + [DataMember(Name = "notrequired_notnullable_enum_integer", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerEnum? NotrequiredNotnullableEnumInteger { get; set; } + /// + /// Defines RequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "required_nullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumIntegerOnlyEnum RequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumIntegerOnly + /// + public enum RequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "required_notnullable_enum_integer_only", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumIntegerOnlyEnum RequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNullableEnumIntegerOnly + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_nullable_enum_integer_only", EmitDefaultValue = true)] + public NotrequiredNullableEnumIntegerOnlyEnum? NotrequiredNullableEnumIntegerOnly { get; set; } + /// + /// Defines NotrequiredNotnullableEnumIntegerOnly + /// + public enum NotrequiredNotnullableEnumIntegerOnlyEnum + { + /// + /// Enum NUMBER_2 for value: 2 + /// + NUMBER_2 = 2, + + /// + /// Enum NUMBER_MINUS_2 for value: -2 + /// + NUMBER_MINUS_2 = -2 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumIntegerOnly + /// + [DataMember(Name = "notrequired_notnullable_enum_integer_only", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumIntegerOnlyEnum? NotrequiredNotnullableEnumIntegerOnly { get; set; } + /// + /// Defines RequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNotnullableEnumString + /// + [DataMember(Name = "required_notnullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNotnullableEnumStringEnum RequiredNotnullableEnumString { get; set; } + /// + /// Defines RequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum RequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets RequiredNullableEnumString + /// + [DataMember(Name = "required_nullable_enum_string", IsRequired = true, EmitDefaultValue = true)] + public RequiredNullableEnumStringEnum RequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNullableEnumString + /// + [DataMember(Name = "notrequired_nullable_enum_string", EmitDefaultValue = true)] + public NotrequiredNullableEnumStringEnum? NotrequiredNullableEnumString { get; set; } + /// + /// Defines NotrequiredNotnullableEnumString + /// + [JsonConverter(typeof(StringEnumConverter))] + public enum NotrequiredNotnullableEnumStringEnum + { + /// + /// Enum UPPER for value: UPPER + /// + [EnumMember(Value = "UPPER")] + UPPER = 1, + + /// + /// Enum Lower for value: lower + /// + [EnumMember(Value = "lower")] + Lower = 2, + + /// + /// Enum Empty for value: + /// + [EnumMember(Value = "")] + Empty = 3, + + /// + /// Enum ValuewithTab for value: Value\twith tab + /// + [EnumMember(Value = "Value\twith tab")] + ValuewithTab = 4, + + /// + /// Enum ValueWithQuote for value: Value with \" quote + /// + [EnumMember(Value = "Value with \" quote")] + ValueWithQuote = 5, + + /// + /// Enum ValueWithEscapedQuote for value: Value with escaped \" quote + /// + [EnumMember(Value = "Value with escaped \" quote")] + ValueWithEscapedQuote = 6, + + /// + /// Enum Duplicatevalue for value: Duplicate\nvalue + /// + [EnumMember(Value = "Duplicate\nvalue")] + Duplicatevalue = 7, + + /// + /// Enum Duplicatevalue2 for value: Duplicate\r\nvalue + /// + [EnumMember(Value = "Duplicate\r\nvalue")] + Duplicatevalue2 = 8 + } + + + /// + /// Gets or Sets NotrequiredNotnullableEnumString + /// + [DataMember(Name = "notrequired_notnullable_enum_string", EmitDefaultValue = false)] + public NotrequiredNotnullableEnumStringEnum? NotrequiredNotnullableEnumString { get; set; } + + /// + /// Gets or Sets RequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_nullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets RequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "required_notnullable_outerEnumDefaultValue", IsRequired = true, EmitDefaultValue = true)] + public OuterEnumDefaultValue RequiredNotnullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_nullable_outerEnumDefaultValue", EmitDefaultValue = true)] + public OuterEnumDefaultValue? NotrequiredNullableOuterEnumDefaultValue { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableOuterEnumDefaultValue + /// + [DataMember(Name = "notrequired_notnullable_outerEnumDefaultValue", EmitDefaultValue = false)] + public OuterEnumDefaultValue? NotrequiredNotnullableOuterEnumDefaultValue { get; set; } + /// + /// Initializes a new instance of the class. + /// + [JsonConstructorAttribute] + protected RequiredClass() { } + /// + /// Initializes a new instance of the class. + /// + /// requiredNullableIntegerProp (required). + /// requiredNotnullableintegerProp (required). + /// notRequiredNullableIntegerProp. + /// notRequiredNotnullableintegerProp. + /// requiredNullableStringProp (required). + /// requiredNotnullableStringProp (required). + /// notrequiredNullableStringProp. + /// notrequiredNotnullableStringProp. + /// requiredNullableBooleanProp (required). + /// requiredNotnullableBooleanProp (required). + /// notrequiredNullableBooleanProp. + /// notrequiredNotnullableBooleanProp. + /// requiredNullableDateProp (required). + /// requiredNotNullableDateProp (required). + /// notRequiredNullableDateProp. + /// notRequiredNotnullableDateProp. + /// requiredNotnullableDatetimeProp (required). + /// requiredNullableDatetimeProp (required). + /// notrequiredNullableDatetimeProp. + /// notrequiredNotnullableDatetimeProp. + /// requiredNullableEnumInteger (required). + /// requiredNotnullableEnumInteger (required). + /// notrequiredNullableEnumInteger. + /// notrequiredNotnullableEnumInteger. + /// requiredNullableEnumIntegerOnly (required). + /// requiredNotnullableEnumIntegerOnly (required). + /// notrequiredNullableEnumIntegerOnly. + /// notrequiredNotnullableEnumIntegerOnly. + /// requiredNotnullableEnumString (required). + /// requiredNullableEnumString (required). + /// notrequiredNullableEnumString. + /// notrequiredNotnullableEnumString. + /// requiredNullableOuterEnumDefaultValue (required). + /// requiredNotnullableOuterEnumDefaultValue (required). + /// notrequiredNullableOuterEnumDefaultValue. + /// notrequiredNotnullableOuterEnumDefaultValue. + /// requiredNullableUuid (required). + /// requiredNotnullableUuid (required). + /// notrequiredNullableUuid. + /// notrequiredNotnullableUuid. + /// requiredNullableArrayOfString (required). + /// requiredNotnullableArrayOfString (required). + /// notrequiredNullableArrayOfString. + /// notrequiredNotnullableArrayOfString. + public RequiredClass(int? requiredNullableIntegerProp = default(int?), int requiredNotnullableintegerProp = default(int), int? notRequiredNullableIntegerProp = default(int?), int notRequiredNotnullableintegerProp = default(int), string requiredNullableStringProp = default(string), string requiredNotnullableStringProp = default(string), string notrequiredNullableStringProp = default(string), string notrequiredNotnullableStringProp = default(string), bool? requiredNullableBooleanProp = default(bool?), bool requiredNotnullableBooleanProp = default(bool), bool? notrequiredNullableBooleanProp = default(bool?), bool notrequiredNotnullableBooleanProp = default(bool), DateOnly requiredNullableDateProp = default(DateOnly), DateOnly requiredNotNullableDateProp = default(DateOnly), DateOnly notRequiredNullableDateProp = default(DateOnly), DateOnly notRequiredNotnullableDateProp = default(DateOnly), DateTime requiredNotnullableDatetimeProp = default(DateTime), DateTime? requiredNullableDatetimeProp = default(DateTime?), DateTime? notrequiredNullableDatetimeProp = default(DateTime?), DateTime notrequiredNotnullableDatetimeProp = default(DateTime), RequiredNullableEnumIntegerEnum requiredNullableEnumInteger = default(RequiredNullableEnumIntegerEnum), RequiredNotnullableEnumIntegerEnum requiredNotnullableEnumInteger = default(RequiredNotnullableEnumIntegerEnum), NotrequiredNullableEnumIntegerEnum? notrequiredNullableEnumInteger = default(NotrequiredNullableEnumIntegerEnum?), NotrequiredNotnullableEnumIntegerEnum? notrequiredNotnullableEnumInteger = default(NotrequiredNotnullableEnumIntegerEnum?), RequiredNullableEnumIntegerOnlyEnum requiredNullableEnumIntegerOnly = default(RequiredNullableEnumIntegerOnlyEnum), RequiredNotnullableEnumIntegerOnlyEnum requiredNotnullableEnumIntegerOnly = default(RequiredNotnullableEnumIntegerOnlyEnum), NotrequiredNullableEnumIntegerOnlyEnum? notrequiredNullableEnumIntegerOnly = default(NotrequiredNullableEnumIntegerOnlyEnum?), NotrequiredNotnullableEnumIntegerOnlyEnum? notrequiredNotnullableEnumIntegerOnly = default(NotrequiredNotnullableEnumIntegerOnlyEnum?), RequiredNotnullableEnumStringEnum requiredNotnullableEnumString = default(RequiredNotnullableEnumStringEnum), RequiredNullableEnumStringEnum requiredNullableEnumString = default(RequiredNullableEnumStringEnum), NotrequiredNullableEnumStringEnum? notrequiredNullableEnumString = default(NotrequiredNullableEnumStringEnum?), NotrequiredNotnullableEnumStringEnum? notrequiredNotnullableEnumString = default(NotrequiredNotnullableEnumStringEnum?), OuterEnumDefaultValue requiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue requiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue), OuterEnumDefaultValue? notrequiredNullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), OuterEnumDefaultValue? notrequiredNotnullableOuterEnumDefaultValue = default(OuterEnumDefaultValue?), Guid? requiredNullableUuid = default(Guid?), Guid requiredNotnullableUuid = default(Guid), Guid? notrequiredNullableUuid = default(Guid?), Guid notrequiredNotnullableUuid = default(Guid), List requiredNullableArrayOfString = default(List), List requiredNotnullableArrayOfString = default(List), List notrequiredNullableArrayOfString = default(List), List notrequiredNotnullableArrayOfString = default(List)) + { + // to ensure "requiredNullableIntegerProp" is required (not null) + if (requiredNullableIntegerProp == null) + { + throw new ArgumentNullException("requiredNullableIntegerProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableIntegerProp = requiredNullableIntegerProp; + this.RequiredNotnullableintegerProp = requiredNotnullableintegerProp; + // to ensure "requiredNullableStringProp" is required (not null) + if (requiredNullableStringProp == null) + { + throw new ArgumentNullException("requiredNullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableStringProp = requiredNullableStringProp; + // to ensure "requiredNotnullableStringProp" is required (not null) + if (requiredNotnullableStringProp == null) + { + throw new ArgumentNullException("requiredNotnullableStringProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableStringProp = requiredNotnullableStringProp; + // to ensure "requiredNullableBooleanProp" is required (not null) + if (requiredNullableBooleanProp == null) + { + throw new ArgumentNullException("requiredNullableBooleanProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableBooleanProp = requiredNullableBooleanProp; + this.RequiredNotnullableBooleanProp = requiredNotnullableBooleanProp; + // to ensure "requiredNullableDateProp" is required (not null) + if (requiredNullableDateProp == null) + { + throw new ArgumentNullException("requiredNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDateProp = requiredNullableDateProp; + // to ensure "requiredNotNullableDateProp" is required (not null) + if (requiredNotNullableDateProp == null) + { + throw new ArgumentNullException("requiredNotNullableDateProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotNullableDateProp = requiredNotNullableDateProp; + this.RequiredNotnullableDatetimeProp = requiredNotnullableDatetimeProp; + // to ensure "requiredNullableDatetimeProp" is required (not null) + if (requiredNullableDatetimeProp == null) + { + throw new ArgumentNullException("requiredNullableDatetimeProp is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableDatetimeProp = requiredNullableDatetimeProp; + this.RequiredNullableEnumInteger = requiredNullableEnumInteger; + this.RequiredNotnullableEnumInteger = requiredNotnullableEnumInteger; + this.RequiredNullableEnumIntegerOnly = requiredNullableEnumIntegerOnly; + this.RequiredNotnullableEnumIntegerOnly = requiredNotnullableEnumIntegerOnly; + this.RequiredNotnullableEnumString = requiredNotnullableEnumString; + this.RequiredNullableEnumString = requiredNullableEnumString; + this.RequiredNullableOuterEnumDefaultValue = requiredNullableOuterEnumDefaultValue; + this.RequiredNotnullableOuterEnumDefaultValue = requiredNotnullableOuterEnumDefaultValue; + // to ensure "requiredNullableUuid" is required (not null) + if (requiredNullableUuid == null) + { + throw new ArgumentNullException("requiredNullableUuid is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableUuid = requiredNullableUuid; + this.RequiredNotnullableUuid = requiredNotnullableUuid; + // to ensure "requiredNullableArrayOfString" is required (not null) + if (requiredNullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNullableArrayOfString = requiredNullableArrayOfString; + // to ensure "requiredNotnullableArrayOfString" is required (not null) + if (requiredNotnullableArrayOfString == null) + { + throw new ArgumentNullException("requiredNotnullableArrayOfString is a required property for RequiredClass and cannot be null"); + } + this.RequiredNotnullableArrayOfString = requiredNotnullableArrayOfString; + this.NotRequiredNullableIntegerProp = notRequiredNullableIntegerProp; + this.NotRequiredNotnullableintegerProp = notRequiredNotnullableintegerProp; + this.NotrequiredNullableStringProp = notrequiredNullableStringProp; + this.NotrequiredNotnullableStringProp = notrequiredNotnullableStringProp; + this.NotrequiredNullableBooleanProp = notrequiredNullableBooleanProp; + this.NotrequiredNotnullableBooleanProp = notrequiredNotnullableBooleanProp; + this.NotRequiredNullableDateProp = notRequiredNullableDateProp; + this.NotRequiredNotnullableDateProp = notRequiredNotnullableDateProp; + this.NotrequiredNullableDatetimeProp = notrequiredNullableDatetimeProp; + this.NotrequiredNotnullableDatetimeProp = notrequiredNotnullableDatetimeProp; + this.NotrequiredNullableEnumInteger = notrequiredNullableEnumInteger; + this.NotrequiredNotnullableEnumInteger = notrequiredNotnullableEnumInteger; + this.NotrequiredNullableEnumIntegerOnly = notrequiredNullableEnumIntegerOnly; + this.NotrequiredNotnullableEnumIntegerOnly = notrequiredNotnullableEnumIntegerOnly; + this.NotrequiredNullableEnumString = notrequiredNullableEnumString; + this.NotrequiredNotnullableEnumString = notrequiredNotnullableEnumString; + this.NotrequiredNullableOuterEnumDefaultValue = notrequiredNullableOuterEnumDefaultValue; + this.NotrequiredNotnullableOuterEnumDefaultValue = notrequiredNotnullableOuterEnumDefaultValue; + this.NotrequiredNullableUuid = notrequiredNullableUuid; + this.NotrequiredNotnullableUuid = notrequiredNotnullableUuid; + this.NotrequiredNullableArrayOfString = notrequiredNullableArrayOfString; + this.NotrequiredNotnullableArrayOfString = notrequiredNotnullableArrayOfString; + } + + /// + /// Gets or Sets RequiredNullableIntegerProp + /// + [DataMember(Name = "required_nullable_integer_prop", IsRequired = true, EmitDefaultValue = true)] + public int? RequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableintegerProp + /// + [DataMember(Name = "required_notnullableinteger_prop", IsRequired = true, EmitDefaultValue = true)] + public int RequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableIntegerProp + /// + [DataMember(Name = "not_required_nullable_integer_prop", EmitDefaultValue = true)] + public int? NotRequiredNullableIntegerProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableintegerProp + /// + [DataMember(Name = "not_required_notnullableinteger_prop", EmitDefaultValue = false)] + public int NotRequiredNotnullableintegerProp { get; set; } + + /// + /// Gets or Sets RequiredNullableStringProp + /// + [DataMember(Name = "required_nullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableStringProp + /// + [DataMember(Name = "required_notnullable_string_prop", IsRequired = true, EmitDefaultValue = true)] + public string RequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableStringProp + /// + [DataMember(Name = "notrequired_nullable_string_prop", EmitDefaultValue = true)] + public string NotrequiredNullableStringProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableStringProp + /// + [DataMember(Name = "notrequired_notnullable_string_prop", EmitDefaultValue = false)] + public string NotrequiredNotnullableStringProp { get; set; } + + /// + /// Gets or Sets RequiredNullableBooleanProp + /// + [DataMember(Name = "required_nullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool? RequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableBooleanProp + /// + [DataMember(Name = "required_notnullable_boolean_prop", IsRequired = true, EmitDefaultValue = true)] + public bool RequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableBooleanProp + /// + [DataMember(Name = "notrequired_nullable_boolean_prop", EmitDefaultValue = true)] + public bool? NotrequiredNullableBooleanProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableBooleanProp + /// + [DataMember(Name = "notrequired_notnullable_boolean_prop", EmitDefaultValue = true)] + public bool NotrequiredNotnullableBooleanProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDateProp + /// + [DataMember(Name = "required_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly RequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotNullableDateProp + /// + [DataMember(Name = "required_not_nullable_date_prop", IsRequired = true, EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly RequiredNotNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNullableDateProp + /// + [DataMember(Name = "not_required_nullable_date_prop", EmitDefaultValue = true)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly NotRequiredNullableDateProp { get; set; } + + /// + /// Gets or Sets NotRequiredNotnullableDateProp + /// + [DataMember(Name = "not_required_notnullable_date_prop", EmitDefaultValue = false)] + [JsonConverter(typeof(OpenAPIDateConverter))] + public DateOnly NotRequiredNotnullableDateProp { get; set; } + + /// + /// Gets or Sets RequiredNotnullableDatetimeProp + /// + [DataMember(Name = "required_notnullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime RequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableDatetimeProp + /// + [DataMember(Name = "required_nullable_datetime_prop", IsRequired = true, EmitDefaultValue = true)] + public DateTime? RequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNullableDatetimeProp + /// + [DataMember(Name = "notrequired_nullable_datetime_prop", EmitDefaultValue = true)] + public DateTime? NotrequiredNullableDatetimeProp { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableDatetimeProp + /// + [DataMember(Name = "notrequired_notnullable_datetime_prop", EmitDefaultValue = false)] + public DateTime NotrequiredNotnullableDatetimeProp { get; set; } + + /// + /// Gets or Sets RequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_nullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid? RequiredNullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "required_notnullable_uuid", IsRequired = true, EmitDefaultValue = true)] + public Guid RequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_nullable_uuid", EmitDefaultValue = true)] + public Guid? NotrequiredNullableUuid { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableUuid + /// + /// 72f98069-206d-4f12-9f12-3d1e525a8e84 + [DataMember(Name = "notrequired_notnullable_uuid", EmitDefaultValue = false)] + public Guid NotrequiredNotnullableUuid { get; set; } + + /// + /// Gets or Sets RequiredNullableArrayOfString + /// + [DataMember(Name = "required_nullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets RequiredNotnullableArrayOfString + /// + [DataMember(Name = "required_notnullable_array_of_string", IsRequired = true, EmitDefaultValue = true)] + public List RequiredNotnullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNullableArrayOfString + /// + [DataMember(Name = "notrequired_nullable_array_of_string", EmitDefaultValue = true)] + public List NotrequiredNullableArrayOfString { get; set; } + + /// + /// Gets or Sets NotrequiredNotnullableArrayOfString + /// + [DataMember(Name = "notrequired_notnullable_array_of_string", EmitDefaultValue = false)] + public List NotrequiredNotnullableArrayOfString { get; set; } + + /// + /// Returns the string presentation of the object + /// + /// String presentation of the object + public override string ToString() + { + StringBuilder sb = new StringBuilder(); + sb.Append("class RequiredClass {\n"); + sb.Append(" RequiredNullableIntegerProp: ").Append(RequiredNullableIntegerProp).Append("\n"); + sb.Append(" RequiredNotnullableintegerProp: ").Append(RequiredNotnullableintegerProp).Append("\n"); + sb.Append(" NotRequiredNullableIntegerProp: ").Append(NotRequiredNullableIntegerProp).Append("\n"); + sb.Append(" NotRequiredNotnullableintegerProp: ").Append(NotRequiredNotnullableintegerProp).Append("\n"); + sb.Append(" RequiredNullableStringProp: ").Append(RequiredNullableStringProp).Append("\n"); + sb.Append(" RequiredNotnullableStringProp: ").Append(RequiredNotnullableStringProp).Append("\n"); + sb.Append(" NotrequiredNullableStringProp: ").Append(NotrequiredNullableStringProp).Append("\n"); + sb.Append(" NotrequiredNotnullableStringProp: ").Append(NotrequiredNotnullableStringProp).Append("\n"); + sb.Append(" RequiredNullableBooleanProp: ").Append(RequiredNullableBooleanProp).Append("\n"); + sb.Append(" RequiredNotnullableBooleanProp: ").Append(RequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNullableBooleanProp: ").Append(NotrequiredNullableBooleanProp).Append("\n"); + sb.Append(" NotrequiredNotnullableBooleanProp: ").Append(NotrequiredNotnullableBooleanProp).Append("\n"); + sb.Append(" RequiredNullableDateProp: ").Append(RequiredNullableDateProp).Append("\n"); + sb.Append(" RequiredNotNullableDateProp: ").Append(RequiredNotNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNullableDateProp: ").Append(NotRequiredNullableDateProp).Append("\n"); + sb.Append(" NotRequiredNotnullableDateProp: ").Append(NotRequiredNotnullableDateProp).Append("\n"); + sb.Append(" RequiredNotnullableDatetimeProp: ").Append(RequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableDatetimeProp: ").Append(RequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNullableDatetimeProp: ").Append(NotrequiredNullableDatetimeProp).Append("\n"); + sb.Append(" NotrequiredNotnullableDatetimeProp: ").Append(NotrequiredNotnullableDatetimeProp).Append("\n"); + sb.Append(" RequiredNullableEnumInteger: ").Append(RequiredNullableEnumInteger).Append("\n"); + sb.Append(" RequiredNotnullableEnumInteger: ").Append(RequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNullableEnumInteger: ").Append(NotrequiredNullableEnumInteger).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumInteger: ").Append(NotrequiredNotnullableEnumInteger).Append("\n"); + sb.Append(" RequiredNullableEnumIntegerOnly: ").Append(RequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumIntegerOnly: ").Append(RequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNullableEnumIntegerOnly: ").Append(NotrequiredNullableEnumIntegerOnly).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumIntegerOnly: ").Append(NotrequiredNotnullableEnumIntegerOnly).Append("\n"); + sb.Append(" RequiredNotnullableEnumString: ").Append(RequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableEnumString: ").Append(RequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNullableEnumString: ").Append(NotrequiredNullableEnumString).Append("\n"); + sb.Append(" NotrequiredNotnullableEnumString: ").Append(NotrequiredNotnullableEnumString).Append("\n"); + sb.Append(" RequiredNullableOuterEnumDefaultValue: ").Append(RequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNotnullableOuterEnumDefaultValue: ").Append(RequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNullableOuterEnumDefaultValue: ").Append(NotrequiredNullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" NotrequiredNotnullableOuterEnumDefaultValue: ").Append(NotrequiredNotnullableOuterEnumDefaultValue).Append("\n"); + sb.Append(" RequiredNullableUuid: ").Append(RequiredNullableUuid).Append("\n"); + sb.Append(" RequiredNotnullableUuid: ").Append(RequiredNotnullableUuid).Append("\n"); + sb.Append(" NotrequiredNullableUuid: ").Append(NotrequiredNullableUuid).Append("\n"); + sb.Append(" NotrequiredNotnullableUuid: ").Append(NotrequiredNotnullableUuid).Append("\n"); + sb.Append(" RequiredNullableArrayOfString: ").Append(RequiredNullableArrayOfString).Append("\n"); + sb.Append(" RequiredNotnullableArrayOfString: ").Append(RequiredNotnullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNullableArrayOfString: ").Append(NotrequiredNullableArrayOfString).Append("\n"); + sb.Append(" NotrequiredNotnullableArrayOfString: ").Append(NotrequiredNotnullableArrayOfString).Append("\n"); + sb.Append("}\n"); + return sb.ToString(); + } + + /// + /// Returns the JSON string presentation of the object + /// + /// JSON string presentation of the object + public virtual string ToJson() + { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + + /// + /// Returns true if objects are equal + /// + /// Object to be compared + /// Boolean + public override bool Equals(object input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input as RequiredClass).AreEqual; + } + + /// + /// Returns true if RequiredClass instances are equal + /// + /// Instance of RequiredClass to be compared + /// Boolean + public bool Equals(RequiredClass input) + { + return OpenAPIClientUtils.compareLogic.Compare(this, input).AreEqual; + } + + /// + /// Gets the hash code + /// + /// Hash code + public override int GetHashCode() + { + unchecked // Overflow is fine, just wrap + { + int hashCode = 41; + if (this.RequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableintegerProp.GetHashCode(); + if (this.NotRequiredNullableIntegerProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableIntegerProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotRequiredNotnullableintegerProp.GetHashCode(); + if (this.RequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableStringProp.GetHashCode(); + } + if (this.RequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableStringProp.GetHashCode(); + } + if (this.NotrequiredNullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableStringProp.GetHashCode(); + } + if (this.NotrequiredNotnullableStringProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableStringProp.GetHashCode(); + } + if (this.RequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNotnullableBooleanProp.GetHashCode(); + if (this.NotrequiredNullableBooleanProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableBooleanProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.NotrequiredNotnullableBooleanProp.GetHashCode(); + if (this.RequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDateProp.GetHashCode(); + } + if (this.RequiredNotNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNullableDateProp.GetHashCode(); + } + if (this.NotRequiredNotnullableDateProp != null) + { + hashCode = (hashCode * 59) + this.NotRequiredNotnullableDateProp.GetHashCode(); + } + if (this.RequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableDatetimeProp.GetHashCode(); + } + if (this.RequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableDatetimeProp.GetHashCode(); + } + if (this.NotrequiredNotnullableDatetimeProp != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableDatetimeProp.GetHashCode(); + } + hashCode = (hashCode * 59) + this.RequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumInteger.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumIntegerOnly.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableEnumString.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.RequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNullableOuterEnumDefaultValue.GetHashCode(); + hashCode = (hashCode * 59) + this.NotrequiredNotnullableOuterEnumDefaultValue.GetHashCode(); + if (this.RequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableUuid.GetHashCode(); + } + if (this.RequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableUuid.GetHashCode(); + } + if (this.NotrequiredNullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableUuid.GetHashCode(); + } + if (this.NotrequiredNotnullableUuid != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableUuid.GetHashCode(); + } + if (this.RequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNullableArrayOfString.GetHashCode(); + } + if (this.RequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.RequiredNotnullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNullableArrayOfString.GetHashCode(); + } + if (this.NotrequiredNotnullableArrayOfString != null) + { + hashCode = (hashCode * 59) + this.NotrequiredNotnullableArrayOfString.GetHashCode(); + } + return hashCode; + } + } + + /// + /// To validate all properties of the instance + /// + /// Validation context + /// Validation Result + IEnumerable IValidatableObject.Validate(ValidationContext validationContext) + { + yield break; + } + } + +} diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs index e668ef1fe4ea..c56b9e336517 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/TestInlineFreeformAdditionalPropertiesRequest.cs @@ -30,13 +30,13 @@ namespace Org.OpenAPITools.Model /// TestInlineFreeformAdditionalPropertiesRequest /// [DataContract(Name = "testInlineFreeformAdditionalProperties_request")] - public partial class TestInlineFreeformAdditionalPropertiesRequest : Dictionary, IEquatable, IValidatableObject + public partial class TestInlineFreeformAdditionalPropertiesRequest : IEquatable, IValidatableObject { /// /// Initializes a new instance of the class. /// /// someProperty. - public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) : base() + public TestInlineFreeformAdditionalPropertiesRequest(string someProperty = default(string)) { this.SomeProperty = someProperty; this.AdditionalProperties = new Dictionary(); @@ -62,7 +62,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class TestInlineFreeformAdditionalPropertiesRequest {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" SomeProperty: ").Append(SomeProperty).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); @@ -73,7 +72,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -106,7 +105,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; if (this.SomeProperty != null) { hashCode = (hashCode * 59) + this.SomeProperty.GetHashCode(); @@ -125,16 +124,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs index 193c3be7973b..58ec23be816e 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Model/Zebra.cs @@ -30,7 +30,7 @@ namespace Org.OpenAPITools.Model /// Zebra /// [DataContract(Name = "zebra")] - public partial class Zebra : Dictionary, IEquatable, IValidatableObject + public partial class Zebra : IEquatable, IValidatableObject { /// /// Defines Type @@ -76,7 +76,7 @@ protected Zebra() /// /// type. /// className (required). - public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) : base() + public Zebra(TypeEnum? type = default(TypeEnum?), string className = default(string)) { // to ensure "className" is required (not null) if (className == null) @@ -108,7 +108,6 @@ public override string ToString() { StringBuilder sb = new StringBuilder(); sb.Append("class Zebra {\n"); - sb.Append(" ").Append(base.ToString().Replace("\n", "\n ")).Append("\n"); sb.Append(" Type: ").Append(Type).Append("\n"); sb.Append(" ClassName: ").Append(ClassName).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); @@ -120,7 +119,7 @@ public override string ToString() /// Returns the JSON string presentation of the object /// /// JSON string presentation of the object - public string ToJson() + public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } @@ -153,7 +152,7 @@ public override int GetHashCode() { unchecked // Overflow is fine, just wrap { - int hashCode = base.GetHashCode(); + int hashCode = 41; hashCode = (hashCode * 59) + this.Type.GetHashCode(); if (this.ClassName != null) { @@ -173,16 +172,6 @@ public override int GetHashCode() /// Validation context /// Validation Result IEnumerable IValidatableObject.Validate(ValidationContext validationContext) - { - return this.BaseValidate(validationContext); - } - - /// - /// To validate all properties of the instance - /// - /// Validation context - /// Validation Result - protected IEnumerable BaseValidate(ValidationContext validationContext) { yield break; } diff --git a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 8c0a21ddae8e..154b17942c57 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClientCore/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -21,11 +21,11 @@ - + - + diff --git a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION +++ b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs index 7577a84df0f5..4482bbdbfbc8 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ApiClient.cs @@ -561,7 +561,8 @@ private ApiResponse Exec(RestRequest request, RequestOptions options, IRea MaxTimeout = configuration.Timeout, Proxy = configuration.Proxy, UserAgent = configuration.UserAgent, - UseDefaultCredentials = configuration.UseDefaultCredentials + UseDefaultCredentials = configuration.UseDefaultCredentials, + RemoteCertificateValidationCallback = configuration.RemoteCertificateValidationCallback }; if (!string.IsNullOrEmpty(configuration.OAuthTokenUrl) && diff --git a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs index 4e45e6485db0..c68a06756f3a 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs +++ b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Client/ClientUtils.cs @@ -36,7 +36,9 @@ public static class ClientUtils /// static ClientUtils() { - compareLogic = new CompareLogic(); + ComparisonConfig comparisonConfig = new ComparisonConfig(); + comparisonConfig.UseHashCodeIdentifier = true; + compareLogic = new CompareLogic(comparisonConfig); } /// diff --git a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj index 508708497434..2acb240dfdee 100644 --- a/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj +++ b/samples/client/petstore/csharp/OpenAPIClientCoreAndNet47/src/Org.OpenAPITools/Org.OpenAPITools.csproj @@ -20,11 +20,11 @@ - + - + diff --git a/samples/client/petstore/elixir/.openapi-generator/VERSION b/samples/client/petstore/elixir/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/elixir/.openapi-generator/VERSION +++ b/samples/client/petstore/elixir/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex index 007d16552eb1..51eaf88a8aff 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/another_fake.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.AnotherFake do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex index d0f10334d062..582091e5464b 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/default.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.Default do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex index e21cc6d51d40..41fbe7a72904 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.Fake do @@ -273,6 +273,37 @@ defmodule OpenapiPetstore.Api.Fake do ]) end + @doc """ + test referenced additionalProperties + + + ### Parameters + + - `connection` (OpenapiPetstore.Connection): Connection to server + - `request_body` (%{optional(String.t) => any()}): request body + - `opts` (keyword): Optional parameters + + ### Returns + + - `{:ok, nil}` on success + - `{:error, Tesla.Env.t}` on failure + """ + @spec test_additional_properties_reference(Tesla.Env.client, %{optional(String.t) => AnyType.t}, keyword()) :: {:ok, nil} | {:error, Tesla.Env.t} + def test_additional_properties_reference(connection, request_body, _opts \\ []) do + request = + %{} + |> method(:post) + |> url("/fake/additionalProperties-reference") + |> add_param(:body, :body, request_body) + |> Enum.into([]) + + connection + |> Connection.request(request) + |> evaluate_response([ + {200, false} + ]) + end + @doc """ For this test, the body has to be a binary file. diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex index 6da0d3be1df3..680b5ac085f9 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/fake_classname_tags123.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.FakeClassnameTags123 do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex index 1dbb727febe2..a1d97abae839 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/pet.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.Pet do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex index c60587f49d7a..31cd41d2c817 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/store.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.Store do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex b/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex index f84ca7e672db..8d8514d5fa20 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/api/user.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Api.User do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex b/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex index 1fddbba77b53..5480760597d2 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/connection.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Connection do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex b/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex index 1c9e374f52b2..fb791614135a 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/deserializer.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Deserializer do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex index d3775b7937a5..e4025b23c100 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/_foo_get_default_response.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.FooGetDefaultResponse do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex index 43b89e8d0acb..a488f3e3128f 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/_special_model_name_.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.SpecialModelName do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex index 660632d285df..d37df9bd528b 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/additional_properties_class.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.AdditionalPropertiesClass do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex index 3e5e10907ec5..41c015f8b988 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/all_of_with_single_ref.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.AllOfWithSingleRef do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex index fcba046deb05..c8f7659cc5a1 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/animal.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Animal do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex index beebbebb3881..119ce22edd4d 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/api_response.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ApiResponse do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex index 55f62fd8f177..a81cc943a72e 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_array_of_number_only.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayOfArrayOfNumberOnly do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex index 2872c887131a..ae5e95cf5abd 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_of_number_only.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayOfNumberOnly do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex index 7197a294d86a..f3c5bdd0c401 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/array_test.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ArrayTest do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex index 7445d8f7f2a0..96689e84deb1 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/capitalization.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Capitalization do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex index bba420aa9b1d..677890cdf5c2 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/cat.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Cat do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex index 9bc4642e5504..d96f1a803fd4 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/category.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Category do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/child_with_nullable.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/child_with_nullable.ex index 5a207ce58a75..2fb989a78d46 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/child_with_nullable.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/child_with_nullable.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ChildWithNullable do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex index 88e49dccf155..b66750f9ff4d 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/class_model.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ClassModel do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex index 0cd1f348d0c0..02214669edc0 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/client.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Client do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex index d1d93be32ac1..d3c58598f3a0 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/deprecated_model.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.DeprecatedModel do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex index 9edf699b0e20..025b253661b8 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/dog.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Dog do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex index 07cbe2af5915..83f7f8898bba 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_arrays.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumArrays do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex index c3e9fc07636c..1cf528453e2f 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_class.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumClass do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex index 6aa656fc1236..fa1c5cd40ee3 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/enum_test.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.EnumTest do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/fake_big_decimal_map_200_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/fake_big_decimal_map_200_response.ex index cfb01b199aec..6a25c758f033 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/fake_big_decimal_map_200_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/fake_big_decimal_map_200_response.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.FakeBigDecimalMap200Response do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex index 61f3c77317ed..6d9d3b964232 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/file.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.File do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex index 0aef62f4284a..b9de3374a6b6 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/file_schema_test_class.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.FileSchemaTestClass do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex index aa0b7ddb1fff..5bdccbcb804e 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/foo.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Foo do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex index 753b6960c178..115ec2c0d7a3 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/format_test.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.FormatTest do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex index 1c0b0901bb9b..f2b2b2d37818 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/has_only_read_only.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.HasOnlyReadOnly do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex index c2c15f4fe05c..0935b624fd5d 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/health_check_result.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.HealthCheckResult do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex index cd7e140187fd..61dcfe53559b 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/list.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.List do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex index 5dd33cc3af1a..f3e620954413 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/map_test.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.MapTest do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex index 69b2050d175e..50680243cdcf 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/mixed_properties_and_additional_properties_class.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.MixedPropertiesAndAdditionalPropertiesClass do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex index d230806294ef..5c495512f618 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/model_200_response.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Model200Response do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex index 771e0b09b3aa..0b45bef6c596 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/name.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Name do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex index 59b1db452a3e..9d765bd32080 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/nullable_class.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.NullableClass do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex index 19fd1c90e597..9b486a1bc8d0 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/number_only.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.NumberOnly do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex index 4915918a007d..54e371e67008 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/object_with_deprecated_fields.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ObjectWithDeprecatedFields do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex index f515b5351e8a..03a04fd49ef5 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/order.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Order do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex index 2a2dcf409c82..a72a56cf09a1 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_composite.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterComposite do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex index 310f5adf44f6..96672df2ca89 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnum do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex index d6b453e0f6dc..0847c95441bd 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_default_value.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumDefaultValue do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex index fdd33826f0cd..f2a83cadf9ac 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumInteger do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex index eba3740d13c6..bd9080ed835f 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_enum_integer_default_value.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterEnumIntegerDefaultValue do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex index f4696158dfc5..ba0ded8eb502 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/outer_object_with_enum_property.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.OuterObjectWithEnumProperty do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/parent_with_nullable.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/parent_with_nullable.ex index 93e2de79946e..ec8b12db523c 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/parent_with_nullable.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/parent_with_nullable.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ParentWithNullable do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex index e9f47d3af33e..fb658acf4020 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/pet.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Pet do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex index 365ae17605a1..319264c18166 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/read_only_first.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.ReadOnlyFirst do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex index 1eb9d9f5d788..405250e8ccef 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/return.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Return do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex index ce3654c9b9f2..0aa0e2aa96ab 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/single_ref_type.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.SingleRefType do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex index 93466fbb0d0c..a2c65ddbf23f 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/tag.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.Tag do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/test_inline_freeform_additional_properties_request.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/test_inline_freeform_additional_properties_request.ex index f3d735d1d70d..e5df773a99c5 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/test_inline_freeform_additional_properties_request.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/test_inline_freeform_additional_properties_request.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.TestInlineFreeformAdditionalPropertiesRequest do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex b/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex index f19a639647bb..631b85653cbd 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/model/user.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.Model.User do diff --git a/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex b/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex index 043b2a10247b..5d0234581018 100644 --- a/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex +++ b/samples/client/petstore/elixir/lib/openapi_petstore/request_builder.ex @@ -1,4 +1,4 @@ -# NOTE: This file is auto generated by OpenAPI Generator 7.1.0-SNAPSHOT (https://openapi-generator.tech). +# NOTE: This file is auto generated by OpenAPI Generator 7.3.0-SNAPSHOT (https://openapi-generator.tech). # Do not edit this file manually. defmodule OpenapiPetstore.RequestBuilder do diff --git a/samples/client/petstore/elm/.openapi-generator/VERSION b/samples/client/petstore/elm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/elm/.openapi-generator/VERSION +++ b/samples/client/petstore/elm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/erlang-client/.openapi-generator/VERSION b/samples/client/petstore/erlang-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/erlang-client/.openapi-generator/VERSION +++ b/samples/client/petstore/erlang-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/erlang-proper/.openapi-generator/VERSION b/samples/client/petstore/erlang-proper/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/erlang-proper/.openapi-generator/VERSION +++ b/samples/client/petstore/erlang-proper/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION b/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/go/go-petstore/README.md b/samples/client/petstore/go/go-petstore/README.md index dffdcd14c5be..162f25584d49 100644 --- a/samples/client/petstore/go/go-petstore/README.md +++ b/samples/client/petstore/go/go-petstore/README.md @@ -13,7 +13,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat Install the following dependencies: -```shell +```sh go get github.com/stretchr/testify/assert go get golang.org/x/oauth2 go get golang.org/x/net/context @@ -21,13 +21,13 @@ go get golang.org/x/net/context Put the package under your project folder and add the following in import: -```golang +```go import petstore "github.com/GIT_USER_ID/GIT_REPO_ID" ``` To use a proxy, set the environment variable `HTTP_PROXY`: -```golang +```go os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") ``` @@ -37,17 +37,17 @@ Default configuration comes with `Servers` field that contains server objects as ### Select Server Configuration -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. +For using other server than the one defined on index 0 set context value `petstore.ContextServerIndex` of type `int`. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextServerIndex, 1) ``` ### Templated Server URL -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. +Templated server URL is formatted using default variables from configuration or from context value `petstore.ContextServerVariables` of type `map[string]string`. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextServerVariables, map[string]string{ "basePath": "v2", }) @@ -59,9 +59,9 @@ Note, enum values are always validated and all unused variables are silently ign Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. +Similar rules for overriding default operation server index and variables applies by using `petstore.ContextOperationServerIndices` and `petstore.ContextOperationServerVariables` context maps. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -182,20 +182,20 @@ Authentication schemes defined for the API: Example -```golang -auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING") +```go +auth := context.WithValue(context.Background(), petstore.ContextAccessToken, "ACCESSTOKENSTRING") r, err := client.Service.Operation(auth, args) ``` Or via OAuth2 module to automatically refresh tokens and perform user authentication. -```golang +```go import "golang.org/x/oauth2" /* Perform OAuth2 round trip request and obtain a token */ tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) -auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) +auth := context.WithValue(oauth2.NoContext, petstore.ContextOAuth2, tokenSource) r, err := client.Service.Operation(auth, args) ``` @@ -209,11 +209,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + petstore.ContextAPIKeys, + map[string]petstore.APIKey{ "api_key": {Key: "API_KEY_STRING"}, }, ) @@ -230,11 +230,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + petstore.ContextAPIKeys, + map[string]petstore.APIKey{ "api_key_query": {Key: "API_KEY_STRING"}, }, ) @@ -247,10 +247,10 @@ r, err := client.Service.Operation(auth, args) Example -```golang -auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ - UserName: "username", - Password: "password", +```go +auth := context.WithValue(context.Background(), petstore.ContextBasicAuth, petstore.BasicAuth{ + UserName: "username", + Password: "password", }) r, err := client.Service.Operation(auth, args) ``` diff --git a/samples/client/petstore/go/go-petstore/api_fake.go b/samples/client/petstore/go/go-petstore/api_fake.go index b03ecad89370..47622657f748 100644 --- a/samples/client/petstore/go/go-petstore/api_fake.go +++ b/samples/client/petstore/go/go-petstore/api_fake.go @@ -1270,8 +1270,6 @@ func (a *FakeAPIService) TestEndpointParametersExecute(r ApiTestEndpointParamete var binaryLocalVarFileBytes []byte binaryLocalVarFormFileName = "binary" - - binaryLocalVarFile := r.binary if binaryLocalVarFile != nil { diff --git a/samples/client/petstore/go/go-petstore/api_pet.go b/samples/client/petstore/go/go-petstore/api_pet.go index 0ae279248f1e..29cf9638aa6a 100644 --- a/samples/client/petstore/go/go-petstore/api_pet.go +++ b/samples/client/petstore/go/go-petstore/api_pet.go @@ -976,8 +976,6 @@ func (a *PetAPIService) UploadFileExecute(r ApiUploadFileRequest) (*ApiResponse, var fileLocalVarFileBytes []byte fileLocalVarFormFileName = "file" - - fileLocalVarFile := r.file if fileLocalVarFile != nil { @@ -1114,8 +1112,6 @@ func (a *PetAPIService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq var requiredFileLocalVarFileBytes []byte requiredFileLocalVarFormFileName = "requiredFile" - - requiredFileLocalVarFile := r.requiredFile if requiredFileLocalVarFile != nil { diff --git a/samples/client/petstore/go/go-petstore/client.go b/samples/client/petstore/go/go-petstore/client.go index 620543ae4ff6..66cc7f921a41 100644 --- a/samples/client/petstore/go/go-petstore/client.go +++ b/samples/client/petstore/go/go-petstore/client.go @@ -36,8 +36,8 @@ import ( ) var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) ) @@ -468,7 +468,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = f.Seek(0, io.SeekStart) - err = os.Remove(f.Name()) return } if f, ok := v.(**os.File); ok { @@ -481,16 +480,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = (*f).Seek(0, io.SeekStart) - err = os.Remove((*f).Name()) return } - if xmlCheck.MatchString(contentType) { + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } - if jsonCheck.MatchString(contentType) { + if JsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { @@ -555,9 +553,9 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { + } else if XmlCheck.MatchString(contentType) { var bs []byte bs, err = xml.Marshal(body) if err == nil { diff --git a/samples/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md b/samples/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md index fe1788992d25..87709d905917 100644 --- a/samples/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md +++ b/samples/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md @@ -22,25 +22,25 @@ To test special tags package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - uuidTest := "38400000-8cf0-11bd-b23e-10b96e4ef00d" // string | to test uuid example value - body := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.AnotherFakeAPI.Call123TestSpecialTags(context.Background()).UuidTest(uuidTest).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `AnotherFakeAPI.Call123TestSpecialTags``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `Call123TestSpecialTags`: Client - fmt.Fprintf(os.Stdout, "Response from `AnotherFakeAPI.Call123TestSpecialTags`: %v\n", resp) + uuidTest := "38400000-8cf0-11bd-b23e-10b96e4ef00d" // string | to test uuid example value + body := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.AnotherFakeAPI.Call123TestSpecialTags(context.Background()).UuidTest(uuidTest).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `AnotherFakeAPI.Call123TestSpecialTags``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `Call123TestSpecialTags`: Client + fmt.Fprintf(os.Stdout, "Response from `AnotherFakeAPI.Call123TestSpecialTags`: %v\n", resp) } ``` diff --git a/samples/client/petstore/go/go-petstore/docs/FakeAPI.md b/samples/client/petstore/go/go-petstore/docs/FakeAPI.md index 59c3df6eec15..34a895493c67 100644 --- a/samples/client/petstore/go/go-petstore/docs/FakeAPI.md +++ b/samples/client/petstore/go/go-petstore/docs/FakeAPI.md @@ -35,22 +35,22 @@ creates an XmlItem package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - xmlItem := *openapiclient.NewXmlItem() // XmlItem | XmlItem Body - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.CreateXmlItem(context.Background()).XmlItem(xmlItem).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.CreateXmlItem``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + xmlItem := *openapiclient.NewXmlItem() // XmlItem | XmlItem Body + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.CreateXmlItem(context.Background()).XmlItem(xmlItem).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.CreateXmlItem``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -99,24 +99,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := true // bool | Input boolean as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterBooleanSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterBooleanSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterBooleanSerialize`: bool - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterBooleanSerialize`: %v\n", resp) + body := true // bool | Input boolean as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterBooleanSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterBooleanSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterBooleanSerialize`: bool + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterBooleanSerialize`: %v\n", resp) } ``` @@ -165,24 +165,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewOuterComposite() // OuterComposite | Input composite as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterCompositeSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterCompositeSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterCompositeSerialize`: OuterComposite - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterCompositeSerialize`: %v\n", resp) + body := *openapiclient.NewOuterComposite() // OuterComposite | Input composite as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterCompositeSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterCompositeSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterCompositeSerialize`: OuterComposite + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterCompositeSerialize`: %v\n", resp) } ``` @@ -231,24 +231,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := float32(8.14) // float32 | Input number as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterNumberSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterNumberSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterNumberSerialize`: float32 - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterNumberSerialize`: %v\n", resp) + body := float32(8.14) // float32 | Input number as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterNumberSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterNumberSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterNumberSerialize`: float32 + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterNumberSerialize`: %v\n", resp) } ``` @@ -297,24 +297,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := "body_example" // string | Input string as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterStringSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterStringSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterStringSerialize`: string - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterStringSerialize`: %v\n", resp) + body := "body_example" // string | Input string as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterStringSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterStringSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterStringSerialize`: string + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterStringSerialize`: %v\n", resp) } ``` @@ -363,22 +363,22 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewFileSchemaTestClass() // FileSchemaTestClass | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestBodyWithFileSchema(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithFileSchema``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := *openapiclient.NewFileSchemaTestClass() // FileSchemaTestClass | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestBodyWithFileSchema(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithFileSchema``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -425,23 +425,23 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - query := "query_example" // string | - body := *openapiclient.NewUser() // User | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestBodyWithQueryParams(context.Background()).Query(query).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithQueryParams``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + query := "query_example" // string | + body := *openapiclient.NewUser() // User | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestBodyWithQueryParams(context.Background()).Query(query).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithQueryParams``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -491,24 +491,24 @@ To test \"client\" model package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.TestClientModel(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestClientModel``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestClientModel`: Client - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestClientModel`: %v\n", resp) + body := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.TestClientModel(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestClientModel``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestClientModel`: Client + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestClientModel`: %v\n", resp) } ``` @@ -557,36 +557,36 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイ package main import ( - "context" - "fmt" - "os" + "context" + "fmt" + "os" "time" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - number := float32(8.14) // float32 | None - double := float64(1.2) // float64 | None - patternWithoutDelimiter := "patternWithoutDelimiter_example" // string | None - byte_ := string(BYTE_ARRAY_DATA_HERE) // string | None - integer := int32(56) // int32 | None (optional) - int32_ := int32(56) // int32 | None (optional) - int64_ := int64(789) // int64 | None (optional) - float := float32(3.4) // float32 | None (optional) - string_ := "string__example" // string | None (optional) - binary := os.NewFile(1234, "some_file") // *os.File | None (optional) - date := time.Now() // string | None (optional) - dateTime := time.Now() // time.Time | None (optional) - password := "password_example" // string | None (optional) - callback := "callback_example" // string | None (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestEndpointParameters(context.Background()).Number(number).Double(double).PatternWithoutDelimiter(patternWithoutDelimiter).Byte_(byte_).Integer(integer).Int32_(int32_).Int64_(int64_).Float(float).String_(string_).Binary(binary).Date(date).DateTime(dateTime).Password(password).Callback(callback).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEndpointParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + number := float32(8.14) // float32 | None + double := float64(1.2) // float64 | None + patternWithoutDelimiter := "patternWithoutDelimiter_example" // string | None + byte_ := string(BYTE_ARRAY_DATA_HERE) // string | None + integer := int32(56) // int32 | None (optional) + int32_ := int32(56) // int32 | None (optional) + int64_ := int64(789) // int64 | None (optional) + float := float32(3.4) // float32 | None (optional) + string_ := "string__example" // string | None (optional) + binary := os.NewFile(1234, "some_file") // *os.File | None (optional) + date := time.Now() // string | None (optional) + dateTime := time.Now() // time.Time | None (optional) + password := "password_example" // string | None (optional) + callback := "callback_example" // string | None (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestEndpointParameters(context.Background()).Number(number).Double(double).PatternWithoutDelimiter(patternWithoutDelimiter).Byte_(byte_).Integer(integer).Int32_(int32_).Int64_(int64_).Float(float).String_(string_).Binary(binary).Date(date).DateTime(dateTime).Password(password).Callback(callback).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEndpointParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -648,29 +648,29 @@ To test enum parameters package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - enumHeaderStringArray := []string{"EnumHeaderStringArray_example"} // []string | Header parameter enum test (string array) (optional) - enumHeaderString := "enumHeaderString_example" // string | Header parameter enum test (string) (optional) (default to "-efg") - enumQueryStringArray := []string{"EnumQueryStringArray_example"} // []string | Query parameter enum test (string array) (optional) - enumQueryString := "enumQueryString_example" // string | Query parameter enum test (string) (optional) (default to "-efg") - enumQueryInteger := int32(56) // int32 | Query parameter enum test (double) (optional) - enumQueryDouble := float64(1.2) // float64 | Query parameter enum test (double) (optional) - enumFormStringArray := []string{"Inner_example"} // []string | Form parameter enum test (string array) (optional) (default to "$") - enumFormString := "enumFormString_example" // string | Form parameter enum test (string) (optional) (default to "-efg") - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestEnumParameters(context.Background()).EnumHeaderStringArray(enumHeaderStringArray).EnumHeaderString(enumHeaderString).EnumQueryStringArray(enumQueryStringArray).EnumQueryString(enumQueryString).EnumQueryInteger(enumQueryInteger).EnumQueryDouble(enumQueryDouble).EnumFormStringArray(enumFormStringArray).EnumFormString(enumFormString).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEnumParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + enumHeaderStringArray := []string{"EnumHeaderStringArray_example"} // []string | Header parameter enum test (string array) (optional) + enumHeaderString := "enumHeaderString_example" // string | Header parameter enum test (string) (optional) (default to "-efg") + enumQueryStringArray := []string{"EnumQueryStringArray_example"} // []string | Query parameter enum test (string array) (optional) + enumQueryString := "enumQueryString_example" // string | Query parameter enum test (string) (optional) (default to "-efg") + enumQueryInteger := int32(56) // int32 | Query parameter enum test (double) (optional) + enumQueryDouble := float64(1.2) // float64 | Query parameter enum test (double) (optional) + enumFormStringArray := []string{"Inner_example"} // []string | Form parameter enum test (string array) (optional) (default to "$") + enumFormString := "enumFormString_example" // string | Form parameter enum test (string) (optional) (default to "-efg") + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestEnumParameters(context.Background()).EnumHeaderStringArray(enumHeaderStringArray).EnumHeaderString(enumHeaderString).EnumQueryStringArray(enumQueryStringArray).EnumQueryString(enumQueryString).EnumQueryInteger(enumQueryInteger).EnumQueryDouble(enumQueryDouble).EnumFormStringArray(enumFormStringArray).EnumFormString(enumFormString).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEnumParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -726,27 +726,27 @@ Fake endpoint to test group parameters (optional) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - requiredStringGroup := int32(56) // int32 | Required String in group parameters - requiredBooleanGroup := true // bool | Required Boolean in group parameters - requiredInt64Group := int64(789) // int64 | Required Integer in group parameters - stringGroup := int32(56) // int32 | String in group parameters (optional) - booleanGroup := true // bool | Boolean in group parameters (optional) - int64Group := int64(789) // int64 | Integer in group parameters (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestGroupParameters(context.Background()).RequiredStringGroup(requiredStringGroup).RequiredBooleanGroup(requiredBooleanGroup).RequiredInt64Group(requiredInt64Group).StringGroup(stringGroup).BooleanGroup(booleanGroup).Int64Group(int64Group).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestGroupParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + requiredStringGroup := int32(56) // int32 | Required String in group parameters + requiredBooleanGroup := true // bool | Required Boolean in group parameters + requiredInt64Group := int64(789) // int64 | Required Integer in group parameters + stringGroup := int32(56) // int32 | String in group parameters (optional) + booleanGroup := true // bool | Boolean in group parameters (optional) + int64Group := int64(789) // int64 | Integer in group parameters (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestGroupParameters(context.Background()).RequiredStringGroup(requiredStringGroup).RequiredBooleanGroup(requiredBooleanGroup).RequiredInt64Group(requiredInt64Group).StringGroup(stringGroup).BooleanGroup(booleanGroup).Int64Group(int64Group).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestGroupParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -798,22 +798,22 @@ test inline additionalProperties package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - param := map[string]string{"key": "Inner_example"} // map[string]string | request body - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestInlineAdditionalProperties(context.Background()).Param(param).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineAdditionalProperties``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + param := map[string]string{"key": "Inner_example"} // map[string]string | request body + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestInlineAdditionalProperties(context.Background()).Param(param).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineAdditionalProperties``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -860,23 +860,23 @@ test json serialization of form data package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - param := "param_example" // string | field1 - param2 := "param2_example" // string | field2 - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestJsonFormData(context.Background()).Param(param).Param2(param2).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestJsonFormData``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + param := "param_example" // string | field1 + param2 := "param2_example" // string | field2 + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestJsonFormData(context.Background()).Param(param).Param2(param2).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestJsonFormData``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -926,26 +926,26 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pipe := []string{"Inner_example"} // []string | - ioutil := []string{"Inner_example"} // []string | - http := []string{"Inner_example"} // []string | - url := []string{"Inner_example"} // []string | - context := []string{"Inner_example"} // []string | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestQueryParameterCollectionFormat(context.Background()).Pipe(pipe).Ioutil(ioutil).Http(http).Url(url).Context(context).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryParameterCollectionFormat``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + pipe := []string{"Inner_example"} // []string | + ioutil := []string{"Inner_example"} // []string | + http := []string{"Inner_example"} // []string | + url := []string{"Inner_example"} // []string | + context := []string{"Inner_example"} // []string | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestQueryParameterCollectionFormat(context.Background()).Pipe(pipe).Ioutil(ioutil).Http(http).Url(url).Context(context).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryParameterCollectionFormat``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` diff --git a/samples/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md b/samples/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md index cf15937a87f1..340a5751ba33 100644 --- a/samples/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md +++ b/samples/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md @@ -22,24 +22,24 @@ To test class name in snake case package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeClassnameTags123API.TestClassname(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeClassnameTags123API.TestClassname``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestClassname`: Client - fmt.Fprintf(os.Stdout, "Response from `FakeClassnameTags123API.TestClassname`: %v\n", resp) + body := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeClassnameTags123API.TestClassname(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeClassnameTags123API.TestClassname``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestClassname`: Client + fmt.Fprintf(os.Stdout, "Response from `FakeClassnameTags123API.TestClassname`: %v\n", resp) } ``` diff --git a/samples/client/petstore/go/go-petstore/docs/PetAPI.md b/samples/client/petstore/go/go-petstore/docs/PetAPI.md index a454f486cf40..adaec60d0556 100644 --- a/samples/client/petstore/go/go-petstore/docs/PetAPI.md +++ b/samples/client/petstore/go/go-petstore/docs/PetAPI.md @@ -28,22 +28,22 @@ Add a new pet to the store package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.AddPet(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.AddPet(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -90,23 +90,23 @@ Deletes a pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | Pet id to delete - apiKey := "apiKey_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.DeletePet(context.Background(), petId).ApiKey(apiKey).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.DeletePet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + petId := int64(789) // int64 | Pet id to delete + apiKey := "apiKey_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.DeletePet(context.Background(), petId).ApiKey(apiKey).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.DeletePet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -160,24 +160,24 @@ Finds Pets by status package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - status := []string{"Status_example"} // []string | Status values that need to be considered for filter - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.FindPetsByStatus(context.Background()).Status(status).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByStatus``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FindPetsByStatus`: []Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByStatus`: %v\n", resp) + status := []string{"Status_example"} // []string | Status values that need to be considered for filter + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.FindPetsByStatus(context.Background()).Status(status).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByStatus``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FindPetsByStatus`: []Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByStatus`: %v\n", resp) } ``` @@ -226,24 +226,24 @@ Finds Pets by tags package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - tags := []string{"Inner_example"} // []string | Tags to filter by - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.FindPetsByTags(context.Background()).Tags(tags).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByTags``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FindPetsByTags`: []Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByTags`: %v\n", resp) + tags := []string{"Inner_example"} // []string | Tags to filter by + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.FindPetsByTags(context.Background()).Tags(tags).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByTags``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FindPetsByTags`: []Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByTags`: %v\n", resp) } ``` @@ -292,24 +292,24 @@ Find pet by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to return - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.GetPetById(context.Background(), petId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.GetPetById``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetPetById`: Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.GetPetById`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to return + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.GetPetById(context.Background(), petId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.GetPetById``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetPetById`: Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.GetPetById`: %v\n", resp) } ``` @@ -360,22 +360,22 @@ Update an existing pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.UpdatePet(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.UpdatePet(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -422,24 +422,24 @@ Updates a pet in the store with form data package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet that needs to be updated - name := "name_example" // string | Updated name of the pet (optional) - status := "status_example" // string | Updated status of the pet (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.UpdatePetWithForm(context.Background(), petId).Name(name).Status(status).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePetWithForm``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + petId := int64(789) // int64 | ID of pet that needs to be updated + name := "name_example" // string | Updated name of the pet (optional) + status := "status_example" // string | Updated status of the pet (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.UpdatePetWithForm(context.Background(), petId).Name(name).Status(status).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePetWithForm``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -492,26 +492,26 @@ uploads an image package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to update - additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) - file := os.NewFile(1234, "some_file") // *os.File | file to upload (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.UploadFile(context.Background(), petId).AdditionalMetadata(additionalMetadata).File(file).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFile``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `UploadFile`: ApiResponse - fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFile`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to update + additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) + file := os.NewFile(1234, "some_file") // *os.File | file to upload (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.UploadFile(context.Background(), petId).AdditionalMetadata(additionalMetadata).File(file).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFile``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `UploadFile`: ApiResponse + fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFile`: %v\n", resp) } ``` @@ -564,26 +564,26 @@ uploads an image (required) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to update - requiredFile := os.NewFile(1234, "some_file") // *os.File | file to upload - additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.UploadFileWithRequiredFile(context.Background(), petId).RequiredFile(requiredFile).AdditionalMetadata(additionalMetadata).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFileWithRequiredFile``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `UploadFileWithRequiredFile`: ApiResponse - fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFileWithRequiredFile`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to update + requiredFile := os.NewFile(1234, "some_file") // *os.File | file to upload + additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.UploadFileWithRequiredFile(context.Background(), petId).RequiredFile(requiredFile).AdditionalMetadata(additionalMetadata).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFileWithRequiredFile``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `UploadFileWithRequiredFile`: ApiResponse + fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFileWithRequiredFile`: %v\n", resp) } ``` diff --git a/samples/client/petstore/go/go-petstore/docs/StoreAPI.md b/samples/client/petstore/go/go-petstore/docs/StoreAPI.md index e27106923154..e78d6a9db373 100644 --- a/samples/client/petstore/go/go-petstore/docs/StoreAPI.md +++ b/samples/client/petstore/go/go-petstore/docs/StoreAPI.md @@ -25,22 +25,22 @@ Delete purchase order by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - orderId := "orderId_example" // string | ID of the order that needs to be deleted - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.StoreAPI.DeleteOrder(context.Background(), orderId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.DeleteOrder``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + orderId := "orderId_example" // string | ID of the order that needs to be deleted + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.StoreAPI.DeleteOrder(context.Background(), orderId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.DeleteOrder``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -93,23 +93,23 @@ Returns pet inventories by status package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.GetInventory(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetInventory``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetInventory`: map[string]int32 - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetInventory`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.GetInventory(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetInventory``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetInventory`: map[string]int32 + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetInventory`: %v\n", resp) } ``` @@ -154,24 +154,24 @@ Find purchase order by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - orderId := int64(789) // int64 | ID of pet that needs to be fetched - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.GetOrderById(context.Background(), orderId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetOrderById``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetOrderById`: Order - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetOrderById`: %v\n", resp) + orderId := int64(789) // int64 | ID of pet that needs to be fetched + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.GetOrderById(context.Background(), orderId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetOrderById``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetOrderById`: Order + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetOrderById`: %v\n", resp) } ``` @@ -222,24 +222,24 @@ Place an order for a pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewOrder() // Order | order placed for purchasing the pet - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.PlaceOrder(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.PlaceOrder``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `PlaceOrder`: Order - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.PlaceOrder`: %v\n", resp) + body := *openapiclient.NewOrder() // Order | order placed for purchasing the pet + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.PlaceOrder(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.PlaceOrder``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `PlaceOrder`: Order + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.PlaceOrder`: %v\n", resp) } ``` diff --git a/samples/client/petstore/go/go-petstore/docs/UserAPI.md b/samples/client/petstore/go/go-petstore/docs/UserAPI.md index af61745c62f2..480ea53a65a3 100644 --- a/samples/client/petstore/go/go-petstore/docs/UserAPI.md +++ b/samples/client/petstore/go/go-petstore/docs/UserAPI.md @@ -29,22 +29,22 @@ Create user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := *openapiclient.NewUser() // User | Created user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUser(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := *openapiclient.NewUser() // User | Created user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUser(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -91,22 +91,22 @@ Creates list of users with given input array package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUsersWithArrayInput(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithArrayInput``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUsersWithArrayInput(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithArrayInput``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -153,22 +153,22 @@ Creates list of users with given input array package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUsersWithListInput(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithListInput``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + body := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUsersWithListInput(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithListInput``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -217,22 +217,22 @@ Delete user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The name that needs to be deleted - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.DeleteUser(context.Background(), username).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.DeleteUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + username := "username_example" // string | The name that needs to be deleted + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.DeleteUser(context.Background(), username).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.DeleteUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -283,24 +283,24 @@ Get user by user name package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The name that needs to be fetched. Use user1 for testing. - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UserAPI.GetUserByName(context.Background(), username).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.GetUserByName``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetUserByName`: User - fmt.Fprintf(os.Stdout, "Response from `UserAPI.GetUserByName`: %v\n", resp) + username := "username_example" // string | The name that needs to be fetched. Use user1 for testing. + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UserAPI.GetUserByName(context.Background(), username).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.GetUserByName``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetUserByName`: User + fmt.Fprintf(os.Stdout, "Response from `UserAPI.GetUserByName`: %v\n", resp) } ``` @@ -351,25 +351,25 @@ Logs user into the system package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The user name for login - password := "password_example" // string | The password for login in clear text - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UserAPI.LoginUser(context.Background()).Username(username).Password(password).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LoginUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `LoginUser`: string - fmt.Fprintf(os.Stdout, "Response from `UserAPI.LoginUser`: %v\n", resp) + username := "username_example" // string | The user name for login + password := "password_example" // string | The password for login in clear text + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UserAPI.LoginUser(context.Background()).Username(username).Password(password).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LoginUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `LoginUser`: string + fmt.Fprintf(os.Stdout, "Response from `UserAPI.LoginUser`: %v\n", resp) } ``` @@ -417,21 +417,21 @@ Logs out current logged in user session package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.LogoutUser(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LogoutUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.LogoutUser(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LogoutUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -476,23 +476,23 @@ Updated user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | name that need to be deleted - body := *openapiclient.NewUser() // User | Updated user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.UpdateUser(context.Background(), username).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.UpdateUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + username := "username_example" // string | name that need to be deleted + body := *openapiclient.NewUser() // User | Updated user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.UpdateUser(context.Background(), username).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.UpdateUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go b/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go index 880f95e954ab..69d99b022d6f 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_any_type.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesAnyType) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesAnyType) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesAnyType) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesAnyType := _AdditionalPropertiesAnyType{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesAnyType) + err = json.Unmarshal(data, &varAdditionalPropertiesAnyType) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesAnyType) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_array.go b/samples/client/petstore/go/go-petstore/model_additional_properties_array.go index 22c59ee9a613..58633a54e851 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_array.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_array.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesArray) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesArray) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesArray) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesArray := _AdditionalPropertiesArray{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesArray) + err = json.Unmarshal(data, &varAdditionalPropertiesArray) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesArray) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go b/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go index e898485760ab..9b5347dd1d3c 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_boolean.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesBoolean) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesBoolean) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesBoolean) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesBoolean := _AdditionalPropertiesBoolean{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesBoolean) + err = json.Unmarshal(data, &varAdditionalPropertiesBoolean) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesBoolean) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go b/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go index af609f1474c0..c91aab6e5067 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_integer.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesInteger) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesInteger) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesInteger) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesInteger := _AdditionalPropertiesInteger{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesInteger) + err = json.Unmarshal(data, &varAdditionalPropertiesInteger) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesInteger) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_number.go b/samples/client/petstore/go/go-petstore/model_additional_properties_number.go index f3eb23fc4560..e64cc22eb5b2 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_number.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_number.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesNumber) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesNumber) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesNumber) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesNumber := _AdditionalPropertiesNumber{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesNumber) + err = json.Unmarshal(data, &varAdditionalPropertiesNumber) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesNumber) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_object.go b/samples/client/petstore/go/go-petstore/model_additional_properties_object.go index d0730dc7f53d..e5f793dda338 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_object.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_object.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesObject) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesObject) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesObject) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesObject := _AdditionalPropertiesObject{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesObject) + err = json.Unmarshal(data, &varAdditionalPropertiesObject) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesObject) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_additional_properties_string.go b/samples/client/petstore/go/go-petstore/model_additional_properties_string.go index acfc3440092f..f5e2f79fe202 100644 --- a/samples/client/petstore/go/go-petstore/model_additional_properties_string.go +++ b/samples/client/petstore/go/go-petstore/model_additional_properties_string.go @@ -95,10 +95,10 @@ func (o AdditionalPropertiesString) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesString) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesString) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesString := _AdditionalPropertiesString{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesString) + err = json.Unmarshal(data, &varAdditionalPropertiesString) if err != nil { return err @@ -108,7 +108,7 @@ func (o *AdditionalPropertiesString) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/client/petstore/go/go-petstore/model_animal.go b/samples/client/petstore/go/go-petstore/model_animal.go index a884b8473f60..e23baa88fcc6 100644 --- a/samples/client/petstore/go/go-petstore/model_animal.go +++ b/samples/client/petstore/go/go-petstore/model_animal.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Animal type satisfies the MappedNullable interface at compile time @@ -23,6 +25,8 @@ type Animal struct { Color *string `json:"color,omitempty"` } +type _Animal Animal + // NewAnimal instantiates a new Animal object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -118,6 +122,43 @@ func (o Animal) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Animal) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varAnimal := _Animal{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varAnimal) + + if err != nil { + return err + } + + *o = Animal(varAnimal) + + return err +} + type NullableAnimal struct { value *Animal isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_big_cat.go b/samples/client/petstore/go/go-petstore/model_big_cat.go index 503a742ab8f5..4000f2096d9d 100644 --- a/samples/client/petstore/go/go-petstore/model_big_cat.go +++ b/samples/client/petstore/go/go-petstore/model_big_cat.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the BigCat type satisfies the MappedNullable interface at compile time @@ -23,6 +25,8 @@ type BigCat struct { Kind *string `json:"kind,omitempty"` } +type _BigCat BigCat + // NewBigCat instantiates a new BigCat object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -99,6 +103,43 @@ func (o BigCat) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *BigCat) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varBigCat := _BigCat{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varBigCat) + + if err != nil { + return err + } + + *o = BigCat(varBigCat) + + return err +} + type NullableBigCat struct { value *BigCat isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_cat.go b/samples/client/petstore/go/go-petstore/model_cat.go index ab791a527ac1..b3937685f6af 100644 --- a/samples/client/petstore/go/go-petstore/model_cat.go +++ b/samples/client/petstore/go/go-petstore/model_cat.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Cat type satisfies the MappedNullable interface at compile time @@ -23,6 +25,8 @@ type Cat struct { Declawed *bool `json:"declawed,omitempty"` } +type _Cat Cat + // NewCat instantiates a new Cat object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -99,6 +103,43 @@ func (o Cat) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Cat) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varCat := _Cat{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varCat) + + if err != nil { + return err + } + + *o = Cat(varCat) + + return err +} + type NullableCat struct { value *Cat isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_category.go b/samples/client/petstore/go/go-petstore/model_category.go index 5275e7150648..d19362640391 100644 --- a/samples/client/petstore/go/go-petstore/model_category.go +++ b/samples/client/petstore/go/go-petstore/model_category.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Category type satisfies the MappedNullable interface at compile time @@ -23,6 +25,8 @@ type Category struct { Name string `json:"name"` } +type _Category Category + // NewCategory instantiates a new Category object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -116,6 +120,43 @@ func (o Category) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Category) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varCategory := _Category{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varCategory) + + if err != nil { + return err + } + + *o = Category(varCategory) + + return err +} + type NullableCategory struct { value *Category isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_dog.go b/samples/client/petstore/go/go-petstore/model_dog.go index f0fdbf8b7120..92d5dece9e79 100644 --- a/samples/client/petstore/go/go-petstore/model_dog.go +++ b/samples/client/petstore/go/go-petstore/model_dog.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Dog type satisfies the MappedNullable interface at compile time @@ -23,6 +25,8 @@ type Dog struct { Breed *string `json:"breed,omitempty"` } +type _Dog Dog + // NewDog instantiates a new Dog object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -99,6 +103,43 @@ func (o Dog) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Dog) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varDog := _Dog{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varDog) + + if err != nil { + return err + } + + *o = Dog(varDog) + + return err +} + type NullableDog struct { value *Dog isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_enum_test_.go b/samples/client/petstore/go/go-petstore/model_enum_test_.go index 25114a9f9bb2..cf858376f48b 100644 --- a/samples/client/petstore/go/go-petstore/model_enum_test_.go +++ b/samples/client/petstore/go/go-petstore/model_enum_test_.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the EnumTest type satisfies the MappedNullable interface at compile time @@ -26,6 +28,8 @@ type EnumTest struct { OuterEnum *OuterEnum `json:"outerEnum,omitempty"` } +type _EnumTest EnumTest + // NewEnumTest instantiates a new EnumTest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -222,6 +226,43 @@ func (o EnumTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *EnumTest) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "enum_string_required", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varEnumTest := _EnumTest{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varEnumTest) + + if err != nil { + return err + } + + *o = EnumTest(varEnumTest) + + return err +} + type NullableEnumTest struct { value *EnumTest isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_format_test_.go b/samples/client/petstore/go/go-petstore/model_format_test_.go index 233c531076bb..d2cb7e88a331 100644 --- a/samples/client/petstore/go/go-petstore/model_format_test_.go +++ b/samples/client/petstore/go/go-petstore/model_format_test_.go @@ -14,6 +14,8 @@ import ( "encoding/json" "os" "time" + "bytes" + "fmt" ) // checks if the FormatTest type satisfies the MappedNullable interface at compile time @@ -37,6 +39,8 @@ type FormatTest struct { BigDecimal *float64 `json:"BigDecimal,omitempty"` } +type _FormatTest FormatTest + // NewFormatTest instantiates a new FormatTest object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -521,6 +525,46 @@ func (o FormatTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *FormatTest) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "number", + "byte", + "date", + "password", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varFormatTest := _FormatTest{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varFormatTest) + + if err != nil { + return err + } + + *o = FormatTest(varFormatTest) + + return err +} + type NullableFormatTest struct { value *FormatTest isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_name.go b/samples/client/petstore/go/go-petstore/model_name.go index e1fe302008f3..7e009e1cf0b5 100644 --- a/samples/client/petstore/go/go-petstore/model_name.go +++ b/samples/client/petstore/go/go-petstore/model_name.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Name type satisfies the MappedNullable interface at compile time @@ -25,6 +27,8 @@ type Name struct { Var123Number *int32 `json:"123Number,omitempty"` } +type _Name Name + // NewName instantiates a new Name object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -186,6 +190,43 @@ func (o Name) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Name) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varName := _Name{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varName) + + if err != nil { + return err + } + + *o = Name(varName) + + return err +} + type NullableName struct { value *Name isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_pet.go b/samples/client/petstore/go/go-petstore/model_pet.go index 04ae05c1e182..de782511daa3 100644 --- a/samples/client/petstore/go/go-petstore/model_pet.go +++ b/samples/client/petstore/go/go-petstore/model_pet.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the Pet type satisfies the MappedNullable interface at compile time @@ -28,6 +30,8 @@ type Pet struct { Status *string `json:"status,omitempty"` } +type _Pet Pet + // NewPet instantiates a new Pet object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -250,6 +254,44 @@ func (o Pet) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *Pet) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + "photoUrls", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varPet := _Pet{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varPet) + + if err != nil { + return err + } + + *o = Pet(varPet) + + return err +} + type NullablePet struct { value *Pet isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_type_holder_default.go b/samples/client/petstore/go/go-petstore/model_type_holder_default.go index a06478caad71..8a67e9f7a2df 100644 --- a/samples/client/petstore/go/go-petstore/model_type_holder_default.go +++ b/samples/client/petstore/go/go-petstore/model_type_holder_default.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the TypeHolderDefault type satisfies the MappedNullable interface at compile time @@ -26,6 +28,8 @@ type TypeHolderDefault struct { ArrayItem []int32 `json:"array_item"` } +type _TypeHolderDefault TypeHolderDefault + // NewTypeHolderDefault instantiates a new TypeHolderDefault object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -190,6 +194,47 @@ func (o TypeHolderDefault) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *TypeHolderDefault) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "string_item", + "number_item", + "integer_item", + "bool_item", + "array_item", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varTypeHolderDefault := _TypeHolderDefault{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varTypeHolderDefault) + + if err != nil { + return err + } + + *o = TypeHolderDefault(varTypeHolderDefault) + + return err +} + type NullableTypeHolderDefault struct { value *TypeHolderDefault isSet bool diff --git a/samples/client/petstore/go/go-petstore/model_type_holder_example.go b/samples/client/petstore/go/go-petstore/model_type_holder_example.go index be5869db9b77..a08223070828 100644 --- a/samples/client/petstore/go/go-petstore/model_type_holder_example.go +++ b/samples/client/petstore/go/go-petstore/model_type_holder_example.go @@ -12,6 +12,8 @@ package petstore import ( "encoding/json" + "bytes" + "fmt" ) // checks if the TypeHolderExample type satisfies the MappedNullable interface at compile time @@ -27,6 +29,8 @@ type TypeHolderExample struct { ArrayItem []int32 `json:"array_item"` } +type _TypeHolderExample TypeHolderExample + // NewTypeHolderExample instantiates a new TypeHolderExample object // This constructor will assign default values to properties that have it defined, // and makes sure properties required by API are set, but the set of arguments @@ -213,6 +217,48 @@ func (o TypeHolderExample) ToMap() (map[string]interface{}, error) { return toSerialize, nil } +func (o *TypeHolderExample) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "string_item", + "number_item", + "float_item", + "integer_item", + "bool_item", + "array_item", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varTypeHolderExample := _TypeHolderExample{} + + decoder := json.NewDecoder(bytes.NewReader(data)) + decoder.DisallowUnknownFields() + err = decoder.Decode(&varTypeHolderExample) + + if err != nil { + return err + } + + *o = TypeHolderExample(varTypeHolderExample) + + return err +} + type NullableTypeHolderExample struct { value *TypeHolderExample isSet bool diff --git a/samples/client/petstore/go/go.sum b/samples/client/petstore/go/go.sum index 2eaa32c259ef..918ee1769ee8 100644 --- a/samples/client/petstore/go/go.sum +++ b/samples/client/petstore/go/go.sum @@ -273,9 +273,11 @@ golang.org/x/sys v0.0.0-20211216021012-1d35b9e2eb4e/go.mod h1:oPkhp1MJrh7nUepCBc golang.org/x/sys v0.0.0-20220520151302-bc2c85ada10a/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220722155257-8c9f86f7a55f/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.2.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo= golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8= golang.org/x/term v0.2.0/go.mod h1:TVmDHMZPmdnySmBfhjOoOdhjzdE1h4u1VwSiw2l1Nuc= +golang.org/x/term v0.5.0/go.mod h1:jMB1sMXY+tzblOD4FWmEbocvup2/aLOaQEp7JmGp78k= golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= @@ -283,6 +285,7 @@ golang.org/x/text v0.3.2/go.mod h1:bEr9sfX3Q8Zfm5fL9x+3itogRgK3+ptLWKqgva+5dAk= golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ= golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ= golang.org/x/text v0.4.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ= diff --git a/samples/client/petstore/go/model_test.go b/samples/client/petstore/go/model_test.go new file mode 100644 index 000000000000..aebd3cce45ba --- /dev/null +++ b/samples/client/petstore/go/model_test.go @@ -0,0 +1,21 @@ +package main + +import ( + "testing" + + sw "github.com/OpenAPITools/openapi-generator/samples/client/petstore/go/go-petstore" + + "github.com/stretchr/testify/assert" +) + +func TestRequiredFieldsWithAdditionalPropertiesFalse(t *testing.T) { + assert := assert.New(t) + + newAnimal := (sw.Animal{}) + jsonAnimal := `{"className":"invalidAnimal","extraThing":"foo"}` + + err := newAnimal.UnmarshalJSON([]byte(jsonAnimal)) + expected := "json: unknown field \"extraThing\"" + + assert.ErrorContains(err, expected, "Animal should return error when missing additional fields are present") +} diff --git a/samples/client/petstore/groovy/.openapi-generator/VERSION b/samples/client/petstore/groovy/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/groovy/.openapi-generator/VERSION +++ b/samples/client/petstore/groovy/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION +++ b/samples/client/petstore/haskell-http-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION +++ b/samples/client/petstore/java-helidon-client/mp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md b/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md index 7f7a569f2b43..7e243e14b73c 100644 --- a/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md +++ b/samples/client/petstore/java-helidon-client/mp/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -299,6 +300,41 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> void testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > void testBodyWithBinary(body) diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java index 533c19442d56..4c321d1cee84 100644 --- a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/api/FakeApi.java @@ -102,6 +102,15 @@ public interface FakeApi { @Produces({ "*/*" }) OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws ApiException, ProcessingException; + /** + * test referenced additionalProperties + * + */ + @POST + @Path("/additionalProperties-reference") + @Consumes({ "application/json" }) + void testAdditionalPropertiesReference(Map requestBody) throws ApiException, ProcessingException; + @PUT @Path("/body-with-binary") @Consumes({ "image/png" }) diff --git a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java index 6f6b62d497c8..1f3fc84b65ae 100644 --- a/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java-helidon-client/mp/src/main/java/org/openapitools/client/model/FormatTest.java @@ -418,7 +418,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION b/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION +++ b/samples/client/petstore/java-helidon-client/se/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md b/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md +++ b/samples/client/petstore/java-helidon-client/se/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java index dc7a20295b50..b3afad3461cd 100644 --- a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApi.java @@ -65,6 +65,14 @@ public interface FakeApi { ApiResponse fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty); + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return {@code ApiResponse} + */ + ApiResponse testAdditionalPropertiesReference(Map requestBody); + ApiResponse testBodyWithBinary(File body); ApiResponse testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass); diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java index db9dce74ca31..b8ff4b360056 100644 --- a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/api/FakeApiImpl.java @@ -68,6 +68,7 @@ public class FakeApiImpl implements FakeApi { protected static final GenericType RESPONSE_TYPE_fakeOuterNumberSerialize = ResponseType.create(BigDecimal.class); protected static final GenericType RESPONSE_TYPE_fakeOuterStringSerialize = ResponseType.create(String.class); protected static final GenericType RESPONSE_TYPE_fakePropertyEnumIntegerSerialize = ResponseType.create(OuterObjectWithEnumProperty.class); + protected static final GenericType RESPONSE_TYPE_testAdditionalPropertiesReference = ResponseType.create(Void.class); protected static final GenericType RESPONSE_TYPE_testBodyWithBinary = ResponseType.create(Void.class); protected static final GenericType RESPONSE_TYPE_testBodyWithFileSchema = ResponseType.create(Void.class); protected static final GenericType RESPONSE_TYPE_testBodyWithQueryParams = ResponseType.create(Void.class); @@ -398,6 +399,44 @@ protected ApiResponse fakePropertyEnumIntegerSerial return ApiResponse.create(RESPONSE_TYPE_fakePropertyEnumIntegerSerialize, webClientResponse); } + @Override + public ApiResponse testAdditionalPropertiesReference(Map requestBody) { + Objects.requireNonNull(requestBody, "Required parameter 'requestBody' not specified"); + WebClientRequestBuilder webClientRequestBuilder = testAdditionalPropertiesReferenceRequestBuilder(requestBody); + return testAdditionalPropertiesReferenceSubmit(webClientRequestBuilder, requestBody); + } + + /** + * Creates a {@code WebClientRequestBuilder} for the testAdditionalPropertiesReference operation. + * Optional customization point for subclasses. + * + * @param requestBody request body (required) + * @return WebClientRequestBuilder for testAdditionalPropertiesReference + */ + protected WebClientRequestBuilder testAdditionalPropertiesReferenceRequestBuilder(Map requestBody) { + WebClientRequestBuilder webClientRequestBuilder = apiClient.webClient() + .method("POST"); + + webClientRequestBuilder.path("/fake/additionalProperties-reference"); + webClientRequestBuilder.contentType(MediaType.APPLICATION_JSON); + webClientRequestBuilder.accept(MediaType.APPLICATION_JSON); + + return webClientRequestBuilder; + } + + /** + * Initiates the request for the testAdditionalPropertiesReference operation. + * Optional customization point for subclasses. + * + * @param webClientRequestBuilder the request builder to use for submitting the request + * @param requestBody request body (required) + * @return {@code ApiResponse} for the submitted request + */ + protected ApiResponse testAdditionalPropertiesReferenceSubmit(WebClientRequestBuilder webClientRequestBuilder, Map requestBody) { + Single webClientResponse = webClientRequestBuilder.submit(requestBody); + return ApiResponse.create(RESPONSE_TYPE_testAdditionalPropertiesReference, webClientResponse); + } + @Override public ApiResponse testBodyWithBinary(File body) { Objects.requireNonNull(body, "Required parameter 'body' not specified"); diff --git a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java index 6f6b62d497c8..1f3fc84b65ae 100644 --- a/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java-helidon-client/se/src/main/java/org/openapitools/client/model/FormatTest.java @@ -418,7 +418,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java-micronaut-client/.openapi-generator/VERSION b/samples/client/petstore/java-micronaut-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java-micronaut-client/.openapi-generator/VERSION +++ b/samples/client/petstore/java-micronaut-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java-micronaut-client/docs/apis/UserApi.md b/samples/client/petstore/java-micronaut-client/docs/apis/UserApi.md index bb760808f4df..ca85889bcf5e 100644 --- a/samples/client/petstore/java-micronaut-client/docs/apis/UserApi.md +++ b/samples/client/petstore/java-micronaut-client/docs/apis/UserApi.md @@ -77,7 +77,7 @@ Creates list of users with given input array ### Parameters | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **_body** | [**List<User>**](User.md)| List of user object | | +| **_body** | [**List<@Valid User>**](User.md)| List of user object | | @@ -99,7 +99,7 @@ Creates list of users with given input array ### Parameters | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **_body** | [**List<User>**](User.md)| List of user object | | +| **_body** | [**List<@Valid User>**](User.md)| List of user object | | diff --git a/samples/client/petstore/java-micronaut-client/docs/models/ArrayTest.md b/samples/client/petstore/java-micronaut-client/docs/models/ArrayTest.md index 3f3ec33c736e..c95e61a50f59 100644 --- a/samples/client/petstore/java-micronaut-client/docs/models/ArrayTest.md +++ b/samples/client/petstore/java-micronaut-client/docs/models/ArrayTest.md @@ -10,7 +10,7 @@ Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **arrayOfString** | `List<String>` | | [optional property] **arrayArrayOfInteger** | `List<List<Long>>` | | [optional property] -**arrayArrayOfModel** | `List<List<ReadOnlyFirst>>` | | [optional property] +**arrayArrayOfModel** | `List<List<@Valid ReadOnlyFirst>>` | | [optional property] diff --git a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/api/UserApi.java index fc76d17cfd6e..524a2eb2c58a 100644 --- a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/api/UserApi.java @@ -48,7 +48,7 @@ Mono createUser( */ @Post(uri="/user/createWithArray") Mono createUsersWithArrayInput( - @Body @NotNull List _body + @Body @NotNull List<@Valid User> _body ); /** @@ -58,7 +58,7 @@ Mono createUsersWithArrayInput( */ @Post(uri="/user/createWithList") Mono createUsersWithListInput( - @Body @NotNull List _body + @Body @NotNull List<@Valid User> _body ); /** diff --git a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/ArrayTest.java b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/ArrayTest.java index 0b0d73bea2e1..9dcb6ea376ae 100644 --- a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { private List> arrayArrayOfInteger = null; public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; - private List> arrayArrayOfModel = null; + private List> arrayArrayOfModel = null; public ArrayTest() { } @@ -108,12 +108,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -128,13 +128,13 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @Nullable @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FileSchemaTestClass.java b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FileSchemaTestClass.java index 7e964895e156..4a4421313811 100644 --- a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { private ModelFile _file; public static final String JSON_PROPERTY_FILES = "files"; - private List files = null; + private List<@Valid ModelFile> files = null; public FileSchemaTestClass() { } @@ -67,7 +67,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -87,13 +87,13 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @Nullable @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FormatTest.java b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FormatTest.java index 1929ddf3f6bf..79665f92cfae 100644 --- a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/FormatTest.java @@ -474,7 +474,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/Pet.java b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/Pet.java index 4f4db37b47bc..19afe15d87de 100644 --- a/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/Pet.java +++ b/samples/client/petstore/java-micronaut-client/src/main/java/org/openapitools/model/Pet.java @@ -57,7 +57,7 @@ public class Pet { private Set photoUrls = new LinkedHashSet<>(); public static final String JSON_PROPERTY_TAGS = "tags"; - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -193,7 +193,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -213,13 +213,13 @@ public Pet addTagsItem(Tag tagsItem) { @Nullable @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/apache-httpclient/.openapi-generator/VERSION b/samples/client/petstore/java/apache-httpclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/apache-httpclient/.openapi-generator/VERSION +++ b/samples/client/petstore/java/apache-httpclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/apache-httpclient/README.md b/samples/client/petstore/java/apache-httpclient/README.md index fa0d4f88db0a..4e08e78fc162 100644 --- a/samples/client/petstore/java/apache-httpclient/README.md +++ b/samples/client/petstore/java/apache-httpclient/README.md @@ -116,6 +116,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/apache-httpclient/api/openapi.yaml b/samples/client/petstore/java/apache-httpclient/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/apache-httpclient/api/openapi.yaml +++ b/samples/client/petstore/java/apache-httpclient/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/apache-httpclient/docs/FakeApi.md b/samples/client/petstore/java/apache-httpclient/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/apache-httpclient/docs/FakeApi.md +++ b/samples/client/petstore/java/apache-httpclient/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java index 1a938cde9593..ada6dcf55ce5 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/ApiClient.java @@ -55,6 +55,7 @@ import java.util.Arrays; import java.util.ArrayList; import java.util.Date; +import java.util.function.Supplier; import java.util.TimeZone; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -66,6 +67,7 @@ import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.charset.Charset; +import java.nio.charset.StandardCharsets; import java.nio.charset.UnsupportedCharsetException; import java.nio.file.Files; import java.nio.file.StandardCopyOption; @@ -353,6 +355,20 @@ public ApiClient setBearerToken(String bearerToken) { throw new RuntimeException("No Bearer authentication configured!"); } + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier the token supplier function + */ + public void setBearerToken(Supplier tokenSupplier) { + for (Authentication auth : authentications.values()) { + if (auth instanceof HttpBearerAuth) { + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); + return; + } + } + throw new RuntimeException("No Bearer authentication configured!"); + } /** * Helper method to set username for the first HTTP basic authentication. @@ -619,7 +635,7 @@ public List parameterToPairs(String collectionFormat, String name, Collect List params = new ArrayList(); // preconditions - if (name == null || name.isEmpty() || value == null) { + if (name == null || name.isEmpty() || value == null || value.isEmpty()) { return params; } @@ -781,7 +797,7 @@ public HttpEntity serialize(Object obj, Map formParams, ContentT String mimeType = contentType.getMimeType(); if (isJsonMime(mimeType)) { try { - return new StringEntity(objectMapper.writeValueAsString(obj), contentType); + return new StringEntity(objectMapper.writeValueAsString(obj), contentType.withCharset(StandardCharsets.UTF_8)); } catch (JsonProcessingException e) { throw new ApiException(e); } diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/FakeApi.java index de6b83f45ac0..dfa04ecda4f4 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/api/FakeApi.java @@ -627,6 +627,77 @@ public OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(OuterObjectW ); } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException if fails to make API call + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + this.testAdditionalPropertiesReference(requestBody, Collections.emptyMap()); + } + + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param additionalHeaders additionalHeaders for this call + * @throws ApiException if fails to make API call + */ + public void testAdditionalPropertiesReference(Map requestBody, Map additionalHeaders) throws ApiException { + Object localVarPostBody = requestBody; + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + // create path and map variables + String localVarPath = "/fake/additionalProperties-reference"; + + StringJoiner localVarQueryStringJoiner = new StringJoiner("&"); + String localVarQueryParameterBaseName; + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + localVarHeaderParams.putAll(additionalHeaders); + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + apiClient.invokeAPI( + localVarPath, + "POST", + localVarQueryParams, + localVarCollectionQueryParams, + localVarQueryStringJoiner.toString(), + localVarPostBody, + localVarHeaderParams, + localVarCookieParams, + localVarFormParams, + localVarAccept, + localVarContentType, + localVarAuthNames, + null + ); + } + /** * * For this test, the body has to be a binary file. diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index e9d4c678963a..a0083b8cf989 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -15,13 +15,15 @@ import org.openapitools.client.Pair; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -33,7 +35,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -42,12 +44,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java index d7e7bb3b9b5b..34da8b03615c 100644 --- a/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/apache-httpclient/src/main/java/org/openapitools/client/model/FormatTest.java @@ -580,7 +580,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/java/feign-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/feign-no-nullable/pom.xml b/samples/client/petstore/java/feign-no-nullable/pom.xml index fae107a9b8ec..c7975dc07593 100644 --- a/samples/client/petstore/java/feign-no-nullable/pom.xml +++ b/samples/client/petstore/java/feign-no-nullable/pom.xml @@ -278,7 +278,7 @@ ch.qos.logback logback-classic - 1.2.12 + 1.3.13 test diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/ApiClient.java index 020dc860b05a..5a8e49298187 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/ApiClient.java @@ -2,6 +2,7 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -206,6 +207,15 @@ public void setBearerToken(String bearerToken) { apiAuthorization.setBearerToken(bearerToken); } + /** + * Helper method to configure the supplier of bearer tokens. + * @param tokenSupplier the supplier of bearer tokens. + */ + public void setBearerToken(Supplier tokenSupplier) { + HttpBearerAuth apiAuthorization = getAuthorization(HttpBearerAuth.class); + apiAuthorization.setBearerToken(tokenSupplier); + } + /** * Helper method to configure the first api key found * @param apiKey API key diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index d4c9cbe6361e..43c1a722ad9f 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -2,13 +2,15 @@ import feign.RequestInterceptor; import feign.RequestTemplate; +import java.util.Optional; +import java.util.function.Supplier; /** * An interceptor that adds the request header needed to use HTTP bearer authentication. */ public class HttpBearerAuth implements RequestInterceptor { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -16,21 +18,35 @@ public HttpBearerAuth(String scheme) { /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void apply(RequestTemplate template) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java index 54561ed8bc30..9635f75f229c 100644 --- a/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java @@ -516,7 +516,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/feign/.openapi-generator/VERSION b/samples/client/petstore/java/feign/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/feign/.openapi-generator/VERSION +++ b/samples/client/petstore/java/feign/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/feign/api/openapi.yaml b/samples/client/petstore/java/feign/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/feign/api/openapi.yaml +++ b/samples/client/petstore/java/feign/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/feign/pom.xml b/samples/client/petstore/java/feign/pom.xml index ff7ae3a800d2..63f065af613d 100644 --- a/samples/client/petstore/java/feign/pom.xml +++ b/samples/client/petstore/java/feign/pom.xml @@ -283,7 +283,7 @@ ch.qos.logback logback-classic - 1.2.12 + 1.3.13 test diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/ApiClient.java index 43f12eea390c..f62a3ba56080 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/ApiClient.java @@ -2,6 +2,7 @@ import java.util.LinkedHashMap; import java.util.Map; +import java.util.function.Supplier; import java.util.logging.Level; import java.util.logging.Logger; @@ -212,6 +213,15 @@ public void setBearerToken(String bearerToken) { apiAuthorization.setBearerToken(bearerToken); } + /** + * Helper method to configure the supplier of bearer tokens. + * @param tokenSupplier the supplier of bearer tokens. + */ + public void setBearerToken(Supplier tokenSupplier) { + HttpBearerAuth apiAuthorization = getAuthorization(HttpBearerAuth.class); + apiAuthorization.setBearerToken(tokenSupplier); + } + /** * Helper method to configure the first api key found * @param apiKey API key diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/api/FakeApi.java index 1d216f59627a..983e5ae93726 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/api/FakeApi.java @@ -314,6 +314,33 @@ public FakeHttpSignatureTestQueryParams query1(final String value) { + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + */ + @RequestLine("POST /fake/additionalProperties-reference") + @Headers({ + "Content-Type: application/json", + "Accept: application/json", + }) + void testAdditionalPropertiesReference(Map requestBody); + + /** + * test referenced additionalProperties + * Similar to testAdditionalPropertiesReference but it also returns the http response headers . + * + * @param requestBody request body (required) + */ + @RequestLine("POST /fake/additionalProperties-reference") + @Headers({ + "Content-Type: application/json", + "Accept: application/json", + }) + ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody); + + + /** * * For this test, the body has to be a binary file. diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index d4c9cbe6361e..43c1a722ad9f 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -2,13 +2,15 @@ import feign.RequestInterceptor; import feign.RequestTemplate; +import java.util.Optional; +import java.util.function.Supplier; /** * An interceptor that adds the request header needed to use HTTP bearer authentication. */ public class HttpBearerAuth implements RequestInterceptor { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -16,21 +18,35 @@ public HttpBearerAuth(String scheme) { /** * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void apply(RequestTemplate template) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java index 0be153739ce6..adc98c41b670 100644 --- a/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/feign/src/main/java/org/openapitools/client/model/FormatTest.java @@ -578,7 +578,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION b/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION +++ b/samples/client/petstore/java/google-api-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java index 9831eac4992d..97bc1facd5a8 100644 --- a/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/google-api-client/src/main/java/org/openapitools/client/model/FormatTest.java @@ -514,7 +514,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION b/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/model/FormatTest.java index d38c78d5d24d..f0a7be27287d 100644 --- a/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8-localdatetime/src/main/java/org/openapitools/client/model/FormatTest.java @@ -507,7 +507,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java index 4094b8e88e6d..f1154d7a1d19 100644 --- a/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java @@ -507,7 +507,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/jersey3/.openapi-generator/VERSION b/samples/client/petstore/java/jersey3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/jersey3/.openapi-generator/VERSION +++ b/samples/client/petstore/java/jersey3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/jersey3/README.md b/samples/client/petstore/java/jersey3/README.md index a4946d81fb5d..42cef0edc3ef 100644 --- a/samples/client/petstore/java/jersey3/README.md +++ b/samples/client/petstore/java/jersey3/README.md @@ -121,6 +121,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/client/petstore/java/jersey3/api/openapi.yaml b/samples/client/petstore/java/jersey3/api/openapi.yaml index 2dcf21ae0b3d..814354567b04 100644 --- a/samples/client/petstore/java/jersey3/api/openapi.yaml +++ b/samples/client/petstore/java/jersey3/api/openapi.yaml @@ -937,6 +937,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1760,6 +1779,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed diff --git a/samples/client/petstore/java/jersey3/docs/FakeApi.md b/samples/client/petstore/java/jersey3/docs/FakeApi.md index 83f469863c9a..55a9c935065e 100644 --- a/samples/client/petstore/java/jersey3/docs/FakeApi.md +++ b/samples/client/petstore/java/jersey3/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | @@ -402,6 +403,70 @@ No authorization required | **200** | Got named array of enums | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | **Map<String,Object>**| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java index 9bf3abd9fbe6..9b965c9b57c4 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/api/FakeApi.java @@ -268,6 +268,45 @@ public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiExce new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(), localVarAccept, localVarContentType, null, localVarReturnType, false); } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException if fails to make API call + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws ApiException { + // Check required parameters + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + String localVarAccept = apiClient.selectHeaderAccept(); + String localVarContentType = apiClient.selectHeaderContentType("application/json"); + return apiClient.invokeAPI("FakeApi.testAdditionalPropertiesReference", "/fake/additionalProperties-reference", "POST", new ArrayList<>(), requestBody, + new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(), localVarAccept, localVarContentType, + null, null, false); + } /** * * For this test, the body for this request much reference a schema named `File`. diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/FormatTest.java index 6b11ca62e0bd..7d038b622e63 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/FormatTest.java @@ -568,7 +568,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java index 73931bb93b1f..6bfc09aaf381 100644 --- a/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ b/samples/client/petstore/java/jersey3/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -45,12 +45,15 @@ public class ObjectWithDeprecatedFields { private String uuid; public static final String JSON_PROPERTY_ID = "id"; + @Deprecated private BigDecimal id; public static final String JSON_PROPERTY_DEPRECATED_REF = "deprecatedRef"; + @Deprecated private DeprecatedObject deprecatedRef; public static final String JSON_PROPERTY_BARS = "bars"; + @Deprecated private List bars; public ObjectWithDeprecatedFields() { @@ -81,6 +84,7 @@ public void setUuid(String uuid) { } + @Deprecated public ObjectWithDeprecatedFields id(BigDecimal id) { this.id = id; return this; @@ -101,6 +105,7 @@ public BigDecimal getId() { } + @Deprecated @JsonProperty(JSON_PROPERTY_ID) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setId(BigDecimal id) { @@ -108,6 +113,7 @@ public void setId(BigDecimal id) { } + @Deprecated public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { this.deprecatedRef = deprecatedRef; return this; @@ -128,6 +134,7 @@ public DeprecatedObject getDeprecatedRef() { } + @Deprecated @JsonProperty(JSON_PROPERTY_DEPRECATED_REF) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setDeprecatedRef(DeprecatedObject deprecatedRef) { @@ -135,6 +142,7 @@ public void setDeprecatedRef(DeprecatedObject deprecatedRef) { } + @Deprecated public ObjectWithDeprecatedFields bars(List bars) { this.bars = bars; return this; @@ -163,6 +171,7 @@ public List getBars() { } + @Deprecated @JsonProperty(JSON_PROPERTY_BARS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) public void setBars(List bars) { diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/.openapi-generator/VERSION +++ b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/pom.xml b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/pom.xml index 455e21c1752a..6e4d713cd549 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/pom.xml +++ b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson-with-xml/pom.xml @@ -155,7 +155,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 3.2.7 2.15.2 2.15.2 @@ -177,4 +177,4 @@ 1.9.1 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/pom.xml b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/pom.xml index a8c63806a460..5bbd1cc4126c 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/pom.xml +++ b/samples/client/petstore/java/microprofile-rest-client-3.0-jackson/pom.xml @@ -144,7 +144,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 3.2.7 2.15.2 2.15.2 @@ -166,4 +166,4 @@ 1.9.1 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client-3.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0/.openapi-generator/VERSION +++ b/samples/client/petstore/java/microprofile-rest-client-3.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client-3.0/pom.xml b/samples/client/petstore/java/microprofile-rest-client-3.0/pom.xml index a626f54ce729..96d1ecac63c2 100644 --- a/samples/client/petstore/java/microprofile-rest-client-3.0/pom.xml +++ b/samples/client/petstore/java/microprofile-rest-client-3.0/pom.xml @@ -153,7 +153,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 3.2.7 2.15.2 2.1.0 @@ -174,4 +174,4 @@ 1.9.1 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator-ignore b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/FILES b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/FILES new file mode 100644 index 000000000000..ae145903e52b --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/FILES @@ -0,0 +1,22 @@ +README.md +docs/Category.md +docs/ModelApiResponse.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +pom.xml +src/main/java/org/openapitools/client/api/ApiException.java +src/main/java/org/openapitools/client/api/ApiExceptionMapper.java +src/main/java/org/openapitools/client/api/PetApi.java +src/main/java/org/openapitools/client/api/StoreApi.java +src/main/java/org/openapitools/client/api/UserApi.java +src/main/java/org/openapitools/client/model/Category.java +src/main/java/org/openapitools/client/model/ModelApiResponse.java +src/main/java/org/openapitools/client/model/Order.java +src/main/java/org/openapitools/client/model/Pet.java +src/main/java/org/openapitools/client/model/Tag.java +src/main/java/org/openapitools/client/model/User.java diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/README.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/README.md new file mode 100644 index 000000000000..e95301f74cda --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/README.md @@ -0,0 +1,8 @@ +# OpenAPI Petstore - MicroProfile Rest Client + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +[MicroProfile Rest Client](https://github.com/eclipse/microprofile-rest-client) is a type-safe way of calling +REST services. The generated client contains an interface which acts as the client, you can inject it into dependent classes. diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Category.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Category.md new file mode 100644 index 000000000000..a7fc939d252e --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Category.md @@ -0,0 +1,15 @@ + + +# Category + +A category for a pet + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/ModelApiResponse.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/ModelApiResponse.md new file mode 100644 index 000000000000..cd7e3c400be6 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/ModelApiResponse.md @@ -0,0 +1,16 @@ + + +# ModelApiResponse + +Describes the result of uploading an image resource + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**code** | **Integer** | | [optional] | +|**type** | **String** | | [optional] | +|**message** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Order.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Order.md new file mode 100644 index 000000000000..7bfa42e6a902 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Order.md @@ -0,0 +1,29 @@ + + +# Order + +An order for a pets from the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **Date** | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Pet.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Pet.md new file mode 100644 index 000000000000..8bb363301232 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Pet.md @@ -0,0 +1,29 @@ + + +# Pet + +A pet for sale in the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | pet status in the store | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| AVAILABLE | "available" | +| PENDING | "pending" | +| SOLD | "sold" | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/PetApi.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/PetApi.md new file mode 100644 index 000000000000..fb5361b0808f --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/PetApi.md @@ -0,0 +1,604 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store | +| [**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet | +| [**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status | +| [**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags | +| [**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID | +| [**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet | +| [**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data | +| [**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image | + + + +## addPet + +> Pet addPet(pet) + +Add a new pet to the store + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.addPet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + + +## deletePet + +> void deletePet(petId, apiKey) + +Deletes a pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | Pet id to delete + String apiKey = "apiKey_example"; // String | + try { + void result = apiInstance.deletePet(petId, apiKey); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#deletePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| Pet id to delete | | +| **apiKey** | **String**| | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + + +## findPetsByStatus + +> List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List status = Arrays.asList("available"); // List | Status values that need to be considered for filter + try { + List result = apiInstance.findPetsByStatus(status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByStatus"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **status** | [**List<String>**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + List tags = Arrays.asList(); // List | Tags to filter by + try { + List result = apiInstance.findPetsByTags(tags); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#findPetsByTags"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **tags** | [**List<String>**](String.md)| Tags to filter by | | + +### Return type + +[**List<Pet>**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to return + try { + Pet result = apiInstance.getPetById(petId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#getPetById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to return | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> Pet updatePet(pet) + +Update an existing pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + try { + Pet result = apiInstance.updatePet(pet); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePet"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> void updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet that needs to be updated + String name = "name_example"; // String | Updated name of the pet + String status = "status_example"; // String | Updated status of the pet + try { + void result = apiInstance.updatePetWithForm(petId, name, status); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#updatePetWithForm"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet that needs to be updated | | +| **name** | **String**| Updated name of the pet | [optional] | +| **status** | **String**| Updated status of the pet | [optional] | + +### Return type + +[**void**](Void.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **405** | Invalid input | - | + + +## uploadFile + +> ModelApiResponse uploadFile(petId, additionalMetadata, _file) + +uploads an image + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.PetApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure OAuth2 access token for authorization: petstore_auth + OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); + petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); + + PetApi apiInstance = new PetApi(defaultClient); + Long petId = 56L; // Long | ID of pet to update + String additionalMetadata = "additionalMetadata_example"; // String | Additional data to pass to server + File _file = new File("/path/to/file"); // File | file to upload + try { + ModelApiResponse result = apiInstance.uploadFile(petId, additionalMetadata, _file); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling PetApi#uploadFile"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **petId** | **Long**| ID of pet to update | | +| **additionalMetadata** | **String**| Additional data to pass to server | [optional] | +| **_file** | **File**| file to upload | [optional] | + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/StoreApi.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/StoreApi.md new file mode 100644 index 000000000000..ae64b8574e22 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/StoreApi.md @@ -0,0 +1,283 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID | +| [**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status | +| [**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID | +| [**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet | + + + +## deleteOrder + +> void deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + String orderId = "orderId_example"; // String | ID of the order that needs to be deleted + try { + void result = apiInstance.deleteOrder(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#deleteOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **String**| ID of the order that needs to be deleted | | + +### Return type + +[**void**](Void.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> Map<String, Integer> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + StoreApi apiInstance = new StoreApi(defaultClient); + try { + Map result = apiInstance.getInventory(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getInventory"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +**Map<String, Integer>** + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Long orderId = 56L; // Long | ID of pet that needs to be fetched + try { + Order result = apiInstance.getOrderById(orderId); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#getOrderById"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **orderId** | **Long**| ID of pet that needs to be fetched | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> Order placeOrder(order) + +Place an order for a pet + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.StoreApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + StoreApi apiInstance = new StoreApi(defaultClient); + Order order = new Order(); // Order | order placed for purchasing the pet + try { + Order result = apiInstance.placeOrder(order); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling StoreApi#placeOrder"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **order** | [**Order**](Order.md)| order placed for purchasing the pet | | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Tag.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Tag.md new file mode 100644 index 000000000000..abfde4afb501 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/Tag.md @@ -0,0 +1,15 @@ + + +# Tag + +A tag for a pet + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/User.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/User.md new file mode 100644 index 000000000000..426845227bd3 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/User.md @@ -0,0 +1,21 @@ + + +# User + +A User who is purchasing from the pet store + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | + + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/UserApi.md b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/UserApi.md new file mode 100644 index 000000000000..89c1bfc6026d --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/docs/UserApi.md @@ -0,0 +1,591 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**createUser**](UserApi.md#createUser) | **POST** /user | Create user | +| [**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array | +| [**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array | +| [**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user | +| [**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name | +| [**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system | +| [**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session | +| [**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user | + + + +## createUser + +> void createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + User user = new User(); // User | Created user object + try { + void result = apiInstance.createUser(user); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**User**](User.md)| Created user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## createUsersWithArrayInput + +> void createUsersWithArrayInput(user) + +Creates list of users with given input array + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + void result = apiInstance.createUsersWithArrayInput(user); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithArrayInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## createUsersWithListInput + +> void createUsersWithListInput(user) + +Creates list of users with given input array + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + List user = Arrays.asList(); // List | List of user object + try { + void result = apiInstance.createUsersWithListInput(user); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#createUsersWithListInput"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **user** | [**List<User>**](User.md)| List of user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## deleteUser + +> void deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be deleted + try { + void result = apiInstance.deleteUser(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#deleteUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be deleted | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> User getUserByName(username) + +Get user by user name + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The name that needs to be fetched. Use user1 for testing. + try { + User result = apiInstance.getUserByName(username); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#getUserByName"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The name that needs to be fetched. Use user1 for testing. | | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> String loginUser(username, password) + +Logs user into the system + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | The user name for login + String password = "password_example"; // String | The password for login in clear text + try { + String result = apiInstance.loginUser(username, password); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#loginUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| The user name for login | | +| **password** | **String**| The password for login in clear text | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `api_key` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> void logoutUser() + +Logs out current logged in user session + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + try { + void result = apiInstance.logoutUser(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#logoutUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## updateUser + +> void updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.auth.*; +import org.openapitools.client.models.*; +import org.openapitools.client.api.UserApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + // Configure API key authorization: api_key + ApiKeyAuth api_key = (ApiKeyAuth) defaultClient.getAuthentication("api_key"); + api_key.setApiKey("YOUR API KEY"); + // Uncomment the following line to set a prefix for the API key, e.g. "Token" (defaults to null) + //api_key.setApiKeyPrefix("Token"); + + UserApi apiInstance = new UserApi(defaultClient); + String username = "username_example"; // String | name that need to be deleted + User user = new User(); // User | Updated user object + try { + void result = apiInstance.updateUser(username, user); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling UserApi#updateUser"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **username** | **String**| name that need to be deleted | | +| **user** | [**User**](User.md)| Updated user object | | + +### Return type + +[**void**](Void.md) + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/pom.xml b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/pom.xml new file mode 100644 index 000000000000..0e9d09ffb0a3 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/pom.xml @@ -0,0 +1,177 @@ + + 4.0.0 + org.openapitools + microprofile-rest-client + jar + microprofile-rest-client + This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + 1.0.0 + + src/main/java + + + org.jboss.jandex + jandex-maven-plugin + ${jandex.maven.plugin.version} + + + make-index + + jandex + + + + + + maven-failsafe-plugin + ${maven.failsafe.plugin.version} + + + + integration-test + verify + + + + + + org.codehaus.mojo + build-helper-maven-plugin + ${build.helper.maven.plugin.version} + + + add-source + generate-sources + + add-source + + + + src/gen/java + + + + + + + + + + junit + junit + ${junit.version} + test + + + + org.eclipse.microprofile.rest.client + microprofile-rest-client-api + ${microprofile.rest.client.api.version} + + + + + jakarta.ws.rs + jakarta.ws.rs-api + ${jakarta.ws.rs.version} + provided + + + + org.glassfish.jersey.ext.microprofile + jersey-mp-rest-client + ${jersey.mp.rest.client.version} + test + + + org.apache.geronimo.config + geronimo-config-impl + ${geronimo.config.impl.version} + test + + + + org.apache.cxf + cxf-rt-rs-extension-providers + ${cxf.rt.rs.extension.providers.version} + + + jakarta.json.bind + jakarta.json.bind-api + ${jakarta.json.bind.version} + + + jakarta.json + jakarta.json-api + ${jakarta.json.version} + + + jakarta.xml.bind + jakarta.xml.bind-api + ${jakarta.xml.bind.version} + + + com.sun.xml.bind + jaxb-core + ${jaxb.core.version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb.impl.version} + + + jakarta.activation + jakarta.activation-api + ${jakarta.activation.version} + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + ${jackson.jaxrs.version} + + + jakarta.annotation + jakarta.annotation-api + ${jakarta.annotation.version} + provided + + + + + sonatype-snapshots + https://oss.sonatype.org/content/repositories/snapshots + + true + + + + + 11 + ${java.version} + ${java.version} + 1.5.18 + 9.2.9.v20150224 + 4.13.2 + 1.4.14 + 3.2.7 + 2.15.2 + 2.1.0 + 2.0.0 + 2.0.0 + 2.0.1 + 3.0.0 + 3.0.1 + 3.0 + 3.0.4 + 1.2.3 + 3.5.1 + 3.0.2 + 3.0.2 + 7.0.4.Final + 1.1.0 + 2.6 + 1.9.1 + UTF-8 + + diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiException.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiException.java new file mode 100644 index 000000000000..2fc6d04ee687 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiException.java @@ -0,0 +1,34 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import jakarta.ws.rs.core.Response; + +public class ApiException extends Exception { + + private static final long serialVersionUID = 1L; + private Response response; + + public ApiException() { + super(); + } + + public ApiException(Response response) { + super("Api response has status code " + response.getStatus()); + this.response = response; + } + + public Response getResponse() { + return this.response; + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java new file mode 100644 index 000000000000..0dec2c6aec06 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/ApiExceptionMapper.java @@ -0,0 +1,33 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import jakarta.ws.rs.core.MultivaluedMap; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.ext.Provider; +import org.eclipse.microprofile.rest.client.ext.ResponseExceptionMapper; + +@Provider +public class ApiExceptionMapper + implements ResponseExceptionMapper { + + @Override + public boolean handles(int status, MultivaluedMap headers) { + return status >= 400; + } + + @Override + public ApiException toThrowable(Response response) { + return new ApiException(response); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/PetApi.java new file mode 100644 index 000000000000..55c25f97f820 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/PetApi.java @@ -0,0 +1,312 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +/** + * OpenAPI Petstore + * + *

              This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + */ + +@RegisterRestClient(configKey="petstore") +@RegisterProvider(ApiExceptionMapper.class) +@Path("/pet") +public interface PetApi { + + /** + * Add a new pet to the store + * + * + * + */ + @POST + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Pet addPet(Pet pet) throws ApiException, ProcessingException; + + /** + * Deletes a pet + * + * + * + */ + @DELETE + @Path("/{petId}") + void deletePet(@BeanParam DeletePetRequest request) throws ApiException, ProcessingException; + public class DeletePetRequest { + + private @HeaderParam("api_key") String apiKey; + private @PathParam("petId") Long petId; + + private DeletePetRequest() { + } + + public static DeletePetRequest newInstance() { + return new DeletePetRequest(); + } + + /** + * Set petId + * @param petId Pet id to delete (required) + * @return DeletePetRequest + */ + public DeletePetRequest petId(Long petId) { + this.petId = petId; + return this; + } + /** + * Set apiKey + * @param apiKey (optional) + * @return DeletePetRequest + */ + public DeletePetRequest apiKey(String apiKey) { + this.apiKey = apiKey; + return this; + } + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + */ + @GET + @Path("/findByStatus") + @Produces({ "application/xml", "application/json" }) + List findPetsByStatus(@BeanParam FindPetsByStatusRequest request) throws ApiException, ProcessingException; + public class FindPetsByStatusRequest { + + private @QueryParam("status") List status; + + private FindPetsByStatusRequest() { + } + + public static FindPetsByStatusRequest newInstance() { + return new FindPetsByStatusRequest(); + } + + /** + * Set status + * @param status Status values that need to be considered for filter (required) + * @return FindPetsByStatusRequest + */ + public FindPetsByStatusRequest status(List status) { + this.status = status; + return this; + } + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @deprecated + */ + @Deprecated + @GET + @Path("/findByTags") + @Produces({ "application/xml", "application/json" }) + List findPetsByTags(@BeanParam FindPetsByTagsRequest request) throws ApiException, ProcessingException; + public class FindPetsByTagsRequest { + + private @QueryParam("tags") List tags; + + private FindPetsByTagsRequest() { + } + + public static FindPetsByTagsRequest newInstance() { + return new FindPetsByTagsRequest(); + } + + /** + * Set tags + * @param tags Tags to filter by (required) + * @return FindPetsByTagsRequest + */ + public FindPetsByTagsRequest tags(List tags) { + this.tags = tags; + return this; + } + } + + /** + * Find pet by ID + * + * Returns a single pet + * + */ + @GET + @Path("/{petId}") + @Produces({ "application/xml", "application/json" }) + Pet getPetById(@BeanParam GetPetByIdRequest request) throws ApiException, ProcessingException; + public class GetPetByIdRequest { + + private @PathParam("petId") Long petId; + + private GetPetByIdRequest() { + } + + public static GetPetByIdRequest newInstance() { + return new GetPetByIdRequest(); + } + + /** + * Set petId + * @param petId ID of pet to return (required) + * @return GetPetByIdRequest + */ + public GetPetByIdRequest petId(Long petId) { + this.petId = petId; + return this; + } + } + + /** + * Update an existing pet + * + * + * + */ + @PUT + + @Consumes({ "application/json", "application/xml" }) + @Produces({ "application/xml", "application/json" }) + Pet updatePet(Pet pet) throws ApiException, ProcessingException; + + /** + * Updates a pet in the store with form data + * + * + * + */ + @POST + @Path("/{petId}") + @Consumes({ "application/x-www-form-urlencoded" }) + void updatePetWithForm(@BeanParam UpdatePetWithFormRequest request) throws ApiException, ProcessingException; + public class UpdatePetWithFormRequest { + + private @PathParam("petId") Long petId; + private @Multipart(value = "name", required = false) String name; + private @Multipart(value = "status", required = false) String status; + + private UpdatePetWithFormRequest() { + } + + public static UpdatePetWithFormRequest newInstance() { + return new UpdatePetWithFormRequest(); + } + + /** + * Set petId + * @param petId ID of pet that needs to be updated (required) + * @return UpdatePetWithFormRequest + */ + public UpdatePetWithFormRequest petId(Long petId) { + this.petId = petId; + return this; + } + /** + * Set name + * @param name Updated name of the pet (optional) + * @return UpdatePetWithFormRequest + */ + public UpdatePetWithFormRequest name(String name) { + this.name = name; + return this; + } + /** + * Set status + * @param status Updated status of the pet (optional) + * @return UpdatePetWithFormRequest + */ + public UpdatePetWithFormRequest status(String status) { + this.status = status; + return this; + } + } + + /** + * uploads an image + * + * + * + */ + @POST + @Path("/{petId}/uploadImage") + @Consumes({ "multipart/form-data" }) + @Produces({ "application/json" }) + ModelApiResponse uploadFile(@BeanParam UploadFileRequest request) throws ApiException, ProcessingException; + public class UploadFileRequest { + + private @PathParam("petId") Long petId; + private @Multipart(value = "additionalMetadata", required = false) String additionalMetadata; + private @Multipart(value = "file" , required = false) Attachment _fileDetail; + + private UploadFileRequest() { + } + + public static UploadFileRequest newInstance() { + return new UploadFileRequest(); + } + + /** + * Set petId + * @param petId ID of pet to update (required) + * @return UploadFileRequest + */ + public UploadFileRequest petId(Long petId) { + this.petId = petId; + return this; + } + /** + * Set additionalMetadata + * @param additionalMetadata Additional data to pass to server (optional) + * @return UploadFileRequest + */ + public UploadFileRequest additionalMetadata(String additionalMetadata) { + this.additionalMetadata = additionalMetadata; + return this; + } + /** + * Set _fileDetail + * @param _fileDetail file to upload (optional) + * @return UploadFileRequest + */ + public UploadFileRequest _fileDetail( Attachment _fileDetail) { + this._fileDetail = _fileDetail; + return this; + } + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/StoreApi.java new file mode 100644 index 000000000000..d95b73db2091 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/StoreApi.java @@ -0,0 +1,128 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import org.openapitools.client.model.Order; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +/** + * OpenAPI Petstore + * + *

              This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + */ + +@RegisterRestClient(configKey="petstore") +@RegisterProvider(ApiExceptionMapper.class) +@Path("/store") +public interface StoreApi { + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + */ + @DELETE + @Path("/order/{orderId}") + void deleteOrder(@BeanParam DeleteOrderRequest request) throws ApiException, ProcessingException; + public class DeleteOrderRequest { + + private @PathParam("orderId") String orderId; + + private DeleteOrderRequest() { + } + + public static DeleteOrderRequest newInstance() { + return new DeleteOrderRequest(); + } + + /** + * Set orderId + * @param orderId ID of the order that needs to be deleted (required) + * @return DeleteOrderRequest + */ + public DeleteOrderRequest orderId(String orderId) { + this.orderId = orderId; + return this; + } + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + */ + @GET + @Path("/inventory") + @Produces({ "application/json" }) + Map getInventory() throws ApiException, ProcessingException; + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * + */ + @GET + @Path("/order/{orderId}") + @Produces({ "application/xml", "application/json" }) + Order getOrderById(@BeanParam GetOrderByIdRequest request) throws ApiException, ProcessingException; + public class GetOrderByIdRequest { + + private @PathParam("orderId") Long orderId; + + private GetOrderByIdRequest() { + } + + public static GetOrderByIdRequest newInstance() { + return new GetOrderByIdRequest(); + } + + /** + * Set orderId + * @param orderId ID of pet that needs to be fetched (required) + * @return GetOrderByIdRequest + */ + public GetOrderByIdRequest orderId(Long orderId) { + this.orderId = orderId; + return this; + } + } + + /** + * Place an order for a pet + * + * + * + */ + @POST + @Path("/order") + @Consumes({ "application/json" }) + @Produces({ "application/xml", "application/json" }) + Order placeOrder(Order order) throws ApiException, ProcessingException; +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/UserApi.java new file mode 100644 index 000000000000..a45d07d34581 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/api/UserApi.java @@ -0,0 +1,223 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import java.util.Date; +import org.openapitools.client.model.User; + +import java.io.InputStream; +import java.io.OutputStream; +import java.util.List; +import java.util.Map; +import java.util.Set; +import jakarta.ws.rs.*; +import jakarta.ws.rs.core.Response; +import jakarta.ws.rs.core.MediaType; +import org.apache.cxf.jaxrs.ext.multipart.*; + + +import org.eclipse.microprofile.rest.client.annotation.RegisterProvider; +import org.eclipse.microprofile.rest.client.inject.RegisterRestClient; + +/** + * OpenAPI Petstore + * + *

              This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + */ + +@RegisterRestClient(configKey="petstore") +@RegisterProvider(ApiExceptionMapper.class) +@Path("/user") +public interface UserApi { + + /** + * Create user + * + * This can only be done by the logged in user. + * + */ + @POST + + @Consumes({ "application/json" }) + void createUser(User user) throws ApiException, ProcessingException; + + /** + * Creates list of users with given input array + * + * + * + */ + @POST + @Path("/createWithArray") + @Consumes({ "application/json" }) + void createUsersWithArrayInput(List user) throws ApiException, ProcessingException; + + /** + * Creates list of users with given input array + * + * + * + */ + @POST + @Path("/createWithList") + @Consumes({ "application/json" }) + void createUsersWithListInput(List user) throws ApiException, ProcessingException; + + /** + * Delete user + * + * This can only be done by the logged in user. + * + */ + @DELETE + @Path("/{username}") + void deleteUser(@BeanParam DeleteUserRequest request) throws ApiException, ProcessingException; + public class DeleteUserRequest { + + private @PathParam("username") String username; + + private DeleteUserRequest() { + } + + public static DeleteUserRequest newInstance() { + return new DeleteUserRequest(); + } + + /** + * Set username + * @param username The name that needs to be deleted (required) + * @return DeleteUserRequest + */ + public DeleteUserRequest username(String username) { + this.username = username; + return this; + } + } + + /** + * Get user by user name + * + * + * + */ + @GET + @Path("/{username}") + @Produces({ "application/xml", "application/json" }) + User getUserByName(@BeanParam GetUserByNameRequest request) throws ApiException, ProcessingException; + public class GetUserByNameRequest { + + private @PathParam("username") String username; + + private GetUserByNameRequest() { + } + + public static GetUserByNameRequest newInstance() { + return new GetUserByNameRequest(); + } + + /** + * Set username + * @param username The name that needs to be fetched. Use user1 for testing. (required) + * @return GetUserByNameRequest + */ + public GetUserByNameRequest username(String username) { + this.username = username; + return this; + } + } + + /** + * Logs user into the system + * + * + * + */ + @GET + @Path("/login") + @Produces({ "application/xml", "application/json" }) + String loginUser(@BeanParam LoginUserRequest request) throws ApiException, ProcessingException; + public class LoginUserRequest { + + private @QueryParam("username") String username; + private @QueryParam("password") String password; + + private LoginUserRequest() { + } + + public static LoginUserRequest newInstance() { + return new LoginUserRequest(); + } + + /** + * Set username + * @param username The user name for login (required) + * @return LoginUserRequest + */ + public LoginUserRequest username(String username) { + this.username = username; + return this; + } + /** + * Set password + * @param password The password for login in clear text (required) + * @return LoginUserRequest + */ + public LoginUserRequest password(String password) { + this.password = password; + return this; + } + } + + /** + * Logs out current logged in user session + * + * + * + */ + @GET + @Path("/logout") + void logoutUser() throws ApiException, ProcessingException; + + /** + * Updated user + * + * This can only be done by the logged in user. + * + */ + @PUT + @Path("/{username}") + @Consumes({ "application/json" }) + void updateUser(@BeanParam UpdateUserRequest request, User user) throws ApiException, ProcessingException; + public class UpdateUserRequest { + + private @PathParam("username") String username; + + private UpdateUserRequest() { + } + + public static UpdateUserRequest newInstance() { + return new UpdateUserRequest(); + } + + /** + * Set username + * @param username name that need to be deleted (required) + * @return UpdateUserRequest + */ + public UpdateUserRequest username(String username) { + this.username = username; + return this; + } + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Category.java new file mode 100644 index 000000000000..f288f561181b --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Category.java @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * A category for a pet + **/ + +public class Category { + + @JsonbProperty("id") + private Long id; + + @JsonbProperty("name") + private String name; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Category name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java new file mode 100644 index 000000000000..b1a8ea4f25e5 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -0,0 +1,127 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * Describes the result of uploading an image resource + **/ + +public class ModelApiResponse { + + @JsonbProperty("code") + private Integer code; + + @JsonbProperty("type") + private String type; + + @JsonbProperty("message") + private String message; + + /** + * Get code + * @return code + **/ + public Integer getCode() { + return code; + } + + /** + * Set code + **/ + public void setCode(Integer code) { + this.code = code; + } + + public ModelApiResponse code(Integer code) { + this.code = code; + return this; + } + + /** + * Get type + * @return type + **/ + public String getType() { + return type; + } + + /** + * Set type + **/ + public void setType(String type) { + this.type = type; + } + + public ModelApiResponse type(String type) { + this.type = type; + return this; + } + + /** + * Get message + * @return message + **/ + public String getMessage() { + return message; + } + + /** + * Set message + **/ + public void setMessage(String message) { + this.message = message; + } + + public ModelApiResponse message(String message) { + this.message = message; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class ModelApiResponse {\n"); + + sb.append(" code: ").append(toIndentedString(code)).append("\n"); + sb.append(" type: ").append(toIndentedString(type)).append("\n"); + sb.append(" message: ").append(toIndentedString(message)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Order.java new file mode 100644 index 000000000000..6518f71fce6e --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Order.java @@ -0,0 +1,245 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.util.Date; +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * An order for a pets from the pet store + **/ + +public class Order { + + @JsonbProperty("id") + private Long id; + + @JsonbProperty("petId") + private Long petId; + + @JsonbProperty("quantity") + private Integer quantity; + + @JsonbProperty("shipDate") + private Date shipDate; + + @JsonbTypeSerializer(StatusEnum.Serializer.class) + @JsonbTypeDeserializer(StatusEnum.Deserializer.class) + public enum StatusEnum { + + PLACED(String.valueOf("placed")), APPROVED(String.valueOf("approved")), DELIVERED(String.valueOf("delivered")); + + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static final class Deserializer implements JsonbDeserializer { + @Override + public StatusEnum deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'"); + } + } + + public static final class Serializer implements JsonbSerializer { + @Override + public void serialize(StatusEnum obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } + } + + /** + * Order Status + **/ + @JsonbProperty("status") + private StatusEnum status; + + @JsonbProperty("complete") + private Boolean complete = false; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Order id(Long id) { + this.id = id; + return this; + } + + /** + * Get petId + * @return petId + **/ + public Long getPetId() { + return petId; + } + + /** + * Set petId + **/ + public void setPetId(Long petId) { + this.petId = petId; + } + + public Order petId(Long petId) { + this.petId = petId; + return this; + } + + /** + * Get quantity + * @return quantity + **/ + public Integer getQuantity() { + return quantity; + } + + /** + * Set quantity + **/ + public void setQuantity(Integer quantity) { + this.quantity = quantity; + } + + public Order quantity(Integer quantity) { + this.quantity = quantity; + return this; + } + + /** + * Get shipDate + * @return shipDate + **/ + public Date getShipDate() { + return shipDate; + } + + /** + * Set shipDate + **/ + public void setShipDate(Date shipDate) { + this.shipDate = shipDate; + } + + public Order shipDate(Date shipDate) { + this.shipDate = shipDate; + return this; + } + + /** + * Order Status + * @return status + **/ + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Order status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * Get complete + * @return complete + **/ + public Boolean getComplete() { + return complete; + } + + /** + * Set complete + **/ + public void setComplete(Boolean complete) { + this.complete = complete; + } + + public Order complete(Boolean complete) { + this.complete = complete; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Order {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" petId: ").append(toIndentedString(petId)).append("\n"); + sb.append(" quantity: ").append(toIndentedString(quantity)).append("\n"); + sb.append(" shipDate: ").append(toIndentedString(shipDate)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append(" complete: ").append(toIndentedString(complete)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Pet.java new file mode 100644 index 000000000000..50d982f0be7f --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Pet.java @@ -0,0 +1,267 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * A pet for sale in the pet store + **/ + +public class Pet { + + @JsonbProperty("id") + private Long id; + + @JsonbProperty("category") + private Category category; + + @JsonbProperty("name") + private String name; + + @JsonbProperty("photoUrls") + private List photoUrls = new ArrayList<>(); + + @JsonbProperty("tags") + private List tags = null; + + @JsonbTypeSerializer(StatusEnum.Serializer.class) + @JsonbTypeDeserializer(StatusEnum.Deserializer.class) + public enum StatusEnum { + + AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); + + + String value; + + StatusEnum (String v) { + value = v; + } + + public String value() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + public static final class Deserializer implements JsonbDeserializer { + @Override + public StatusEnum deserialize(JsonParser parser, DeserializationContext ctx, Type rtType) { + for (StatusEnum b : StatusEnum.values()) { + if (String.valueOf(b.value).equals(parser.getString())) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + parser.getString() + "'"); + } + } + + public static final class Serializer implements JsonbSerializer { + @Override + public void serialize(StatusEnum obj, JsonGenerator generator, SerializationContext ctx) { + generator.write(obj.value); + } + } + } + + /** + * pet status in the store + **/ + @JsonbProperty("status") + private StatusEnum status; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get category + * @return category + **/ + public Category getCategory() { + return category; + } + + /** + * Set category + **/ + public void setCategory(Category category) { + this.category = category; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get photoUrls + * @return photoUrls + **/ + public List getPhotoUrls() { + return photoUrls; + } + + /** + * Set photoUrls + **/ + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get tags + * @return tags + **/ + public List getTags() { + return tags; + } + + /** + * Set tags + **/ + public void setTags(List tags) { + this.tags = tags; + } + + public Pet tags(List tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * pet status in the store + * @return status + * @deprecated + **/ + @Deprecated + public StatusEnum getStatus() { + return status; + } + + /** + * Set status + **/ + public void setStatus(StatusEnum status) { + this.status = status; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Tag.java new file mode 100644 index 000000000000..09ed3b6f9750 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/Tag.java @@ -0,0 +1,103 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * A tag for a pet + **/ + +public class Tag { + + @JsonbProperty("id") + private Long id; + + @JsonbProperty("name") + private String name; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get name + * @return name + **/ + public String getName() { + return name; + } + + /** + * Set name + **/ + public void setName(String name) { + this.name = name; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/User.java new file mode 100644 index 000000000000..9dce754424ba --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/main/java/org/openapitools/client/model/User.java @@ -0,0 +1,250 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.model; + +import java.lang.reflect.Type; +import jakarta.json.bind.annotation.JsonbTypeDeserializer; +import jakarta.json.bind.annotation.JsonbTypeSerializer; +import jakarta.json.bind.serializer.DeserializationContext; +import jakarta.json.bind.serializer.JsonbDeserializer; +import jakarta.json.bind.serializer.JsonbSerializer; +import jakarta.json.bind.serializer.SerializationContext; +import jakarta.json.stream.JsonGenerator; +import jakarta.json.stream.JsonParser; +import jakarta.json.bind.annotation.JsonbProperty; + +/** + * A User who is purchasing from the pet store + **/ + +public class User { + + @JsonbProperty("id") + private Long id; + + @JsonbProperty("username") + private String username; + + @JsonbProperty("firstName") + private String firstName; + + @JsonbProperty("lastName") + private String lastName; + + @JsonbProperty("email") + private String email; + + @JsonbProperty("password") + private String password; + + @JsonbProperty("phone") + private String phone; + + /** + * User Status + **/ + @JsonbProperty("userStatus") + private Integer userStatus; + + /** + * Get id + * @return id + **/ + public Long getId() { + return id; + } + + /** + * Set id + **/ + public void setId(Long id) { + this.id = id; + } + + public User id(Long id) { + this.id = id; + return this; + } + + /** + * Get username + * @return username + **/ + public String getUsername() { + return username; + } + + /** + * Set username + **/ + public void setUsername(String username) { + this.username = username; + } + + public User username(String username) { + this.username = username; + return this; + } + + /** + * Get firstName + * @return firstName + **/ + public String getFirstName() { + return firstName; + } + + /** + * Set firstName + **/ + public void setFirstName(String firstName) { + this.firstName = firstName; + } + + public User firstName(String firstName) { + this.firstName = firstName; + return this; + } + + /** + * Get lastName + * @return lastName + **/ + public String getLastName() { + return lastName; + } + + /** + * Set lastName + **/ + public void setLastName(String lastName) { + this.lastName = lastName; + } + + public User lastName(String lastName) { + this.lastName = lastName; + return this; + } + + /** + * Get email + * @return email + **/ + public String getEmail() { + return email; + } + + /** + * Set email + **/ + public void setEmail(String email) { + this.email = email; + } + + public User email(String email) { + this.email = email; + return this; + } + + /** + * Get password + * @return password + **/ + public String getPassword() { + return password; + } + + /** + * Set password + **/ + public void setPassword(String password) { + this.password = password; + } + + public User password(String password) { + this.password = password; + return this; + } + + /** + * Get phone + * @return phone + **/ + public String getPhone() { + return phone; + } + + /** + * Set phone + **/ + public void setPhone(String phone) { + this.phone = phone; + } + + public User phone(String phone) { + this.phone = phone; + return this; + } + + /** + * User Status + * @return userStatus + **/ + public Integer getUserStatus() { + return userStatus; + } + + /** + * Set userStatus + **/ + public void setUserStatus(Integer userStatus) { + this.userStatus = userStatus; + } + + public User userStatus(Integer userStatus) { + this.userStatus = userStatus; + return this; + } + + + /** + * Create a string representation of this pojo. + **/ + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class User {\n"); + + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" username: ").append(toIndentedString(username)).append("\n"); + sb.append(" firstName: ").append(toIndentedString(firstName)).append("\n"); + sb.append(" lastName: ").append(toIndentedString(lastName)).append("\n"); + sb.append(" email: ").append(toIndentedString(email)).append("\n"); + sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" phone: ").append(toIndentedString(phone)).append("\n"); + sb.append(" userStatus: ").append(toIndentedString(userStatus)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private static String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 000000000000..5ba1fd677b1b --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,198 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.io.File; +import org.openapitools.client.model.ModelApiResponse; +import org.openapitools.client.model.Pet; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for PetApi + */ +public class PetApiTest { + + private PetApi client; + private String baseUrl = "http://localhost:9080"; + + @Before + public void setup() throws MalformedURLException { + // TODO initialize the client + } + + + /** + * Add a new pet to the store + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void addPetTest() { + // TODO: test validations + Pet pet = null; + //Pet response = api.addPet(pet); + //assertNotNull(response); + + + } + + /** + * Deletes a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deletePetTest() { + // TODO: test validations + Long petId = null; + String apiKey = null; + //api.deletePet(petId, apiKey); + //assertNotNull(response); + + + } + + /** + * Finds Pets by status + * + * Multiple status values can be provided with comma separated strings + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByStatusTest() { + // TODO: test validations + List status = null; + //List response = api.findPetsByStatus(status); + //assertNotNull(response); + + + } + + /** + * Finds Pets by tags + * + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void findPetsByTagsTest() { + // TODO: test validations + List tags = null; + //List response = api.findPetsByTags(tags); + //assertNotNull(response); + + + } + + /** + * Find pet by ID + * + * Returns a single pet + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getPetByIdTest() { + // TODO: test validations + Long petId = null; + //Pet response = api.getPetById(petId); + //assertNotNull(response); + + + } + + /** + * Update an existing pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetTest() { + // TODO: test validations + Pet pet = null; + //Pet response = api.updatePet(pet); + //assertNotNull(response); + + + } + + /** + * Updates a pet in the store with form data + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updatePetWithFormTest() { + // TODO: test validations + Long petId = null; + String name = null; + String status = null; + //api.updatePetWithForm(petId, name, status); + //assertNotNull(response); + + + } + + /** + * uploads an image + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void uploadFileTest() { + // TODO: test validations + Long petId = null; + String additionalMetadata = null; + org.apache.cxf.jaxrs.ext.multipart.Attachment _file = null; + //ModelApiResponse response = api.uploadFile(petId, additionalMetadata, _file); + //assertNotNull(response); + + + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/StoreApiTest.java new file mode 100644 index 000000000000..d2267491d2db --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -0,0 +1,118 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.model.Order; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for StoreApi + */ +public class StoreApiTest { + + private StoreApi client; + private String baseUrl = "http://localhost:9080"; + + @Before + public void setup() throws MalformedURLException { + // TODO initialize the client + } + + + /** + * Delete purchase order by ID + * + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteOrderTest() { + // TODO: test validations + String orderId = null; + //api.deleteOrder(orderId); + //assertNotNull(response); + + + } + + /** + * Returns pet inventories by status + * + * Returns a map of status codes to quantities + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getInventoryTest() { + // TODO: test validations + //Map response = api.getInventory(); + //assertNotNull(response); + + + } + + /** + * Find purchase order by ID + * + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getOrderByIdTest() { + // TODO: test validations + Long orderId = null; + //Order response = api.getOrderById(orderId); + //assertNotNull(response); + + + } + + /** + * Place an order for a pet + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void placeOrderTest() { + // TODO: test validations + Order order = null; + //Order response = api.placeOrder(order); + //assertNotNull(response); + + + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/UserApiTest.java new file mode 100644 index 000000000000..a391586b2e05 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -0,0 +1,193 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import java.util.Date; +import org.openapitools.client.model.User; +import org.junit.Test; +import org.junit.Before; +import static org.junit.Assert.*; + +import org.eclipse.microprofile.rest.client.RestClientBuilder; + +import java.net.URL; +import java.net.MalformedURLException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * OpenAPI Petstore Test + * + * API tests for UserApi + */ +public class UserApiTest { + + private UserApi client; + private String baseUrl = "http://localhost:9080"; + + @Before + public void setup() throws MalformedURLException { + // TODO initialize the client + } + + + /** + * Create user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUserTest() { + // TODO: test validations + User user = null; + //api.createUser(user); + //assertNotNull(response); + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithArrayInputTest() { + // TODO: test validations + List user = null; + //api.createUsersWithArrayInput(user); + //assertNotNull(response); + + + } + + /** + * Creates list of users with given input array + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void createUsersWithListInputTest() { + // TODO: test validations + List user = null; + //api.createUsersWithListInput(user); + //assertNotNull(response); + + + } + + /** + * Delete user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void deleteUserTest() { + // TODO: test validations + String username = null; + //api.deleteUser(username); + //assertNotNull(response); + + + } + + /** + * Get user by user name + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void getUserByNameTest() { + // TODO: test validations + String username = null; + //User response = api.getUserByName(username); + //assertNotNull(response); + + + } + + /** + * Logs user into the system + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void loginUserTest() { + // TODO: test validations + String username = null; + String password = null; + //String response = api.loginUser(username, password); + //assertNotNull(response); + + + } + + /** + * Logs out current logged in user session + * + * + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void logoutUserTest() { + // TODO: test validations + //api.logoutUser(); + //assertNotNull(response); + + + } + + /** + * Updated user + * + * This can only be done by the logged in user. + * + * @throws ApiException + * if the Api call fails + */ + @Test + public void updateUserTest() { + // TODO: test validations + String username = null; + User user = null; + //api.updateUser(username, user); + //assertNotNull(response); + + + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/CategoryTest.java new file mode 100644 index 000000000000..de8fb5b2ab21 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Category + */ +public class CategoryTest { + private final Category model = new Category(); + + /** + * Model tests for Category + */ + @Test + public void testCategory() { + // TODO: test Category + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java new file mode 100644 index 000000000000..ec18c3b5a3da --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -0,0 +1,58 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for ModelApiResponse + */ +public class ModelApiResponseTest { + private final ModelApiResponse model = new ModelApiResponse(); + + /** + * Model tests for ModelApiResponse + */ + @Test + public void testModelApiResponse() { + // TODO: test ModelApiResponse + } + + /** + * Test the property 'code' + */ + @Test + public void codeTest() { + // TODO: test code + } + + /** + * Test the property 'type' + */ + @Test + public void typeTest() { + // TODO: test type + } + + /** + * Test the property 'message' + */ + @Test + public void messageTest() { + // TODO: test message + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/OrderTest.java new file mode 100644 index 000000000000..623cc884e229 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/OrderTest.java @@ -0,0 +1,83 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Date; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Order + */ +public class OrderTest { + private final Order model = new Order(); + + /** + * Model tests for Order + */ + @Test + public void testOrder() { + // TODO: test Order + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..4ed68d492dd2 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,87 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/TagTest.java new file mode 100644 index 000000000000..eb425b209607 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/TagTest.java @@ -0,0 +1,50 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for Tag + */ +public class TagTest { + private final Tag model = new Tag(); + + /** + * Model tests for Tag + */ + @Test + public void testTag() { + // TODO: test Tag + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/UserTest.java new file mode 100644 index 000000000000..b31687866d73 --- /dev/null +++ b/samples/client/petstore/java/microprofile-rest-client-with-useSingleRequestParameter/src/test/java/org/openapitools/client/model/UserTest.java @@ -0,0 +1,98 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import org.junit.Assert; +import org.junit.Ignore; +import org.junit.Test; + +/** + * Model tests for User + */ +public class UserTest { + private final User model = new User(); + + /** + * Model tests for User + */ + @Test + public void testUser() { + // TODO: test User + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + +} diff --git a/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION b/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION +++ b/samples/client/petstore/java/microprofile-rest-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/microprofile-rest-client/pom.xml b/samples/client/petstore/java/microprofile-rest-client/pom.xml index da269412bece..e73ae7a664a5 100644 --- a/samples/client/petstore/java/microprofile-rest-client/pom.xml +++ b/samples/client/petstore/java/microprofile-rest-client/pom.xml @@ -153,7 +153,7 @@ 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 3.2.7 2.15.2 1.2.2 @@ -174,4 +174,4 @@ 1.9.1 UTF-8 - \ No newline at end of file + diff --git a/samples/client/petstore/java/native-async/.openapi-generator/VERSION b/samples/client/petstore/java/native-async/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/native-async/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native-async/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native-async/README.md b/samples/client/petstore/java/native-async/README.md index 5bbd36da0008..0148d0b2d3c5 100644 --- a/samples/client/petstore/java/native-async/README.md +++ b/samples/client/petstore/java/native-async/README.md @@ -124,6 +124,8 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterStringSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums *FakeApi* | [**getArrayOfEnumsWithHttpInfo**](docs/FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties +*FakeApi* | [**testAdditionalPropertiesReferenceWithHttpInfo**](docs/FakeApi.md#testAdditionalPropertiesReferenceWithHttpInfo) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithFileSchemaWithHttpInfo**](docs/FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/native-async/api/openapi.yaml b/samples/client/petstore/java/native-async/api/openapi.yaml index 79127951b04d..07a440cfe9dc 100644 --- a/samples/client/petstore/java/native-async/api/openapi.yaml +++ b/samples/client/petstore/java/native-async/api/openapi.yaml @@ -952,6 +952,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1775,6 +1794,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed diff --git a/samples/client/petstore/java/native-async/docs/FakeApi.md b/samples/client/petstore/java/native-async/docs/FakeApi.md index 5ad79f6eba2c..cac951a5edc9 100644 --- a/samples/client/petstore/java/native-async/docs/FakeApi.md +++ b/samples/client/petstore/java/native-async/docs/FakeApi.md @@ -18,6 +18,8 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterStringSerializeWithHttpInfo**](FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | | [**getArrayOfEnumsWithHttpInfo**](FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | +| [**testAdditionalPropertiesReferenceWithHttpInfo**](FakeApi.md#testAdditionalPropertiesReferenceWithHttpInfo) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithFileSchemaWithHttpInfo**](FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -1010,6 +1012,147 @@ No authorization required | **200** | Got named array of enums | - | +## testAdditionalPropertiesReference + +> CompletableFuture testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; +import java.util.concurrent.CompletableFuture; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + CompletableFuture result = apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + + +CompletableFuture (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +## testAdditionalPropertiesReferenceWithHttpInfo + +> CompletableFuture> testAdditionalPropertiesReference testAdditionalPropertiesReferenceWithHttpInfo(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; +import java.util.concurrent.CompletableFuture; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + CompletableFuture> response = apiInstance.testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + System.out.println("Status code: " + response.get().getStatusCode()); + System.out.println("Response headers: " + response.get().getHeaders()); + } catch (InterruptedException | ExecutionException e) { + ApiException apiException = (ApiException)e.getCause(); + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + apiException.getCode()); + System.err.println("Response headers: " + apiException.getResponseHeaders()); + System.err.println("Reason: " + apiException.getResponseBody()); + e.printStackTrace(); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Response headers: " + e.getResponseHeaders()); + System.err.println("Reason: " + e.getResponseBody()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + + +CompletableFuture> + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithFileSchema > CompletableFuture testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/JSON.java index 1ce1e47b4fb6..5c966f6fa4a9 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/JSON.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; import org.openapitools.jackson.nullable.JsonNullableModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.client.model.*; @@ -17,16 +18,17 @@ public class JSON { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .build(); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); } diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java index c3a4b4bbedee..efd06759640b 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/api/FakeApi.java @@ -728,6 +728,89 @@ private HttpRequest.Builder getArrayOfEnumsRequestBuilder() throws ApiException } return localVarRequestBuilder; } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return CompletableFuture<Void> + * @throws ApiException if fails to make API call + */ + public CompletableFuture testAdditionalPropertiesReference(Map requestBody) throws ApiException { + try { + HttpRequest.Builder localVarRequestBuilder = testAdditionalPropertiesReferenceRequestBuilder(requestBody); + return memberVarHttpClient.sendAsync( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> { + if (localVarResponse.statusCode()/ 100 != 2) { + return CompletableFuture.failedFuture(getApiException("testAdditionalPropertiesReference", localVarResponse)); + } + return CompletableFuture.completedFuture(null); + }); + } + catch (ApiException e) { + return CompletableFuture.failedFuture(e); + } + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return CompletableFuture<ApiResponse<Void>> + * @throws ApiException if fails to make API call + */ + public CompletableFuture> testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws ApiException { + try { + HttpRequest.Builder localVarRequestBuilder = testAdditionalPropertiesReferenceRequestBuilder(requestBody); + return memberVarHttpClient.sendAsync( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofString()).thenComposeAsync(localVarResponse -> { + if (memberVarAsyncResponseInterceptor != null) { + memberVarAsyncResponseInterceptor.accept(localVarResponse); + } + if (localVarResponse.statusCode()/ 100 != 2) { + return CompletableFuture.failedFuture(getApiException("testAdditionalPropertiesReference", localVarResponse)); + } + return CompletableFuture.completedFuture( + new ApiResponse(localVarResponse.statusCode(), localVarResponse.headers().map(), null) + ); + } + ); + } + catch (ApiException e) { + return CompletableFuture.failedFuture(e); + } + } + + private HttpRequest.Builder testAdditionalPropertiesReferenceRequestBuilder(Map requestBody) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/fake/additionalProperties-reference"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(requestBody); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } /** * * For this test, the body for this request much reference a schema named `File`. diff --git a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/FormatTest.java index 3b561321f4b3..cb68ac98da14 100644 --- a/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/native-async/src/main/java/org/openapitools/client/model/FormatTest.java @@ -569,7 +569,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/native-jakarta/.openapi-generator/VERSION b/samples/client/petstore/java/native-jakarta/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/native-jakarta/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native-jakarta/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native-jakarta/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/native-jakarta/src/main/java/org/openapitools/client/JSON.java index 38564358737d..b929796031f8 100644 --- a/samples/client/petstore/java/native-jakarta/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/native-jakarta/src/main/java/org/openapitools/client/JSON.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; import org.openapitools.jackson.nullable.JsonNullableModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.client.model.*; @@ -17,16 +18,17 @@ public class JSON { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .build(); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); } diff --git a/samples/client/petstore/java/native/.openapi-generator/VERSION b/samples/client/petstore/java/native/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/native/.openapi-generator/VERSION +++ b/samples/client/petstore/java/native/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/native/README.md b/samples/client/petstore/java/native/README.md index c0ada1a69ccb..bafb85f35de1 100644 --- a/samples/client/petstore/java/native/README.md +++ b/samples/client/petstore/java/native/README.md @@ -123,6 +123,8 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterStringSerializeWithHttpInfo**](docs/FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums *FakeApi* | [**getArrayOfEnumsWithHttpInfo**](docs/FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties +*FakeApi* | [**testAdditionalPropertiesReferenceWithHttpInfo**](docs/FakeApi.md#testAdditionalPropertiesReferenceWithHttpInfo) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithFileSchemaWithHttpInfo**](docs/FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/native/api/openapi.yaml b/samples/client/petstore/java/native/api/openapi.yaml index 79127951b04d..07a440cfe9dc 100644 --- a/samples/client/petstore/java/native/api/openapi.yaml +++ b/samples/client/petstore/java/native/api/openapi.yaml @@ -952,6 +952,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1775,6 +1794,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed diff --git a/samples/client/petstore/java/native/docs/FakeApi.md b/samples/client/petstore/java/native/docs/FakeApi.md index d741761672da..adff98c08895 100644 --- a/samples/client/petstore/java/native/docs/FakeApi.md +++ b/samples/client/petstore/java/native/docs/FakeApi.md @@ -18,6 +18,8 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterStringSerializeWithHttpInfo**](FakeApi.md#fakeOuterStringSerializeWithHttpInfo) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | | [**getArrayOfEnumsWithHttpInfo**](FakeApi.md#getArrayOfEnumsWithHttpInfo) | **GET** /fake/array-of-enums | Array of Enums | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | +| [**testAdditionalPropertiesReferenceWithHttpInfo**](FakeApi.md#testAdditionalPropertiesReferenceWithHttpInfo) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithFileSchemaWithHttpInfo**](FakeApi.md#testBodyWithFileSchemaWithHttpInfo) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -947,6 +949,138 @@ No authorization required | **200** | Got named array of enums | - | +## testAdditionalPropertiesReference + +> void testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + +## testAdditionalPropertiesReferenceWithHttpInfo + +> ApiResponse testAdditionalPropertiesReference testAdditionalPropertiesReferenceWithHttpInfo(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + ApiResponse response = apiInstance.testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + System.out.println("Status code: " + response.getStatusCode()); + System.out.println("Response headers: " + response.getHeaders()); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Response headers: " + e.getResponseHeaders()); + System.err.println("Reason: " + e.getResponseBody()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + + +ApiResponse + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithFileSchema > void testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java index 1ce1e47b4fb6..5c966f6fa4a9 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/JSON.java @@ -2,6 +2,7 @@ import com.fasterxml.jackson.annotation.*; import com.fasterxml.jackson.databind.*; +import com.fasterxml.jackson.databind.json.JsonMapper; import org.openapitools.jackson.nullable.JsonNullableModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.client.model.*; @@ -17,16 +18,17 @@ public class JSON { private ObjectMapper mapper; public JSON() { - mapper = new ObjectMapper(); - mapper.setSerializationInclusion(JsonInclude.Include.NON_NULL); - mapper.configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false); - mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true); - mapper.configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true); - mapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS); - mapper.enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING); - mapper.enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING); - mapper.setDateFormat(new RFC3339DateFormat()); - mapper.registerModule(new JavaTimeModule()); + mapper = JsonMapper.builder() + .serializationInclusion(JsonInclude.Include.NON_NULL) + .configure(MapperFeature.ALLOW_COERCION_OF_SCALARS, false) + .configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, true) + .configure(DeserializationFeature.FAIL_ON_INVALID_SUBTYPE, true) + .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS) + .enable(SerializationFeature.WRITE_ENUMS_USING_TO_STRING) + .enable(DeserializationFeature.READ_ENUMS_USING_TO_STRING) + .defaultDateFormat(new RFC3339DateFormat()) + .addModule(new JavaTimeModule()) + .build(); JsonNullableModule jnm = new JsonNullableModule(); mapper.registerModule(jnm); } diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java index 8a8b89d22adc..4ae6a081cdc6 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/api/FakeApi.java @@ -580,6 +580,86 @@ private HttpRequest.Builder getArrayOfEnumsRequestBuilder() throws ApiException } return localVarRequestBuilder; } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException if fails to make API call + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @throws ApiException if fails to make API call + */ + public ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws ApiException { + HttpRequest.Builder localVarRequestBuilder = testAdditionalPropertiesReferenceRequestBuilder(requestBody); + try { + HttpResponse localVarResponse = memberVarHttpClient.send( + localVarRequestBuilder.build(), + HttpResponse.BodyHandlers.ofInputStream()); + if (memberVarResponseInterceptor != null) { + memberVarResponseInterceptor.accept(localVarResponse); + } + try { + if (localVarResponse.statusCode()/ 100 != 2) { + throw getApiException("testAdditionalPropertiesReference", localVarResponse); + } + return new ApiResponse( + localVarResponse.statusCode(), + localVarResponse.headers().map(), + null + ); + } finally { + // Drain the InputStream + while (localVarResponse.body().read() != -1) { + // Ignore + } + localVarResponse.body().close(); + } + } catch (IOException e) { + throw new ApiException(e); + } + catch (InterruptedException e) { + Thread.currentThread().interrupt(); + throw new ApiException(e); + } + } + + private HttpRequest.Builder testAdditionalPropertiesReferenceRequestBuilder(Map requestBody) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + HttpRequest.Builder localVarRequestBuilder = HttpRequest.newBuilder(); + + String localVarPath = "/fake/additionalProperties-reference"; + + localVarRequestBuilder.uri(URI.create(memberVarBaseUri + localVarPath)); + + localVarRequestBuilder.header("Content-Type", "application/json"); + localVarRequestBuilder.header("Accept", "application/json"); + + try { + byte[] localVarPostBody = memberVarObjectMapper.writeValueAsBytes(requestBody); + localVarRequestBuilder.method("POST", HttpRequest.BodyPublishers.ofByteArray(localVarPostBody)); + } catch (IOException e) { + throw new ApiException(e); + } + if (memberVarReadTimeout != null) { + localVarRequestBuilder.timeout(memberVarReadTimeout); + } + if (memberVarInterceptor != null) { + memberVarInterceptor.accept(localVarRequestBuilder); + } + return localVarRequestBuilder; + } /** * * For this test, the body for this request much reference a schema named `File`. diff --git a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java index 3b561321f4b3..cb68ac98da14 100644 --- a/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/native/src/main/java/org/openapitools/client/model/FormatTest.java @@ -569,7 +569,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/FILES index af9fa6831fb6..0a065d67dc83 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/FILES @@ -6,9 +6,11 @@ api/openapi.yaml build.gradle build.sbt docs/Animal.md +docs/AnyTypeTest.md docs/Cat.md docs/Category.md docs/Dog.md +docs/FakeApi.md docs/ModelApiResponse.md docs/OneOfStringOrInt.md docs/Order.md @@ -41,6 +43,7 @@ src/main/java/org/openapitools/client/ProgressResponseBody.java src/main/java/org/openapitools/client/ServerConfiguration.java src/main/java/org/openapitools/client/ServerVariable.java src/main/java/org/openapitools/client/StringUtil.java +src/main/java/org/openapitools/client/api/FakeApi.java src/main/java/org/openapitools/client/api/PetApi.java src/main/java/org/openapitools/client/api/StoreApi.java src/main/java/org/openapitools/client/api/UserApi.java @@ -54,6 +57,7 @@ src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java src/main/java/org/openapitools/client/auth/RetryingOAuth.java src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java src/main/java/org/openapitools/client/model/Animal.java +src/main/java/org/openapitools/client/model/AnyTypeTest.java src/main/java/org/openapitools/client/model/Cat.java src/main/java/org/openapitools/client/model/Category.java src/main/java/org/openapitools/client/model/Dog.java diff --git a/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-3.1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-3.1/README.md b/samples/client/petstore/java/okhttp-gson-3.1/README.md index 4d1472eaa92a..8a4562dbc092 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/README.md +++ b/samples/client/petstore/java/okhttp-gson-3.1/README.md @@ -82,26 +82,21 @@ Please follow the [installation](#installation) instruction and execute the foll import org.openapitools.client.ApiClient; import org.openapitools.client.ApiException; import org.openapitools.client.Configuration; -import org.openapitools.client.auth.*; import org.openapitools.client.models.*; -import org.openapitools.client.api.PetApi; +import org.openapitools.client.api.FakeApi; public class Example { public static void main(String[] args) { ApiClient defaultClient = Configuration.getDefaultApiClient(); defaultClient.setBasePath("http://petstore.swagger.io/v2"); - - // Configure OAuth2 access token for authorization: petstore_auth - OAuth petstore_auth = (OAuth) defaultClient.getAuthentication("petstore_auth"); - petstore_auth.setAccessToken("YOUR ACCESS TOKEN"); - PetApi apiInstance = new PetApi(defaultClient); - Pet pet = new Pet(); // Pet | Pet object that needs to be added to the store + FakeApi apiInstance = new FakeApi(defaultClient); + UUID refToUuid = UUID.fromString("61864654-6e6b-4152-a62f-795fdd606bc2"); // UUID | to test ref to parameter (uuid) try { - Pet result = apiInstance.addPet(pet); + String result = apiInstance.refToRefParameter(refToUuid); System.out.println(result); } catch (ApiException e) { - System.err.println("Exception when calling PetApi#addPet"); + System.err.println("Exception when calling FakeApi#refToRefParameter"); System.err.println("Status code: " + e.getCode()); System.err.println("Reason: " + e.getResponseBody()); System.err.println("Response headers: " + e.getResponseHeaders()); @@ -118,6 +113,10 @@ All URIs are relative to *http://petstore.swagger.io/v2* Class | Method | HTTP request | Description ------------ | ------------- | ------------- | ------------- +*FakeApi* | [**refToRefParameter**](docs/FakeApi.md#refToRefParameter) | **GET** /ref/ref_to_parameter | +*FakeApi* | [**responseNoRef**](docs/FakeApi.md#responseNoRef) | **GET** /no_ref | +*FakeApi* | [**responseRefToNoRef**](docs/FakeApi.md#responseRefToNoRef) | **GET** /ref/no_ref | +*FakeApi* | [**responseRefToRef**](docs/FakeApi.md#responseRefToRef) | **GET** /ref/ref | *PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store *PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet *PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status @@ -143,6 +142,7 @@ Class | Method | HTTP request | Description ## Documentation for Models - [Animal](docs/Animal.md) + - [AnyTypeTest](docs/AnyTypeTest.md) - [Cat](docs/Cat.md) - [Category](docs/Category.md) - [Dog](docs/Dog.md) diff --git a/samples/client/petstore/java/okhttp-gson-3.1/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson-3.1/api/openapi.yaml index bc23e2bb6c6c..542d67302af9 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson-3.1/api/openapi.yaml @@ -610,7 +610,63 @@ paths: - user x-content-type: application/json x-accepts: application/json + /no_ref: + get: + operationId: response_no_ref + responses: + "200": + content: + text/plain: + schema: + type: string + description: required to pass validation + tags: + - fake + x-accepts: text/plain + /ref/no_ref: + get: + operationId: response_ref_to_no_ref + responses: + "200": + $ref: '#/components/responses/no_ref' + tags: + - fake + x-accepts: text/plain + /ref/ref: + get: + operationId: response_ref_to_ref + responses: + "200": + $ref: '#/components/responses/ref' + tags: + - fake + x-accepts: text/plain + /ref/ref_to_parameter: + get: + operationId: ref_to_ref_parameter + parameters: + - $ref: '#/components/parameters/ref_to_uuid' + responses: + "200": + $ref: '#/components/responses/ref' + tags: + - fake + x-accepts: text/plain + parameters: + - $ref: '#/components/parameters/ref_to_uuid' components: + parameters: + ref_to_uuid: + description: to test ref to parameter (uuid) + explode: false + in: header + name: ref_to_uuid + required: true + schema: + example: 61864654-6e6b-4152-a62f-795fdd606bc2 + format: uuid + type: string + style: simple requestBodies: UserArray: content: @@ -631,6 +687,19 @@ components: $ref: '#/components/schemas/Pet' description: Pet object that needs to be added to the store required: true + responses: + no_ref: + content: + text/plain: + schema: + type: string + description: required to pass validation + ref: + content: + text/plain: + schema: + $ref: '#/components/schemas/simple_text' + description: required to pass validation schemas: Order: description: An order for a pets from the pet store @@ -833,6 +902,16 @@ components: type: string required: - className + simple_text: + type: string + any_type_test: + properties: + any_type_property: {} + array_prop: + description: test array in 3.1 spec + items: + type: string + type: array updatePetWithForm_request: properties: name: diff --git a/samples/client/petstore/java/okhttp-gson-3.1/build.gradle b/samples/client/petstore/java/okhttp-gson-3.1/build.gradle index a627a524f03a..1a8bab77d860 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-3.1/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-3.1/build.sbt b/samples/client/petstore/java/okhttp-gson-3.1/build.sbt index 5f2876292595..6a364198de52 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-3.1/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-3.1/docs/AnyTypeTest.md b/samples/client/petstore/java/okhttp-gson-3.1/docs/AnyTypeTest.md new file mode 100644 index 000000000000..7c46d45edb4d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/docs/AnyTypeTest.md @@ -0,0 +1,14 @@ + + +# AnyTypeTest + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**anyTypeProperty** | **Object** | | [optional] | +|**arrayProp** | **List<String>** | test array in 3.1 spec | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson-3.1/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson-3.1/docs/FakeApi.md new file mode 100644 index 000000000000..79da3fbb4fd3 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/docs/FakeApi.md @@ -0,0 +1,240 @@ +# FakeApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +| Method | HTTP request | Description | +|------------- | ------------- | -------------| +| [**refToRefParameter**](FakeApi.md#refToRefParameter) | **GET** /ref/ref_to_parameter | | +| [**responseNoRef**](FakeApi.md#responseNoRef) | **GET** /no_ref | | +| [**responseRefToNoRef**](FakeApi.md#responseRefToNoRef) | **GET** /ref/no_ref | | +| [**responseRefToRef**](FakeApi.md#responseRefToRef) | **GET** /ref/ref | | + + + +# **refToRefParameter** +> String refToRefParameter(refToUuid) + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + UUID refToUuid = UUID.fromString("61864654-6e6b-4152-a62f-795fdd606bc2"); // UUID | to test ref to parameter (uuid) + try { + String result = apiInstance.refToRefParameter(refToUuid); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#refToRefParameter"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **refToUuid** | **UUID**| to test ref to parameter (uuid) | | + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | | - | + + +# **responseNoRef** +> String responseNoRef() + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + String result = apiInstance.responseNoRef(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#responseNoRef"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | required to pass validation | - | + + +# **responseRefToNoRef** +> String responseRefToNoRef() + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + String result = apiInstance.responseRefToNoRef(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#responseRefToNoRef"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | | - | + + +# **responseRefToRef** +> String responseRefToRef() + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + try { + String result = apiInstance.responseRefToRef(); + System.out.println(result); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#responseRefToRef"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | | - | + diff --git a/samples/client/petstore/java/okhttp-gson-3.1/pom.xml b/samples/client/petstore/java/okhttp-gson-3.1/pom.xml index a8b231a8d93c..c8fb9ee6022a 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-3.1/pom.xml @@ -333,7 +333,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/ApiClient.java index 6d1cc62db7e7..08a6cfe9ddd5 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java index 6791d767d970..842131f6c78e 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/JSON.java @@ -122,6 +122,7 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapter(OffsetDateTime.class, offsetDateTimeTypeAdapter); gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AnyTypeTest.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Cat.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Category.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Dog.CustomTypeAdapterFactory()); diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/api/FakeApi.java new file mode 100644 index 000000000000..c830be226b64 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/api/FakeApi.java @@ -0,0 +1,540 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiCallback; +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.ApiResponse; +import org.openapitools.client.Configuration; +import org.openapitools.client.Pair; +import org.openapitools.client.ProgressRequestBody; +import org.openapitools.client.ProgressResponseBody; + +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; + + +import java.util.UUID; + +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +public class FakeApi { + private ApiClient localVarApiClient; + private int localHostIndex; + private String localCustomBaseUrl; + + public FakeApi() { + this(Configuration.getDefaultApiClient()); + } + + public FakeApi(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public ApiClient getApiClient() { + return localVarApiClient; + } + + public void setApiClient(ApiClient apiClient) { + this.localVarApiClient = apiClient; + } + + public int getHostIndex() { + return localHostIndex; + } + + public void setHostIndex(int hostIndex) { + this.localHostIndex = hostIndex; + } + + public String getCustomBaseUrl() { + return localCustomBaseUrl; + } + + public void setCustomBaseUrl(String customBaseUrl) { + this.localCustomBaseUrl = customBaseUrl; + } + + /** + * Build call for refToRefParameter + * @param refToUuid to test ref to parameter (uuid) (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call refToRefParameterCall(UUID refToUuid, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/ref/ref_to_parameter"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (refToUuid != null) { + localVarHeaderParams.put("ref_to_uuid", localVarApiClient.parameterToString(refToUuid)); + } + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call refToRefParameterValidateBeforeCall(UUID refToUuid, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'refToUuid' is set + if (refToUuid == null) { + throw new ApiException("Missing the required parameter 'refToUuid' when calling refToRefParameter(Async)"); + } + + return refToRefParameterCall(refToUuid, _callback); + + } + + /** + * + * + * @param refToUuid to test ref to parameter (uuid) (required) + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public String refToRefParameter(UUID refToUuid) throws ApiException { + ApiResponse localVarResp = refToRefParameterWithHttpInfo(refToUuid); + return localVarResp.getData(); + } + + /** + * + * + * @param refToUuid to test ref to parameter (uuid) (required) + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public ApiResponse refToRefParameterWithHttpInfo(UUID refToUuid) throws ApiException { + okhttp3.Call localVarCall = refToRefParameterValidateBeforeCall(refToUuid, null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param refToUuid to test ref to parameter (uuid) (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call refToRefParameterAsync(UUID refToUuid, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = refToRefParameterValidateBeforeCall(refToUuid, _callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for responseNoRef + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 required to pass validation -
              + */ + public okhttp3.Call responseNoRefCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/no_ref"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call responseNoRefValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return responseNoRefCall(_callback); + + } + + /** + * + * + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 required to pass validation -
              + */ + public String responseNoRef() throws ApiException { + ApiResponse localVarResp = responseNoRefWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 required to pass validation -
              + */ + public ApiResponse responseNoRefWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = responseNoRefValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 required to pass validation -
              + */ + public okhttp3.Call responseNoRefAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = responseNoRefValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for responseRefToNoRef + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call responseRefToNoRefCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/ref/no_ref"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call responseRefToNoRefValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return responseRefToNoRefCall(_callback); + + } + + /** + * + * + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public String responseRefToNoRef() throws ApiException { + ApiResponse localVarResp = responseRefToNoRefWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public ApiResponse responseRefToNoRefWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = responseRefToNoRefValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call responseRefToNoRefAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = responseRefToNoRefValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } + /** + * Build call for responseRefToRef + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call responseRefToRefCall(final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/ref/ref"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + "text/plain" + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call responseRefToRefValidateBeforeCall(final ApiCallback _callback) throws ApiException { + return responseRefToRefCall(_callback); + + } + + /** + * + * + * @return String + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public String responseRefToRef() throws ApiException { + ApiResponse localVarResp = responseRefToRefWithHttpInfo(); + return localVarResp.getData(); + } + + /** + * + * + * @return ApiResponse<String> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public ApiResponse responseRefToRefWithHttpInfo() throws ApiException { + okhttp3.Call localVarCall = responseRefToRefValidateBeforeCall(null); + Type localVarReturnType = new TypeToken(){}.getType(); + return localVarApiClient.execute(localVarCall, localVarReturnType); + } + + /** + * (asynchronously) + * + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call responseRefToRefAsync(final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = responseRefToRefValidateBeforeCall(_callback); + Type localVarReturnType = new TypeToken(){}.getType(); + localVarApiClient.executeAsync(localVarCall, localVarReturnType, _callback); + return localVarCall; + } +} diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Animal.java index ce03faf30dda..e93327f47e76 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Animal.java @@ -64,7 +64,6 @@ public Animal() { } public Animal className(String className) { - this.className = className; return this; } @@ -78,14 +77,12 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } public Animal color(String color) { - this.color = color; return this; } @@ -99,7 +96,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AnyTypeTest.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AnyTypeTest.java new file mode 100644 index 000000000000..30d571e2cdc8 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/AnyTypeTest.java @@ -0,0 +1,331 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.jackson.nullable.JsonNullable; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * AnyTypeTest + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AnyTypeTest { + public static final String SERIALIZED_NAME_ANY_TYPE_PROPERTY = "any_type_property"; + @SerializedName(SERIALIZED_NAME_ANY_TYPE_PROPERTY) + private Object anyTypeProperty = null; + + public static final String SERIALIZED_NAME_ARRAY_PROP = "array_prop"; + @SerializedName(SERIALIZED_NAME_ARRAY_PROP) + private List arrayProp; + + public AnyTypeTest() { + } + + public AnyTypeTest anyTypeProperty(Object anyTypeProperty) { + this.anyTypeProperty = anyTypeProperty; + return this; + } + + /** + * Get anyTypeProperty + * @return anyTypeProperty + **/ + @javax.annotation.Nullable + public Object getAnyTypeProperty() { + return anyTypeProperty; + } + + public void setAnyTypeProperty(Object anyTypeProperty) { + this.anyTypeProperty = anyTypeProperty; + } + + + public AnyTypeTest arrayProp(List arrayProp) { + this.arrayProp = arrayProp; + return this; + } + + public AnyTypeTest addArrayPropItem(String arrayPropItem) { + if (this.arrayProp == null) { + this.arrayProp = new ArrayList<>(); + } + this.arrayProp.add(arrayPropItem); + return this; + } + + /** + * test array in 3.1 spec + * @return arrayProp + **/ + @javax.annotation.Nullable + public List getArrayProp() { + return arrayProp; + } + + public void setArrayProp(List arrayProp) { + this.arrayProp = arrayProp; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AnyTypeTest instance itself + */ + public AnyTypeTest putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnyTypeTest anyTypeTest = (AnyTypeTest) o; + return Objects.equals(this.anyTypeProperty, anyTypeTest.anyTypeProperty) && + Objects.equals(this.arrayProp, anyTypeTest.arrayProp)&& + Objects.equals(this.additionalProperties, anyTypeTest.additionalProperties); + } + + private static boolean equalsNullable(JsonNullable a, JsonNullable b) { + return a == b || (a != null && b != null && a.isPresent() && b.isPresent() && Objects.deepEquals(a.get(), b.get())); + } + + @Override + public int hashCode() { + return Objects.hash(anyTypeProperty, arrayProp, additionalProperties); + } + + private static int hashCodeNullable(JsonNullable a) { + if (a == null) { + return 1; + } + return a.isPresent() ? Arrays.deepHashCode(new Object[]{a.get()}) : 31; + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AnyTypeTest {\n"); + sb.append(" anyTypeProperty: ").append(toIndentedString(anyTypeProperty)).append("\n"); + sb.append(" arrayProp: ").append(toIndentedString(arrayProp)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("any_type_property"); + openapiFields.add("array_prop"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AnyTypeTest + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AnyTypeTest.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AnyTypeTest is not found in the empty JSON string", AnyTypeTest.openapiRequiredFields.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the optional json data is an array if present + if (jsonObj.get("array_prop") != null && !jsonObj.get("array_prop").isJsonNull() && !jsonObj.get("array_prop").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `array_prop` to be an array in the JSON string but got `%s`", jsonObj.get("array_prop").toString())); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AnyTypeTest.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AnyTypeTest' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AnyTypeTest.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AnyTypeTest value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AnyTypeTest read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AnyTypeTest instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AnyTypeTest given an JSON string + * + * @param jsonString JSON string + * @return An instance of AnyTypeTest + * @throws IOException if the JSON string is invalid with respect to AnyTypeTest + */ + public static AnyTypeTest fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AnyTypeTest.class); + } + + /** + * Convert an instance of AnyTypeTest to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Cat.java index 669801f89208..876f2c52bb26 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Cat.java @@ -61,7 +61,6 @@ public Cat() { } public Cat declawed(Boolean declawed) { - this.declawed = declawed; return this; } @@ -75,7 +74,6 @@ public Boolean getDeclawed() { return declawed; } - public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Category.java index ec41d25fa99f..f12855dae504 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Dog.java index 569f75188d9f..52f9e1adea2a 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Dog.java @@ -61,7 +61,6 @@ public Dog() { } public Dog breed(String breed) { - this.breed = breed; return this; } @@ -75,7 +74,6 @@ public String getBreed() { return breed; } - public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/ModelApiResponse.java index a1df10aece5f..59645dcffcc2 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Order.java index ae66537b4824..53a96c763a7c 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -382,6 +375,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Pet.java index 69cec0b898e2..9d0e1e017afa 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -133,7 +138,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -168,14 +170,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -189,14 +189,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -218,14 +216,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -247,7 +243,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -255,7 +250,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -442,6 +435,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Tag.java index 262ef93dbbd3..bae59a3dedb3 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/User.java index 8c1f31e4d16a..157f92c49599 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/main/java/org/openapitools/client/model/User.java @@ -87,7 +87,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -101,14 +100,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -122,14 +119,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -143,14 +138,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -164,14 +157,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -185,14 +176,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -206,14 +195,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -227,14 +214,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -248,7 +233,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/FakeApiTest.java new file mode 100644 index 000000000000..097e64f0218d --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -0,0 +1,60 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.api; + +import org.openapitools.client.ApiException; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * API tests for FakeApi + */ +@Disabled +public class FakeApiTest { + + private final FakeApi api = new FakeApi(); + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void responseNoRefTest() throws ApiException { + String response = api.responseNoRef(); + // TODO: test validations + } + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void responseRefToNoRefTest() throws ApiException { + String response = api.responseRefToNoRef(); + // TODO: test validations + } + + /** + * @throws ApiException if the Api call fails + */ + @Test + public void responseRefToRefTest() throws ApiException { + String response = api.responseRefToRef(); + // TODO: test validations + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/PetApiTest.java index 3983042bcc4e..869dc302a973 100644 --- a/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/PetApiTest.java +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -373,6 +373,13 @@ public void testEqualsAndHashCode() { assertTrue(pet1.hashCode() == pet1.hashCode()); } + @Test + public void testAnyType() { // test any type in v3.1 spec + AnyTypeTest a = new AnyTypeTest(); + a.setAnyTypeProperty("test"); // shouldn't throw exception + assertEquals("test", a.getAnyTypeProperty()); + } + private Pet createPet() { Pet pet = new Pet(); pet.setId(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE)); diff --git a/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/model/AnyTypeTestTest.java b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/model/AnyTypeTestTest.java new file mode 100644 index 000000000000..98a31faf01ac --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson-3.1/src/test/java/org/openapitools/client/model/AnyTypeTestTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AnyTypeTest + */ +public class AnyTypeTestTest { + private final AnyTypeTest model = new AnyTypeTest(); + + /** + * Model tests for AnyTypeTest + */ + @Test + public void testAnyTypeTest() { + // TODO: test AnyTypeTest + } + + /** + * Test the property 'anyTypeProperty' + */ + @Test + public void anyTypePropertyTest() { + // TODO: test anyTypeProperty + } + +} diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-awsv4signature/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/build.gradle b/samples/client/petstore/java/okhttp-gson-awsv4signature/build.gradle index 504ebafa3665..bc6ac3ee3dbd 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/build.sbt b/samples/client/petstore/java/okhttp-gson-awsv4signature/build.sbt index b86eb7e785c4..e61ec17d8dd0 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/build.sbt @@ -19,7 +19,7 @@ lazy val root = (project in file(".")). "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "software.amazon.awssdk" % "auth" % "2.20.157", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/pom.xml b/samples/client/petstore/java/okhttp-gson-awsv4signature/pom.xml index 599f9c354f04..65baca5212f4 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/pom.xml @@ -338,7 +338,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/ApiClient.java index 21ac39664037..209f378884b6 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Category.java index ec41d25fa99f..f12855dae504 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/ModelApiResponse.java index a1df10aece5f..59645dcffcc2 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Order.java index ae66537b4824..53a96c763a7c 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -382,6 +375,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Pet.java index 69cec0b898e2..9d0e1e017afa 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -133,7 +138,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -168,14 +170,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -189,14 +189,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -218,14 +216,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -247,7 +243,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -255,7 +250,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -442,6 +435,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Tag.java index 262ef93dbbd3..bae59a3dedb3 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/User.java index 8c1f31e4d16a..157f92c49599 100644 --- a/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-awsv4signature/src/main/java/org/openapitools/client/model/User.java @@ -87,7 +87,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -101,14 +100,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -122,14 +119,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -143,14 +138,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -164,14 +157,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -185,14 +176,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -206,14 +195,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -227,14 +214,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -248,7 +233,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle index d77de6ff6603..3aebceafc6fc 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt index 3a01e5b041a3..0bb9b8e7bb8e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/build.sbt @@ -19,7 +19,7 @@ lazy val root = (project in file(".")). "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", "io.swagger.parser.v3" % "swagger-parser-v3" "2.0.30" % "compile" - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/pom.xml b/samples/client/petstore/java/okhttp-gson-dynamicOperations/pom.xml index 63423ec5c6e9..f59a23c05d43 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/pom.xml @@ -338,7 +338,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java index 3b744150e977..ac08baa4cc4d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/ApiClient.java @@ -55,6 +55,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -786,7 +787,7 @@ public List parameterToPairs(Parameter param, Collection value) { List params = new ArrayList(); // preconditions - if (param == null || param.getName() == null || param.getName().isEmpty() || value == null) { + if (param == null || param.getName() == null || param.getName().isEmpty() || value == null || value.isEmpty()) { return params; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 460ad224963c..e6ae1d454c79 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index fbe51042e1a9..f50f7a96cc56 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index ec21cd1712b4..668b07a52c66 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -59,7 +59,6 @@ public AdditionalPropertiesAnyType() { } public AdditionalPropertiesAnyType name(String name) { - this.name = name; return this; } @@ -73,7 +72,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index 7a1c195ef71c..26d5f8cdd69c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -60,7 +60,6 @@ public AdditionalPropertiesArray() { } public AdditionalPropertiesArray name(String name) { - this.name = name; return this; } @@ -74,7 +73,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index c2da10296171..9e411cc5ba72 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -59,7 +59,6 @@ public AdditionalPropertiesBoolean() { } public AdditionalPropertiesBoolean name(String name) { - this.name = name; return this; } @@ -73,7 +72,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 6f46c20df649..c8778337114d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -103,7 +103,6 @@ public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { - this.mapString = mapString; return this; } @@ -125,14 +124,12 @@ public Map getMapString() { return mapString; } - public void setMapString(Map mapString) { this.mapString = mapString; } public AdditionalPropertiesClass mapNumber(Map mapNumber) { - this.mapNumber = mapNumber; return this; } @@ -154,14 +151,12 @@ public Map getMapNumber() { return mapNumber; } - public void setMapNumber(Map mapNumber) { this.mapNumber = mapNumber; } public AdditionalPropertiesClass mapInteger(Map mapInteger) { - this.mapInteger = mapInteger; return this; } @@ -183,14 +178,12 @@ public Map getMapInteger() { return mapInteger; } - public void setMapInteger(Map mapInteger) { this.mapInteger = mapInteger; } public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { - this.mapBoolean = mapBoolean; return this; } @@ -212,14 +205,12 @@ public Map getMapBoolean() { return mapBoolean; } - public void setMapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; } public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { - this.mapArrayInteger = mapArrayInteger; return this; } @@ -241,14 +232,12 @@ public Map> getMapArrayInteger() { return mapArrayInteger; } - public void setMapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; } public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { - this.mapArrayAnytype = mapArrayAnytype; return this; } @@ -270,14 +259,12 @@ public Map> getMapArrayAnytype() { return mapArrayAnytype; } - public void setMapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; } public AdditionalPropertiesClass mapMapString(Map> mapMapString) { - this.mapMapString = mapMapString; return this; } @@ -299,14 +286,12 @@ public Map> getMapMapString() { return mapMapString; } - public void setMapMapString(Map> mapMapString) { this.mapMapString = mapMapString; } public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { - this.mapMapAnytype = mapMapAnytype; return this; } @@ -328,14 +313,12 @@ public Map> getMapMapAnytype() { return mapMapAnytype; } - public void setMapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; } public AdditionalPropertiesClass anytype1(Object anytype1) { - this.anytype1 = anytype1; return this; } @@ -349,14 +332,12 @@ public Object getAnytype1() { return anytype1; } - public void setAnytype1(Object anytype1) { this.anytype1 = anytype1; } public AdditionalPropertiesClass anytype2(Object anytype2) { - this.anytype2 = anytype2; return this; } @@ -370,14 +351,12 @@ public Object getAnytype2() { return anytype2; } - public void setAnytype2(Object anytype2) { this.anytype2 = anytype2; } public AdditionalPropertiesClass anytype3(Object anytype3) { - this.anytype3 = anytype3; return this; } @@ -391,7 +370,6 @@ public Object getAnytype3() { return anytype3; } - public void setAnytype3(Object anytype3) { this.anytype3 = anytype3; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 019fa46ff80a..cd8624dcc7ce 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -59,7 +59,6 @@ public AdditionalPropertiesInteger() { } public AdditionalPropertiesInteger name(String name) { - this.name = name; return this; } @@ -73,7 +72,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index 567c325dcaab..c5bba0308f6f 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -60,7 +60,6 @@ public AdditionalPropertiesNumber() { } public AdditionalPropertiesNumber name(String name) { - this.name = name; return this; } @@ -74,7 +73,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index 37b7091e0bcc..d5523899c5ba 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -60,7 +60,6 @@ public AdditionalPropertiesObject() { } public AdditionalPropertiesObject name(String name) { - this.name = name; return this; } @@ -74,7 +73,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index 9d911a03b4da..9f40983f2dc8 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -59,7 +59,6 @@ public AdditionalPropertiesString() { } public AdditionalPropertiesString name(String name) { - this.name = name; return this; } @@ -73,7 +72,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java index bdb0dcd35913..0136596cb66f 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Animal.java @@ -64,7 +64,6 @@ public Animal() { } public Animal className(String className) { - this.className = className; return this; } @@ -78,14 +77,12 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } public Animal color(String color) { - this.color = color; return this; } @@ -99,7 +96,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 84e446adfe35..8fd1a94f2598 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -62,7 +62,6 @@ public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; return this; } @@ -84,7 +83,6 @@ public List> getArrayArrayNumber() { return arrayArrayNumber; } - public void setArrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index b032848a8052..4c1a3fd40b04 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -62,7 +62,6 @@ public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; return this; } @@ -84,7 +83,6 @@ public List getArrayNumber() { return arrayNumber; } - public void setArrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java index 1d325c079da5..52dc1f51e136 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -70,7 +70,6 @@ public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; return this; } @@ -92,14 +91,12 @@ public List getArrayOfString() { return arrayOfString; } - public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } @@ -121,14 +118,12 @@ public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -150,7 +145,6 @@ public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java index bc85b824e386..ab690a217b09 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/BigCat.java @@ -101,6 +101,11 @@ public KindEnum read(final JsonReader jsonReader) throws IOException { return KindEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + KindEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_KIND = "kind"; @@ -112,7 +117,6 @@ public BigCat() { } public BigCat kind(KindEnum kind) { - this.kind = kind; return this; } @@ -126,7 +130,6 @@ public KindEnum getKind() { return kind; } - public void setKind(KindEnum kind) { this.kind = kind; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java index 366e48a5a77b..288c559b9a4a 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Capitalization.java @@ -79,7 +79,6 @@ public Capitalization() { } public Capitalization smallCamel(String smallCamel) { - this.smallCamel = smallCamel; return this; } @@ -93,14 +92,12 @@ public String getSmallCamel() { return smallCamel; } - public void setSmallCamel(String smallCamel) { this.smallCamel = smallCamel; } public Capitalization capitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; return this; } @@ -114,14 +111,12 @@ public String getCapitalCamel() { return capitalCamel; } - public void setCapitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; } public Capitalization smallSnake(String smallSnake) { - this.smallSnake = smallSnake; return this; } @@ -135,14 +130,12 @@ public String getSmallSnake() { return smallSnake; } - public void setSmallSnake(String smallSnake) { this.smallSnake = smallSnake; } public Capitalization capitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; return this; } @@ -156,14 +149,12 @@ public String getCapitalSnake() { return capitalSnake; } - public void setCapitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; } public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; return this; } @@ -177,14 +168,12 @@ public String getScAETHFlowPoints() { return scAETHFlowPoints; } - public void setScAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; } public Capitalization ATT_NAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; return this; } @@ -198,7 +187,6 @@ public String getATTNAME() { return ATT_NAME; } - public void setATTNAME(String ATT_NAME) { this.ATT_NAME = ATT_NAME; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java index 80e40e90099b..82abfcbae8a6 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Cat.java @@ -61,7 +61,6 @@ public Cat() { } public Cat declawed(Boolean declawed) { - this.declawed = declawed; return this; } @@ -75,7 +74,6 @@ public Boolean getDeclawed() { return declawed; } - public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java index 671e228b4205..47b8484413eb 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java index b473437102ca..73d93ccab308 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ClassModel.java @@ -59,7 +59,6 @@ public ClassModel() { } public ClassModel propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -73,7 +72,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java index fde656f3e93b..b5bf39b59833 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Client.java @@ -59,7 +59,6 @@ public Client() { } public Client client(String client) { - this.client = client; return this; } @@ -73,7 +72,6 @@ public String getClient() { return client; } - public void setClient(String client) { this.client = client; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java index 56ba84484ee0..8688f797390d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Dog.java @@ -61,7 +61,6 @@ public Dog() { } public Dog breed(String breed) { - this.breed = breed; return this; } @@ -75,7 +74,6 @@ public String getBreed() { return breed; } - public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java index c84d4fad4efa..ac1d4b206962 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -98,6 +98,11 @@ public JustSymbolEnum read(final JsonReader jsonReader) throws IOException { return JustSymbolEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + JustSymbolEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_JUST_SYMBOL = "just_symbol"; @@ -149,6 +154,11 @@ public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { return ArrayEnumEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ArrayEnumEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ARRAY_ENUM = "array_enum"; @@ -159,7 +169,6 @@ public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; return this; } @@ -173,14 +182,12 @@ public JustSymbolEnum getJustSymbol() { return justSymbol; } - public void setJustSymbol(JustSymbolEnum justSymbol) { this.justSymbol = justSymbol; } public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; return this; } @@ -202,7 +209,6 @@ public List getArrayEnum() { return arrayEnum; } - public void setArrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; } @@ -286,6 +292,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } + // validate the optional field `just_symbol` + if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) { + JustSymbolEnum.validateJsonElement(jsonObj.get("just_symbol")); + } // ensure the optional json data is an array if present if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonNull() && !jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumClass.java index d3639fe679bb..c2dfd3aecd7c 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumClass.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public EnumClass read(final JsonReader jsonReader) throws IOException { return EnumClass.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumClass.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java index eb4dac3d80a1..162d8f7285b5 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/EnumTest.java @@ -99,6 +99,11 @@ public EnumStringEnum read(final JsonReader jsonReader) throws IOException { return EnumStringEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING = "enum_string"; @@ -152,6 +157,11 @@ public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOExcepti return EnumStringRequiredEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringRequiredEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING_REQUIRED = "enum_string_required"; @@ -203,6 +213,11 @@ public EnumIntegerEnum read(final JsonReader jsonReader) throws IOException { return EnumIntegerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_INTEGER = "enum_integer"; @@ -254,6 +269,11 @@ public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { return EnumNumberEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Double value = jsonElement.getAsDouble(); + EnumNumberEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_NUMBER = "enum_number"; @@ -268,7 +288,6 @@ public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; return this; } @@ -282,14 +301,12 @@ public EnumStringEnum getEnumString() { return enumString; } - public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { - this.enumStringRequired = enumStringRequired; return this; } @@ -303,14 +320,12 @@ public EnumStringRequiredEnum getEnumStringRequired() { return enumStringRequired; } - public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; } public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; return this; } @@ -324,14 +339,12 @@ public EnumIntegerEnum getEnumInteger() { return enumInteger; } - public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; return this; } @@ -345,14 +358,12 @@ public EnumNumberEnum getEnumNumber() { return enumNumber; } - public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } public EnumTest outerEnum(OuterEnum outerEnum) { - this.outerEnum = outerEnum; return this; } @@ -366,7 +377,6 @@ public OuterEnum getOuterEnum() { return outerEnum; } - public void setOuterEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; } @@ -467,9 +477,27 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } + // validate the optional field `enum_string` + if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) { + EnumStringEnum.validateJsonElement(jsonObj.get("enum_string")); + } if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } + // validate the required field `enum_string_required` + EnumStringRequiredEnum.validateJsonElement(jsonObj.get("enum_string_required")); + // validate the optional field `enum_integer` + if (jsonObj.get("enum_integer") != null && !jsonObj.get("enum_integer").isJsonNull()) { + EnumIntegerEnum.validateJsonElement(jsonObj.get("enum_integer")); + } + // validate the optional field `enum_number` + if (jsonObj.get("enum_number") != null && !jsonObj.get("enum_number").isJsonNull()) { + EnumNumberEnum.validateJsonElement(jsonObj.get("enum_number")); + } + // validate the optional field `outerEnum` + if (jsonObj.get("outerEnum") != null && !jsonObj.get("outerEnum").isJsonNull()) { + OuterEnum.validateJsonElement(jsonObj.get("outerEnum")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 8adfae2c7418..94f2a71eae4b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -66,7 +66,6 @@ public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { - this._file = _file; return this; } @@ -80,14 +79,12 @@ public ModelFile getFile() { return _file; } - public void setFile(ModelFile _file) { this._file = _file; } public FileSchemaTestClass files(List files) { - this.files = files; return this; } @@ -109,7 +106,6 @@ public List getFiles() { return files; } - public void setFiles(List files) { this.files = files; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java index 9f0c736a1823..12e860ed470e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/FormatTest.java @@ -116,7 +116,6 @@ public FormatTest() { } public FormatTest integer(Integer integer) { - this.integer = integer; return this; } @@ -132,14 +131,12 @@ public Integer getInteger() { return integer; } - public void setInteger(Integer integer) { this.integer = integer; } public FormatTest int32(Integer int32) { - this.int32 = int32; return this; } @@ -155,14 +152,12 @@ public Integer getInt32() { return int32; } - public void setInt32(Integer int32) { this.int32 = int32; } public FormatTest int64(Long int64) { - this.int64 = int64; return this; } @@ -176,14 +171,12 @@ public Long getInt64() { return int64; } - public void setInt64(Long int64) { this.int64 = int64; } public FormatTest number(BigDecimal number) { - this.number = number; return this; } @@ -199,14 +192,12 @@ public BigDecimal getNumber() { return number; } - public void setNumber(BigDecimal number) { this.number = number; } public FormatTest _float(Float _float) { - this._float = _float; return this; } @@ -222,14 +213,12 @@ public Float getFloat() { return _float; } - public void setFloat(Float _float) { this._float = _float; } public FormatTest _double(Double _double) { - this._double = _double; return this; } @@ -245,14 +234,12 @@ public Double getDouble() { return _double; } - public void setDouble(Double _double) { this._double = _double; } public FormatTest string(String string) { - this.string = string; return this; } @@ -266,14 +253,12 @@ public String getString() { return string; } - public void setString(String string) { this.string = string; } public FormatTest _byte(byte[] _byte) { - this._byte = _byte; return this; } @@ -287,14 +272,12 @@ public byte[] getByte() { return _byte; } - public void setByte(byte[] _byte) { this._byte = _byte; } public FormatTest binary(File binary) { - this.binary = binary; return this; } @@ -308,14 +291,12 @@ public File getBinary() { return binary; } - public void setBinary(File binary) { this.binary = binary; } public FormatTest date(LocalDate date) { - this.date = date; return this; } @@ -329,14 +310,12 @@ public LocalDate getDate() { return date; } - public void setDate(LocalDate date) { this.date = date; } public FormatTest dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -350,14 +329,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public FormatTest uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -371,14 +348,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public FormatTest password(String password) { - this.password = password; return this; } @@ -392,14 +367,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public FormatTest bigDecimal(BigDecimal bigDecimal) { - this.bigDecimal = bigDecimal; return this; } @@ -413,7 +386,6 @@ public BigDecimal getBigDecimal() { return bigDecimal; } - public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } @@ -466,7 +438,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 1c5d73e03bae..32032e5bc343 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -62,7 +62,6 @@ public class HasOnlyReadOnly { public HasOnlyReadOnly() { } - public HasOnlyReadOnly( String bar, String foo @@ -83,7 +82,6 @@ public String getBar() { - /** * Get foo * @return foo @@ -96,7 +94,6 @@ public String getFoo() { - @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java index 6afb183e497d..cc727e2593be 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MapTest.java @@ -102,6 +102,11 @@ public InnerEnum read(final JsonReader jsonReader) throws IOException { return InnerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + InnerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_MAP_OF_ENUM_STRING = "map_of_enum_string"; @@ -120,7 +125,6 @@ public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; return this; } @@ -142,14 +146,12 @@ public Map> getMapMapOfString() { return mapMapOfString; } - public void setMapMapOfString(Map> mapMapOfString) { this.mapMapOfString = mapMapOfString; } public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; return this; } @@ -171,14 +173,12 @@ public Map getMapOfEnumString() { return mapOfEnumString; } - public void setMapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; } public MapTest directMap(Map directMap) { - this.directMap = directMap; return this; } @@ -200,14 +200,12 @@ public Map getDirectMap() { return directMap; } - public void setDirectMap(Map directMap) { this.directMap = directMap; } public MapTest indirectMap(Map indirectMap) { - this.indirectMap = indirectMap; return this; } @@ -229,7 +227,6 @@ public Map getIndirectMap() { return indirectMap; } - public void setIndirectMap(Map indirectMap) { this.indirectMap = indirectMap; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index 79f54cca16fa..d0826a2b882d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -72,7 +72,6 @@ public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -86,14 +85,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -107,14 +104,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; return this; } @@ -136,7 +131,6 @@ public Map getMap() { return map; } - public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java index dec6111e406a..8297feeb63c9 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Model200Response.java @@ -63,7 +63,6 @@ public Model200Response() { } public Model200Response name(Integer name) { - this.name = name; return this; } @@ -77,14 +76,12 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -98,7 +95,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 376aeed28c3d..177129845247 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java index 52f2a80efac7..11ae33c68658 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelFile.java @@ -59,7 +59,6 @@ public ModelFile() { } public ModelFile sourceURI(String sourceURI) { - this.sourceURI = sourceURI; return this; } @@ -73,7 +72,6 @@ public String getSourceURI() { return sourceURI; } - public void setSourceURI(String sourceURI) { this.sourceURI = sourceURI; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java index d99033eeb2c2..dccad3c38e6b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelList.java @@ -59,7 +59,6 @@ public ModelList() { } public ModelList _123list(String _123list) { - this._123list = _123list; return this; } @@ -73,7 +72,6 @@ public String get123list() { return _123list; } - public void set123list(String _123list) { this._123list = _123list; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java index 127d5ba93373..5e3c67935087 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -59,7 +59,6 @@ public ModelReturn() { } public ModelReturn _return(Integer _return) { - this._return = _return; return this; } @@ -73,7 +72,6 @@ public Integer getReturn() { return _return; } - public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java index c47403447339..6bd4ca194801 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Name.java @@ -70,7 +70,6 @@ public class Name { public Name() { } - public Name( Integer snakeCase, Integer _123number @@ -81,7 +80,6 @@ public Name( } public Name name(Integer name) { - this.name = name; return this; } @@ -95,7 +93,6 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } @@ -112,9 +109,7 @@ public Integer getSnakeCase() { - public Name property(String property) { - this.property = property; return this; } @@ -128,7 +123,6 @@ public String getProperty() { return property; } - public void setProperty(String property) { this.property = property; } @@ -146,7 +140,6 @@ public Integer get123number() { - @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java index 2ba74c8749df..af3b96e032fd 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -60,7 +60,6 @@ public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; return this; } @@ -74,7 +73,6 @@ public BigDecimal getJustNumber() { return justNumber; } - public void setJustNumber(BigDecimal justNumber) { this.justNumber = justNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java index 1d9a094e176c..78bdbf3a864b 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -344,6 +337,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java index f160e0fb4a42..bc13c7ae288d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -68,7 +68,6 @@ public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { - this.myNumber = myNumber; return this; } @@ -82,14 +81,12 @@ public BigDecimal getMyNumber() { return myNumber; } - public void setMyNumber(BigDecimal myNumber) { this.myNumber = myNumber; } public OuterComposite myString(String myString) { - this.myString = myString; return this; } @@ -103,14 +100,12 @@ public String getMyString() { return myString; } - public void setMyString(String myString) { this.myString = myString; } public OuterComposite myBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; return this; } @@ -124,7 +119,6 @@ public Boolean getMyBoolean() { return myBoolean; } - public void setMyBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterEnum.java index 40c7905b50b7..7f2bd742d75e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterEnum.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public OuterEnum read(final JsonReader jsonReader) throws IOException { return OuterEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnum.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java index 46fd792c466d..26194976154e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Pet.java @@ -124,6 +124,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -134,7 +139,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -148,14 +152,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -169,14 +171,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -190,14 +190,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(Set photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -219,14 +217,12 @@ public Set getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -248,14 +244,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -269,7 +263,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -401,6 +394,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index fdc80bb4cd9b..23839d4ca244 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -62,7 +62,6 @@ public class ReadOnlyFirst { public ReadOnlyFirst() { } - public ReadOnlyFirst( String bar ) { @@ -81,9 +80,7 @@ public String getBar() { - public ReadOnlyFirst baz(String baz) { - this.baz = baz; return this; } @@ -97,7 +94,6 @@ public String getBaz() { return baz; } - public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java index cc84c9dbd0a3..132b997b8b1d 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -59,7 +59,6 @@ public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; return this; } @@ -73,7 +72,6 @@ public SpecialModelName() { return $specialPropertyName; } - public void set$SpecialPropertyName(Long $specialPropertyName) { this.$specialPropertyName = $specialPropertyName; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java index aa4e38f9d985..efb4f0925bef 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 8edb189ba004..5fef2c268a54 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -78,7 +78,6 @@ public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { - this.stringItem = stringItem; return this; } @@ -92,14 +91,12 @@ public String getStringItem() { return stringItem; } - public void setStringItem(String stringItem) { this.stringItem = stringItem; } public TypeHolderDefault numberItem(BigDecimal numberItem) { - this.numberItem = numberItem; return this; } @@ -113,14 +110,12 @@ public BigDecimal getNumberItem() { return numberItem; } - public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; } public TypeHolderDefault integerItem(Integer integerItem) { - this.integerItem = integerItem; return this; } @@ -134,14 +129,12 @@ public Integer getIntegerItem() { return integerItem; } - public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; } public TypeHolderDefault boolItem(Boolean boolItem) { - this.boolItem = boolItem; return this; } @@ -155,14 +148,12 @@ public Boolean getBoolItem() { return boolItem; } - public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; } public TypeHolderDefault arrayItem(List arrayItem) { - this.arrayItem = arrayItem; return this; } @@ -184,7 +175,6 @@ public List getArrayItem() { return arrayItem; } - public void setArrayItem(List arrayItem) { this.arrayItem = arrayItem; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java index d1510fde0e55..9996cdd7a987 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -82,7 +82,6 @@ public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { - this.stringItem = stringItem; return this; } @@ -96,14 +95,12 @@ public String getStringItem() { return stringItem; } - public void setStringItem(String stringItem) { this.stringItem = stringItem; } public TypeHolderExample numberItem(BigDecimal numberItem) { - this.numberItem = numberItem; return this; } @@ -117,14 +114,12 @@ public BigDecimal getNumberItem() { return numberItem; } - public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; } public TypeHolderExample floatItem(Float floatItem) { - this.floatItem = floatItem; return this; } @@ -138,14 +133,12 @@ public Float getFloatItem() { return floatItem; } - public void setFloatItem(Float floatItem) { this.floatItem = floatItem; } public TypeHolderExample integerItem(Integer integerItem) { - this.integerItem = integerItem; return this; } @@ -159,14 +152,12 @@ public Integer getIntegerItem() { return integerItem; } - public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; } public TypeHolderExample boolItem(Boolean boolItem) { - this.boolItem = boolItem; return this; } @@ -180,14 +171,12 @@ public Boolean getBoolItem() { return boolItem; } - public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; } public TypeHolderExample arrayItem(List arrayItem) { - this.arrayItem = arrayItem; return this; } @@ -209,7 +198,6 @@ public List getArrayItem() { return arrayItem; } - public void setArrayItem(List arrayItem) { this.arrayItem = arrayItem; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java index 32df1b0dd1b4..fb730ebf22bc 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/User.java @@ -87,7 +87,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -101,14 +100,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -122,14 +119,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -143,14 +138,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -164,14 +157,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -185,14 +176,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -206,14 +195,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -227,14 +214,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -248,7 +233,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java index 94ac9dcc8bab..9c3b7f0ecd1e 100644 --- a/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/okhttp-gson-dynamicOperations/src/main/java/org/openapitools/client/model/XmlItem.java @@ -174,7 +174,6 @@ public XmlItem() { } public XmlItem attributeString(String attributeString) { - this.attributeString = attributeString; return this; } @@ -188,14 +187,12 @@ public String getAttributeString() { return attributeString; } - public void setAttributeString(String attributeString) { this.attributeString = attributeString; } public XmlItem attributeNumber(BigDecimal attributeNumber) { - this.attributeNumber = attributeNumber; return this; } @@ -209,14 +206,12 @@ public BigDecimal getAttributeNumber() { return attributeNumber; } - public void setAttributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; } public XmlItem attributeInteger(Integer attributeInteger) { - this.attributeInteger = attributeInteger; return this; } @@ -230,14 +225,12 @@ public Integer getAttributeInteger() { return attributeInteger; } - public void setAttributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; } public XmlItem attributeBoolean(Boolean attributeBoolean) { - this.attributeBoolean = attributeBoolean; return this; } @@ -251,14 +244,12 @@ public Boolean getAttributeBoolean() { return attributeBoolean; } - public void setAttributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; } public XmlItem wrappedArray(List wrappedArray) { - this.wrappedArray = wrappedArray; return this; } @@ -280,14 +271,12 @@ public List getWrappedArray() { return wrappedArray; } - public void setWrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; } public XmlItem nameString(String nameString) { - this.nameString = nameString; return this; } @@ -301,14 +290,12 @@ public String getNameString() { return nameString; } - public void setNameString(String nameString) { this.nameString = nameString; } public XmlItem nameNumber(BigDecimal nameNumber) { - this.nameNumber = nameNumber; return this; } @@ -322,14 +309,12 @@ public BigDecimal getNameNumber() { return nameNumber; } - public void setNameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; } public XmlItem nameInteger(Integer nameInteger) { - this.nameInteger = nameInteger; return this; } @@ -343,14 +328,12 @@ public Integer getNameInteger() { return nameInteger; } - public void setNameInteger(Integer nameInteger) { this.nameInteger = nameInteger; } public XmlItem nameBoolean(Boolean nameBoolean) { - this.nameBoolean = nameBoolean; return this; } @@ -364,14 +347,12 @@ public Boolean getNameBoolean() { return nameBoolean; } - public void setNameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; } public XmlItem nameArray(List nameArray) { - this.nameArray = nameArray; return this; } @@ -393,14 +374,12 @@ public List getNameArray() { return nameArray; } - public void setNameArray(List nameArray) { this.nameArray = nameArray; } public XmlItem nameWrappedArray(List nameWrappedArray) { - this.nameWrappedArray = nameWrappedArray; return this; } @@ -422,14 +401,12 @@ public List getNameWrappedArray() { return nameWrappedArray; } - public void setNameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; } public XmlItem prefixString(String prefixString) { - this.prefixString = prefixString; return this; } @@ -443,14 +420,12 @@ public String getPrefixString() { return prefixString; } - public void setPrefixString(String prefixString) { this.prefixString = prefixString; } public XmlItem prefixNumber(BigDecimal prefixNumber) { - this.prefixNumber = prefixNumber; return this; } @@ -464,14 +439,12 @@ public BigDecimal getPrefixNumber() { return prefixNumber; } - public void setPrefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; } public XmlItem prefixInteger(Integer prefixInteger) { - this.prefixInteger = prefixInteger; return this; } @@ -485,14 +458,12 @@ public Integer getPrefixInteger() { return prefixInteger; } - public void setPrefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; } public XmlItem prefixBoolean(Boolean prefixBoolean) { - this.prefixBoolean = prefixBoolean; return this; } @@ -506,14 +477,12 @@ public Boolean getPrefixBoolean() { return prefixBoolean; } - public void setPrefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; } public XmlItem prefixArray(List prefixArray) { - this.prefixArray = prefixArray; return this; } @@ -535,14 +504,12 @@ public List getPrefixArray() { return prefixArray; } - public void setPrefixArray(List prefixArray) { this.prefixArray = prefixArray; } public XmlItem prefixWrappedArray(List prefixWrappedArray) { - this.prefixWrappedArray = prefixWrappedArray; return this; } @@ -564,14 +531,12 @@ public List getPrefixWrappedArray() { return prefixWrappedArray; } - public void setPrefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; } public XmlItem namespaceString(String namespaceString) { - this.namespaceString = namespaceString; return this; } @@ -585,14 +550,12 @@ public String getNamespaceString() { return namespaceString; } - public void setNamespaceString(String namespaceString) { this.namespaceString = namespaceString; } public XmlItem namespaceNumber(BigDecimal namespaceNumber) { - this.namespaceNumber = namespaceNumber; return this; } @@ -606,14 +569,12 @@ public BigDecimal getNamespaceNumber() { return namespaceNumber; } - public void setNamespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; } public XmlItem namespaceInteger(Integer namespaceInteger) { - this.namespaceInteger = namespaceInteger; return this; } @@ -627,14 +588,12 @@ public Integer getNamespaceInteger() { return namespaceInteger; } - public void setNamespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; } public XmlItem namespaceBoolean(Boolean namespaceBoolean) { - this.namespaceBoolean = namespaceBoolean; return this; } @@ -648,14 +607,12 @@ public Boolean getNamespaceBoolean() { return namespaceBoolean; } - public void setNamespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; } public XmlItem namespaceArray(List namespaceArray) { - this.namespaceArray = namespaceArray; return this; } @@ -677,14 +634,12 @@ public List getNamespaceArray() { return namespaceArray; } - public void setNamespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; } public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { - this.namespaceWrappedArray = namespaceWrappedArray; return this; } @@ -706,14 +661,12 @@ public List getNamespaceWrappedArray() { return namespaceWrappedArray; } - public void setNamespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; } public XmlItem prefixNsString(String prefixNsString) { - this.prefixNsString = prefixNsString; return this; } @@ -727,14 +680,12 @@ public String getPrefixNsString() { return prefixNsString; } - public void setPrefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; } public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { - this.prefixNsNumber = prefixNsNumber; return this; } @@ -748,14 +699,12 @@ public BigDecimal getPrefixNsNumber() { return prefixNsNumber; } - public void setPrefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; } public XmlItem prefixNsInteger(Integer prefixNsInteger) { - this.prefixNsInteger = prefixNsInteger; return this; } @@ -769,14 +718,12 @@ public Integer getPrefixNsInteger() { return prefixNsInteger; } - public void setPrefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; } public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { - this.prefixNsBoolean = prefixNsBoolean; return this; } @@ -790,14 +737,12 @@ public Boolean getPrefixNsBoolean() { return prefixNsBoolean; } - public void setPrefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; } public XmlItem prefixNsArray(List prefixNsArray) { - this.prefixNsArray = prefixNsArray; return this; } @@ -819,14 +764,12 @@ public List getPrefixNsArray() { return prefixNsArray; } - public void setPrefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; } public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { - this.prefixNsWrappedArray = prefixNsWrappedArray; return this; } @@ -848,7 +791,6 @@ public List getPrefixNsWrappedArray() { return prefixNsWrappedArray; } - public void setPrefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-group-parameter/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/build.gradle b/samples/client/petstore/java/okhttp-gson-group-parameter/build.gradle index d74a21f6c8ae..2d46c1a9f7ef 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/build.sbt b/samples/client/petstore/java/okhttp-gson-group-parameter/build.sbt index 898a141449cc..8c6f95e13849 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/pom.xml b/samples/client/petstore/java/okhttp-gson-group-parameter/pom.xml index b2fddfc36eba..f72699f66202 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/pom.xml @@ -333,7 +333,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java index 6d1cc62db7e7..08a6cfe9ddd5 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java index ec41d25fa99f..f12855dae504 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java index a1df10aece5f..59645dcffcc2 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java index ae66537b4824..53a96c763a7c 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -382,6 +375,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java index 69cec0b898e2..9d0e1e017afa 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -133,7 +138,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -168,14 +170,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -189,14 +189,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -218,14 +216,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -247,7 +243,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -255,7 +250,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -442,6 +435,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java index 262ef93dbbd3..bae59a3dedb3 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java index 8c1f31e4d16a..157f92c49599 100644 --- a/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-group-parameter/src/main/java/org/openapitools/client/model/User.java @@ -87,7 +87,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -101,14 +100,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -122,14 +119,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -143,14 +138,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -164,14 +157,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -185,14 +176,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -206,14 +195,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -227,14 +214,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -248,7 +233,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-nullable-required/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/build.gradle b/samples/client/petstore/java/okhttp-gson-nullable-required/build.gradle index f6f4d79be320..984b8135b0f7 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/build.sbt b/samples/client/petstore/java/okhttp-gson-nullable-required/build.sbt index c00d1b032136..65ec5ab37581 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/pom.xml b/samples/client/petstore/java/okhttp-gson-nullable-required/pom.xml index 9470b5baf425..d2dcf6efd9e3 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/pom.xml @@ -333,7 +333,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/ApiClient.java index 3f95f4861622..bccc06dde46a 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Category.java index ec41d25fa99f..f12855dae504 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/ModelApiResponse.java index a1df10aece5f..59645dcffcc2 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Order.java index ae66537b4824..53a96c763a7c 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -382,6 +375,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Pet.java index 69cec0b898e2..9d0e1e017afa 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -133,7 +138,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -168,14 +170,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -189,14 +189,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -218,14 +216,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -247,7 +243,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -255,7 +250,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -442,6 +435,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java index 1a60aace70bc..dea91cf710b6 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases1.java @@ -123,6 +123,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -134,7 +139,6 @@ public PetWithRequiredNullableCases1() { } public PetWithRequiredNullableCases1 id(Long id) { - this.id = id; return this; } @@ -148,14 +152,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public PetWithRequiredNullableCases1 category(Category category) { - this.category = category; return this; } @@ -169,14 +171,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public PetWithRequiredNullableCases1 name(String name) { - this.name = name; return this; } @@ -190,14 +190,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public PetWithRequiredNullableCases1 photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -219,14 +217,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public PetWithRequiredNullableCases1 tags(List tags) { - this.tags = tags; return this; } @@ -248,7 +244,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -256,7 +251,6 @@ public void setTags(List tags) { @Deprecated public PetWithRequiredNullableCases1 status(StatusEnum status) { - this.status = status; return this; } @@ -272,7 +266,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -454,6 +447,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases2.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases2.java index 7e1fa54da98b..df70736606c8 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases2.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/PetWithRequiredNullableCases2.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -133,7 +138,6 @@ public PetWithRequiredNullableCases2() { } public PetWithRequiredNullableCases2 id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public PetWithRequiredNullableCases2 category(Category category) { - this.category = category; return this; } @@ -168,14 +170,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public PetWithRequiredNullableCases2 name(String name) { - this.name = name; return this; } @@ -189,14 +189,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public PetWithRequiredNullableCases2 photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -218,14 +216,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public PetWithRequiredNullableCases2 tags(List tags) { - this.tags = tags; return this; } @@ -247,7 +243,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -255,7 +250,6 @@ public void setTags(List tags) { @Deprecated public PetWithRequiredNullableCases2 status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -442,6 +435,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Tag.java index 262ef93dbbd3..bae59a3dedb3 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/User.java index 8c1f31e4d16a..157f92c49599 100644 --- a/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-nullable-required/src/main/java/org/openapitools/client/model/User.java @@ -87,7 +87,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -101,14 +100,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -122,14 +119,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -143,14 +138,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -164,14 +157,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -185,14 +176,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -206,14 +195,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -227,14 +214,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -248,7 +233,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle index 0358b0c8fa7d..9f27b1ebb500 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt index 14a79d4e6fa4..0dcbbab8dd27 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml index 94c5f6d81043..54b13240c6fb 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/pom.xml @@ -340,7 +340,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java index ccc405823612..f211421d38b4 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 460ad224963c..e6ae1d454c79 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index fbe51042e1a9..f50f7a96cc56 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java index 869c75fbc82b..fce6c842805d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesAnyType.java @@ -61,7 +61,6 @@ public AdditionalPropertiesAnyType() { } public AdditionalPropertiesAnyType name(String name) { - this.name = name; return this; } @@ -75,7 +74,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java index a9982955fce7..4200d730130a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesArray.java @@ -62,7 +62,6 @@ public AdditionalPropertiesArray() { } public AdditionalPropertiesArray name(String name) { - this.name = name; return this; } @@ -76,7 +75,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java index 37980109cdfe..1927fc3a5ac8 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesBoolean.java @@ -61,7 +61,6 @@ public AdditionalPropertiesBoolean() { } public AdditionalPropertiesBoolean name(String name) { - this.name = name; return this; } @@ -75,7 +74,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 45ccb799d064..2caca34dfab0 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -105,7 +105,6 @@ public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapString(Map mapString) { - this.mapString = mapString; return this; } @@ -127,14 +126,12 @@ public Map getMapString() { return mapString; } - public void setMapString(Map mapString) { this.mapString = mapString; } public AdditionalPropertiesClass mapNumber(Map mapNumber) { - this.mapNumber = mapNumber; return this; } @@ -156,14 +153,12 @@ public Map getMapNumber() { return mapNumber; } - public void setMapNumber(Map mapNumber) { this.mapNumber = mapNumber; } public AdditionalPropertiesClass mapInteger(Map mapInteger) { - this.mapInteger = mapInteger; return this; } @@ -185,14 +180,12 @@ public Map getMapInteger() { return mapInteger; } - public void setMapInteger(Map mapInteger) { this.mapInteger = mapInteger; } public AdditionalPropertiesClass mapBoolean(Map mapBoolean) { - this.mapBoolean = mapBoolean; return this; } @@ -214,14 +207,12 @@ public Map getMapBoolean() { return mapBoolean; } - public void setMapBoolean(Map mapBoolean) { this.mapBoolean = mapBoolean; } public AdditionalPropertiesClass mapArrayInteger(Map> mapArrayInteger) { - this.mapArrayInteger = mapArrayInteger; return this; } @@ -243,14 +234,12 @@ public Map> getMapArrayInteger() { return mapArrayInteger; } - public void setMapArrayInteger(Map> mapArrayInteger) { this.mapArrayInteger = mapArrayInteger; } public AdditionalPropertiesClass mapArrayAnytype(Map> mapArrayAnytype) { - this.mapArrayAnytype = mapArrayAnytype; return this; } @@ -272,14 +261,12 @@ public Map> getMapArrayAnytype() { return mapArrayAnytype; } - public void setMapArrayAnytype(Map> mapArrayAnytype) { this.mapArrayAnytype = mapArrayAnytype; } public AdditionalPropertiesClass mapMapString(Map> mapMapString) { - this.mapMapString = mapMapString; return this; } @@ -301,14 +288,12 @@ public Map> getMapMapString() { return mapMapString; } - public void setMapMapString(Map> mapMapString) { this.mapMapString = mapMapString; } public AdditionalPropertiesClass mapMapAnytype(Map> mapMapAnytype) { - this.mapMapAnytype = mapMapAnytype; return this; } @@ -330,14 +315,12 @@ public Map> getMapMapAnytype() { return mapMapAnytype; } - public void setMapMapAnytype(Map> mapMapAnytype) { this.mapMapAnytype = mapMapAnytype; } public AdditionalPropertiesClass anytype1(Object anytype1) { - this.anytype1 = anytype1; return this; } @@ -351,14 +334,12 @@ public Object getAnytype1() { return anytype1; } - public void setAnytype1(Object anytype1) { this.anytype1 = anytype1; } public AdditionalPropertiesClass anytype2(Object anytype2) { - this.anytype2 = anytype2; return this; } @@ -372,14 +353,12 @@ public Object getAnytype2() { return anytype2; } - public void setAnytype2(Object anytype2) { this.anytype2 = anytype2; } public AdditionalPropertiesClass anytype3(Object anytype3) { - this.anytype3 = anytype3; return this; } @@ -393,7 +372,6 @@ public Object getAnytype3() { return anytype3; } - public void setAnytype3(Object anytype3) { this.anytype3 = anytype3; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java index 049441a9747e..e897db69fa32 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesInteger.java @@ -61,7 +61,6 @@ public AdditionalPropertiesInteger() { } public AdditionalPropertiesInteger name(String name) { - this.name = name; return this; } @@ -75,7 +74,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java index bba08fa29920..ecb9eebe7834 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesNumber.java @@ -62,7 +62,6 @@ public AdditionalPropertiesNumber() { } public AdditionalPropertiesNumber name(String name) { - this.name = name; return this; } @@ -76,7 +75,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java index cac4aa9c62eb..2240e88cc7db 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesObject.java @@ -62,7 +62,6 @@ public AdditionalPropertiesObject() { } public AdditionalPropertiesObject name(String name) { - this.name = name; return this; } @@ -76,7 +75,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java index a05ec68e139f..84a3278be2d7 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/AdditionalPropertiesString.java @@ -61,7 +61,6 @@ public AdditionalPropertiesString() { } public AdditionalPropertiesString name(String name) { - this.name = name; return this; } @@ -75,7 +74,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java index 791e9a803c78..5eb6e448bdb8 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Animal.java @@ -66,7 +66,6 @@ public Animal() { } public Animal className(String className) { - this.className = className; return this; } @@ -80,14 +79,12 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } public Animal color(String color) { - this.color = color; return this; } @@ -101,7 +98,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 189ba1a2f01e..56363a103f5a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -64,7 +64,6 @@ public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; return this; } @@ -86,7 +85,6 @@ public List> getArrayArrayNumber() { return arrayArrayNumber; } - public void setArrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index afd92de01c6f..895c38d5a30b 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -64,7 +64,6 @@ public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; return this; } @@ -86,7 +85,6 @@ public List getArrayNumber() { return arrayNumber; } - public void setArrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java index 3c53a2c1472e..78591ee3f931 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -72,7 +72,6 @@ public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; return this; } @@ -94,14 +93,12 @@ public List getArrayOfString() { return arrayOfString; } - public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } @@ -123,14 +120,12 @@ public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -152,7 +147,6 @@ public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java index 98eba0fbbcff..1f55dc021f43 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/BigCat.java @@ -103,6 +103,11 @@ public KindEnum read(final JsonReader jsonReader) throws IOException { return KindEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + KindEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_KIND = "kind"; @@ -115,7 +120,6 @@ public BigCat() { } public BigCat kind(KindEnum kind) { - this.kind = kind; return this; } @@ -129,7 +133,6 @@ public KindEnum getKind() { return kind; } - public void setKind(KindEnum kind) { this.kind = kind; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java index f1e1f7b26438..1f1ba12c811a 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Capitalization.java @@ -81,7 +81,6 @@ public Capitalization() { } public Capitalization smallCamel(String smallCamel) { - this.smallCamel = smallCamel; return this; } @@ -95,14 +94,12 @@ public String getSmallCamel() { return smallCamel; } - public void setSmallCamel(String smallCamel) { this.smallCamel = smallCamel; } public Capitalization capitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; return this; } @@ -116,14 +113,12 @@ public String getCapitalCamel() { return capitalCamel; } - public void setCapitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; } public Capitalization smallSnake(String smallSnake) { - this.smallSnake = smallSnake; return this; } @@ -137,14 +132,12 @@ public String getSmallSnake() { return smallSnake; } - public void setSmallSnake(String smallSnake) { this.smallSnake = smallSnake; } public Capitalization capitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; return this; } @@ -158,14 +151,12 @@ public String getCapitalSnake() { return capitalSnake; } - public void setCapitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; } public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; return this; } @@ -179,14 +170,12 @@ public String getScAETHFlowPoints() { return scAETHFlowPoints; } - public void setScAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; } public Capitalization ATT_NAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; return this; } @@ -200,7 +189,6 @@ public String getATTNAME() { return ATT_NAME; } - public void setATTNAME(String ATT_NAME) { this.ATT_NAME = ATT_NAME; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java index 1b5c6626f0f8..e50186056906 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Cat.java @@ -64,7 +64,6 @@ public Cat() { } public Cat declawed(Boolean declawed) { - this.declawed = declawed; return this; } @@ -78,7 +77,6 @@ public Boolean getDeclawed() { return declawed; } - public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java index 17277ecb05b5..c33b5fddc169 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Category.java @@ -65,7 +65,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -79,14 +78,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -100,7 +97,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java index c439f0e47ec7..fdb8f7fde3dd 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ClassModel.java @@ -61,7 +61,6 @@ public ClassModel() { } public ClassModel propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -75,7 +74,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java index 111f813645e9..eff9a8e4c6f3 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Client.java @@ -61,7 +61,6 @@ public Client() { } public Client client(String client) { - this.client = client; return this; } @@ -75,7 +74,6 @@ public String getClient() { return client; } - public void setClient(String client) { this.client = client; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java index ffc75f091c97..28e5b7f8d5c7 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Dog.java @@ -64,7 +64,6 @@ public Dog() { } public Dog breed(String breed) { - this.breed = breed; return this; } @@ -78,7 +77,6 @@ public String getBreed() { return breed; } - public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java index 655ff2065088..ef44420e0b0d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -100,6 +100,11 @@ public JustSymbolEnum read(final JsonReader jsonReader) throws IOException { return JustSymbolEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + JustSymbolEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_JUST_SYMBOL = "just_symbol"; @@ -151,6 +156,11 @@ public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { return ArrayEnumEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ArrayEnumEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ARRAY_ENUM = "array_enum"; @@ -161,7 +171,6 @@ public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; return this; } @@ -175,14 +184,12 @@ public JustSymbolEnum getJustSymbol() { return justSymbol; } - public void setJustSymbol(JustSymbolEnum justSymbol) { this.justSymbol = justSymbol; } public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; return this; } @@ -204,7 +211,6 @@ public List getArrayEnum() { return arrayEnum; } - public void setArrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; } @@ -311,6 +317,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } + // validate the optional field `just_symbol` + if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) { + JustSymbolEnum.validateJsonElement(jsonObj.get("just_symbol")); + } // ensure the optional json data is an array if present if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonNull() && !jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumClass.java index 643c5d1d864d..5668c62bebe2 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumClass.java @@ -20,6 +20,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -72,5 +73,10 @@ public EnumClass read(final JsonReader jsonReader) throws IOException { return EnumClass.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumClass.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java index 0ec996e7338a..252907697aba 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/EnumTest.java @@ -101,6 +101,11 @@ public EnumStringEnum read(final JsonReader jsonReader) throws IOException { return EnumStringEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING = "enum_string"; @@ -154,6 +159,11 @@ public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOExcepti return EnumStringRequiredEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringRequiredEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING_REQUIRED = "enum_string_required"; @@ -205,6 +215,11 @@ public EnumIntegerEnum read(final JsonReader jsonReader) throws IOException { return EnumIntegerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_INTEGER = "enum_integer"; @@ -256,6 +271,11 @@ public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { return EnumNumberEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Double value = jsonElement.getAsDouble(); + EnumNumberEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_NUMBER = "enum_number"; @@ -270,7 +290,6 @@ public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; return this; } @@ -284,14 +303,12 @@ public EnumStringEnum getEnumString() { return enumString; } - public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { - this.enumStringRequired = enumStringRequired; return this; } @@ -305,14 +322,12 @@ public EnumStringRequiredEnum getEnumStringRequired() { return enumStringRequired; } - public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; } public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; return this; } @@ -326,14 +341,12 @@ public EnumIntegerEnum getEnumInteger() { return enumInteger; } - public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; return this; } @@ -347,14 +360,12 @@ public EnumNumberEnum getEnumNumber() { return enumNumber; } - public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } public EnumTest outerEnum(OuterEnum outerEnum) { - this.outerEnum = outerEnum; return this; } @@ -368,7 +379,6 @@ public OuterEnum getOuterEnum() { return outerEnum; } - public void setOuterEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; } @@ -498,9 +508,27 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } + // validate the optional field `enum_string` + if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) { + EnumStringEnum.validateJsonElement(jsonObj.get("enum_string")); + } if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } + // validate the required field `enum_string_required` + EnumStringRequiredEnum.validateJsonElement(jsonObj.get("enum_string_required")); + // validate the optional field `enum_integer` + if (jsonObj.get("enum_integer") != null && !jsonObj.get("enum_integer").isJsonNull()) { + EnumIntegerEnum.validateJsonElement(jsonObj.get("enum_integer")); + } + // validate the optional field `enum_number` + if (jsonObj.get("enum_number") != null && !jsonObj.get("enum_number").isJsonNull()) { + EnumNumberEnum.validateJsonElement(jsonObj.get("enum_number")); + } + // validate the optional field `outerEnum` + if (jsonObj.get("outerEnum") != null && !jsonObj.get("outerEnum").isJsonNull()) { + OuterEnum.validateJsonElement(jsonObj.get("outerEnum")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 83cd0c5647ff..8f9f79761bd0 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -68,7 +68,6 @@ public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { - this._file = _file; return this; } @@ -82,14 +81,12 @@ public ModelFile getFile() { return _file; } - public void setFile(ModelFile _file) { this._file = _file; } public FileSchemaTestClass files(List files) { - this.files = files; return this; } @@ -111,7 +108,6 @@ public List getFiles() { return files; } - public void setFiles(List files) { this.files = files; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java index 2aa4ff41826f..20b4ff70f417 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/FormatTest.java @@ -118,7 +118,6 @@ public FormatTest() { } public FormatTest integer(Integer integer) { - this.integer = integer; return this; } @@ -134,14 +133,12 @@ public Integer getInteger() { return integer; } - public void setInteger(Integer integer) { this.integer = integer; } public FormatTest int32(Integer int32) { - this.int32 = int32; return this; } @@ -157,14 +154,12 @@ public Integer getInt32() { return int32; } - public void setInt32(Integer int32) { this.int32 = int32; } public FormatTest int64(Long int64) { - this.int64 = int64; return this; } @@ -178,14 +173,12 @@ public Long getInt64() { return int64; } - public void setInt64(Long int64) { this.int64 = int64; } public FormatTest number(BigDecimal number) { - this.number = number; return this; } @@ -201,14 +194,12 @@ public BigDecimal getNumber() { return number; } - public void setNumber(BigDecimal number) { this.number = number; } public FormatTest _float(Float _float) { - this._float = _float; return this; } @@ -224,14 +215,12 @@ public Float getFloat() { return _float; } - public void setFloat(Float _float) { this._float = _float; } public FormatTest _double(Double _double) { - this._double = _double; return this; } @@ -247,14 +236,12 @@ public Double getDouble() { return _double; } - public void setDouble(Double _double) { this._double = _double; } public FormatTest string(String string) { - this.string = string; return this; } @@ -268,14 +255,12 @@ public String getString() { return string; } - public void setString(String string) { this.string = string; } public FormatTest _byte(byte[] _byte) { - this._byte = _byte; return this; } @@ -289,14 +274,12 @@ public byte[] getByte() { return _byte; } - public void setByte(byte[] _byte) { this._byte = _byte; } public FormatTest binary(File binary) { - this.binary = binary; return this; } @@ -310,14 +293,12 @@ public File getBinary() { return binary; } - public void setBinary(File binary) { this.binary = binary; } public FormatTest date(LocalDate date) { - this.date = date; return this; } @@ -331,14 +312,12 @@ public LocalDate getDate() { return date; } - public void setDate(LocalDate date) { this.date = date; } public FormatTest dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -352,14 +331,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public FormatTest uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -373,14 +350,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public FormatTest password(String password) { - this.password = password; return this; } @@ -394,14 +369,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public FormatTest bigDecimal(BigDecimal bigDecimal) { - this.bigDecimal = bigDecimal; return this; } @@ -415,7 +388,6 @@ public BigDecimal getBigDecimal() { return bigDecimal; } - public void setBigDecimal(BigDecimal bigDecimal) { this.bigDecimal = bigDecimal; } @@ -468,7 +440,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index 67c601002152..06525b52074d 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -64,7 +64,6 @@ public class HasOnlyReadOnly implements Parcelable { public HasOnlyReadOnly() { } - public HasOnlyReadOnly( String bar, String foo @@ -85,7 +84,6 @@ public String getBar() { - /** * Get foo * @return foo @@ -98,7 +96,6 @@ public String getFoo() { - @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java index 6958a69ffb32..5d376530b172 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MapTest.java @@ -104,6 +104,11 @@ public InnerEnum read(final JsonReader jsonReader) throws IOException { return InnerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + InnerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_MAP_OF_ENUM_STRING = "map_of_enum_string"; @@ -122,7 +127,6 @@ public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; return this; } @@ -144,14 +148,12 @@ public Map> getMapMapOfString() { return mapMapOfString; } - public void setMapMapOfString(Map> mapMapOfString) { this.mapMapOfString = mapMapOfString; } public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; return this; } @@ -173,14 +175,12 @@ public Map getMapOfEnumString() { return mapOfEnumString; } - public void setMapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; } public MapTest directMap(Map directMap) { - this.directMap = directMap; return this; } @@ -202,14 +202,12 @@ public Map getDirectMap() { return directMap; } - public void setDirectMap(Map directMap) { this.directMap = directMap; } public MapTest indirectMap(Map indirectMap) { - this.indirectMap = indirectMap; return this; } @@ -231,7 +229,6 @@ public Map getIndirectMap() { return indirectMap; } - public void setIndirectMap(Map indirectMap) { this.indirectMap = indirectMap; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index c45274a1b892..67e777bc3950 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -74,7 +74,6 @@ public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -88,14 +87,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -109,14 +106,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; return this; } @@ -138,7 +133,6 @@ public Map getMap() { return map; } - public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java index f5c73cdb43b0..2f8ec36e0ef6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Model200Response.java @@ -65,7 +65,6 @@ public Model200Response() { } public Model200Response name(Integer name) { - this.name = name; return this; } @@ -79,14 +78,12 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -100,7 +97,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java index a23df3a13c78..5b312ced45ea 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -69,7 +69,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -83,14 +82,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -104,14 +101,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -125,7 +120,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java index 8f3483020899..adb2b574c44f 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelFile.java @@ -61,7 +61,6 @@ public ModelFile() { } public ModelFile sourceURI(String sourceURI) { - this.sourceURI = sourceURI; return this; } @@ -75,7 +74,6 @@ public String getSourceURI() { return sourceURI; } - public void setSourceURI(String sourceURI) { this.sourceURI = sourceURI; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java index fb26a6e8ce1e..c65bb0b66df5 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelList.java @@ -61,7 +61,6 @@ public ModelList() { } public ModelList _123list(String _123list) { - this._123list = _123list; return this; } @@ -75,7 +74,6 @@ public String get123list() { return _123list; } - public void set123list(String _123list) { this._123list = _123list; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java index 556612cdb6d3..787f98a8afa6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -61,7 +61,6 @@ public ModelReturn() { } public ModelReturn _return(Integer _return) { - this._return = _return; return this; } @@ -75,7 +74,6 @@ public Integer getReturn() { return _return; } - public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java index 7c6922f1fec2..92101c648816 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Name.java @@ -72,7 +72,6 @@ public class Name implements Parcelable { public Name() { } - public Name( Integer snakeCase, Integer _123number @@ -83,7 +82,6 @@ public Name( } public Name name(Integer name) { - this.name = name; return this; } @@ -97,7 +95,6 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } @@ -114,9 +111,7 @@ public Integer getSnakeCase() { - public Name property(String property) { - this.property = property; return this; } @@ -130,7 +125,6 @@ public String getProperty() { return property; } - public void setProperty(String property) { this.property = property; } @@ -148,7 +142,6 @@ public Integer get123number() { - @Override public boolean equals(Object o) { if (this == o) { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java index 433ccbe9ad78..c9cab3da84b9 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -62,7 +62,6 @@ public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; return this; } @@ -76,7 +75,6 @@ public BigDecimal getJustNumber() { return justNumber; } - public void setJustNumber(BigDecimal justNumber) { this.justNumber = justNumber; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java index 212ccc32fda3..0934a149f5ae 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Order.java @@ -117,6 +117,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -131,7 +136,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -145,14 +149,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -166,14 +168,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -187,14 +187,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -208,14 +206,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -229,14 +225,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -250,7 +244,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -377,6 +370,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java index 1b91cc66b891..694acc793679 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -70,7 +70,6 @@ public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { - this.myNumber = myNumber; return this; } @@ -84,14 +83,12 @@ public BigDecimal getMyNumber() { return myNumber; } - public void setMyNumber(BigDecimal myNumber) { this.myNumber = myNumber; } public OuterComposite myString(String myString) { - this.myString = myString; return this; } @@ -105,14 +102,12 @@ public String getMyString() { return myString; } - public void setMyString(String myString) { this.myString = myString; } public OuterComposite myBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; return this; } @@ -126,7 +121,6 @@ public Boolean getMyBoolean() { return myBoolean; } - public void setMyBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterEnum.java index 86e01b2d8296..f9002dca2ded 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterEnum.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -20,6 +20,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -72,5 +73,10 @@ public OuterEnum read(final JsonReader jsonReader) throws IOException { return OuterEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnum.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java index 38dab5c2193c..25216412fc82 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Pet.java @@ -126,6 +126,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -136,7 +141,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -150,14 +154,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -171,14 +173,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -192,14 +192,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(Set photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -221,14 +219,12 @@ public Set getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -250,14 +246,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -271,7 +265,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -434,6 +427,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index d6a6dd981d75..7aeb3a73c1d5 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -64,7 +64,6 @@ public class ReadOnlyFirst implements Parcelable { public ReadOnlyFirst() { } - public ReadOnlyFirst( String bar ) { @@ -83,9 +82,7 @@ public String getBar() { - public ReadOnlyFirst baz(String baz) { - this.baz = baz; return this; } @@ -99,7 +96,6 @@ public String getBaz() { return baz; } - public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java index 3c2b3320e699..b6c92e881545 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -61,7 +61,6 @@ public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; return this; } @@ -75,7 +74,6 @@ public SpecialModelName() { return $specialPropertyName; } - public void set$SpecialPropertyName(Long $specialPropertyName) { this.$specialPropertyName = $specialPropertyName; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java index 521da9b77d9b..68dbf7e100b3 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/Tag.java @@ -65,7 +65,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -79,14 +78,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -100,7 +97,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java index 6b47b72bd7f5..9c3661530af6 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderDefault.java @@ -80,7 +80,6 @@ public TypeHolderDefault() { } public TypeHolderDefault stringItem(String stringItem) { - this.stringItem = stringItem; return this; } @@ -94,14 +93,12 @@ public String getStringItem() { return stringItem; } - public void setStringItem(String stringItem) { this.stringItem = stringItem; } public TypeHolderDefault numberItem(BigDecimal numberItem) { - this.numberItem = numberItem; return this; } @@ -115,14 +112,12 @@ public BigDecimal getNumberItem() { return numberItem; } - public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; } public TypeHolderDefault integerItem(Integer integerItem) { - this.integerItem = integerItem; return this; } @@ -136,14 +131,12 @@ public Integer getIntegerItem() { return integerItem; } - public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; } public TypeHolderDefault boolItem(Boolean boolItem) { - this.boolItem = boolItem; return this; } @@ -157,14 +150,12 @@ public Boolean getBoolItem() { return boolItem; } - public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; } public TypeHolderDefault arrayItem(List arrayItem) { - this.arrayItem = arrayItem; return this; } @@ -186,7 +177,6 @@ public List getArrayItem() { return arrayItem; } - public void setArrayItem(List arrayItem) { this.arrayItem = arrayItem; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java index eaa770cfffe3..731407590f7c 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/TypeHolderExample.java @@ -84,7 +84,6 @@ public TypeHolderExample() { } public TypeHolderExample stringItem(String stringItem) { - this.stringItem = stringItem; return this; } @@ -98,14 +97,12 @@ public String getStringItem() { return stringItem; } - public void setStringItem(String stringItem) { this.stringItem = stringItem; } public TypeHolderExample numberItem(BigDecimal numberItem) { - this.numberItem = numberItem; return this; } @@ -119,14 +116,12 @@ public BigDecimal getNumberItem() { return numberItem; } - public void setNumberItem(BigDecimal numberItem) { this.numberItem = numberItem; } public TypeHolderExample floatItem(Float floatItem) { - this.floatItem = floatItem; return this; } @@ -140,14 +135,12 @@ public Float getFloatItem() { return floatItem; } - public void setFloatItem(Float floatItem) { this.floatItem = floatItem; } public TypeHolderExample integerItem(Integer integerItem) { - this.integerItem = integerItem; return this; } @@ -161,14 +154,12 @@ public Integer getIntegerItem() { return integerItem; } - public void setIntegerItem(Integer integerItem) { this.integerItem = integerItem; } public TypeHolderExample boolItem(Boolean boolItem) { - this.boolItem = boolItem; return this; } @@ -182,14 +173,12 @@ public Boolean getBoolItem() { return boolItem; } - public void setBoolItem(Boolean boolItem) { this.boolItem = boolItem; } public TypeHolderExample arrayItem(List arrayItem) { - this.arrayItem = arrayItem; return this; } @@ -211,7 +200,6 @@ public List getArrayItem() { return arrayItem; } - public void setArrayItem(List arrayItem) { this.arrayItem = arrayItem; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java index 886bcde68448..6c7a391d3941 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/User.java @@ -89,7 +89,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -103,14 +102,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -124,14 +121,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -145,14 +140,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -166,14 +159,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -187,14 +178,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -208,14 +197,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -229,14 +216,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -250,7 +235,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java index f8eca10657be..2681238d0506 100644 --- a/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java +++ b/samples/client/petstore/java/okhttp-gson-parcelableModel/src/main/java/org/openapitools/client/model/XmlItem.java @@ -176,7 +176,6 @@ public XmlItem() { } public XmlItem attributeString(String attributeString) { - this.attributeString = attributeString; return this; } @@ -190,14 +189,12 @@ public String getAttributeString() { return attributeString; } - public void setAttributeString(String attributeString) { this.attributeString = attributeString; } public XmlItem attributeNumber(BigDecimal attributeNumber) { - this.attributeNumber = attributeNumber; return this; } @@ -211,14 +208,12 @@ public BigDecimal getAttributeNumber() { return attributeNumber; } - public void setAttributeNumber(BigDecimal attributeNumber) { this.attributeNumber = attributeNumber; } public XmlItem attributeInteger(Integer attributeInteger) { - this.attributeInteger = attributeInteger; return this; } @@ -232,14 +227,12 @@ public Integer getAttributeInteger() { return attributeInteger; } - public void setAttributeInteger(Integer attributeInteger) { this.attributeInteger = attributeInteger; } public XmlItem attributeBoolean(Boolean attributeBoolean) { - this.attributeBoolean = attributeBoolean; return this; } @@ -253,14 +246,12 @@ public Boolean getAttributeBoolean() { return attributeBoolean; } - public void setAttributeBoolean(Boolean attributeBoolean) { this.attributeBoolean = attributeBoolean; } public XmlItem wrappedArray(List wrappedArray) { - this.wrappedArray = wrappedArray; return this; } @@ -282,14 +273,12 @@ public List getWrappedArray() { return wrappedArray; } - public void setWrappedArray(List wrappedArray) { this.wrappedArray = wrappedArray; } public XmlItem nameString(String nameString) { - this.nameString = nameString; return this; } @@ -303,14 +292,12 @@ public String getNameString() { return nameString; } - public void setNameString(String nameString) { this.nameString = nameString; } public XmlItem nameNumber(BigDecimal nameNumber) { - this.nameNumber = nameNumber; return this; } @@ -324,14 +311,12 @@ public BigDecimal getNameNumber() { return nameNumber; } - public void setNameNumber(BigDecimal nameNumber) { this.nameNumber = nameNumber; } public XmlItem nameInteger(Integer nameInteger) { - this.nameInteger = nameInteger; return this; } @@ -345,14 +330,12 @@ public Integer getNameInteger() { return nameInteger; } - public void setNameInteger(Integer nameInteger) { this.nameInteger = nameInteger; } public XmlItem nameBoolean(Boolean nameBoolean) { - this.nameBoolean = nameBoolean; return this; } @@ -366,14 +349,12 @@ public Boolean getNameBoolean() { return nameBoolean; } - public void setNameBoolean(Boolean nameBoolean) { this.nameBoolean = nameBoolean; } public XmlItem nameArray(List nameArray) { - this.nameArray = nameArray; return this; } @@ -395,14 +376,12 @@ public List getNameArray() { return nameArray; } - public void setNameArray(List nameArray) { this.nameArray = nameArray; } public XmlItem nameWrappedArray(List nameWrappedArray) { - this.nameWrappedArray = nameWrappedArray; return this; } @@ -424,14 +403,12 @@ public List getNameWrappedArray() { return nameWrappedArray; } - public void setNameWrappedArray(List nameWrappedArray) { this.nameWrappedArray = nameWrappedArray; } public XmlItem prefixString(String prefixString) { - this.prefixString = prefixString; return this; } @@ -445,14 +422,12 @@ public String getPrefixString() { return prefixString; } - public void setPrefixString(String prefixString) { this.prefixString = prefixString; } public XmlItem prefixNumber(BigDecimal prefixNumber) { - this.prefixNumber = prefixNumber; return this; } @@ -466,14 +441,12 @@ public BigDecimal getPrefixNumber() { return prefixNumber; } - public void setPrefixNumber(BigDecimal prefixNumber) { this.prefixNumber = prefixNumber; } public XmlItem prefixInteger(Integer prefixInteger) { - this.prefixInteger = prefixInteger; return this; } @@ -487,14 +460,12 @@ public Integer getPrefixInteger() { return prefixInteger; } - public void setPrefixInteger(Integer prefixInteger) { this.prefixInteger = prefixInteger; } public XmlItem prefixBoolean(Boolean prefixBoolean) { - this.prefixBoolean = prefixBoolean; return this; } @@ -508,14 +479,12 @@ public Boolean getPrefixBoolean() { return prefixBoolean; } - public void setPrefixBoolean(Boolean prefixBoolean) { this.prefixBoolean = prefixBoolean; } public XmlItem prefixArray(List prefixArray) { - this.prefixArray = prefixArray; return this; } @@ -537,14 +506,12 @@ public List getPrefixArray() { return prefixArray; } - public void setPrefixArray(List prefixArray) { this.prefixArray = prefixArray; } public XmlItem prefixWrappedArray(List prefixWrappedArray) { - this.prefixWrappedArray = prefixWrappedArray; return this; } @@ -566,14 +533,12 @@ public List getPrefixWrappedArray() { return prefixWrappedArray; } - public void setPrefixWrappedArray(List prefixWrappedArray) { this.prefixWrappedArray = prefixWrappedArray; } public XmlItem namespaceString(String namespaceString) { - this.namespaceString = namespaceString; return this; } @@ -587,14 +552,12 @@ public String getNamespaceString() { return namespaceString; } - public void setNamespaceString(String namespaceString) { this.namespaceString = namespaceString; } public XmlItem namespaceNumber(BigDecimal namespaceNumber) { - this.namespaceNumber = namespaceNumber; return this; } @@ -608,14 +571,12 @@ public BigDecimal getNamespaceNumber() { return namespaceNumber; } - public void setNamespaceNumber(BigDecimal namespaceNumber) { this.namespaceNumber = namespaceNumber; } public XmlItem namespaceInteger(Integer namespaceInteger) { - this.namespaceInteger = namespaceInteger; return this; } @@ -629,14 +590,12 @@ public Integer getNamespaceInteger() { return namespaceInteger; } - public void setNamespaceInteger(Integer namespaceInteger) { this.namespaceInteger = namespaceInteger; } public XmlItem namespaceBoolean(Boolean namespaceBoolean) { - this.namespaceBoolean = namespaceBoolean; return this; } @@ -650,14 +609,12 @@ public Boolean getNamespaceBoolean() { return namespaceBoolean; } - public void setNamespaceBoolean(Boolean namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; } public XmlItem namespaceArray(List namespaceArray) { - this.namespaceArray = namespaceArray; return this; } @@ -679,14 +636,12 @@ public List getNamespaceArray() { return namespaceArray; } - public void setNamespaceArray(List namespaceArray) { this.namespaceArray = namespaceArray; } public XmlItem namespaceWrappedArray(List namespaceWrappedArray) { - this.namespaceWrappedArray = namespaceWrappedArray; return this; } @@ -708,14 +663,12 @@ public List getNamespaceWrappedArray() { return namespaceWrappedArray; } - public void setNamespaceWrappedArray(List namespaceWrappedArray) { this.namespaceWrappedArray = namespaceWrappedArray; } public XmlItem prefixNsString(String prefixNsString) { - this.prefixNsString = prefixNsString; return this; } @@ -729,14 +682,12 @@ public String getPrefixNsString() { return prefixNsString; } - public void setPrefixNsString(String prefixNsString) { this.prefixNsString = prefixNsString; } public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { - this.prefixNsNumber = prefixNsNumber; return this; } @@ -750,14 +701,12 @@ public BigDecimal getPrefixNsNumber() { return prefixNsNumber; } - public void setPrefixNsNumber(BigDecimal prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; } public XmlItem prefixNsInteger(Integer prefixNsInteger) { - this.prefixNsInteger = prefixNsInteger; return this; } @@ -771,14 +720,12 @@ public Integer getPrefixNsInteger() { return prefixNsInteger; } - public void setPrefixNsInteger(Integer prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; } public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { - this.prefixNsBoolean = prefixNsBoolean; return this; } @@ -792,14 +739,12 @@ public Boolean getPrefixNsBoolean() { return prefixNsBoolean; } - public void setPrefixNsBoolean(Boolean prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; } public XmlItem prefixNsArray(List prefixNsArray) { - this.prefixNsArray = prefixNsArray; return this; } @@ -821,14 +766,12 @@ public List getPrefixNsArray() { return prefixNsArray; } - public void setPrefixNsArray(List prefixNsArray) { this.prefixNsArray = prefixNsArray; } public XmlItem prefixNsWrappedArray(List prefixNsWrappedArray) { - this.prefixNsWrappedArray = prefixNsWrappedArray; return this; } @@ -850,7 +793,6 @@ public List getPrefixNsWrappedArray() { return prefixNsWrappedArray; } - public void setPrefixNsWrappedArray(List prefixNsWrappedArray) { this.prefixNsWrappedArray = prefixNsWrappedArray; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-swagger1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-swagger1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/build.gradle b/samples/client/petstore/java/okhttp-gson-swagger1/build.gradle index 00e6e91c613d..c48a850d1974 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-swagger1/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/build.sbt b/samples/client/petstore/java/okhttp-gson-swagger1/build.sbt index e5dccb22db3d..66c0359a4533 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-swagger1/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/pom.xml b/samples/client/petstore/java/okhttp-gson-swagger1/pom.xml index 91cd2a1bc629..ae3a2764f51d 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-swagger1/pom.xml @@ -338,7 +338,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 1.6.6 4.11.0 2.10.1 diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/ApiClient.java index 6d1cc62db7e7..08a6cfe9ddd5 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Category.java index 1226e87fd79c..94ef2380da2f 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Category.java @@ -66,7 +66,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -81,14 +80,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -103,7 +100,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/ModelApiResponse.java index e4545a10b0b2..5e45e9cbb5c6 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -70,7 +70,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -85,14 +84,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -107,14 +104,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -129,7 +124,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Order.java index b5181f246c51..2f5c92ea24f0 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Order.java @@ -118,6 +118,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -132,7 +137,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -147,14 +151,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -169,14 +171,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -191,14 +191,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -213,14 +211,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -235,14 +231,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -257,7 +251,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -391,6 +384,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Pet.java index 19a7873eabe2..4de57ffcf427 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Pet.java @@ -125,6 +125,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -136,7 +141,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -151,14 +155,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -173,14 +175,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -195,14 +195,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -225,14 +223,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -255,7 +251,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -263,7 +258,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -280,7 +274,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -451,6 +444,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Tag.java index 2d4c0bd37409..6344b83163f1 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/Tag.java @@ -66,7 +66,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -81,14 +80,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -103,7 +100,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/User.java index dc91068c424b..b90cf6a61167 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-swagger1/src/main/java/org/openapitools/client/model/User.java @@ -90,7 +90,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -105,14 +104,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -127,14 +124,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -149,14 +144,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -171,14 +164,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -193,14 +184,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -215,14 +204,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -237,14 +224,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -259,7 +244,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson-swagger2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson-swagger2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/build.gradle b/samples/client/petstore/java/okhttp-gson-swagger2/build.gradle index 00e6e91c613d..c48a850d1974 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/build.gradle +++ b/samples/client/petstore/java/okhttp-gson-swagger2/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/build.sbt b/samples/client/petstore/java/okhttp-gson-swagger2/build.sbt index e5dccb22db3d..66c0359a4533 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/build.sbt +++ b/samples/client/petstore/java/okhttp-gson-swagger2/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/pom.xml b/samples/client/petstore/java/okhttp-gson-swagger2/pom.xml index 3ada667e9d75..26cdcb0b14f8 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/pom.xml +++ b/samples/client/petstore/java/okhttp-gson-swagger2/pom.xml @@ -338,7 +338,7 @@ 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 2.2.15 4.11.0 2.10.1 diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/ApiClient.java index 6d1cc62db7e7..08a6cfe9ddd5 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index b282a35e1a1f..627c09689cf5 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index b11d62b0718a..d25e81a52783 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Category.java index 30f74d21b8ce..f9db9aa2d845 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Category.java @@ -65,7 +65,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -80,14 +79,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -102,7 +99,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 87f5cb13f42d..2303dd860515 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -69,7 +69,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -84,14 +83,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -106,14 +103,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -128,7 +123,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Order.java index 267f7d1326e0..3ae19717874d 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Order.java @@ -117,6 +117,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -131,7 +136,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -146,14 +150,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -168,14 +170,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -190,14 +190,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -212,14 +210,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -234,14 +230,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -256,7 +250,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -390,6 +383,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Pet.java index ddc50c761778..9ce45418da62 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Pet.java @@ -124,6 +124,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -135,7 +140,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -150,14 +154,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -172,14 +174,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -194,14 +194,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -224,14 +222,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -254,7 +250,6 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } @@ -262,7 +257,6 @@ public void setTags(List tags) { @Deprecated public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -279,7 +273,6 @@ public StatusEnum getStatus() { return status; } - @Deprecated public void setStatus(StatusEnum status) { this.status = status; @@ -450,6 +443,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Tag.java index efe5fff33af0..1b9168c583aa 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/Tag.java @@ -65,7 +65,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -80,14 +79,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -102,7 +99,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/User.java index 8f9cf858edda..e191ba04322d 100644 --- a/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson-swagger2/src/main/java/org/openapitools/client/model/User.java @@ -89,7 +89,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -104,14 +103,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -126,14 +123,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -148,14 +143,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -170,14 +163,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -192,14 +183,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -214,14 +203,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -236,14 +223,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -258,7 +243,6 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator-ignore b/samples/client/petstore/java/okhttp-gson/.openapi-generator-ignore index 6ba435b5655f..fcc3c36a6e5e 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator-ignore +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator-ignore @@ -11,4 +11,4 @@ src/test/java/org/openapitools/client/model/PetTest.java src/test/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnlyTest.java src/test/java/org/openapitools/client/JSONTest.java src/test/java/org/openapitools/client/api/PetApiTest.java - +pom.xml diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES index c164cd913e32..281e17b9052f 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/FILES @@ -6,6 +6,11 @@ api/openapi.yaml build.gradle build.sbt docs/AdditionalPropertiesClass.md +docs/AllOfModelArrayAnyOf.md +docs/AllOfModelArrayAnyOfAllOfAttributes.md +docs/AllOfModelArrayAnyOfAllOfAttributesC.md +docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md +docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md docs/Animal.md docs/AnotherFakeApi.md docs/Apple.md @@ -105,7 +110,6 @@ gradle/wrapper/gradle-wrapper.jar gradle/wrapper/gradle-wrapper.properties gradlew gradlew.bat -pom.xml settings.gradle src/main/AndroidManifest.xml src/main/java/org/openapitools/client/ApiCallback.java @@ -139,6 +143,11 @@ src/main/java/org/openapitools/client/auth/OAuthOkHttpClient.java src/main/java/org/openapitools/client/auth/RetryingOAuth.java src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java +src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java src/main/java/org/openapitools/client/model/Animal.java src/main/java/org/openapitools/client/model/Apple.java src/main/java/org/openapitools/client/model/AppleReq.java diff --git a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/okhttp-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/okhttp-gson/README.md b/samples/client/petstore/java/okhttp-gson/README.md index 4b2ed954eaf0..999fe54e5946 100644 --- a/samples/client/petstore/java/okhttp-gson/README.md +++ b/samples/client/petstore/java/okhttp-gson/README.md @@ -116,6 +116,7 @@ Class | Method | HTTP request | Description *AnotherFakeApi* | [**call123testSpecialTags**](docs/AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags *AnotherFakeApi* | [**getParameterArrayNumber**](docs/AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value *AnotherFakeApi* | [**getParameterStringNumber**](docs/AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number +*AnotherFakeApi* | [**nullRequestBody**](docs/AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body *DefaultApi* | [**fooGet**](docs/DefaultApi.md#fooGet) | **GET** /foo | *FakeApi* | [**fakeHealthGet**](docs/FakeApi.md#fakeHealthGet) | **GET** /fake/health | Health check endpoint *FakeApi* | [**fakeOuterBooleanSerialize**](docs/FakeApi.md#fakeOuterBooleanSerialize) | **POST** /fake/outer/boolean | @@ -124,6 +125,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums *FakeApi* | [**getParameterNameMapping**](docs/FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model @@ -162,6 +164,11 @@ Class | Method | HTTP request | Description ## Documentation for Models - [AdditionalPropertiesClass](docs/AdditionalPropertiesClass.md) + - [AllOfModelArrayAnyOf](docs/AllOfModelArrayAnyOf.md) + - [AllOfModelArrayAnyOfAllOfAttributes](docs/AllOfModelArrayAnyOfAllOfAttributes.md) + - [AllOfModelArrayAnyOfAllOfAttributesC](docs/AllOfModelArrayAnyOfAllOfAttributesC.md) + - [AllOfModelArrayAnyOfAllOfLinkListColumn1](docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md) + - [AllOfModelArrayAnyOfAllOfLinkListColumn1Value](docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md) - [Animal](docs/Animal.md) - [Apple](docs/Apple.md) - [AppleReq](docs/AppleReq.md) diff --git a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml index 75e2a80fee94..f6a9c90eaaf4 100644 --- a/samples/client/petstore/java/okhttp-gson/api/openapi.yaml +++ b/samples/client/petstore/java/okhttp-gson/api/openapi.yaml @@ -933,6 +933,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1230,6 +1249,56 @@ paths: tags: - another_fake x-accepts: application/json + /fake/null-request-body: + get: + operationId: null-request-body + parameters: + - explode: false + in: header + name: Accept-Language + required: false + schema: + example: application/json + type: string + style: simple + requestBody: + content: + text/plain: + examples: + Generar Orden por External ID: + value: |- + { + "external_reference": "{{external_order_ref}}", + "notification_url": "www.yourserver.com/yourendpoint", + "sponsor_id": 446566691, + "items": [ + { + "title": "Papas frita", + "currency_id": "{{currency_id}}", + "unit_price": 6000, + "quantity": 1 + }, + { + "title": "Gaseosa", + "currency_id": "{{currency_id}}", + "unit_price": 3000, + "quantity": 1 + } + ]/*, + "taxes": [ + { + "value": 0, + "type": "IVA" + } + ]*/ + } + responses: + "200": + description: "" + summary: null request body + tags: + - another_fake + x-accepts: application/json /values: get: description: "" @@ -1856,11 +1925,17 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed - approved - delivered + - s + - S nullable: true type: string OuterEnumInteger: @@ -2336,7 +2411,7 @@ components: description: Value object example: name: variable_1 - value: null + value: Scalar properties: name: example: variable_1 @@ -2419,6 +2494,15 @@ components: type_: type: string type: object + AllOfModelArrayAnyOf: + allOf: + - $ref: '#/components/schemas/Category' + - properties: + linkListColumn1: + $ref: '#/components/schemas/AllOfModelArrayAnyOf_allOf_linkListColumn1' + attributes: + $ref: '#/components/schemas/AllOfModelArrayAnyOf_allOf_attributes' + type: object _foo_get_default_response: example: string: @@ -2602,6 +2686,28 @@ components: required: - name type: object + AllOfModelArrayAnyOf_allOf_linkListColumn1_value: + anyOf: + - $ref: '#/components/schemas/User' + - $ref: '#/components/schemas/Tag' + AllOfModelArrayAnyOf_allOf_linkListColumn1: + properties: + value: + items: + $ref: '#/components/schemas/AllOfModelArrayAnyOf_allOf_linkListColumn1_value' + type: array + required: + - value + type: object + AllOfModelArrayAnyOf_allOf_attributes_C: + oneOf: + - $ref: '#/components/schemas/Pet' + - $ref: '#/components/schemas/Order' + AllOfModelArrayAnyOf_allOf_attributes: + properties: + C: + $ref: '#/components/schemas/AllOfModelArrayAnyOf_allOf_attributes_C' + type: object securitySchemes: petstore_auth: flows: diff --git a/samples/client/petstore/java/okhttp-gson/build.gradle b/samples/client/petstore/java/okhttp-gson/build.gradle index 00e6e91c613d..c48a850d1974 100644 --- a/samples/client/petstore/java/okhttp-gson/build.gradle +++ b/samples/client/petstore/java/okhttp-gson/build.gradle @@ -111,7 +111,7 @@ dependencies { implementation 'com.squareup.okhttp3:okhttp:4.10.0' implementation 'com.squareup.okhttp3:logging-interceptor:4.10.0' implementation 'com.google.code.gson:gson:2.9.1' - implementation 'io.gsonfire:gson-fire:1.8.5' + implementation 'io.gsonfire:gson-fire:1.9.0' implementation 'javax.ws.rs:jsr311-api:1.1.1' implementation 'javax.ws.rs:javax.ws.rs-api:2.1.1' implementation 'org.openapitools:jackson-databind-nullable:0.2.6' diff --git a/samples/client/petstore/java/okhttp-gson/build.sbt b/samples/client/petstore/java/okhttp-gson/build.sbt index e5dccb22db3d..66c0359a4533 100644 --- a/samples/client/petstore/java/okhttp-gson/build.sbt +++ b/samples/client/petstore/java/okhttp-gson/build.sbt @@ -18,7 +18,7 @@ lazy val root = (project in file(".")). "javax.ws.rs" % "javax.ws.rs-api" % "2.1.1", "org.openapitools" % "jackson-databind-nullable" % "0.2.6", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.2", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "com.google.code.findbugs" % "jsr305" % "3.0.2" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", diff --git a/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOf.md b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOf.md new file mode 100644 index 000000000000..96dc5a34d089 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOf.md @@ -0,0 +1,16 @@ + + +# AllOfModelArrayAnyOf + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**name** | **String** | | | +|**linkListColumn1** | [**AllOfModelArrayAnyOfAllOfLinkListColumn1**](AllOfModelArrayAnyOfAllOfLinkListColumn1.md) | | [optional] | +|**attributes** | [**AllOfModelArrayAnyOfAllOfAttributes**](AllOfModelArrayAnyOfAllOfAttributes.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributes.md b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributes.md new file mode 100644 index 000000000000..c9096e515367 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributes.md @@ -0,0 +1,13 @@ + + +# AllOfModelArrayAnyOfAllOfAttributes + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**C** | [**AllOfModelArrayAnyOfAllOfAttributesC**](AllOfModelArrayAnyOfAllOfAttributesC.md) | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributesC.md b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributesC.md new file mode 100644 index 000000000000..5229de89b299 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfAttributesC.md @@ -0,0 +1,32 @@ + + +# AllOfModelArrayAnyOfAllOfAttributesC + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**category** | [**Category**](Category.md) | | [optional] | +|**name** | **String** | | | +|**photoUrls** | **List<String>** | | | +|**tags** | [**List<Tag>**](Tag.md) | | [optional] | +|**status** | [**StatusEnum**](#StatusEnum) | Order Status | [optional] | +|**petId** | **Long** | | [optional] | +|**quantity** | **Integer** | | [optional] | +|**shipDate** | **OffsetDateTime** | | [optional] | +|**complete** | **Boolean** | | [optional] | + + + +## Enum: StatusEnum + +| Name | Value | +|---- | -----| +| PLACED | "placed" | +| APPROVED | "approved" | +| DELIVERED | "delivered" | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md new file mode 100644 index 000000000000..43fa9b696377 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1.md @@ -0,0 +1,13 @@ + + +# AllOfModelArrayAnyOfAllOfLinkListColumn1 + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**value** | [**List<AllOfModelArrayAnyOfAllOfLinkListColumn1Value>**](AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md) | | | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md new file mode 100644 index 000000000000..6379cac28b02 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/docs/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.md @@ -0,0 +1,25 @@ + + +# AllOfModelArrayAnyOfAllOfLinkListColumn1Value + + +## Properties + +| Name | Type | Description | Notes | +|------------ | ------------- | ------------- | -------------| +|**id** | **Long** | | [optional] | +|**username** | **String** | | [optional] | +|**firstName** | **String** | | [optional] | +|**lastName** | **String** | | [optional] | +|**email** | **String** | | [optional] | +|**password** | **String** | | [optional] | +|**phone** | **String** | | [optional] | +|**userStatus** | **Integer** | User Status | [optional] | +|**objectWithNoDeclaredProps** | **Object** | test code generation for objects Value must be a map of strings to values. It cannot be the 'null' value. | [optional] | +|**objectWithNoDeclaredPropsNullable** | **Object** | test code generation for nullable objects. Value must be a map of strings to values or the 'null' value. | [optional] | +|**anyTypeProp** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. See https://github.com/OAI/OpenAPI-Specification/issues/1389 | [optional] | +|**anyTypePropNullable** | **Object** | test code generation for any type Here the 'type' attribute is not specified, which means the value can be anything, including the null value, string, number, boolean, array or object. The 'nullable' attribute does not change the allowed values. | [optional] | +|**name** | **String** | | [optional] | + + + diff --git a/samples/client/petstore/java/okhttp-gson/docs/AnotherFakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/AnotherFakeApi.md index 6cca209c72b1..d21e29ab0926 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/AnotherFakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/AnotherFakeApi.md @@ -7,6 +7,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**call123testSpecialTags**](AnotherFakeApi.md#call123testSpecialTags) | **PATCH** /another-fake/dummy | To test special tags | | [**getParameterArrayNumber**](AnotherFakeApi.md#getParameterArrayNumber) | **GET** /fake/parameter-array-number | parameter array number default value | | [**getParameterStringNumber**](AnotherFakeApi.md#getParameterStringNumber) | **GET** /fake/parameter-string-number | parameter string number | +| [**nullRequestBody**](AnotherFakeApi.md#nullRequestBody) | **GET** /fake/null-request-body | null request body | @@ -189,3 +190,62 @@ No authorization required |-------------|-------------|------------------| | **200** | OK | - | + +# **nullRequestBody** +> nullRequestBody(acceptLanguage) + +null request body + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.AnotherFakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + AnotherFakeApi apiInstance = new AnotherFakeApi(defaultClient); + String acceptLanguage = "application/json"; // String | + try { + apiInstance.nullRequestBody(acceptLanguage); + } catch (ApiException e) { + System.err.println("Exception when calling AnotherFakeApi#nullRequestBody"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **acceptLanguage** | **String**| | [optional] | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: text/plain + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | | - | + diff --git a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md index bbfe7c1b97e9..6af91003380e 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md +++ b/samples/client/petstore/java/okhttp-gson/docs/FakeApi.md @@ -11,6 +11,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | | [**getParameterNameMapping**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | @@ -446,6 +447,67 @@ No authorization required |-------------|-------------|------------------| | **200** | OK | - | + +# **testAdditionalPropertiesReference** +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + # **testBodyWithFileSchema** > testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md b/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md index 1f9b723eb8e7..e9228f060d25 100644 --- a/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md +++ b/samples/client/petstore/java/okhttp-gson/docs/OuterEnum.md @@ -11,5 +11,9 @@ * `DELIVERED` (value: `"delivered"`) +* `LOWER_CASE_S` (value: `"s"`) + +* `UPPER_CASE_S` (value: `"S"`) + diff --git a/samples/client/petstore/java/okhttp-gson/pom.xml b/samples/client/petstore/java/okhttp-gson/pom.xml index 0cadcd6a209a..5bd5c322feee 100644 --- a/samples/client/petstore/java/okhttp-gson/pom.xml +++ b/samples/client/petstore/java/okhttp-gson/pom.xml @@ -328,12 +328,19 @@ ${junit-platform-runner.version} test + + + org.mockito + mockito-core + 5.7.0 + test + 1.8 ${java.version} ${java.version} - 1.8.5 + 1.9.0 4.11.0 2.10.1 3.13.0 diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java index 8593e66829db..b74876964ed0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/ApiClient.java @@ -49,6 +49,7 @@ import java.util.*; import java.util.Map.Entry; import java.util.concurrent.TimeUnit; +import java.util.function.Supplier; import java.util.regex.Matcher; import java.util.regex.Pattern; @@ -510,14 +511,23 @@ public Authentication getAuthentication(String authName) { return authentications.get(authName); } - /** - * Helper method to set access token for the first Bearer authentication. - * @param bearerToken Bearer token - */ + /** + * Helper method to set access token for the first Bearer authentication. + * @param bearerToken Bearer token + */ public void setBearerToken(String bearerToken) { + setBearerToken(() -> bearerToken); + } + + /** + * Helper method to set the supplier of access tokens for Bearer authentication. + * + * @param tokenSupplier The supplier of bearer tokens + */ + public void setBearerToken(Supplier tokenSupplier) { for (Authentication auth : authentications.values()) { if (auth instanceof HttpBearerAuth) { - ((HttpBearerAuth) auth).setBearerToken(bearerToken); + ((HttpBearerAuth) auth).setBearerToken(tokenSupplier); return; } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java index dc729b10c5eb..bcad4347e627 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/JSON.java @@ -230,6 +230,11 @@ private static Class getClassByDiscriminator(Map classByDiscriminatorValue, Stri gsonBuilder.registerTypeAdapter(LocalDate.class, localDateTypeAdapter); gsonBuilder.registerTypeAdapter(byte[].class, byteArrayAdapter); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AdditionalPropertiesClass.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOf.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributes.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributesC.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1.CustomTypeAdapterFactory()); + gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1Value.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.Apple.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.AppleReq.CustomTypeAdapterFactory()); gsonBuilder.registerTypeAdapterFactory(new org.openapitools.client.model.ArrayDefault.CustomTypeAdapterFactory()); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index f7529bc74764..a58d4bf127b5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -438,4 +438,121 @@ public okhttp3.Call getParameterStringNumberAsync(BigDecimal stringNumber, final localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } + /** + * Build call for nullRequestBody + * @param acceptLanguage (optional) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call nullRequestBodyCall(String acceptLanguage, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = null; + + // create path and map variables + String localVarPath = "/fake/null-request-body"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + if (acceptLanguage != null) { + localVarHeaderParams.put("Accept-Language", localVarApiClient.parameterToString(acceptLanguage)); + } + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "text/plain" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "GET", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call nullRequestBodyValidateBeforeCall(String acceptLanguage, final ApiCallback _callback) throws ApiException { + return nullRequestBodyCall(acceptLanguage, _callback); + + } + + /** + * null request body + * + * @param acceptLanguage (optional) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public void nullRequestBody(String acceptLanguage) throws ApiException { + nullRequestBodyWithHttpInfo(acceptLanguage); + } + + /** + * null request body + * + * @param acceptLanguage (optional) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public ApiResponse nullRequestBodyWithHttpInfo(String acceptLanguage) throws ApiException { + okhttp3.Call localVarCall = nullRequestBodyValidateBeforeCall(acceptLanguage, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * null request body (asynchronously) + * + * @param acceptLanguage (optional) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 -
              + */ + public okhttp3.Call nullRequestBodyAsync(String acceptLanguage, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = nullRequestBodyValidateBeforeCall(acceptLanguage, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java index 3f048ddf6a25..35608948029c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -927,6 +927,124 @@ public okhttp3.Call getParameterNameMappingAsync(Long underscoreType, String typ localVarApiClient.executeAsync(localVarCall, _callback); return localVarCall; } + /** + * Build call for testAdditionalPropertiesReference + * @param requestBody request body (required) + * @param _callback Callback for upload/download progress + * @return Call to execute + * @throws ApiException If fail to serialize the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public okhttp3.Call testAdditionalPropertiesReferenceCall(Map requestBody, final ApiCallback _callback) throws ApiException { + String basePath = null; + // Operation Servers + String[] localBasePaths = new String[] { }; + + // Determine Base Path to Use + if (localCustomBaseUrl != null){ + basePath = localCustomBaseUrl; + } else if ( localBasePaths.length > 0 ) { + basePath = localBasePaths[localHostIndex]; + } else { + basePath = null; + } + + Object localVarPostBody = requestBody; + + // create path and map variables + String localVarPath = "/fake/additionalProperties-reference"; + + List localVarQueryParams = new ArrayList(); + List localVarCollectionQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + final String[] localVarAccepts = { + }; + final String localVarAccept = localVarApiClient.selectHeaderAccept(localVarAccepts); + if (localVarAccept != null) { + localVarHeaderParams.put("Accept", localVarAccept); + } + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = localVarApiClient.selectHeaderContentType(localVarContentTypes); + if (localVarContentType != null) { + localVarHeaderParams.put("Content-Type", localVarContentType); + } + + String[] localVarAuthNames = new String[] { }; + return localVarApiClient.buildCall(basePath, localVarPath, "POST", localVarQueryParams, localVarCollectionQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAuthNames, _callback); + } + + @SuppressWarnings("rawtypes") + private okhttp3.Call testAdditionalPropertiesReferenceValidateBeforeCall(Map requestBody, final ApiCallback _callback) throws ApiException { + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference(Async)"); + } + + return testAdditionalPropertiesReferenceCall(requestBody, _callback); + + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @throws ApiException If fail to call the API, e.g. server error or cannot deserialize the response body + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws ApiException { + okhttp3.Call localVarCall = testAdditionalPropertiesReferenceValidateBeforeCall(requestBody, null); + return localVarApiClient.execute(localVarCall); + } + + /** + * test referenced additionalProperties (asynchronously) + * + * @param requestBody request body (required) + * @param _callback The callback to be executed when the API call finishes + * @return The request call + * @throws ApiException If fail to process the API call, e.g. serializing the request body object + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public okhttp3.Call testAdditionalPropertiesReferenceAsync(Map requestBody, final ApiCallback _callback) throws ApiException { + + okhttp3.Call localVarCall = testAdditionalPropertiesReferenceValidateBeforeCall(requestBody, _callback); + localVarApiClient.executeAsync(localVarCall, _callback); + return localVarCall; + } /** * Build call for testBodyWithFileSchema * @param fileSchemaTestClass (required) diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 460ad224963c..e6ae1d454c79 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -17,13 +17,15 @@ import org.openapitools.client.Pair; import java.net.URI; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -35,7 +37,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -44,12 +46,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams, String payload, String method, URI uri) throws ApiException { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java index fbe51042e1a9..f50f7a96cc56 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AbstractOpenApiSchema.java @@ -18,8 +18,6 @@ import java.lang.reflect.Type; import java.util.Map; -//import com.fasterxml.jackson.annotation.JsonValue; - /** * Abstract class for oneOf,anyOf schemas defined in OpenAPI spec */ diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java index 18d619235d26..6678d9c6e18b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AdditionalPropertiesClass.java @@ -90,7 +90,6 @@ public AdditionalPropertiesClass() { } public AdditionalPropertiesClass mapProperty(Map mapProperty) { - this.mapProperty = mapProperty; return this; } @@ -112,14 +111,12 @@ public Map getMapProperty() { return mapProperty; } - public void setMapProperty(Map mapProperty) { this.mapProperty = mapProperty; } public AdditionalPropertiesClass mapOfMapProperty(Map> mapOfMapProperty) { - this.mapOfMapProperty = mapOfMapProperty; return this; } @@ -141,14 +138,12 @@ public Map> getMapOfMapProperty() { return mapOfMapProperty; } - public void setMapOfMapProperty(Map> mapOfMapProperty) { this.mapOfMapProperty = mapOfMapProperty; } public AdditionalPropertiesClass anytype1(Object anytype1) { - this.anytype1 = anytype1; return this; } @@ -162,14 +157,12 @@ public Object getAnytype1() { return anytype1; } - public void setAnytype1(Object anytype1) { this.anytype1 = anytype1; } public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { - this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; return this; } @@ -183,14 +176,12 @@ public Object getMapWithUndeclaredPropertiesAnytype1() { return mapWithUndeclaredPropertiesAnytype1; } - public void setMapWithUndeclaredPropertiesAnytype1(Object mapWithUndeclaredPropertiesAnytype1) { this.mapWithUndeclaredPropertiesAnytype1 = mapWithUndeclaredPropertiesAnytype1; } public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { - this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; return this; } @@ -204,14 +195,12 @@ public Object getMapWithUndeclaredPropertiesAnytype2() { return mapWithUndeclaredPropertiesAnytype2; } - public void setMapWithUndeclaredPropertiesAnytype2(Object mapWithUndeclaredPropertiesAnytype2) { this.mapWithUndeclaredPropertiesAnytype2 = mapWithUndeclaredPropertiesAnytype2; } public AdditionalPropertiesClass mapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { - this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; return this; } @@ -233,14 +222,12 @@ public Map getMapWithUndeclaredPropertiesAnytype3() { return mapWithUndeclaredPropertiesAnytype3; } - public void setMapWithUndeclaredPropertiesAnytype3(Map mapWithUndeclaredPropertiesAnytype3) { this.mapWithUndeclaredPropertiesAnytype3 = mapWithUndeclaredPropertiesAnytype3; } public AdditionalPropertiesClass emptyMap(Object emptyMap) { - this.emptyMap = emptyMap; return this; } @@ -254,14 +241,12 @@ public Object getEmptyMap() { return emptyMap; } - public void setEmptyMap(Object emptyMap) { this.emptyMap = emptyMap; } public AdditionalPropertiesClass mapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { - this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; return this; } @@ -283,7 +268,6 @@ public Map getMapWithUndeclaredPropertiesString() { return mapWithUndeclaredPropertiesString; } - public void setMapWithUndeclaredPropertiesString(Map mapWithUndeclaredPropertiesString) { this.mapWithUndeclaredPropertiesString = mapWithUndeclaredPropertiesString; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java new file mode 100644 index 000000000000..edf34d1b4752 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOf.java @@ -0,0 +1,378 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributes; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOf + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfModelArrayAnyOf { + public static final String SERIALIZED_NAME_ID = "id"; + @SerializedName(SERIALIZED_NAME_ID) + private Long id; + + public static final String SERIALIZED_NAME_NAME = "name"; + @SerializedName(SERIALIZED_NAME_NAME) + private String name = "default-name"; + + public static final String SERIALIZED_NAME_LINK_LIST_COLUMN1 = "linkListColumn1"; + @SerializedName(SERIALIZED_NAME_LINK_LIST_COLUMN1) + private AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1; + + public static final String SERIALIZED_NAME_ATTRIBUTES = "attributes"; + @SerializedName(SERIALIZED_NAME_ATTRIBUTES) + private AllOfModelArrayAnyOfAllOfAttributes attributes; + + public AllOfModelArrayAnyOf() { + } + + public AllOfModelArrayAnyOf id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + **/ + @javax.annotation.Nullable + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + + public AllOfModelArrayAnyOf name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + **/ + @javax.annotation.Nonnull + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + + public AllOfModelArrayAnyOf linkListColumn1(AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1) { + this.linkListColumn1 = linkListColumn1; + return this; + } + + /** + * Get linkListColumn1 + * @return linkListColumn1 + **/ + @javax.annotation.Nullable + public AllOfModelArrayAnyOfAllOfLinkListColumn1 getLinkListColumn1() { + return linkListColumn1; + } + + public void setLinkListColumn1(AllOfModelArrayAnyOfAllOfLinkListColumn1 linkListColumn1) { + this.linkListColumn1 = linkListColumn1; + } + + + public AllOfModelArrayAnyOf attributes(AllOfModelArrayAnyOfAllOfAttributes attributes) { + this.attributes = attributes; + return this; + } + + /** + * Get attributes + * @return attributes + **/ + @javax.annotation.Nullable + public AllOfModelArrayAnyOfAllOfAttributes getAttributes() { + return attributes; + } + + public void setAttributes(AllOfModelArrayAnyOfAllOfAttributes attributes) { + this.attributes = attributes; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOf instance itself + */ + public AllOfModelArrayAnyOf putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOf allOfModelArrayAnyOf = (AllOfModelArrayAnyOf) o; + return Objects.equals(this.id, allOfModelArrayAnyOf.id) && + Objects.equals(this.name, allOfModelArrayAnyOf.name) && + Objects.equals(this.linkListColumn1, allOfModelArrayAnyOf.linkListColumn1) && + Objects.equals(this.attributes, allOfModelArrayAnyOf.attributes)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOf.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(id, name, linkListColumn1, attributes, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOf {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" linkListColumn1: ").append(toIndentedString(linkListColumn1)).append("\n"); + sb.append(" attributes: ").append(toIndentedString(attributes)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("id"); + openapiFields.add("name"); + openapiFields.add("linkListColumn1"); + openapiFields.add("attributes"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("name"); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AllOfModelArrayAnyOf + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOf.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfModelArrayAnyOf is not found in the empty JSON string", AllOfModelArrayAnyOf.openapiRequiredFields.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfModelArrayAnyOf.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + if (!jsonObj.get("name").isJsonPrimitive()) { + throw new IllegalArgumentException(String.format("Expected the field `name` to be a primitive type in the JSON string but got `%s`", jsonObj.get("name").toString())); + } + // validate the optional field `linkListColumn1` + if (jsonObj.get("linkListColumn1") != null && !jsonObj.get("linkListColumn1").isJsonNull()) { + AllOfModelArrayAnyOfAllOfLinkListColumn1.validateJsonElement(jsonObj.get("linkListColumn1")); + } + // validate the optional field `attributes` + if (jsonObj.get("attributes") != null && !jsonObj.get("attributes").isJsonNull()) { + AllOfModelArrayAnyOfAllOfAttributes.validateJsonElement(jsonObj.get("attributes")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOf.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOf' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOf.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOf value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOf read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOf instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOf given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOf + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOf + */ + public static AllOfModelArrayAnyOf fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOf.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOf to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java new file mode 100644 index 000000000000..6762aa60cfc7 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributes.java @@ -0,0 +1,284 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributesC; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOfAllOfAttributes + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfModelArrayAnyOfAllOfAttributes { + public static final String SERIALIZED_NAME_C = "C"; + @SerializedName(SERIALIZED_NAME_C) + private AllOfModelArrayAnyOfAllOfAttributesC C; + + public AllOfModelArrayAnyOfAllOfAttributes() { + } + + public AllOfModelArrayAnyOfAllOfAttributes C(AllOfModelArrayAnyOfAllOfAttributesC C) { + this.C = C; + return this; + } + + /** + * Get C + * @return C + **/ + @javax.annotation.Nullable + public AllOfModelArrayAnyOfAllOfAttributesC getC() { + return C; + } + + public void setC(AllOfModelArrayAnyOfAllOfAttributesC C) { + this.C = C; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfAttributes instance itself + */ + public AllOfModelArrayAnyOfAllOfAttributes putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOfAllOfAttributes allOfModelArrayAnyOfAllOfAttributes = (AllOfModelArrayAnyOfAllOfAttributes) o; + return Objects.equals(this.C, allOfModelArrayAnyOfAllOfAttributes.C)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOfAllOfAttributes.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(C, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOfAllOfAttributes {\n"); + sb.append(" C: ").append(toIndentedString(C)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("C"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AllOfModelArrayAnyOfAllOfAttributes + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOfAllOfAttributes.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfModelArrayAnyOfAllOfAttributes is not found in the empty JSON string", AllOfModelArrayAnyOfAllOfAttributes.openapiRequiredFields.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // validate the optional field `C` + if (jsonObj.get("C") != null && !jsonObj.get("C").isJsonNull()) { + AllOfModelArrayAnyOfAllOfAttributesC.validateJsonElement(jsonObj.get("C")); + } + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfAttributes.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfAttributes' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOfAllOfAttributes.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfAttributes value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOfAllOfAttributes read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOfAllOfAttributes instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfAttributes given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfAttributes + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfAttributes + */ + public static AllOfModelArrayAnyOfAllOfAttributes fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfAttributes.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfAttributes to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java new file mode 100644 index 000000000000..2669e1493402 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesC.java @@ -0,0 +1,283 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Order; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; + + + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfModelArrayAnyOfAllOfAttributesC extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AllOfModelArrayAnyOfAllOfAttributesC.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfAttributesC.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfAttributesC' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterPet = gson.getDelegateAdapter(this, TypeToken.get(Pet.class)); + final TypeAdapter adapterOrder = gson.getDelegateAdapter(this, TypeToken.get(Order.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfAttributesC value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type `Pet` + if (value.getActualInstance() instanceof Pet) { + JsonElement element = adapterPet.toJsonTree((Pet)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + // check if the actual instance is of the type `Order` + if (value.getActualInstance() instanceof Order) { + JsonElement element = adapterOrder.toJsonTree((Order)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + throw new IOException("Failed to serialize as the type doesn't match oneOf schemas: Order, Pet"); + } + + @Override + public AllOfModelArrayAnyOfAllOfAttributesC read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + int match = 0; + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize Pet + try { + // validate the JSON object to see if any exception is thrown + Pet.validateJsonElement(jsonElement); + actualAdapter = adapterPet; + match++; + log.log(Level.FINER, "Input data matches schema 'Pet'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Pet failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Pet'", e); + } + // deserialize Order + try { + // validate the JSON object to see if any exception is thrown + Order.validateJsonElement(jsonElement); + actualAdapter = adapterOrder; + match++; + log.log(Level.FINER, "Input data matches schema 'Order'"); + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Order failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Order'", e); + } + + if (match == 1) { + AllOfModelArrayAnyOfAllOfAttributesC ret = new AllOfModelArrayAnyOfAllOfAttributesC(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } + + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfAttributesC: %d classes match result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", match, errorMessages, jsonElement.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in oneOf + public static final Map> schemas = new HashMap>(); + + public AllOfModelArrayAnyOfAllOfAttributesC() { + super("oneOf", Boolean.FALSE); + } + + public AllOfModelArrayAnyOfAllOfAttributesC(Order o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + public AllOfModelArrayAnyOfAllOfAttributesC(Pet o) { + super("oneOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("Pet", Pet.class); + schemas.put("Order", Order.class); + } + + @Override + public Map> getSchemas() { + return AllOfModelArrayAnyOfAllOfAttributesC.schemas; + } + + /** + * Set the instance that matches the oneOf child schema, check + * the instance parameter is valid against the oneOf child schemas: + * Order, Pet + * + * It could be an instance of the 'oneOf' schemas. + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof Pet) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Order) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Order, Pet"); + } + + /** + * Get the actual instance, which can be the following: + * Order, Pet + * + * @return The actual instance (Order, Pet) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `Pet`. If the actual instance is not `Pet`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Pet` + * @throws ClassCastException if the instance is not `Pet` + */ + public Pet getPet() throws ClassCastException { + return (Pet)super.getActualInstance(); + } + /** + * Get the actual instance of `Order`. If the actual instance is not `Order`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Order` + * @throws ClassCastException if the instance is not `Order` + */ + public Order getOrder() throws ClassCastException { + return (Order)super.getActualInstance(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AllOfModelArrayAnyOfAllOfAttributesC + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + // validate oneOf schemas one by one + int validCount = 0; + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with Pet + try { + Pet.validateJsonElement(jsonElement); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Pet failed with `%s`.", e.getMessage())); + // continue to the next one + } + // validate the json string with Order + try { + Order.validateJsonElement(jsonElement); + validCount++; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Order failed with `%s`.", e.getMessage())); + // continue to the next one + } + if (validCount != 1) { + throw new IOException(String.format("The JSON string is invalid for AllOfModelArrayAnyOfAllOfAttributesC with oneOf schemas: Order, Pet. %d class(es) match the result, expected 1. Detailed failure message for oneOf schemas: %s. JSON: %s", validCount, errorMessages, jsonElement.toString())); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfAttributesC given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfAttributesC + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfAttributesC + */ + public static AllOfModelArrayAnyOfAllOfAttributesC fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfAttributesC.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfAttributesC to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java new file mode 100644 index 000000000000..76825bcae220 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1.java @@ -0,0 +1,308 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1Value; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonArray; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.TypeAdapter; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; + +import java.lang.reflect.Type; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +import org.openapitools.client.JSON; + +/** + * AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfModelArrayAnyOfAllOfLinkListColumn1 { + public static final String SERIALIZED_NAME_VALUE = "value"; + @SerializedName(SERIALIZED_NAME_VALUE) + private List value = new ArrayList<>(); + + public AllOfModelArrayAnyOfAllOfLinkListColumn1() { + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1 value(List value) { + this.value = value; + return this; + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1 addValueItem(AllOfModelArrayAnyOfAllOfLinkListColumn1Value valueItem) { + if (this.value == null) { + this.value = new ArrayList<>(); + } + this.value.add(valueItem); + return this; + } + + /** + * Get value + * @return value + **/ + @javax.annotation.Nonnull + public List getValue() { + return value; + } + + public void setValue(List value) { + this.value = value; + } + + /** + * A container for additional, undeclared properties. + * This is a holder for any undeclared properties as specified with + * the 'additionalProperties' keyword in the OAS document. + */ + private Map additionalProperties; + + /** + * Set the additional (undeclared) property with the specified name and value. + * If the property does not already exist, create it otherwise replace it. + * + * @param key name of the property + * @param value value of the property + * @return the AllOfModelArrayAnyOfAllOfLinkListColumn1 instance itself + */ + public AllOfModelArrayAnyOfAllOfLinkListColumn1 putAdditionalProperty(String key, Object value) { + if (this.additionalProperties == null) { + this.additionalProperties = new HashMap(); + } + this.additionalProperties.put(key, value); + return this; + } + + /** + * Return the additional (undeclared) property. + * + * @return a map of objects + */ + public Map getAdditionalProperties() { + return additionalProperties; + } + + /** + * Return the additional (undeclared) property with the specified name. + * + * @param key name of the property + * @return an object + */ + public Object getAdditionalProperty(String key) { + if (this.additionalProperties == null) { + return null; + } + return this.additionalProperties.get(key); + } + + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AllOfModelArrayAnyOfAllOfLinkListColumn1 allOfModelArrayAnyOfAllOfLinkListColumn1 = (AllOfModelArrayAnyOfAllOfLinkListColumn1) o; + return Objects.equals(this.value, allOfModelArrayAnyOfAllOfLinkListColumn1.value)&& + Objects.equals(this.additionalProperties, allOfModelArrayAnyOfAllOfLinkListColumn1.additionalProperties); + } + + @Override + public int hashCode() { + return Objects.hash(value, additionalProperties); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class AllOfModelArrayAnyOfAllOfLinkListColumn1 {\n"); + sb.append(" value: ").append(toIndentedString(value)).append("\n"); + sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } + + + public static HashSet openapiFields; + public static HashSet openapiRequiredFields; + + static { + // a set of all properties/fields (JSON key names) + openapiFields = new HashSet(); + openapiFields.add("value"); + + // a set of required properties/fields (JSON key names) + openapiRequiredFields = new HashSet(); + openapiRequiredFields.add("value"); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + if (jsonElement == null) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields.isEmpty()) { // has required fields but JSON element is null + throw new IllegalArgumentException(String.format("The required field(s) %s in AllOfModelArrayAnyOfAllOfLinkListColumn1 is not found in the empty JSON string", AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields.toString())); + } + } + + // check to make sure all required properties/fields are present in the JSON string + for (String requiredField : AllOfModelArrayAnyOfAllOfLinkListColumn1.openapiRequiredFields) { + if (jsonElement.getAsJsonObject().get(requiredField) == null) { + throw new IllegalArgumentException(String.format("The required field `%s` is not found in the JSON string: %s", requiredField, jsonElement.toString())); + } + } + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // ensure the json data is an array + if (!jsonObj.get("value").isJsonArray()) { + throw new IllegalArgumentException(String.format("Expected the field `value` to be an array in the JSON string but got `%s`", jsonObj.get("value").toString())); + } + + JsonArray jsonArrayvalue = jsonObj.getAsJsonArray("value"); + // validate the required field `value` (array) + for (int i = 0; i < jsonArrayvalue.size(); i++) { + AllOfModelArrayAnyOfAllOfLinkListColumn1Value.validateJsonElement(jsonArrayvalue.get(i)); + }; + } + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfLinkListColumn1' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter thisAdapter + = gson.getDelegateAdapter(this, TypeToken.get(AllOfModelArrayAnyOfAllOfLinkListColumn1.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfLinkListColumn1 value) throws IOException { + JsonObject obj = thisAdapter.toJsonTree(value).getAsJsonObject(); + obj.remove("additionalProperties"); + // serialize additional properties + if (value.getAdditionalProperties() != null) { + for (Map.Entry entry : value.getAdditionalProperties().entrySet()) { + if (entry.getValue() instanceof String) + obj.addProperty(entry.getKey(), (String) entry.getValue()); + else if (entry.getValue() instanceof Number) + obj.addProperty(entry.getKey(), (Number) entry.getValue()); + else if (entry.getValue() instanceof Boolean) + obj.addProperty(entry.getKey(), (Boolean) entry.getValue()); + else if (entry.getValue() instanceof Character) + obj.addProperty(entry.getKey(), (Character) entry.getValue()); + else { + obj.add(entry.getKey(), gson.toJsonTree(entry.getValue()).getAsJsonObject()); + } + } + } + elementAdapter.write(out, obj); + } + + @Override + public AllOfModelArrayAnyOfAllOfLinkListColumn1 read(JsonReader in) throws IOException { + JsonElement jsonElement = elementAdapter.read(in); + validateJsonElement(jsonElement); + JsonObject jsonObj = jsonElement.getAsJsonObject(); + // store additional fields in the deserialized instance + AllOfModelArrayAnyOfAllOfLinkListColumn1 instance = thisAdapter.fromJsonTree(jsonObj); + for (Map.Entry entry : jsonObj.entrySet()) { + if (!openapiFields.contains(entry.getKey())) { + if (entry.getValue().isJsonPrimitive()) { // primitive type + if (entry.getValue().getAsJsonPrimitive().isString()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsString()); + else if (entry.getValue().getAsJsonPrimitive().isNumber()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsNumber()); + else if (entry.getValue().getAsJsonPrimitive().isBoolean()) + instance.putAdditionalProperty(entry.getKey(), entry.getValue().getAsBoolean()); + else + throw new IllegalArgumentException(String.format("The field `%s` has unknown primitive type. Value: %s", entry.getKey(), entry.getValue().toString())); + } else if (entry.getValue().isJsonArray()) { + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), List.class)); + } else { // JSON object + instance.putAdditionalProperty(entry.getKey(), gson.fromJson(entry.getValue(), HashMap.class)); + } + } + } + return instance; + } + + }.nullSafe(); + } + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + public static AllOfModelArrayAnyOfAllOfLinkListColumn1 fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfLinkListColumn1.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1 to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java new file mode 100644 index 000000000000..89716f846d36 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Value.java @@ -0,0 +1,272 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import java.util.Objects; +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.Tag; +import org.openapitools.client.model.User; +import org.openapitools.jackson.nullable.JsonNullable; + + + +import java.io.IOException; +import java.lang.reflect.Type; +import java.util.logging.Level; +import java.util.logging.Logger; +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashSet; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonParseException; +import com.google.gson.TypeAdapter; +import com.google.gson.TypeAdapterFactory; +import com.google.gson.reflect.TypeToken; +import com.google.gson.JsonPrimitive; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import com.google.gson.JsonDeserializationContext; +import com.google.gson.JsonDeserializer; +import com.google.gson.JsonSerializationContext; +import com.google.gson.JsonSerializer; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; +import com.google.gson.JsonArray; +import com.google.gson.JsonParseException; + +import org.openapitools.client.JSON; + +@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") +public class AllOfModelArrayAnyOfAllOfLinkListColumn1Value extends AbstractOpenApiSchema { + private static final Logger log = Logger.getLogger(AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class.getName()); + + public static class CustomTypeAdapterFactory implements TypeAdapterFactory { + @SuppressWarnings("unchecked") + @Override + public TypeAdapter create(Gson gson, TypeToken type) { + if (!AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class.isAssignableFrom(type.getRawType())) { + return null; // this class only serializes 'AllOfModelArrayAnyOfAllOfLinkListColumn1Value' and its subtypes + } + final TypeAdapter elementAdapter = gson.getAdapter(JsonElement.class); + final TypeAdapter adapterUser = gson.getDelegateAdapter(this, TypeToken.get(User.class)); + final TypeAdapter adapterTag = gson.getDelegateAdapter(this, TypeToken.get(Tag.class)); + + return (TypeAdapter) new TypeAdapter() { + @Override + public void write(JsonWriter out, AllOfModelArrayAnyOfAllOfLinkListColumn1Value value) throws IOException { + if (value == null || value.getActualInstance() == null) { + elementAdapter.write(out, null); + return; + } + + // check if the actual instance is of the type `User` + if (value.getActualInstance() instanceof User) { + JsonElement element = adapterUser.toJsonTree((User)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + // check if the actual instance is of the type `Tag` + if (value.getActualInstance() instanceof Tag) { + JsonElement element = adapterTag.toJsonTree((Tag)value.getActualInstance()); + elementAdapter.write(out, element); + return; + } + throw new IOException("Failed to serialize as the type doesn't match anyOf schemae: Tag, User"); + } + + @Override + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value read(JsonReader in) throws IOException { + Object deserialized = null; + JsonElement jsonElement = elementAdapter.read(in); + + ArrayList errorMessages = new ArrayList<>(); + TypeAdapter actualAdapter = elementAdapter; + + // deserialize User + try { + // validate the JSON object to see if any exception is thrown + User.validateJsonElement(jsonElement); + actualAdapter = adapterUser; + AllOfModelArrayAnyOfAllOfLinkListColumn1Value ret = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for User failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'User'", e); + } + // deserialize Tag + try { + // validate the JSON object to see if any exception is thrown + Tag.validateJsonElement(jsonElement); + actualAdapter = adapterTag; + AllOfModelArrayAnyOfAllOfLinkListColumn1Value ret = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + ret.setActualInstance(actualAdapter.fromJsonTree(jsonElement)); + return ret; + } catch (Exception e) { + // deserialization failed, continue + errorMessages.add(String.format("Deserialization for Tag failed with `%s`.", e.getMessage())); + log.log(Level.FINER, "Input data does not match schema 'Tag'", e); + } + + throw new IOException(String.format("Failed deserialization for AllOfModelArrayAnyOfAllOfLinkListColumn1Value: no class matches result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); + } + }.nullSafe(); + } + } + + // store a list of schema names defined in anyOf + public static final Map> schemas = new HashMap>(); + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value() { + super("anyOf", Boolean.FALSE); + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value(Tag o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + public AllOfModelArrayAnyOfAllOfLinkListColumn1Value(User o) { + super("anyOf", Boolean.FALSE); + setActualInstance(o); + } + + static { + schemas.put("User", User.class); + schemas.put("Tag", Tag.class); + } + + @Override + public Map> getSchemas() { + return AllOfModelArrayAnyOfAllOfLinkListColumn1Value.schemas; + } + + /** + * Set the instance that matches the anyOf child schema, check + * the instance parameter is valid against the anyOf child schemas: + * Tag, User + * + * It could be an instance of the 'anyOf' schemas. + */ + @Override + public void setActualInstance(Object instance) { + if (instance instanceof User) { + super.setActualInstance(instance); + return; + } + + if (instance instanceof Tag) { + super.setActualInstance(instance); + return; + } + + throw new RuntimeException("Invalid instance type. Must be Tag, User"); + } + + /** + * Get the actual instance, which can be the following: + * Tag, User + * + * @return The actual instance (Tag, User) + */ + @Override + public Object getActualInstance() { + return super.getActualInstance(); + } + + /** + * Get the actual instance of `User`. If the actual instance is not `User`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `User` + * @throws ClassCastException if the instance is not `User` + */ + public User getUser() throws ClassCastException { + return (User)super.getActualInstance(); + } + /** + * Get the actual instance of `Tag`. If the actual instance is not `Tag`, + * the ClassCastException will be thrown. + * + * @return The actual instance of `Tag` + * @throws ClassCastException if the instance is not `Tag` + */ + public Tag getTag() throws ClassCastException { + return (Tag)super.getActualInstance(); + } + + /** + * Validates the JSON Element and throws an exception if issues found + * + * @param jsonElement JSON Element + * @throws IOException if the JSON Element is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + // validate anyOf schemas one by one + ArrayList errorMessages = new ArrayList<>(); + // validate the json string with User + try { + User.validateJsonElement(jsonElement); + return; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for User failed with `%s`.", e.getMessage())); + // continue to the next one + } + // validate the json string with Tag + try { + Tag.validateJsonElement(jsonElement); + return; + } catch (Exception e) { + errorMessages.add(String.format("Deserialization for Tag failed with `%s`.", e.getMessage())); + // continue to the next one + } + throw new IOException(String.format("The JSON string is invalid for AllOfModelArrayAnyOfAllOfLinkListColumn1Value with anyOf schemas: Tag, User. no class match the result, expected at least 1. Detailed failure message for anyOf schemas: %s. JSON: %s", errorMessages, jsonElement.toString())); + + } + + /** + * Create an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value given an JSON string + * + * @param jsonString JSON string + * @return An instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value + * @throws IOException if the JSON string is invalid with respect to AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + public static AllOfModelArrayAnyOfAllOfLinkListColumn1Value fromJson(String jsonString) throws IOException { + return JSON.getGson().fromJson(jsonString, AllOfModelArrayAnyOfAllOfLinkListColumn1Value.class); + } + + /** + * Convert an instance of AllOfModelArrayAnyOfAllOfLinkListColumn1Value to an JSON string + * + * @return JSON string + */ + public String toJson() { + return JSON.getGson().toJson(this); + } +} + diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java index fe146635badd..50a98b04ea4f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Animal.java @@ -64,7 +64,6 @@ public Animal() { } public Animal className(String className) { - this.className = className; return this; } @@ -78,14 +77,12 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } public Animal color(String color) { - this.color = color; return this; } @@ -99,7 +96,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java index f927e212aff7..0432813c2255 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Apple.java @@ -63,7 +63,6 @@ public Apple() { } public Apple cultivar(String cultivar) { - this.cultivar = cultivar; return this; } @@ -77,14 +76,12 @@ public String getCultivar() { return cultivar; } - public void setCultivar(String cultivar) { this.cultivar = cultivar; } public Apple origin(String origin) { - this.origin = origin; return this; } @@ -98,7 +95,6 @@ public String getOrigin() { return origin; } - public void setOrigin(String origin) { this.origin = origin; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java index b4c5a403ee3a..69d000adc280 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/AppleReq.java @@ -63,7 +63,6 @@ public AppleReq() { } public AppleReq cultivar(String cultivar) { - this.cultivar = cultivar; return this; } @@ -77,14 +76,12 @@ public String getCultivar() { return cultivar; } - public void setCultivar(String cultivar) { this.cultivar = cultivar; } public AppleReq mealy(Boolean mealy) { - this.mealy = mealy; return this; } @@ -98,7 +95,6 @@ public Boolean getMealy() { return mealy; } - public void setMealy(Boolean mealy) { this.mealy = mealy; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayDefault.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayDefault.java index c4a841f46e26..44fffcda53da 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayDefault.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayDefault.java @@ -65,7 +65,6 @@ public ArrayDefault() { } public ArrayDefault withDefaultEmptyBracket(List withDefaultEmptyBracket) { - this.withDefaultEmptyBracket = withDefaultEmptyBracket; return this; } @@ -87,14 +86,12 @@ public List getWithDefaultEmptyBracket() { return withDefaultEmptyBracket; } - public void setWithDefaultEmptyBracket(List withDefaultEmptyBracket) { this.withDefaultEmptyBracket = withDefaultEmptyBracket; } public ArrayDefault withoutDefault(List withoutDefault) { - this.withoutDefault = withoutDefault; return this; } @@ -116,7 +113,6 @@ public List getWithoutDefault() { return withoutDefault; } - public void setWithoutDefault(List withoutDefault) { this.withoutDefault = withoutDefault; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java index 05504ec70ef7..6a53ba98352e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfArrayOfNumberOnly.java @@ -62,7 +62,6 @@ public ArrayOfArrayOfNumberOnly() { } public ArrayOfArrayOfNumberOnly arrayArrayNumber(List> arrayArrayNumber) { - this.arrayArrayNumber = arrayArrayNumber; return this; } @@ -84,7 +83,6 @@ public List> getArrayArrayNumber() { return arrayArrayNumber; } - public void setArrayArrayNumber(List> arrayArrayNumber) { this.arrayArrayNumber = arrayArrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java index 5885b0849545..085b1fdcd91f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOf.java @@ -70,7 +70,6 @@ public ArrayOfInlineAllOf() { } public ArrayOfInlineAllOf id(Long id) { - this.id = id; return this; } @@ -84,14 +83,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public ArrayOfInlineAllOf name(String name) { - this.name = name; return this; } @@ -105,14 +102,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public ArrayOfInlineAllOf arrayAllofDogProperty(List arrayAllofDogProperty) { - this.arrayAllofDogProperty = arrayAllofDogProperty; return this; } @@ -134,7 +129,6 @@ public List getArrayAllofDogProper return arrayAllofDogProperty; } - public void setArrayAllofDogProperty(List arrayAllofDogProperty) { this.arrayAllofDogProperty = arrayAllofDogProperty; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java index 5442ca84a4cd..41c5a5b8c13c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInner.java @@ -63,7 +63,6 @@ public ArrayOfInlineAllOfArrayAllofDogPropertyInner() { } public ArrayOfInlineAllOfArrayAllofDogPropertyInner breed(String breed) { - this.breed = breed; return this; } @@ -77,14 +76,12 @@ public String getBreed() { return breed; } - public void setBreed(String breed) { this.breed = breed; } public ArrayOfInlineAllOfArrayAllofDogPropertyInner color(String color) { - this.color = color; return this; } @@ -98,7 +95,6 @@ public String getColor() { return color; } - public void setColor(String color) { this.color = color; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java index 5e08583d21ce..49a39cbdd116 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayOfNumberOnly.java @@ -62,7 +62,6 @@ public ArrayOfNumberOnly() { } public ArrayOfNumberOnly arrayNumber(List arrayNumber) { - this.arrayNumber = arrayNumber; return this; } @@ -84,7 +83,6 @@ public List getArrayNumber() { return arrayNumber; } - public void setArrayNumber(List arrayNumber) { this.arrayNumber = arrayNumber; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java index b5b1bfba4c33..d746708c37c8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -70,7 +70,6 @@ public ArrayTest() { } public ArrayTest arrayOfString(List arrayOfString) { - this.arrayOfString = arrayOfString; return this; } @@ -92,14 +91,12 @@ public List getArrayOfString() { return arrayOfString; } - public void setArrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; } public ArrayTest arrayArrayOfInteger(List> arrayArrayOfInteger) { - this.arrayArrayOfInteger = arrayArrayOfInteger; return this; } @@ -121,14 +118,12 @@ public List> getArrayArrayOfInteger() { return arrayArrayOfInteger; } - public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { - this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -150,7 +145,6 @@ public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java index e90b61781d96..2a0476998e21 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Banana.java @@ -60,7 +60,6 @@ public Banana() { } public Banana lengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; return this; } @@ -74,7 +73,6 @@ public BigDecimal getLengthCm() { return lengthCm; } - public void setLengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java index 79d05b18dfc0..cb83cfd347ce 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BananaReq.java @@ -64,7 +64,6 @@ public BananaReq() { } public BananaReq lengthCm(BigDecimal lengthCm) { - this.lengthCm = lengthCm; return this; } @@ -78,14 +77,12 @@ public BigDecimal getLengthCm() { return lengthCm; } - public void setLengthCm(BigDecimal lengthCm) { this.lengthCm = lengthCm; } public BananaReq sweet(Boolean sweet) { - this.sweet = sweet; return this; } @@ -99,7 +96,6 @@ public Boolean getSweet() { return sweet; } - public void setSweet(Boolean sweet) { this.sweet = sweet; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java index 90b851a6a599..ee1ea4993a85 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/BasquePig.java @@ -59,7 +59,6 @@ public BasquePig() { } public BasquePig className(String className) { - this.className = className; return this; } @@ -73,7 +72,6 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java index aab6db17dfe5..0017449f46e6 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Capitalization.java @@ -79,7 +79,6 @@ public Capitalization() { } public Capitalization smallCamel(String smallCamel) { - this.smallCamel = smallCamel; return this; } @@ -93,14 +92,12 @@ public String getSmallCamel() { return smallCamel; } - public void setSmallCamel(String smallCamel) { this.smallCamel = smallCamel; } public Capitalization capitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; return this; } @@ -114,14 +111,12 @@ public String getCapitalCamel() { return capitalCamel; } - public void setCapitalCamel(String capitalCamel) { this.capitalCamel = capitalCamel; } public Capitalization smallSnake(String smallSnake) { - this.smallSnake = smallSnake; return this; } @@ -135,14 +130,12 @@ public String getSmallSnake() { return smallSnake; } - public void setSmallSnake(String smallSnake) { this.smallSnake = smallSnake; } public Capitalization capitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; return this; } @@ -156,14 +149,12 @@ public String getCapitalSnake() { return capitalSnake; } - public void setCapitalSnake(String capitalSnake) { this.capitalSnake = capitalSnake; } public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; return this; } @@ -177,14 +168,12 @@ public String getScAETHFlowPoints() { return scAETHFlowPoints; } - public void setScAETHFlowPoints(String scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; } public Capitalization ATT_NAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; return this; } @@ -198,7 +187,6 @@ public String getATTNAME() { return ATT_NAME; } - public void setATTNAME(String ATT_NAME) { this.ATT_NAME = ATT_NAME; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java index 24326e6a2747..591a096f5ccb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Cat.java @@ -61,7 +61,6 @@ public Cat() { } public Cat declawed(Boolean declawed) { - this.declawed = declawed; return this; } @@ -75,7 +74,6 @@ public Boolean getDeclawed() { return declawed; } - public void setDeclawed(Boolean declawed) { this.declawed = declawed; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java index 1f80bb7764e3..23059e9bc757 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Category.java @@ -63,7 +63,6 @@ public Category() { } public Category id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Category name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java index bc568aa2a729..0f0b135f6512 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ClassModel.java @@ -59,7 +59,6 @@ public ClassModel() { } public ClassModel propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -73,7 +72,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java index d2c16bb78834..6bdfb17d0a39 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Client.java @@ -59,7 +59,6 @@ public Client() { } public Client client(String client) { - this.client = client; return this; } @@ -73,7 +72,6 @@ public String getClient() { return client; } - public void setClient(String client) { this.client = client; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java index 7167f835a7e7..0fcf924bcd93 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ComplexQuadrilateral.java @@ -63,7 +63,6 @@ public ComplexQuadrilateral() { } public ComplexQuadrilateral shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -77,14 +76,12 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } public ComplexQuadrilateral quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; return this; } @@ -98,7 +95,6 @@ public String getQuadrilateralType() { return quadrilateralType; } - public void setQuadrilateralType(String quadrilateralType) { this.quadrilateralType = quadrilateralType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java index c7d32495f310..4812f05c662d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DanishPig.java @@ -59,7 +59,6 @@ public DanishPig() { } public DanishPig className(String className) { - this.className = className; return this; } @@ -73,7 +72,6 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java index e254d15c350d..680f7492fa6c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/DeprecatedObject.java @@ -61,7 +61,6 @@ public DeprecatedObject() { } public DeprecatedObject name(String name) { - this.name = name; return this; } @@ -75,7 +74,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java index bcc8b6c1a547..841f7995038f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Dog.java @@ -61,7 +61,6 @@ public Dog() { } public Dog breed(String breed) { - this.breed = breed; return this; } @@ -75,7 +74,6 @@ public String getBreed() { return breed; } - public void setBreed(String breed) { this.breed = breed; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java index 5576a241d42c..6e24bac2f69b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Drawing.java @@ -78,7 +78,6 @@ public Drawing() { } public Drawing mainShape(Shape mainShape) { - this.mainShape = mainShape; return this; } @@ -92,14 +91,12 @@ public Shape getMainShape() { return mainShape; } - public void setMainShape(Shape mainShape) { this.mainShape = mainShape; } public Drawing shapeOrNull(ShapeOrNull shapeOrNull) { - this.shapeOrNull = shapeOrNull; return this; } @@ -113,14 +110,12 @@ public ShapeOrNull getShapeOrNull() { return shapeOrNull; } - public void setShapeOrNull(ShapeOrNull shapeOrNull) { this.shapeOrNull = shapeOrNull; } public Drawing nullableShape(NullableShape nullableShape) { - this.nullableShape = nullableShape; return this; } @@ -134,14 +129,12 @@ public NullableShape getNullableShape() { return nullableShape; } - public void setNullableShape(NullableShape nullableShape) { this.nullableShape = nullableShape; } public Drawing shapes(List shapes) { - this.shapes = shapes; return this; } @@ -163,7 +156,6 @@ public List getShapes() { return shapes; } - public void setShapes(List shapes) { this.shapes = shapes; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java index 78f4b0aff16e..9f770ae1df02 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumArrays.java @@ -98,6 +98,11 @@ public JustSymbolEnum read(final JsonReader jsonReader) throws IOException { return JustSymbolEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + JustSymbolEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_JUST_SYMBOL = "just_symbol"; @@ -149,6 +154,11 @@ public ArrayEnumEnum read(final JsonReader jsonReader) throws IOException { return ArrayEnumEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + ArrayEnumEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ARRAY_ENUM = "array_enum"; @@ -159,7 +169,6 @@ public EnumArrays() { } public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; return this; } @@ -173,14 +182,12 @@ public JustSymbolEnum getJustSymbol() { return justSymbol; } - public void setJustSymbol(JustSymbolEnum justSymbol) { this.justSymbol = justSymbol; } public EnumArrays arrayEnum(List arrayEnum) { - this.arrayEnum = arrayEnum; return this; } @@ -202,7 +209,6 @@ public List getArrayEnum() { return arrayEnum; } - public void setArrayEnum(List arrayEnum) { this.arrayEnum = arrayEnum; } @@ -324,6 +330,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) && !jsonObj.get("just_symbol").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `just_symbol` to be a primitive type in the JSON string but got `%s`", jsonObj.get("just_symbol").toString())); } + // validate the optional field `just_symbol` + if (jsonObj.get("just_symbol") != null && !jsonObj.get("just_symbol").isJsonNull()) { + JustSymbolEnum.validateJsonElement(jsonObj.get("just_symbol")); + } // ensure the optional json data is an array if present if (jsonObj.get("array_enum") != null && !jsonObj.get("array_enum").isJsonNull() && !jsonObj.get("array_enum").isJsonArray()) { throw new IllegalArgumentException(String.format("Expected the field `array_enum` to be an array in the JSON string but got `%s`", jsonObj.get("array_enum").toString())); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumClass.java index d3639fe679bb..c2dfd3aecd7c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumClass.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public EnumClass read(final JsonReader jsonReader) throws IOException { return EnumClass.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumClass.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java index 4c1681e8c321..a0b0f90ba7c0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumStringDiscriminator.java @@ -96,6 +96,11 @@ public EnumStrTypeEnum read(final JsonReader jsonReader) throws IOException { return EnumStrTypeEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStrTypeEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STR_TYPE = "enum_str_type"; @@ -106,7 +111,6 @@ public EnumStringDiscriminator() { } public EnumStringDiscriminator enumStrType(EnumStrTypeEnum enumStrType) { - this.enumStrType = enumStrType; return this; } @@ -120,7 +124,6 @@ public EnumStrTypeEnum getEnumStrType() { return enumStrType; } - public void setEnumStrType(EnumStrTypeEnum enumStrType) { this.enumStrType = enumStrType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java index 9e8e63d6fc6b..2a2513d4f872 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EnumTest.java @@ -103,6 +103,11 @@ public EnumStringEnum read(final JsonReader jsonReader) throws IOException { return EnumStringEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING = "enum_string"; @@ -156,6 +161,11 @@ public EnumStringRequiredEnum read(final JsonReader jsonReader) throws IOExcepti return EnumStringRequiredEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + EnumStringRequiredEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_STRING_REQUIRED = "enum_string_required"; @@ -207,6 +217,11 @@ public EnumIntegerEnum read(final JsonReader jsonReader) throws IOException { return EnumIntegerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_INTEGER = "enum_integer"; @@ -258,6 +273,11 @@ public EnumIntegerOnlyEnum read(final JsonReader jsonReader) throws IOException return EnumIntegerOnlyEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + EnumIntegerOnlyEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_INTEGER_ONLY = "enum_integer_only"; @@ -309,6 +329,11 @@ public EnumNumberEnum read(final JsonReader jsonReader) throws IOException { return EnumNumberEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Double value = jsonElement.getAsDouble(); + EnumNumberEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_ENUM_NUMBER = "enum_number"; @@ -335,7 +360,6 @@ public EnumTest() { } public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; return this; } @@ -349,14 +373,12 @@ public EnumStringEnum getEnumString() { return enumString; } - public void setEnumString(EnumStringEnum enumString) { this.enumString = enumString; } public EnumTest enumStringRequired(EnumStringRequiredEnum enumStringRequired) { - this.enumStringRequired = enumStringRequired; return this; } @@ -370,14 +392,12 @@ public EnumStringRequiredEnum getEnumStringRequired() { return enumStringRequired; } - public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { this.enumStringRequired = enumStringRequired; } public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; return this; } @@ -391,14 +411,12 @@ public EnumIntegerEnum getEnumInteger() { return enumInteger; } - public void setEnumInteger(EnumIntegerEnum enumInteger) { this.enumInteger = enumInteger; } public EnumTest enumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { - this.enumIntegerOnly = enumIntegerOnly; return this; } @@ -412,14 +430,12 @@ public EnumIntegerOnlyEnum getEnumIntegerOnly() { return enumIntegerOnly; } - public void setEnumIntegerOnly(EnumIntegerOnlyEnum enumIntegerOnly) { this.enumIntegerOnly = enumIntegerOnly; } public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; return this; } @@ -433,14 +449,12 @@ public EnumNumberEnum getEnumNumber() { return enumNumber; } - public void setEnumNumber(EnumNumberEnum enumNumber) { this.enumNumber = enumNumber; } public EnumTest outerEnum(OuterEnum outerEnum) { - this.outerEnum = outerEnum; return this; } @@ -454,14 +468,12 @@ public OuterEnum getOuterEnum() { return outerEnum; } - public void setOuterEnum(OuterEnum outerEnum) { this.outerEnum = outerEnum; } public EnumTest outerEnumInteger(OuterEnumInteger outerEnumInteger) { - this.outerEnumInteger = outerEnumInteger; return this; } @@ -475,14 +487,12 @@ public OuterEnumInteger getOuterEnumInteger() { return outerEnumInteger; } - public void setOuterEnumInteger(OuterEnumInteger outerEnumInteger) { this.outerEnumInteger = outerEnumInteger; } public EnumTest outerEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { - this.outerEnumDefaultValue = outerEnumDefaultValue; return this; } @@ -496,14 +506,12 @@ public OuterEnumDefaultValue getOuterEnumDefaultValue() { return outerEnumDefaultValue; } - public void setOuterEnumDefaultValue(OuterEnumDefaultValue outerEnumDefaultValue) { this.outerEnumDefaultValue = outerEnumDefaultValue; } public EnumTest outerEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { - this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; return this; } @@ -517,7 +525,6 @@ public OuterEnumIntegerDefaultValue getOuterEnumIntegerDefaultValue() { return outerEnumIntegerDefaultValue; } - public void setOuterEnumIntegerDefaultValue(OuterEnumIntegerDefaultValue outerEnumIntegerDefaultValue) { this.outerEnumIntegerDefaultValue = outerEnumIntegerDefaultValue; } @@ -679,9 +686,43 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) && !jsonObj.get("enum_string").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string").toString())); } + // validate the optional field `enum_string` + if (jsonObj.get("enum_string") != null && !jsonObj.get("enum_string").isJsonNull()) { + EnumStringEnum.validateJsonElement(jsonObj.get("enum_string")); + } if (!jsonObj.get("enum_string_required").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `enum_string_required` to be a primitive type in the JSON string but got `%s`", jsonObj.get("enum_string_required").toString())); } + // validate the required field `enum_string_required` + EnumStringRequiredEnum.validateJsonElement(jsonObj.get("enum_string_required")); + // validate the optional field `enum_integer` + if (jsonObj.get("enum_integer") != null && !jsonObj.get("enum_integer").isJsonNull()) { + EnumIntegerEnum.validateJsonElement(jsonObj.get("enum_integer")); + } + // validate the optional field `enum_integer_only` + if (jsonObj.get("enum_integer_only") != null && !jsonObj.get("enum_integer_only").isJsonNull()) { + EnumIntegerOnlyEnum.validateJsonElement(jsonObj.get("enum_integer_only")); + } + // validate the optional field `enum_number` + if (jsonObj.get("enum_number") != null && !jsonObj.get("enum_number").isJsonNull()) { + EnumNumberEnum.validateJsonElement(jsonObj.get("enum_number")); + } + // validate the optional field `outerEnum` + if (jsonObj.get("outerEnum") != null && !jsonObj.get("outerEnum").isJsonNull()) { + OuterEnum.validateJsonElement(jsonObj.get("outerEnum")); + } + // validate the optional field `outerEnumInteger` + if (jsonObj.get("outerEnumInteger") != null && !jsonObj.get("outerEnumInteger").isJsonNull()) { + OuterEnumInteger.validateJsonElement(jsonObj.get("outerEnumInteger")); + } + // validate the optional field `outerEnumDefaultValue` + if (jsonObj.get("outerEnumDefaultValue") != null && !jsonObj.get("outerEnumDefaultValue").isJsonNull()) { + OuterEnumDefaultValue.validateJsonElement(jsonObj.get("outerEnumDefaultValue")); + } + // validate the optional field `outerEnumIntegerDefaultValue` + if (jsonObj.get("outerEnumIntegerDefaultValue") != null && !jsonObj.get("outerEnumIntegerDefaultValue").isJsonNull()) { + OuterEnumIntegerDefaultValue.validateJsonElement(jsonObj.get("outerEnumIntegerDefaultValue")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java index 4cdc86a22521..e08e3b59bba1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/EquilateralTriangle.java @@ -63,7 +63,6 @@ public EquilateralTriangle() { } public EquilateralTriangle shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -77,14 +76,12 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } public EquilateralTriangle triangleType(String triangleType) { - this.triangleType = triangleType; return this; } @@ -98,7 +95,6 @@ public String getTriangleType() { return triangleType; } - public void setTriangleType(String triangleType) { this.triangleType = triangleType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index dba7bf93f77a..20d67d3dea3b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -66,7 +66,6 @@ public FileSchemaTestClass() { } public FileSchemaTestClass _file(ModelFile _file) { - this._file = _file; return this; } @@ -80,14 +79,12 @@ public ModelFile getFile() { return _file; } - public void setFile(ModelFile _file) { this._file = _file; } public FileSchemaTestClass files(List files) { - this.files = files; return this; } @@ -109,7 +106,6 @@ public List getFiles() { return files; } - public void setFiles(List files) { this.files = files; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java index a44b4b64332f..c4a791e06251 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Foo.java @@ -59,7 +59,6 @@ public Foo() { } public Foo bar(String bar) { - this.bar = bar; return this; } @@ -73,7 +72,6 @@ public String getBar() { return bar; } - public void setBar(String bar) { this.bar = bar; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java index 3184c14874df..60491b9857dc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FooGetDefaultResponse.java @@ -60,7 +60,6 @@ public FooGetDefaultResponse() { } public FooGetDefaultResponse string(Foo string) { - this.string = string; return this; } @@ -74,7 +73,6 @@ public Foo getString() { return string; } - public void setString(Foo string) { this.string = string; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java index 042d0f6b89b1..ac5bac325c7a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/FormatTest.java @@ -128,7 +128,6 @@ public FormatTest() { } public FormatTest integer(Integer integer) { - this.integer = integer; return this; } @@ -144,14 +143,12 @@ public Integer getInteger() { return integer; } - public void setInteger(Integer integer) { this.integer = integer; } public FormatTest int32(Integer int32) { - this.int32 = int32; return this; } @@ -167,14 +164,12 @@ public Integer getInt32() { return int32; } - public void setInt32(Integer int32) { this.int32 = int32; } public FormatTest int64(Long int64) { - this.int64 = int64; return this; } @@ -188,14 +183,12 @@ public Long getInt64() { return int64; } - public void setInt64(Long int64) { this.int64 = int64; } public FormatTest number(BigDecimal number) { - this.number = number; return this; } @@ -211,14 +204,12 @@ public BigDecimal getNumber() { return number; } - public void setNumber(BigDecimal number) { this.number = number; } public FormatTest _float(Float _float) { - this._float = _float; return this; } @@ -234,14 +225,12 @@ public Float getFloat() { return _float; } - public void setFloat(Float _float) { this._float = _float; } public FormatTest _double(Double _double) { - this._double = _double; return this; } @@ -257,14 +246,12 @@ public Double getDouble() { return _double; } - public void setDouble(Double _double) { this._double = _double; } public FormatTest decimal(BigDecimal decimal) { - this.decimal = decimal; return this; } @@ -278,14 +265,12 @@ public BigDecimal getDecimal() { return decimal; } - public void setDecimal(BigDecimal decimal) { this.decimal = decimal; } public FormatTest string(String string) { - this.string = string; return this; } @@ -299,14 +284,12 @@ public String getString() { return string; } - public void setString(String string) { this.string = string; } public FormatTest _byte(byte[] _byte) { - this._byte = _byte; return this; } @@ -320,14 +303,12 @@ public byte[] getByte() { return _byte; } - public void setByte(byte[] _byte) { this._byte = _byte; } public FormatTest binary(File binary) { - this.binary = binary; return this; } @@ -341,14 +322,12 @@ public File getBinary() { return binary; } - public void setBinary(File binary) { this.binary = binary; } public FormatTest date(LocalDate date) { - this.date = date; return this; } @@ -362,14 +341,12 @@ public LocalDate getDate() { return date; } - public void setDate(LocalDate date) { this.date = date; } public FormatTest dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -383,14 +360,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public FormatTest uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -404,14 +379,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public FormatTest uuidWithDefault(UUID uuidWithDefault) { - this.uuidWithDefault = uuidWithDefault; return this; } @@ -425,14 +398,12 @@ public UUID getUuidWithDefault() { return uuidWithDefault; } - public void setUuidWithDefault(UUID uuidWithDefault) { this.uuidWithDefault = uuidWithDefault; } public FormatTest password(String password) { - this.password = password; return this; } @@ -446,14 +417,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public FormatTest patternWithDigits(String patternWithDigits) { - this.patternWithDigits = patternWithDigits; return this; } @@ -467,14 +436,12 @@ public String getPatternWithDigits() { return patternWithDigits; } - public void setPatternWithDigits(String patternWithDigits) { this.patternWithDigits = patternWithDigits; } public FormatTest patternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { - this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; return this; } @@ -488,7 +455,6 @@ public String getPatternWithDigitsAndDelimiter() { return patternWithDigitsAndDelimiter; } - public void setPatternWithDigitsAndDelimiter(String patternWithDigitsAndDelimiter) { this.patternWithDigitsAndDelimiter = patternWithDigitsAndDelimiter; } @@ -591,7 +557,7 @@ public String toString() { sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); sb.append(" uuidWithDefault: ").append(toIndentedString(uuidWithDefault)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append(" additionalProperties: ").append(toIndentedString(additionalProperties)).append("\n"); diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java index d3bd545e3238..db7ac8c957d8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/GrandparentAnimal.java @@ -60,7 +60,6 @@ public GrandparentAnimal() { } public GrandparentAnimal petType(String petType) { - this.petType = petType; return this; } @@ -74,7 +73,6 @@ public String getPetType() { return petType; } - public void setPetType(String petType) { this.petType = petType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java index ca13d52c777c..0e0a97837e43 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HasOnlyReadOnly.java @@ -62,7 +62,6 @@ public class HasOnlyReadOnly { public HasOnlyReadOnly() { } - public HasOnlyReadOnly( String bar, String foo @@ -83,7 +82,6 @@ public String getBar() { - /** * Get foo * @return foo @@ -94,7 +92,6 @@ public String getFoo() { } - /** * A container for additional, undeclared properties. * This is a holder for any undeclared properties as specified with diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java index 5ed30eef075f..334f7d0d514e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/HealthCheckResult.java @@ -60,7 +60,6 @@ public HealthCheckResult() { } public HealthCheckResult nullableMessage(String nullableMessage) { - this.nullableMessage = nullableMessage; return this; } @@ -74,7 +73,6 @@ public String getNullableMessage() { return nullableMessage; } - public void setNullableMessage(String nullableMessage) { this.nullableMessage = nullableMessage; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java index 0a94cb568363..853a361ce94e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/IsoscelesTriangle.java @@ -63,7 +63,6 @@ public IsoscelesTriangle() { } public IsoscelesTriangle shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -77,14 +76,12 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } public IsoscelesTriangle triangleType(String triangleType) { - this.triangleType = triangleType; return this; } @@ -98,7 +95,6 @@ public String getTriangleType() { return triangleType; } - public void setTriangleType(String triangleType) { this.triangleType = triangleType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java index 44f4e60d9330..7152aa83fd9b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MapTest.java @@ -102,6 +102,11 @@ public InnerEnum read(final JsonReader jsonReader) throws IOException { return InnerEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + InnerEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_MAP_OF_ENUM_STRING = "map_of_enum_string"; @@ -120,7 +125,6 @@ public MapTest() { } public MapTest mapMapOfString(Map> mapMapOfString) { - this.mapMapOfString = mapMapOfString; return this; } @@ -142,14 +146,12 @@ public Map> getMapMapOfString() { return mapMapOfString; } - public void setMapMapOfString(Map> mapMapOfString) { this.mapMapOfString = mapMapOfString; } public MapTest mapOfEnumString(Map mapOfEnumString) { - this.mapOfEnumString = mapOfEnumString; return this; } @@ -171,14 +173,12 @@ public Map getMapOfEnumString() { return mapOfEnumString; } - public void setMapOfEnumString(Map mapOfEnumString) { this.mapOfEnumString = mapOfEnumString; } public MapTest directMap(Map directMap) { - this.directMap = directMap; return this; } @@ -200,14 +200,12 @@ public Map getDirectMap() { return directMap; } - public void setDirectMap(Map directMap) { this.directMap = directMap; } public MapTest indirectMap(Map indirectMap) { - this.indirectMap = indirectMap; return this; } @@ -229,7 +227,6 @@ public Map getIndirectMap() { return indirectMap; } - public void setIndirectMap(Map indirectMap) { this.indirectMap = indirectMap; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java index ae108748e626..d22ff1a8b393 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -72,7 +72,6 @@ public MixedPropertiesAndAdditionalPropertiesClass() { } public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { - this.uuid = uuid; return this; } @@ -86,14 +85,12 @@ public UUID getUuid() { return uuid; } - public void setUuid(UUID uuid) { this.uuid = uuid; } public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; return this; } @@ -107,14 +104,12 @@ public OffsetDateTime getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { this.dateTime = dateTime; } public MixedPropertiesAndAdditionalPropertiesClass map(Map map) { - this.map = map; return this; } @@ -136,7 +131,6 @@ public Map getMap() { return map; } - public void setMap(Map map) { this.map = map; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java index 5d0c4924d52b..9dc547f27358 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Model200Response.java @@ -63,7 +63,6 @@ public Model200Response() { } public Model200Response name(Integer name) { - this.name = name; return this; } @@ -77,14 +76,12 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; return this; } @@ -98,7 +95,6 @@ public String getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java index 84e8fd55e302..44737026be2b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelApiResponse.java @@ -67,7 +67,6 @@ public ModelApiResponse() { } public ModelApiResponse code(Integer code) { - this.code = code; return this; } @@ -81,14 +80,12 @@ public Integer getCode() { return code; } - public void setCode(Integer code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; return this; } @@ -123,7 +118,6 @@ public String getMessage() { return message; } - public void setMessage(String message) { this.message = message; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java index b89e35bc9705..cf66685d0666 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelFile.java @@ -59,7 +59,6 @@ public ModelFile() { } public ModelFile sourceURI(String sourceURI) { - this.sourceURI = sourceURI; return this; } @@ -73,7 +72,6 @@ public String getSourceURI() { return sourceURI; } - public void setSourceURI(String sourceURI) { this.sourceURI = sourceURI; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java index 0f63d447a16d..6990be88242c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelList.java @@ -59,7 +59,6 @@ public ModelList() { } public ModelList _123list(String _123list) { - this._123list = _123list; return this; } @@ -73,7 +72,6 @@ public String get123list() { return _123list; } - public void set123list(String _123list) { this._123list = _123list; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java index 406fc1c36066..e0e70a486093 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ModelReturn.java @@ -59,7 +59,6 @@ public ModelReturn() { } public ModelReturn _return(Integer _return) { - this._return = _return; return this; } @@ -73,7 +72,6 @@ public Integer getReturn() { return _return; } - public void setReturn(Integer _return) { this._return = _return; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java index ae591dba4061..c267a8eaad95 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Name.java @@ -70,7 +70,6 @@ public class Name { public Name() { } - public Name( Integer snakeCase, Integer _123number @@ -81,7 +80,6 @@ public Name( } public Name name(Integer name) { - this.name = name; return this; } @@ -95,7 +93,6 @@ public Integer getName() { return name; } - public void setName(Integer name) { this.name = name; } @@ -112,9 +109,7 @@ public Integer getSnakeCase() { - public Name property(String property) { - this.property = property; return this; } @@ -128,7 +123,6 @@ public String getProperty() { return property; } - public void setProperty(String property) { this.property = property; } @@ -144,7 +138,6 @@ public Integer get123number() { } - /** * A container for additional, undeclared properties. * This is a holder for any undeclared properties as specified with diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPet.java index 78ad57f234a2..4db1b70c4c9a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPet.java @@ -127,6 +127,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -137,7 +142,6 @@ public NewPet() { } public NewPet id(Long id) { - this.id = id; return this; } @@ -151,14 +155,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public NewPet categoryInlineAllof(NewPetCategoryInlineAllof categoryInlineAllof) { - this.categoryInlineAllof = categoryInlineAllof; return this; } @@ -172,14 +174,12 @@ public NewPetCategoryInlineAllof getCategoryInlineAllof() { return categoryInlineAllof; } - public void setCategoryInlineAllof(NewPetCategoryInlineAllof categoryInlineAllof) { this.categoryInlineAllof = categoryInlineAllof; } public NewPet categoryAllOfRef(Category categoryAllOfRef) { - this.categoryAllOfRef = categoryAllOfRef; return this; } @@ -193,14 +193,12 @@ public Category getCategoryAllOfRef() { return categoryAllOfRef; } - public void setCategoryAllOfRef(Category categoryAllOfRef) { this.categoryAllOfRef = categoryAllOfRef; } public NewPet name(String name) { - this.name = name; return this; } @@ -214,14 +212,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public NewPet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -243,14 +239,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public NewPet tags(List tags) { - this.tags = tags; return this; } @@ -272,14 +266,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public NewPet status(StatusEnum status) { - this.status = status; return this; } @@ -293,7 +285,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -470,6 +461,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java index a30bddad6039..0a1d6e357757 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllof.java @@ -68,7 +68,6 @@ public NewPetCategoryInlineAllof() { } public NewPetCategoryInlineAllof id(Long id) { - this.id = id; return this; } @@ -82,14 +81,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public NewPetCategoryInlineAllof name(String name) { - this.name = name; return this; } @@ -103,14 +100,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public NewPetCategoryInlineAllof categoryTag(NewPetCategoryInlineAllofAllOfCategoryTag categoryTag) { - this.categoryTag = categoryTag; return this; } @@ -124,7 +119,6 @@ public NewPetCategoryInlineAllofAllOfCategoryTag getCategoryTag() { return categoryTag; } - public void setCategoryTag(NewPetCategoryInlineAllofAllOfCategoryTag categoryTag) { this.categoryTag = categoryTag; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java index 035d0bb636ad..24827720cbf2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NewPetCategoryInlineAllofAllOfCategoryTag.java @@ -63,7 +63,6 @@ public NewPetCategoryInlineAllofAllOfCategoryTag() { } public NewPetCategoryInlineAllofAllOfCategoryTag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public NewPetCategoryInlineAllofAllOfCategoryTag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java index 7cb3b91cf451..2f14f3b93daf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NullableClass.java @@ -111,7 +111,6 @@ public NullableClass() { } public NullableClass integerProp(Integer integerProp) { - this.integerProp = integerProp; return this; } @@ -125,14 +124,12 @@ public Integer getIntegerProp() { return integerProp; } - public void setIntegerProp(Integer integerProp) { this.integerProp = integerProp; } public NullableClass numberProp(BigDecimal numberProp) { - this.numberProp = numberProp; return this; } @@ -146,14 +143,12 @@ public BigDecimal getNumberProp() { return numberProp; } - public void setNumberProp(BigDecimal numberProp) { this.numberProp = numberProp; } public NullableClass booleanProp(Boolean booleanProp) { - this.booleanProp = booleanProp; return this; } @@ -167,14 +162,12 @@ public Boolean getBooleanProp() { return booleanProp; } - public void setBooleanProp(Boolean booleanProp) { this.booleanProp = booleanProp; } public NullableClass stringProp(String stringProp) { - this.stringProp = stringProp; return this; } @@ -188,14 +181,12 @@ public String getStringProp() { return stringProp; } - public void setStringProp(String stringProp) { this.stringProp = stringProp; } public NullableClass dateProp(LocalDate dateProp) { - this.dateProp = dateProp; return this; } @@ -209,14 +200,12 @@ public LocalDate getDateProp() { return dateProp; } - public void setDateProp(LocalDate dateProp) { this.dateProp = dateProp; } public NullableClass datetimeProp(OffsetDateTime datetimeProp) { - this.datetimeProp = datetimeProp; return this; } @@ -230,14 +219,12 @@ public OffsetDateTime getDatetimeProp() { return datetimeProp; } - public void setDatetimeProp(OffsetDateTime datetimeProp) { this.datetimeProp = datetimeProp; } public NullableClass arrayNullableProp(List arrayNullableProp) { - this.arrayNullableProp = arrayNullableProp; return this; } @@ -259,14 +246,12 @@ public List getArrayNullableProp() { return arrayNullableProp; } - public void setArrayNullableProp(List arrayNullableProp) { this.arrayNullableProp = arrayNullableProp; } public NullableClass arrayAndItemsNullableProp(List arrayAndItemsNullableProp) { - this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; return this; } @@ -288,14 +273,12 @@ public List getArrayAndItemsNullableProp() { return arrayAndItemsNullableProp; } - public void setArrayAndItemsNullableProp(List arrayAndItemsNullableProp) { this.arrayAndItemsNullableProp = arrayAndItemsNullableProp; } public NullableClass arrayItemsNullable(List arrayItemsNullable) { - this.arrayItemsNullable = arrayItemsNullable; return this; } @@ -317,14 +300,12 @@ public List getArrayItemsNullable() { return arrayItemsNullable; } - public void setArrayItemsNullable(List arrayItemsNullable) { this.arrayItemsNullable = arrayItemsNullable; } public NullableClass objectNullableProp(Map objectNullableProp) { - this.objectNullableProp = objectNullableProp; return this; } @@ -346,14 +327,12 @@ public Map getObjectNullableProp() { return objectNullableProp; } - public void setObjectNullableProp(Map objectNullableProp) { this.objectNullableProp = objectNullableProp; } public NullableClass objectAndItemsNullableProp(Map objectAndItemsNullableProp) { - this.objectAndItemsNullableProp = objectAndItemsNullableProp; return this; } @@ -375,14 +354,12 @@ public Map getObjectAndItemsNullableProp() { return objectAndItemsNullableProp; } - public void setObjectAndItemsNullableProp(Map objectAndItemsNullableProp) { this.objectAndItemsNullableProp = objectAndItemsNullableProp; } public NullableClass objectItemsNullable(Map objectItemsNullable) { - this.objectItemsNullable = objectItemsNullable; return this; } @@ -404,7 +381,6 @@ public Map getObjectItemsNullable() { return objectItemsNullable; } - public void setObjectItemsNullable(Map objectItemsNullable) { this.objectItemsNullable = objectItemsNullable; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java index 210bdef5598d..923c2f1739dd 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/NumberOnly.java @@ -60,7 +60,6 @@ public NumberOnly() { } public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; return this; } @@ -74,7 +73,6 @@ public BigDecimal getJustNumber() { return justNumber; } - public void setJustNumber(BigDecimal justNumber) { this.justNumber = justNumber; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java index 5e6850019948..f6f5c81f38b9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ObjectWithDeprecatedFields.java @@ -78,7 +78,6 @@ public ObjectWithDeprecatedFields() { } public ObjectWithDeprecatedFields uuid(String uuid) { - this.uuid = uuid; return this; } @@ -92,7 +91,6 @@ public String getUuid() { return uuid; } - public void setUuid(String uuid) { this.uuid = uuid; } @@ -100,7 +98,6 @@ public void setUuid(String uuid) { @Deprecated public ObjectWithDeprecatedFields id(BigDecimal id) { - this.id = id; return this; } @@ -116,7 +113,6 @@ public BigDecimal getId() { return id; } - @Deprecated public void setId(BigDecimal id) { this.id = id; @@ -125,7 +121,6 @@ public void setId(BigDecimal id) { @Deprecated public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) { - this.deprecatedRef = deprecatedRef; return this; } @@ -141,7 +136,6 @@ public DeprecatedObject getDeprecatedRef() { return deprecatedRef; } - @Deprecated public void setDeprecatedRef(DeprecatedObject deprecatedRef) { this.deprecatedRef = deprecatedRef; @@ -150,7 +144,6 @@ public void setDeprecatedRef(DeprecatedObject deprecatedRef) { @Deprecated public ObjectWithDeprecatedFields bars(List bars) { - this.bars = bars; return this; } @@ -174,7 +167,6 @@ public List getBars() { return bars; } - @Deprecated public void setBars(List bars) { this.bars = bars; diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java index f7763b303dac..12d497ecc005 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Order.java @@ -115,6 +115,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -129,7 +134,6 @@ public Order() { } public Order id(Long id) { - this.id = id; return this; } @@ -143,14 +147,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; return this; } @@ -164,14 +166,12 @@ public Long getPetId() { return petId; } - public void setPetId(Long petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; return this; } @@ -185,14 +185,12 @@ public Integer getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; return this; } @@ -206,14 +204,12 @@ public OffsetDateTime getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; return this; } @@ -227,14 +223,12 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; return this; } @@ -248,7 +242,6 @@ public Boolean getComplete() { return complete; } - public void setComplete(Boolean complete) { this.complete = complete; } @@ -382,6 +375,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java index ab21ff720a17..220c40e5c7d4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterComposite.java @@ -68,7 +68,6 @@ public OuterComposite() { } public OuterComposite myNumber(BigDecimal myNumber) { - this.myNumber = myNumber; return this; } @@ -82,14 +81,12 @@ public BigDecimal getMyNumber() { return myNumber; } - public void setMyNumber(BigDecimal myNumber) { this.myNumber = myNumber; } public OuterComposite myString(String myString) { - this.myString = myString; return this; } @@ -103,14 +100,12 @@ public String getMyString() { return myString; } - public void setMyString(String myString) { this.myString = myString; } public OuterComposite myBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; return this; } @@ -124,7 +119,6 @@ public Boolean getMyBoolean() { return myBoolean; } - public void setMyBoolean(Boolean myBoolean) { this.myBoolean = myBoolean; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnum.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnum.java index 00d9c2a1a5c7..849bfbf89285 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnum.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnum.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -32,7 +33,11 @@ public enum OuterEnum { APPROVED("approved"), - DELIVERED("delivered"); + DELIVERED("delivered"), + + LOWER_CASE_S("s"), + + UPPER_CASE_S("S"); private String value; @@ -70,5 +75,10 @@ public OuterEnum read(final JsonReader jsonReader) throws IOException { return OuterEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnum.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java index 6643886ce21d..09897c14f170 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumDefaultValue.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public OuterEnumDefaultValue read(final JsonReader jsonReader) throws IOExceptio return OuterEnumDefaultValue.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + OuterEnumDefaultValue.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumInteger.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumInteger.java index a30b2089e6f6..ae49256b3bad 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumInteger.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumInteger.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public OuterEnumInteger read(final JsonReader jsonReader) throws IOException { return OuterEnumInteger.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + OuterEnumInteger.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java index 3f6efe9ce977..8d5372492bed 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/OuterEnumIntegerDefaultValue.java @@ -18,6 +18,7 @@ import java.io.IOException; import com.google.gson.TypeAdapter; +import com.google.gson.JsonElement; import com.google.gson.annotations.JsonAdapter; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; @@ -70,5 +71,10 @@ public OuterEnumIntegerDefaultValue read(final JsonReader jsonReader) throws IOE return OuterEnumIntegerDefaultValue.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + Integer value = jsonElement.getAsInt(); + OuterEnumIntegerDefaultValue.fromValue(value); + } } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java index b1505e2c864d..90e7f9ef2b31 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Pet.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -132,7 +137,6 @@ public Pet() { } public Pet id(Long id) { - this.id = id; return this; } @@ -146,14 +150,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Pet category(Category category) { - this.category = category; return this; } @@ -167,14 +169,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public Pet name(String name) { - this.name = name; return this; } @@ -188,14 +188,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Pet photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -217,14 +215,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public Pet tags(List tags) { - this.tags = tags; return this; } @@ -246,14 +242,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public Pet status(StatusEnum status) { - this.status = status; return this; } @@ -267,7 +261,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -437,6 +430,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java index 5e90ae0d3770..25815f11b938 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PetWithRequiredTags.java @@ -122,6 +122,11 @@ public StatusEnum read(final JsonReader jsonReader) throws IOException { return StatusEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + StatusEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_STATUS = "status"; @@ -132,7 +137,6 @@ public PetWithRequiredTags() { } public PetWithRequiredTags id(Long id) { - this.id = id; return this; } @@ -146,14 +150,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public PetWithRequiredTags category(Category category) { - this.category = category; return this; } @@ -167,14 +169,12 @@ public Category getCategory() { return category; } - public void setCategory(Category category) { this.category = category; } public PetWithRequiredTags name(String name) { - this.name = name; return this; } @@ -188,14 +188,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public PetWithRequiredTags photoUrls(List photoUrls) { - this.photoUrls = photoUrls; return this; } @@ -217,14 +215,12 @@ public List getPhotoUrls() { return photoUrls; } - public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } public PetWithRequiredTags tags(List tags) { - this.tags = tags; return this; } @@ -246,14 +242,12 @@ public List getTags() { return tags; } - public void setTags(List tags) { this.tags = tags; } public PetWithRequiredTags status(StatusEnum status) { - this.status = status; return this; } @@ -267,7 +261,6 @@ public StatusEnum getStatus() { return status; } - public void setStatus(StatusEnum status) { this.status = status; } @@ -434,6 +427,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) && !jsonObj.get("status").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `status` to be a primitive type in the JSON string but got `%s`", jsonObj.get("status").toString())); } + // validate the optional field `status` + if (jsonObj.get("status") != null && !jsonObj.get("status").isJsonNull()) { + StatusEnum.validateJsonElement(jsonObj.get("status")); + } } public static class CustomTypeAdapterFactory implements TypeAdapterFactory { diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PropertyNameCollision.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PropertyNameCollision.java index ec27136abd10..15c94c8ef4ca 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PropertyNameCollision.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/PropertyNameCollision.java @@ -67,7 +67,6 @@ public PropertyNameCollision() { } public PropertyNameCollision underscoreType(String underscoreType) { - this.underscoreType = underscoreType; return this; } @@ -81,14 +80,12 @@ public String getUnderscoreType() { return underscoreType; } - public void setUnderscoreType(String underscoreType) { this.underscoreType = underscoreType; } public PropertyNameCollision type(String type) { - this.type = type; return this; } @@ -102,14 +99,12 @@ public String getType() { return type; } - public void setType(String type) { this.type = type; } public PropertyNameCollision typeWithUnderscore(String typeWithUnderscore) { - this.typeWithUnderscore = typeWithUnderscore; return this; } @@ -123,7 +118,6 @@ public String getTypeWithUnderscore() { return typeWithUnderscore; } - public void setTypeWithUnderscore(String typeWithUnderscore) { this.typeWithUnderscore = typeWithUnderscore; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java index c95020df057c..64961f1cd447 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/QuadrilateralInterface.java @@ -59,7 +59,6 @@ public QuadrilateralInterface() { } public QuadrilateralInterface quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; return this; } @@ -73,7 +72,6 @@ public String getQuadrilateralType() { return quadrilateralType; } - public void setQuadrilateralType(String quadrilateralType) { this.quadrilateralType = quadrilateralType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java index b62bb2dddc67..e6aaed50f39f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ReadOnlyFirst.java @@ -62,7 +62,6 @@ public class ReadOnlyFirst { public ReadOnlyFirst() { } - public ReadOnlyFirst( String bar ) { @@ -81,9 +80,7 @@ public String getBar() { - public ReadOnlyFirst baz(String baz) { - this.baz = baz; return this; } @@ -97,7 +94,6 @@ public String getBaz() { return baz; } - public void setBaz(String baz) { this.baz = baz; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java index c30678320ca9..a2cf0be049ef 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ScaleneTriangle.java @@ -63,7 +63,6 @@ public ScaleneTriangle() { } public ScaleneTriangle shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -77,14 +76,12 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } public ScaleneTriangle triangleType(String triangleType) { - this.triangleType = triangleType; return this; } @@ -98,7 +95,6 @@ public String getTriangleType() { return triangleType; } - public void setTriangleType(String triangleType) { this.triangleType = triangleType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java index f3dd889e637d..7a5fc8a3f0e8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/ShapeInterface.java @@ -59,7 +59,6 @@ public ShapeInterface() { } public ShapeInterface shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -73,7 +72,6 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java index 8f3b3c9d3dd6..e0cf4149770d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SimpleQuadrilateral.java @@ -63,7 +63,6 @@ public SimpleQuadrilateral() { } public SimpleQuadrilateral shapeType(String shapeType) { - this.shapeType = shapeType; return this; } @@ -77,14 +76,12 @@ public String getShapeType() { return shapeType; } - public void setShapeType(String shapeType) { this.shapeType = shapeType; } public SimpleQuadrilateral quadrilateralType(String quadrilateralType) { - this.quadrilateralType = quadrilateralType; return this; } @@ -98,7 +95,6 @@ public String getQuadrilateralType() { return quadrilateralType; } - public void setQuadrilateralType(String quadrilateralType) { this.quadrilateralType = quadrilateralType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java index 776cea58df91..31986709b6e1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/SpecialModelName.java @@ -63,7 +63,6 @@ public SpecialModelName() { } public SpecialModelName $specialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; return this; } @@ -77,14 +76,12 @@ public SpecialModelName() { return $specialPropertyName; } - public void set$SpecialPropertyName(Long $specialPropertyName) { this.$specialPropertyName = $specialPropertyName; } public SpecialModelName specialModelName(String specialModelName) { - this.specialModelName = specialModelName; return this; } @@ -98,7 +95,6 @@ public String getSpecialModelName() { return specialModelName; } - public void setSpecialModelName(String specialModelName) { this.specialModelName = specialModelName; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java index 6f2b2cb137bb..5eeadfefd5de 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Tag.java @@ -63,7 +63,6 @@ public Tag() { } public Tag id(Long id) { - this.id = id; return this; } @@ -77,14 +76,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public Tag name(String name) { - this.name = name; return this; } @@ -98,7 +95,6 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java index 6aa03af08bcb..a7054eef57cf 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TestInlineFreeformAdditionalPropertiesRequest.java @@ -59,7 +59,6 @@ public TestInlineFreeformAdditionalPropertiesRequest() { } public TestInlineFreeformAdditionalPropertiesRequest someProperty(String someProperty) { - this.someProperty = someProperty; return this; } @@ -73,7 +72,6 @@ public String getSomeProperty() { return someProperty; } - public void setSomeProperty(String someProperty) { this.someProperty = someProperty; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java index dc00208db465..c427ab318054 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/TriangleInterface.java @@ -59,7 +59,6 @@ public TriangleInterface() { } public TriangleInterface triangleType(String triangleType) { - this.triangleType = triangleType; return this; } @@ -73,7 +72,6 @@ public String getTriangleType() { return triangleType; } - public void setTriangleType(String triangleType) { this.triangleType = triangleType; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java index ab60644bf648..94931c39db55 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/User.java @@ -104,7 +104,6 @@ public User() { } public User id(Long id) { - this.id = id; return this; } @@ -118,14 +117,12 @@ public Long getId() { return id; } - public void setId(Long id) { this.id = id; } public User username(String username) { - this.username = username; return this; } @@ -139,14 +136,12 @@ public String getUsername() { return username; } - public void setUsername(String username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; return this; } @@ -160,14 +155,12 @@ public String getFirstName() { return firstName; } - public void setFirstName(String firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; return this; } @@ -181,14 +174,12 @@ public String getLastName() { return lastName; } - public void setLastName(String lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; return this; } @@ -202,14 +193,12 @@ public String getEmail() { return email; } - public void setEmail(String email) { this.email = email; } public User password(String password) { - this.password = password; return this; } @@ -223,14 +212,12 @@ public String getPassword() { return password; } - public void setPassword(String password) { this.password = password; } public User phone(String phone) { - this.phone = phone; return this; } @@ -244,14 +231,12 @@ public String getPhone() { return phone; } - public void setPhone(String phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; return this; } @@ -265,14 +250,12 @@ public Integer getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { this.userStatus = userStatus; } public User objectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { - this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; return this; } @@ -286,14 +269,12 @@ public Object getObjectWithNoDeclaredProps() { return objectWithNoDeclaredProps; } - public void setObjectWithNoDeclaredProps(Object objectWithNoDeclaredProps) { this.objectWithNoDeclaredProps = objectWithNoDeclaredProps; } public User objectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { - this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; return this; } @@ -307,14 +288,12 @@ public Object getObjectWithNoDeclaredPropsNullable() { return objectWithNoDeclaredPropsNullable; } - public void setObjectWithNoDeclaredPropsNullable(Object objectWithNoDeclaredPropsNullable) { this.objectWithNoDeclaredPropsNullable = objectWithNoDeclaredPropsNullable; } public User anyTypeProp(Object anyTypeProp) { - this.anyTypeProp = anyTypeProp; return this; } @@ -328,14 +307,12 @@ public Object getAnyTypeProp() { return anyTypeProp; } - public void setAnyTypeProp(Object anyTypeProp) { this.anyTypeProp = anyTypeProp; } public User anyTypePropNullable(Object anyTypePropNullable) { - this.anyTypePropNullable = anyTypePropNullable; return this; } @@ -349,7 +326,6 @@ public Object getAnyTypePropNullable() { return anyTypePropNullable; } - public void setAnyTypePropNullable(Object anyTypePropNullable) { this.anyTypePropNullable = anyTypePropNullable; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Variable.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Variable.java index 69c3b0d4d519..ce93b3ba30a5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Variable.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Variable.java @@ -64,7 +64,6 @@ public Variable() { } public Variable name(String name) { - this.name = name; return this; } @@ -78,14 +77,12 @@ public String getName() { return name; } - public void setName(String name) { this.name = name; } public Variable value(Value value) { - this.value = value; return this; } @@ -99,7 +96,6 @@ public Value getValue() { return value; } - public void setValue(Value value) { this.value = value; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java index bb0f3f6f4b38..b56277c926fd 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Whale.java @@ -67,7 +67,6 @@ public Whale() { } public Whale hasBaleen(Boolean hasBaleen) { - this.hasBaleen = hasBaleen; return this; } @@ -81,14 +80,12 @@ public Boolean getHasBaleen() { return hasBaleen; } - public void setHasBaleen(Boolean hasBaleen) { this.hasBaleen = hasBaleen; } public Whale hasTeeth(Boolean hasTeeth) { - this.hasTeeth = hasTeeth; return this; } @@ -102,14 +99,12 @@ public Boolean getHasTeeth() { return hasTeeth; } - public void setHasTeeth(Boolean hasTeeth) { this.hasTeeth = hasTeeth; } public Whale className(String className) { - this.className = className; return this; } @@ -123,7 +118,6 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } diff --git a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java index 1e5c2608f2a8..2ceafc48c075 100644 --- a/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java +++ b/samples/client/petstore/java/okhttp-gson/src/main/java/org/openapitools/client/model/Zebra.java @@ -98,6 +98,11 @@ public TypeEnum read(final JsonReader jsonReader) throws IOException { return TypeEnum.fromValue(value); } } + + public static void validateJsonElement(JsonElement jsonElement) throws IOException { + String value = jsonElement.getAsString(); + TypeEnum.fromValue(value); + } } public static final String SERIALIZED_NAME_TYPE = "type"; @@ -112,7 +117,6 @@ public Zebra() { } public Zebra type(TypeEnum type) { - this.type = type; return this; } @@ -126,14 +130,12 @@ public TypeEnum getType() { return type; } - public void setType(TypeEnum type) { this.type = type; } public Zebra className(String className) { - this.className = className; return this; } @@ -147,7 +149,6 @@ public String getClassName() { return className; } - public void setClassName(String className) { this.className = className; } @@ -277,6 +278,10 @@ public static void validateJsonElement(JsonElement jsonElement) throws IOExcepti if ((jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) && !jsonObj.get("type").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `type` to be a primitive type in the JSON string but got `%s`", jsonObj.get("type").toString())); } + // validate the optional field `type` + if (jsonObj.get("type") != null && !jsonObj.get("type").isJsonNull()) { + TypeEnum.validateJsonElement(jsonObj.get("type")); + } if (!jsonObj.get("className").isJsonPrimitive()) { throw new IllegalArgumentException(String.format("Expected the field `className` to be a primitive type in the JSON string but got `%s`", jsonObj.get("className").toString())); } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java new file mode 100644 index 000000000000..05c47e82206e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ApiClientTest.java @@ -0,0 +1,350 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.*; + +import okhttp3.OkHttpClient; +import org.junit.jupiter.api.*; +import org.openapitools.client.auth.*; + +public class ApiClientTest { + ApiClient apiClient; + JSON json; + + @BeforeEach + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + } + + @Test + public void testIsJsonMime() { + assertFalse(apiClient.isJsonMime(null)); + assertFalse(apiClient.isJsonMime("")); + assertFalse(apiClient.isJsonMime("text/plain")); + assertFalse(apiClient.isJsonMime("application/xml")); + assertFalse(apiClient.isJsonMime("application/jsonp")); + assertFalse(apiClient.isJsonMime("example/json")); + assertFalse(apiClient.isJsonMime("example/foo+bar+jsonx")); + assertFalse(apiClient.isJsonMime("example/foo+bar+xjson")); + + assertTrue(apiClient.isJsonMime("application/json")); + assertTrue(apiClient.isJsonMime("application/json; charset=UTF8")); + assertTrue(apiClient.isJsonMime("APPLICATION/JSON")); + + assertTrue(apiClient.isJsonMime("application/problem+json")); + assertTrue(apiClient.isJsonMime("APPLICATION/PROBLEM+JSON")); + assertTrue(apiClient.isJsonMime("application/json\t")); + assertTrue(apiClient.isJsonMime("example/foo+bar+json")); + assertTrue(apiClient.isJsonMime("example/foo+json;x;y")); + assertTrue(apiClient.isJsonMime("example/foo+json\t;")); + assertTrue(apiClient.isJsonMime("Example/fOO+JSON")); + + assertTrue(apiClient.isJsonMime("application/json-patch+json")); + } + + @Test + public void testSelectHeaderAccept() { + String[] accepts = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"APPLICATION/XML", "APPLICATION/JSON"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals("application/json; charset=UTF8", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain,application/xml", apiClient.selectHeaderAccept(accepts)); + + accepts = new String[]{}; + assertNull(apiClient.selectHeaderAccept(accepts)); + } + + @Test + public void testSelectHeaderContentType() { + String[] contentTypes = {"application/json", "application/xml"}; + assertEquals("application/json", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"APPLICATION/JSON", "APPLICATION/XML"}; + assertEquals("APPLICATION/JSON", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"application/xml", "application/json; charset=UTF8"}; + assertEquals( + "application/json; charset=UTF8", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{"text/plain", "application/xml"}; + assertEquals("text/plain", apiClient.selectHeaderContentType(contentTypes)); + + contentTypes = new String[]{}; + assertNull(apiClient.selectHeaderContentType(contentTypes)); + } + + @Test + public void testGetAuthentications() { + Map auths = apiClient.getAuthentications(); + + Authentication auth = auths.get("api_key"); + assertNotNull(auth); + assertTrue(auth instanceof ApiKeyAuth); + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) auth; + assertEquals("header", apiKeyAuth.getLocation()); + assertEquals("api_key", apiKeyAuth.getParamName()); + + auth = auths.get("petstore_auth"); + assertTrue(auth instanceof OAuth); + assertSame(auth, apiClient.getAuthentication("petstore_auth")); + + assertNull(auths.get("unknown")); + + try { + auths.put("my_auth", new HttpBasicAuth()); + fail("the authentications returned should not be modifiable"); + } catch (UnsupportedOperationException e) { + } + } + + /* + @Test + public void testSetUsernameAndPassword() { + HttpBasicAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof HttpBasicAuth) { + auth = (HttpBasicAuth) _auth; + break; + } + } + auth.setUsername(null); + auth.setPassword(null); + + apiClient.setUsername("my-username"); + apiClient.setPassword("my-password"); + assertEquals("my-username", auth.getUsername()); + assertEquals("my-password", auth.getPassword()); + + // reset values + auth.setUsername(null); + auth.setPassword(null); + } + */ + + @Test + public void testSetApiKeyAndPrefix() { + ApiKeyAuth auth = null; + for (Authentication _auth : apiClient.getAuthentications().values()) { + if (_auth instanceof ApiKeyAuth) { + auth = (ApiKeyAuth) _auth; + break; + } + } + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + + apiClient.setApiKey("my-api-key"); + apiClient.setApiKeyPrefix("Token"); + assertEquals("my-api-key", auth.getApiKey()); + assertEquals("Token", auth.getApiKeyPrefix()); + + // reset values + auth.setApiKey(null); + auth.setApiKeyPrefix(null); + } + + @Test + public void testGetAndSetConnectTimeout() { + // connect timeout defaults to 10 seconds + assertEquals(10000, apiClient.getConnectTimeout()); + assertEquals(10000, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(0); + assertEquals(0, apiClient.getConnectTimeout()); + assertEquals(0, apiClient.getHttpClient().connectTimeoutMillis()); + + apiClient.setConnectTimeout(10000); + } + + @Test + public void testGetAndSetReadTimeout() { + // read timeout defaults to 10 seconds + assertEquals(10000, apiClient.getReadTimeout()); + assertEquals(10000, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(0); + assertEquals(0, apiClient.getReadTimeout()); + assertEquals(0, apiClient.getHttpClient().readTimeoutMillis()); + + apiClient.setReadTimeout(10000); + } + + @Test + public void testGetAndSetWriteTimeout() { + // write timeout defaults to 10 seconds + assertEquals(10000, apiClient.getWriteTimeout()); + assertEquals(10000, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(0); + assertEquals(0, apiClient.getWriteTimeout()); + assertEquals(0, apiClient.getHttpClient().writeTimeoutMillis()); + + apiClient.setWriteTimeout(10000); + } + + @Test + public void testParameterToPairWhenNameIsInvalid() throws Exception { + List pairs_a = apiClient.parameterToPair(null, new Integer(1)); + List pairs_b = apiClient.parameterToPair("", new Integer(1)); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPair("param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairWhenValueIsEmptyString() throws Exception { + // single empty string + List pairs = apiClient.parameterToPair("param-a", " "); + assertEquals(1, pairs.size()); + } + + @Test + public void testParameterToPairWhenValueIsNotCollection() throws Exception { + String name = "param-a"; + Integer value = 1; + + List pairs = apiClient.parameterToPair(name, value); + + assertEquals(1, pairs.size()); + assertEquals(value, Integer.valueOf(pairs.get(0).getValue())); + } + + @Test + public void testParameterToPairWhenValueIsCollection() throws Exception { + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + List pairs = apiClient.parameterToPair("param-a", values); + assertEquals(0, pairs.size()); + } + + @Test + public void testParameterToPairsWhenNameIsInvalid() throws Exception { + List objects = new ArrayList(); + objects.add(new Integer(1)); + + List pairs_a = apiClient.parameterToPairs("csv", null, objects); + List pairs_b = apiClient.parameterToPairs("csv", "", objects); + + assertTrue(pairs_a.isEmpty()); + assertTrue(pairs_b.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsNull() throws Exception { + List pairs = apiClient.parameterToPairs("csv", "param-a", null); + + assertTrue(pairs.isEmpty()); + } + + @Test + public void testParameterToPairsWhenValueIsEmptyStrings() throws Exception { + // list of empty strings + List strs = new ArrayList(); + strs.add(" "); + strs.add(" "); + strs.add(" "); + + List concatStrings = apiClient.parameterToPairs("csv", "param-a", strs); + + assertEquals(1, concatStrings.size()); + assertFalse(concatStrings.get(0).getValue().isEmpty()); // should contain some delimiters + } + + @Test + public void testParameterToPairsWhenValueIsCollection() throws Exception { + Map collectionFormatMap = new HashMap(); + collectionFormatMap.put("csv", ","); + collectionFormatMap.put("tsv", "\t"); + collectionFormatMap.put("ssv", " "); + collectionFormatMap.put("pipes", "|"); + collectionFormatMap.put("", ","); // no format, must default to csv + collectionFormatMap.put("unknown", ","); // all other formats, must default to csv + + String name = "param-a"; + + List values = new ArrayList(); + values.add("value-a"); + values.add(123); + values.add(new Date()); + + // check for multi separately + List multiPairs = apiClient.parameterToPairs("multi", name, values); + assertEquals(values.size(), multiPairs.size()); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + multiPairs.get(i).getValue()); + } + + // all other formats + for (String collectionFormat : collectionFormatMap.keySet()) { + List pairs = apiClient.parameterToPairs(collectionFormat, name, values); + + assertEquals(1, pairs.size()); + + String delimiter = collectionFormatMap.get(collectionFormat); + if (!delimiter.equals(",")) { + // commas are not escaped because they are reserved characters in URIs + delimiter = apiClient.escapeString(delimiter); + } + String[] pairValueSplit = pairs.get(0).getValue().split(delimiter); + + // must equal input values + assertEquals(values.size(), pairValueSplit.length); + for (int i = 0; i < values.size(); i++) { + assertEquals( + apiClient.escapeString(apiClient.parameterToString(values.get(i))), + pairValueSplit[i]); + } + } + } + + @Test + public void testSanitizeFilename() { + assertEquals("sun", apiClient.sanitizeFilename("sun")); + assertEquals("sun.gif", apiClient.sanitizeFilename("sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("../sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("/var/tmp/sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("./sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("..\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename("c:\\var\\tmp\\sun.gif")); + assertEquals("sun.gif", apiClient.sanitizeFilename(".\\sun.gif")); + } + + @Test + public void testNewHttpClient() { + OkHttpClient oldClient = apiClient.getHttpClient(); + apiClient.setHttpClient(oldClient.newBuilder().build()); + assertNotSame(apiClient.getHttpClient(), oldClient); + } + + /** + * Tests the invariant that the HttpClient for the ApiClient must never be null + */ + @Test + public void testNullHttpClient() { + NullPointerException thrown = Assertions.assertThrows(NullPointerException.class, () -> { + apiClient.setHttpClient(null); + }); + Assertions.assertEquals("HttpClient must not be null!", thrown.getMessage()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java new file mode 100644 index 000000000000..e5b9d146a4eb --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/ConfigurationTest.java @@ -0,0 +1,15 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.*; + +public class ConfigurationTest { + @Test + public void testDefaultApiClient() { + ApiClient apiClient = Configuration.getDefaultApiClient(); + assertNotNull(apiClient); + assertEquals("http://petstore.swagger.io:80/v2", apiClient.getBasePath()); + assertFalse(apiClient.isDebugging()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java new file mode 100644 index 000000000000..b0cd66291d2e --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/JSONTest.java @@ -0,0 +1,590 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import com.google.gson.Gson; +import com.google.gson.GsonBuilder; +import com.google.gson.JsonObject; +import com.google.gson.reflect.TypeToken; + +import java.io.IOException; +import java.lang.reflect.Type; +import java.nio.charset.StandardCharsets; +import java.text.DateFormat; +import java.text.SimpleDateFormat; +import java.time.format.DateTimeFormatter; +import java.time.LocalDate; +import java.time.OffsetDateTime; +import java.time.ZoneId; +import java.time.ZoneOffset; +import java.util.Calendar; +import java.util.Date; +import java.util.GregorianCalendar; +import java.util.Locale; +import java.util.TimeZone; + +import okio.ByteString; +import org.junit.jupiter.api.*; +import org.openapitools.client.model.Order; + +import org.openapitools.client.model.*; + +public class JSONTest { + private ApiClient apiClient = null; + private JSON json = null; + private Order order = null; + + @BeforeEach + public void setup() { + apiClient = new ApiClient(); + json = apiClient.getJSON(); + order = new Order(); + } + + @Test + public void testSqlDateTypeAdapter() { + final String str = "\"2015-11-07\""; + final java.sql.Date date = java.sql.Date.valueOf("2015-11-07"); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, java.sql.Date.class), date); + assertEquals( + json.deserialize( + "\"2015-11-07T03:49:09.356" + getCurrentTimezoneOffset() + "\"", + java.sql.Date.class) + .toString(), + date.toString()); + + // custom date format: without day + DateFormat format = new SimpleDateFormat("yyyy-MM", Locale.ROOT); + apiClient.setSqlDateFormat(format); + String dateStr = "\"2015-11\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", java.sql.Date.class))); + assertEquals(dateStr, json.serialize(json.deserialize("\"2015-11\"", java.sql.Date.class))); + } + + @Test + public void testDateTypeAdapter() { + Calendar cal = new GregorianCalendar(2015, 10, 7, 3, 49, 9); + cal.setTimeZone(TimeZone.getTimeZone("UTC")); + + assertEquals(json.deserialize("\"2015-11-07T05:49:09+02\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 300); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.3Z\"", Date.class), cal.getTime()); + + cal.set(Calendar.MILLISECOND, 356); + Date date = cal.getTime(); + + final String utcDate = "\"2015-11-07T03:49:09.356Z\""; + assertEquals(json.deserialize(utcDate, Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T05:49:09.356+02:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-01:00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356Z\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356+00\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T02:49:09.356-0100\"", Date.class), date); + assertEquals(json.deserialize("\"2015-11-07T03:49:09.356456789Z\"", Date.class), date); + + assertEquals(utcDate, json.serialize(date)); + + // custom datetime format: without milli-seconds, custom time zone + DateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX", Locale.ROOT); + format.setTimeZone(TimeZone.getTimeZone("GMT+10")); + apiClient.setDateFormat(format); + + String dateStr = "\"2015-11-07T13:49:09+10:00\""; + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T03:49:09+00:00\"", Date.class))); + assertEquals( + dateStr, json.serialize(json.deserialize("\"2015-11-07T03:49:09Z\"", Date.class))); + assertEquals( + dateStr, + json.serialize(json.deserialize("\"2015-11-07T00:49:09-03:00\"", Date.class))); + + try { + // invalid time zone format + json.deserialize("\"2015-11-07T03:49:09+00\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + try { + // unexpected milliseconds + json.deserialize("\"2015-11-07T03:49:09.000Z\"", Date.class); + fail("json parsing should fail"); + } catch (RuntimeException e) { + // OK + } + } + + @Test + public void testOffsetDateTimeTypeAdapter() { + final String str = "\"2016-09-09T08:02:03.123-03:00\""; + OffsetDateTime date = + OffsetDateTime.of(2016, 9, 9, 8, 2, 3, 123000000, ZoneOffset.of("-3")); + + assertEquals(str, json.serialize(date)); + // Use toString() instead of isEqual to verify that the offset is preserved + assertEquals(json.deserialize(str, OffsetDateTime.class).toString(), date.toString()); + } + + @Test + public void testLocalDateTypeAdapter() { + final String str = "\"2016-09-09\""; + final LocalDate date = LocalDate.of(2016, 9, 9); + + assertEquals(str, json.serialize(date)); + assertEquals(json.deserialize(str, LocalDate.class), date); + } + + @Test + public void testDefaultDate() throws Exception { + final DateTimeFormatter datetimeFormat = DateTimeFormatter.ISO_OFFSET_DATE_TIME; + final String dateStr = "2015-11-07T14:11:05.267Z"; + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + + String str = json.serialize(order); + Type type = new TypeToken() { + }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testCustomDate() throws Exception { + final DateTimeFormatter datetimeFormat = + DateTimeFormatter.ISO_OFFSET_DATE_TIME.withZone(ZoneId.of("Etc/GMT+2")); + final String dateStr = "2015-11-07T14:11:05-02:00"; + order.setShipDate(OffsetDateTime.from(datetimeFormat.parse(dateStr))); + + String str = json.serialize(order); + Type type = new TypeToken() { + }.getType(); + Order o = json.deserialize(str, type); + assertEquals(dateStr, datetimeFormat.format(o.getShipDate())); + } + + @Test + public void testByteArrayTypeAdapterSerialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + + // Act + String serializedBytesWithQuotes = json.serialize(expectedBytes); + + // Assert + String serializedBytes = + serializedBytesWithQuotes.substring(1, serializedBytesWithQuotes.length() - 1); + if (json.getGson().htmlSafe()) { + serializedBytes = serializedBytes.replaceAll("\\\\u003d", "="); + } + ByteString actualAsByteString = ByteString.decodeBase64(serializedBytes); + byte[] actualBytes = actualAsByteString.toByteArray(); + assertEquals(expectedBytesAsString, new String(actualBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testByteArrayTypeAdapterDeserialization() { + // Arrange + final String expectedBytesAsString = "Let's pretend this a jpg or something"; + final byte[] expectedBytes = expectedBytesAsString.getBytes(StandardCharsets.UTF_8); + final ByteString expectedByteString = ByteString.of(expectedBytes); + final String serializedBytes = expectedByteString.base64(); + final String serializedBytesWithQuotes = "\"" + serializedBytes + "\""; + Type type = new TypeToken() { + }.getType(); + + // Act + byte[] actualDeserializedBytes = json.deserialize(serializedBytesWithQuotes, type); + + // Assert + assertEquals( + expectedBytesAsString, new String(actualDeserializedBytes, StandardCharsets.UTF_8)); + } + + @Test + public void testRequiredFieldException() { + IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> { + // test json string missing required field(s) to ensure exception is thrown + Gson gson = json.getGson(); + //Gson gson = new GsonBuilder() + // .registerTypeAdapter(Pet.class, new Pet.CustomDeserializer()) + // .create(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; // missing photoUrls (required field) + //String json = "{\"id2\": 5847, \"name\":\"tag test 1\"}"; + //String json = "{\"id\": 5847}"; + Pet p = gson.fromJson(json, Pet.class); + }); + + Assertions.assertEquals("The required field `photoUrls` is not found in the JSON string: {\"id\":5847,\"name\":\"tag test 1\"}", thrown.getMessage()); + } + + @Test + @Disabled("No longer need the following test as additional field(s) should be stored in `additionalProperties`") + public void testAdditionalFieldException() { + IllegalArgumentException thrown = Assertions.assertThrows(IllegalArgumentException.class, () -> { + // test json string with additional field(s) to ensure exception is thrown + Gson gson = json.getGson(); + String json = "{\"id\": 5847, \"name\":\"tag test 1\", \"new-field\": true}"; + org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class); + }); + + Assertions.assertEquals("The field `new-field` in the JSON string is not defined in the `Tag` properties. JSON: {\"id\":5847,\"name\":\"tag test 1\",\"new-field\":true}", thrown.getMessage()); + } + + @Test + public void testCustomDeserializer() { + // test the custom deserializer to ensure it can deserialize json payload into objects + Gson gson = json.getGson(); + //Gson gson = new GsonBuilder() + // .registerTypeAdapter(Tag.class, new Tag.CustomDeserializer()) + // .create(); + // id and name + String json = "{\"id\": 5847, \"name\":\"tag test 1\"}"; + org.openapitools.client.model.Tag t = gson.fromJson(json, org.openapitools.client.model.Tag.class); + assertEquals(t.getName(), "tag test 1"); + assertEquals(t.getId(), Long.valueOf(5847L)); + + // name only + String json2 = "{\"name\":\"tag test 1\"}"; + org.openapitools.client.model.Tag t2 = gson.fromJson(json2, org.openapitools.client.model.Tag.class); + assertEquals(t2.getName(), "tag test 1"); + assertEquals(t2.getId(), null); + + // with all required fields + String json3 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}"; + Pet t3 = gson.fromJson(json3, Pet.class); + assertEquals(t3.getName(), "pet test 1"); + assertEquals(t3.getId(), Long.valueOf(5847)); + + // with all required fields and tags (optional) + String json4 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"id\":\"tag 123\"}]}"; + Pet t4 = gson.fromJson(json3, Pet.class); + assertEquals(t4.getName(), "pet test 1"); + assertEquals(t4.getId(), Long.valueOf(5847)); + } + + @Test + @Disabled("Unknown fields are now correctly deserialized into `additionalProperties`") + public void testUnknownFields() { + // test unknown fields in the payload + Gson gson = json.getGson(); + // test Tag + String json5 = "{\"unknown_field\": 543, \"id\":\"tag 123\"}"; + Exception exception5 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + org.openapitools.client.model.Tag t5 = gson.fromJson(json5, org.openapitools.client.model.Tag.class); + }); + assertTrue(exception5.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags + String json6 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}"; + Exception exception6 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet t6 = gson.fromJson(json6, Pet.class); + }); + assertTrue(exception6.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags (required) + String json7 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"tags\":[{\"unknown_field\": 543, \"id\":\"tag 123\"}]}"; + Exception exception7 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + PetWithRequiredTags t7 = gson.fromJson(json7, PetWithRequiredTags.class); + }); + assertTrue(exception7.getMessage().contains("The field `unknown_field` in the JSON string is not defined in the `Tag` properties. JSON: {\"unknown_field\":543,\"id\":\"tag 123\"}")); + + // test Pet with invalid tags (missing reqired) + String json8 = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"]}"; + Exception exception8 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + PetWithRequiredTags t8 = gson.fromJson(json8, PetWithRequiredTags.class); + }); + assertTrue(exception8.getMessage().contains("The required field `tags` is not found in the JSON string: {\"id\":5847,\"name\":\"pet test 1\",\"photoUrls\":[\"https://a.com\",\"https://b.com\"]}")); + } + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // test Pet + Pet model = new Pet(); + model.setId(1029L); + model.setName("Dog"); + + Pet model2 = new Pet(); + model2.setId(1029L); + model2.setName("Dog"); + + assertTrue(model.equals(model2)); + } + + // Obtained 22JAN2018 from stackoverflow answer by PuguaSoft + // https://stackoverflow.com/questions/11399491/java-timezone-offset + // Direct link https://stackoverflow.com/a/16680815/3166133 + public static String getCurrentTimezoneOffset() { + + TimeZone tz = TimeZone.getDefault(); + Calendar cal = GregorianCalendar.getInstance(tz, Locale.ROOT); + int offsetInMillis = tz.getOffset(cal.getTimeInMillis()); + + String offset = + String.format( + Locale.ROOT, + "%02d:%02d", + Math.abs(offsetInMillis / 3600000), + Math.abs((offsetInMillis / 60000) % 60)); + offset = (offsetInMillis >= 0 ? "+" : "-") + offset; + + return offset; + } + + /** + * Validate an anyOf schema can be deserialized into the expected class. + * The anyOf schema does not have a discriminator. + */ + @Test + public void testAnyOfSchemaWithoutDiscriminator() throws Exception { + { + String str = "{ \"cultivar\": \"golden delicious\", \"origin\": \"japan\" }"; + + // make sure deserialization works for pojo object + Apple a = json.getGson().fromJson(str, Apple.class); + assertEquals(a.getCultivar(), "golden delicious"); + assertEquals(a.getOrigin(), "japan"); + + GmFruit o = json.getGson().fromJson(str, GmFruit.class); + assertTrue(o.getActualInstance() instanceof Apple); + Apple inst = (Apple) o.getActualInstance(); + assertEquals(inst.getCultivar(), "golden delicious"); + assertEquals(inst.getOrigin(), "japan"); + assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"origin\":\"japan\"}"); + + /* comment out the following as we've added "additionalProperties" support + String str2 = "{ \"origin_typo\": \"japan\" }"; + // no match + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Apple o3 = json.getGson().fromJson(str2, Apple.class); + }); + + // no match + Exception exception3 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Banana o2 = json.getGson().fromJson(str2, Banana.class); + }); + + // no match + Exception exception4 = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + GmFruit o2 = json.getGson().fromJson(str2, GmFruit.class); + }); + */ + } + } + + /** + * Validate a oneOf schema can be deserialized into the expected class. + * The oneOf schema has a discriminator. + */ + @Test + public void testOneOfSchemaWithDiscriminator() throws Exception { + { + String str = "{ \"className\": \"whale\", \"hasBaleen\": false, \"hasTeeth\": false }"; + + // make sure deserialization works for pojo object + Whale w = json.getGson().fromJson(str, Whale.class); + assertEquals(w.getClassName(), "whale"); + assertEquals(w.getHasBaleen(), false); + assertEquals(w.getHasTeeth(), false); + + Mammal o = json.getGson().fromJson(str, Mammal.class); + assertTrue(o.getActualInstance() instanceof Whale); + Whale inst = (Whale) o.getActualInstance(); + assertEquals(inst.getClassName(), "whale"); + assertEquals(inst.getHasBaleen(), false); + assertEquals(inst.getHasTeeth(), false); + assertEquals(json.getGson().toJson(inst), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(inst.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(json.getGson().toJson(o), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + assertEquals(o.toJson(), "{\"hasBaleen\":false,\"hasTeeth\":false,\"className\":\"whale\"}"); + + String str2 = "{ \"className\": \"zebra\", \"type\": \"plains\" }"; + + // make sure deserialization works for pojo object + Zebra z = Zebra.fromJson(str2); + assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + + Mammal o2 = json.getGson().fromJson(str2, Mammal.class); + assertTrue(o2.getActualInstance() instanceof Zebra); + Zebra inst2 = (Zebra) o2.getActualInstance(); + assertEquals(json.getGson().toJson(inst2), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(inst2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(json.getGson().toJson(o2), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + assertEquals(o2.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\"}"); + } + { + // incorrect payload results in exception + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + Mammal o = json.getGson().fromJson(str, Mammal.class); + }); + //assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage()); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for Mammal")); + } + { + // Try to deserialize empty object. This should fail 'oneOf' because none will match + // whale or zebra. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, Mammal.class); + }); + //assertEquals("java.io.IOException: Failed deserialization for Mammal: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for Pig failed with `The JSON string is invalid for Pig with oneOf schemas: BasquePig, DanishPig. 0 class(es) match the result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for BasquePig failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for DanishPig failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}`., Deserialization for Whale failed with `The required field `className` is not found in the JSON string: {}`., Deserialization for Zebra failed with `The required field `className` is not found in the JSON string: {}`.]. JSON: {}", exception.getMessage()); + assertTrue(exception.getMessage().contains("java.io.IOException: Failed deserialization for Mammal")); + } + } + + /** + * Test JSON validation method + */ + @Test + public void testJsonValidation() throws Exception { + String str = "{ \"cultivar\": [\"golden delicious\"], \"mealy\": false }"; + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + AppleReq a = json.getGson().fromJson(str, AppleReq.class); + }); + assertTrue(exception.getMessage().contains("Expected the field `cultivar` to be a primitive type in the JSON string but got `[\"golden delicious\"]`")); + + String str2 = "{ \"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": 123 }"; + Exception exception2 = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet p1 = json.getGson().fromJson(str2, Pet.class); + }); + assertTrue(exception2.getMessage().contains("Expected the field `photoUrls` to be an array in the JSON string but got `123`")); + } + + /** + * Validate a oneOf schema can be deserialized into the expected class. + * The oneOf schema does not have a discriminator. + */ + @Test + public void testOneOfSchemaWithoutDiscriminator() throws Exception { + // BananaReq and AppleReq have explicitly defined properties that are different by name. + // There is no discriminator property. + { + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false }"; + + // make sure deserialization works for pojo object + AppleReq a = json.getGson().fromJson(str, AppleReq.class); + assertEquals(a.getCultivar(), "golden delicious"); + assertEquals(a.getMealy(), false); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof AppleReq); + AppleReq inst = (AppleReq) o.getActualInstance(); + assertEquals(inst.getCultivar(), "golden delicious"); + assertEquals(inst.getMealy(), false); + assertEquals(json.getGson().toJson(inst), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(json.getGson().toJson(o), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(o.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + + AppleReq inst2 = o.getAppleReq(); + assertEquals(inst2.getCultivar(), "golden delicious"); + assertEquals(inst2.getMealy(), false); + assertEquals(json.getGson().toJson(inst2), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst2.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + + // test fromJson + FruitReq o3 = FruitReq.fromJson(str); + assertTrue(o3.getActualInstance() instanceof AppleReq); + AppleReq inst3 = (AppleReq) o3.getActualInstance(); + assertEquals(inst3.getCultivar(), "golden delicious"); + assertEquals(inst3.getMealy(), false); + assertEquals(json.getGson().toJson(inst3), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(inst3.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + assertEquals(o3.toJson(), "{\"cultivar\":\"golden delicious\",\"mealy\":false}"); + } + { + // test to ensure the oneOf object can be serialized to "null" correctly + FruitReq o = new FruitReq(); + assertEquals(o.getActualInstance(), null); + assertEquals(json.getGson().toJson(o), "null"); + assertEquals(o.toJson(), "null"); + assertEquals(json.getGson().toJson(null), "null"); + } + { + // Same test, but this time with additional (undeclared) properties. + // Since FruitReq has additionalProperties: false, deserialization should fail. + String str = "{ \"cultivar\": \"golden delicious\", \"mealy\": false, \"garbage_prop\": \"abc\" }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + }); + assertEquals("java.io.IOException: Failed deserialization for FruitReq: 0 classes match result, expected 1. Detailed failure message for oneOf schemas: [Deserialization for AppleReq failed with `The field `garbage_prop` in the JSON string is not defined in the `AppleReq` properties. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`., Deserialization for BananaReq failed with `The field `cultivar` in the JSON string is not defined in the `BananaReq` properties. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}`.]. JSON: {\"cultivar\":\"golden delicious\",\"mealy\":false,\"garbage_prop\":\"abc\"}", exception.getMessage()); + } + { + String str = "{ \"lengthCm\": 17 }"; + + // make sure deserialization works for pojo object + BananaReq b = json.getGson().fromJson(str, BananaReq.class); + assertEquals(b.getLengthCm(), new java.math.BigDecimal(17)); + + FruitReq o = json.getGson().fromJson(str, FruitReq.class); + assertTrue(o.getActualInstance() instanceof BananaReq); + BananaReq inst = (BananaReq) o.getActualInstance(); + assertEquals(inst.getLengthCm(), new java.math.BigDecimal(17)); + assertEquals(json.getGson().toJson(o), "{\"lengthCm\":17}"); + assertEquals(json.getGson().toJson(inst), "{\"lengthCm\":17}"); + } + { + // Try to deserialize empty object. This should fail 'oneOf' because none will match + // AppleReq or BananaReq. + String str = "{ }"; + Exception exception = assertThrows(com.google.gson.JsonSyntaxException.class, () -> { + json.getGson().fromJson(str, FruitReq.class); + }); + assertTrue(exception.getMessage().contains("Failed deserialization for FruitReq: 0 classes match result, expected 1")); + } + } + + + /** + * Test validateJsonObject with null object + */ + @Test + public void testValidateJsonObject() throws Exception { + JsonObject jsonObject = new JsonObject(); + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet.validateJsonElement(jsonObject); + }); + assertEquals(exception.getMessage(), "The required field `photoUrls` is not found in the JSON string: {}"); + } + + /** + * Test additional properties. + */ + @Test + public void testAdditionalProperties() throws Exception { + String str = "{ \"className\": \"zebra\", \"type\": \"plains\", \"from_json\": 4567, \"from_json_map\": {\"nested_string\": \"nested_value\"} }"; + Zebra z = Zebra.fromJson(str); + z.putAdditionalProperty("new_key", "new_value"); + z.putAdditionalProperty("new_number", 1.23); + z.putAdditionalProperty("new_boolean", true); + org.openapitools.client.model.Tag t = new org.openapitools.client.model.Tag(); + t.setId(34L); + t.setName("just a tag"); + z.putAdditionalProperty("new_object", t); + assertEquals(z.toJson(), "{\"type\":\"plains\",\"className\":\"zebra\",\"new_key\":\"new_value\",\"new_boolean\":true,\"new_object\":{\"id\":34,\"name\":\"just a tag\"},\"from_json\":4567,\"from_json_map\":{\"nested_string\":\"nested_value\"},\"new_number\":1.23}"); + } + + + @Test + public void testInvalidEnumValueException() { + // test Pet with invalid status + String str = "{\"id\": 5847, \"name\":\"pet test 1\", \"photoUrls\": [\"https://a.com\", \"https://b.com\"],\"status\":\"sleeping\"}"; + Exception exception = assertThrows(java.lang.IllegalArgumentException.class, () -> { + Pet t7 = Pet.fromJson(str); + }); + assertTrue(exception.getMessage().contains("Unexpected value 'sleeping'")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java new file mode 100644 index 000000000000..c946674e470a --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/StringUtilTest.java @@ -0,0 +1,33 @@ +package org.openapitools.client; + +import static org.junit.jupiter.api.Assertions.*; + +import org.junit.jupiter.api.*; + +public class StringUtilTest { + @Test + public void testContainsIgnoreCase() { + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{"ABC"}, "abc")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, "ABC")); + assertTrue(StringUtil.containsIgnoreCase(new String[]{null, "abc"}, null)); + + assertFalse(StringUtil.containsIgnoreCase(new String[]{"abc"}, "def")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, "ABC")); + assertFalse(StringUtil.containsIgnoreCase(new String[]{}, null)); + } + + @Test + public void testJoin() { + String[] array = {"aa", "bb", "cc"}; + assertEquals("aa,bb,cc", StringUtil.join(array, ",")); + assertEquals("aa, bb, cc", StringUtil.join(array, ", ")); + assertEquals("aabbcc", StringUtil.join(array, "")); + assertEquals("aa bb cc", StringUtil.join(array, " ")); + assertEquals("aa\nbb\ncc", StringUtil.join(array, "\n")); + + assertEquals("", StringUtil.join(new String[]{}, ",")); + assertEquals("abc", StringUtil.join(new String[]{"abc"}, ",")); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java index face3d9b785e..0f49c5e2e01c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/AnotherFakeApiTest.java @@ -2,31 +2,23 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * The version of the OpenAPI document: 1.0.0 - * + * OpenAPI spec version: 1.0.0 + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - package org.openapitools.client.api; -import org.openapitools.client.ApiException; -import java.math.BigDecimal; -import org.openapitools.client.model.Client; + import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Client; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for AnotherFakeApi - */ +/** API tests for AnotherFakeApi */ @Disabled public class AnotherFakeApiTest { @@ -35,39 +27,15 @@ public class AnotherFakeApiTest { /** * To test special tags * - * To test special tags and operation ID starting with number + *

              To test special tags and operation ID starting with number * * @throws ApiException if the Api call fails */ @Test public void call123testSpecialTagsTest() throws ApiException { - Client client = null; - Client response = api.call123testSpecialTags(client); - // TODO: test validations - } + Client body = null; + Client response = api.call123testSpecialTags(body); - /** - * parameter array number default value - * - * @throws ApiException if the Api call fails - */ - @Test - public void getParameterArrayNumberTest() throws ApiException { - List array = null; - api.getParameterArrayNumber(array); - // TODO: test validations - } - - /** - * parameter string number - * - * @throws ApiException if the Api call fails - */ - @Test - public void getParameterStringNumberTest() throws ApiException { - BigDecimal stringNumber = null; - api.getParameterStringNumber(stringNumber); // TODO: test validations } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java index badfac3b4cc2..4dea80f5e403 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeApiTest.java @@ -24,8 +24,8 @@ import org.openapitools.client.model.OuterComposite; import org.openapitools.client.model.OuterEnum; import org.openapitools.client.model.User; -import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.Disabled; import java.util.ArrayList; import java.util.HashMap; @@ -40,133 +40,148 @@ public class FakeApiTest { private final FakeApi api = new FakeApi(); + /** * Health check endpoint * - * @throws ApiException if the Api call fails + * + * + * @throws ApiException + * if the Api call fails */ @Test public void fakeHealthGetTest() throws ApiException { - HealthCheckResult response = api.fakeHealthGet(); + HealthCheckResult response = api.fakeHealthGet(); // TODO: test validations } - + /** + * + * * Test serialization of outer boolean types * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void fakeOuterBooleanSerializeTest() throws ApiException { Boolean body = null; - Boolean response = api.fakeOuterBooleanSerialize(body); + Boolean response = api.fakeOuterBooleanSerialize(body); // TODO: test validations } - + /** + * + * * Test serialization of object with outer number type * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void fakeOuterCompositeSerializeTest() throws ApiException { OuterComposite outerComposite = null; - OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); + OuterComposite response = api.fakeOuterCompositeSerialize(outerComposite); // TODO: test validations } - + /** + * + * * Test serialization of outer number types * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void fakeOuterNumberSerializeTest() throws ApiException { BigDecimal body = null; - BigDecimal response = api.fakeOuterNumberSerialize(body); + BigDecimal response = api.fakeOuterNumberSerialize(body); // TODO: test validations } - + /** + * + * * Test serialization of outer string types * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void fakeOuterStringSerializeTest() throws ApiException { String body = null; - String response = api.fakeOuterStringSerialize(body); + String response = api.fakeOuterStringSerialize(body); // TODO: test validations } - + /** * Array of Enums * - * @throws ApiException if the Api call fails + * + * + * @throws ApiException + * if the Api call fails */ @Test public void getArrayOfEnumsTest() throws ApiException { - List response = api.getArrayOfEnums(); + List response = api.getArrayOfEnums(); // TODO: test validations } - + /** - * parameter name mapping test + * * - * @throws ApiException if the Api call fails - */ - @Test - public void getParameterNameMappingTest() throws ApiException { - Long underscoreType = null; - String type = null; - String typeWithUnderscore = null; - api.getParameterNameMapping(underscoreType, type, typeWithUnderscore); - // TODO: test validations - } - - /** * For this test, the body for this request much reference a schema named `File`. * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testBodyWithFileSchemaTest() throws ApiException { FileSchemaTestClass fileSchemaTestClass = null; - api.testBodyWithFileSchema(fileSchemaTestClass); + api.testBodyWithFileSchema(fileSchemaTestClass); // TODO: test validations } - + /** - * @throws ApiException if the Api call fails + * + * + * + * + * @throws ApiException + * if the Api call fails */ @Test public void testBodyWithQueryParamsTest() throws ApiException { String query = null; User user = null; - api.testBodyWithQueryParams(query, user); + api.testBodyWithQueryParams(query, user); // TODO: test validations } - + /** * To test \"client\" model * * To test \"client\" model * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testClientModelTest() throws ApiException { Client client = null; - Client response = api.testClientModel(client); + Client response = api.testClientModel(client); // TODO: test validations } - + /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testEndpointParametersTest() throws ApiException { @@ -184,16 +199,17 @@ public void testEndpointParametersTest() throws ApiException { OffsetDateTime dateTime = null; String password = null; String paramCallback = null; - api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); + api.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, paramCallback); // TODO: test validations } - + /** * To test enum parameters * * To test enum parameters * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testEnumParametersTest() throws ApiException { @@ -205,16 +221,17 @@ public void testEnumParametersTest() throws ApiException { Double enumQueryDouble = null; List enumFormStringArray = null; String enumFormString = null; - api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); + api.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString); // TODO: test validations } - + /** * Fake endpoint to test group parameters (optional) * * Fake endpoint to test group parameters (optional) * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testGroupParametersTest() throws ApiException { @@ -224,47 +241,52 @@ public void testGroupParametersTest() throws ApiException { Integer stringGroup = null; Boolean booleanGroup = null; Long int64Group = null; - api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) + api.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group) .stringGroup(stringGroup) .booleanGroup(booleanGroup) .int64Group(int64Group) .execute(); // TODO: test validations } - + /** * test inline additionalProperties * * * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testInlineAdditionalPropertiesTest() throws ApiException { Map requestBody = null; - api.testInlineAdditionalProperties(requestBody); + api.testInlineAdditionalProperties(requestBody); // TODO: test validations } - + /** * test json serialization of form data * * * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testJsonFormDataTest() throws ApiException { String param = null; String param2 = null; - api.testJsonFormData(param, param2); + api.testJsonFormData(param, param2); // TODO: test validations } - + /** + * + * * To test the collection format in query parameters * - * @throws ApiException if the Api call fails + * @throws ApiException + * if the Api call fails */ @Test public void testQueryParameterCollectionFormatTest() throws ApiException { @@ -273,8 +295,8 @@ public void testQueryParameterCollectionFormatTest() throws ApiException { List http = null; List url = null; List context = null; - api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); + api.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context); // TODO: test validations } - + } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java index aa1b824dd5a2..3eb19491b9b0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/FakeClassnameTags123ApiTest.java @@ -2,30 +2,23 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * The version of the OpenAPI document: 1.0.0 - * + * OpenAPI spec version: 1.0.0 + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - package org.openapitools.client.api; -import org.openapitools.client.ApiException; -import org.openapitools.client.model.Client; + import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Client; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -/** - * API tests for FakeClassnameTags123Api - */ +/** API tests for FakeClassnameTags123Api */ @Disabled public class FakeClassnameTags123ApiTest { @@ -34,15 +27,15 @@ public class FakeClassnameTags123ApiTest { /** * To test class name in snake case * - * To test class name in snake case + *

              To test class name in snake case * * @throws ApiException if the Api call fails */ @Test public void testClassnameTest() throws ApiException { - Client client = null; - Client response = api.testClassname(client); + Client body = null; + Client response = api.testClassname(body); + // TODO: test validations } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java new file mode 100644 index 000000000000..89fe1d01c460 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/PetApiTest.java @@ -0,0 +1,579 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * OpenAPI spec version: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + +package org.openapitools.client.api; + +import static org.junit.jupiter.api.Assertions.*; + +import java.io.BufferedWriter; +import java.io.File; +import java.io.FileWriter; +import java.lang.reflect.Type; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.ConcurrentLinkedQueue; +import java.util.concurrent.CountDownLatch; +import java.util.concurrent.ThreadLocalRandom; +import java.util.concurrent.TimeUnit; + +import org.junit.jupiter.api.*; +import org.openapitools.client.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.auth.*; +import org.openapitools.client.model.*; +import org.openapitools.client.model.Pet; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * API tests for PetApi + */ +public class PetApiTest { + + private PetApi api = new PetApi(); + private final Logger LOG = LoggerFactory.getLogger(PetApiTest.class); + // In the circle.yml file, /etc/host is configured with an entry to resolve petstore.swagger.io + // to 127.0.0.1 + private static String basePath = "http://petstore.swagger.io:80/v2"; + + @BeforeEach + public void setup() { + // setup authentication + ApiKeyAuth apiKeyAuth = (ApiKeyAuth) api.getApiClient().getAuthentication("api_key"); + apiKeyAuth.setApiKey("special-key"); + api.getApiClient().setBasePath(basePath); + } + + @Test + public void testApiClient() { + // the default api client is used + assertEquals(Configuration.getDefaultApiClient(), api.getApiClient()); + assertNotNull(api.getApiClient()); + assertEquals(basePath, api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + + ApiClient oldClient = api.getApiClient(); + + ApiClient newClient = new ApiClient(); + newClient.setVerifyingSsl(true); + newClient.setBasePath("http://example.com"); + newClient.setDebugging(true); + + // set api client via constructor + api = new PetApi(newClient); + assertNotNull(api.getApiClient()); + assertEquals("http://example.com", api.getApiClient().getBasePath()); + assertTrue(api.getApiClient().isDebugging()); + + // set api client via setter method + api.setApiClient(oldClient); + assertNotNull(api.getApiClient()); + assertEquals(basePath, api.getApiClient().getBasePath()); + assertFalse(api.getApiClient().isDebugging()); + } + + @Test + public void testCreateAndGetPet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetWithHttpInfo() throws Exception { + Pet pet = createPet(); + api.addPetWithHttpInfo(pet); + + ApiResponse resp = api.getPetByIdWithHttpInfo(pet.getId()); + assertEquals(200, resp.getStatusCode()); + assertEquals("application/json", resp.getHeaders().get("Content-Type").get(0)); + Pet fetched = resp.getData(); + + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetAsync() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + api.getPetByIdAsync( + pet.getId(), + new ApiCallback() { + @Override + public void onFailure( + ApiException e, + int statusCode, + Map> responseHeaders) { + result.put("error", e.getMessage()); + } + + @Override + public void onSuccess( + Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress( + long bytesWritten, long contentLength, boolean done) { + // empty + } + + @Override + public void onDownloadProgress( + long bytesRead, long contentLength, boolean done) { + // empty + } + }); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("error") != null) fail((String) result.get("error")); + if (result.get("pet") != null) { + fetched = (Pet) result.get("pet"); + break; + } + } while (result.isEmpty()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetPetAsyncInvalidID() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + // to store returned Pet or error message/exception + final Map result = new HashMap(); + + // test getting a nonexistent pet + result.clear(); + api.getPetByIdAsync( + -10000L, + new ApiCallback() { + @Override + public void onFailure( + ApiException e, + int statusCode, + Map> responseHeaders) { + result.put("exception", e); + } + + @Override + public void onSuccess( + Pet pet, int statusCode, Map> responseHeaders) { + result.put("pet", pet); + } + + @Override + public void onUploadProgress( + long bytesWritten, long contentLength, boolean done) { + // empty + } + + @Override + public void onDownloadProgress( + long bytesRead, long contentLength, boolean done) { + // empty + } + }); + + // wait for the asynchronous call to finish (at most 10 seconds) + final int maxTry = 10; + int tryCount = 1; + Pet fetched = null; + ApiException exception = null; + + do { + if (tryCount > maxTry) fail("have not got result of getPetByIdAsync after 10 seconds"); + Thread.sleep(1000); + tryCount += 1; + if (result.get("pet") != null) fail("expected an error"); + if (result.get("exception") != null) { + exception = (ApiException) result.get("exception"); + break; + } + } while (result.isEmpty()); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + String pattern = "^Message: Not Found\\RHTTP response code: 404\\RHTTP response body: .*\\RHTTP response headers: .*$"; + assertTrue(exception.getMessage().matches(pattern)); + assertEquals("application/json", exception.getResponseHeaders().get("Content-Type").get(0)); + api.deletePet(pet.getId(), null); + } + + @Test + public void testCreateAndGetMultiplePetsAsync() throws Exception { + Pet pet1 = createPet(); + Pet pet2 = createPet(); + + final CountDownLatch addLatch = new CountDownLatch(2); + final TestApiCallback addCallback1 = new TestApiCallback(addLatch); + final TestApiCallback addCallback2 = new TestApiCallback(addLatch); + + // Make 2 simultaneous calls + api.addPetAsync(pet1, addCallback1); + api.addPetAsync(pet2, addCallback2); + + // wait for both asynchronous calls to finish (at most 10 seconds) + assertTrue(addLatch.await(10, TimeUnit.SECONDS)); + + assertTrue(addCallback1.isDone()); + assertTrue(addCallback2.isDone()); + + if (!addCallback1.isSuccess()) throw addCallback1.getException(); + if (!addCallback2.isSuccess()) throw addCallback2.getException(); + + assertValidProgress(addCallback1.getUploadProgress()); + assertValidProgress(addCallback2.getUploadProgress()); + + final CountDownLatch getLatch = new CountDownLatch(3); + final TestApiCallback getCallback1 = new TestApiCallback(getLatch); + final TestApiCallback getCallback2 = new TestApiCallback(getLatch); + final TestApiCallback getCallback3 = new TestApiCallback(getLatch); + + api.getPetByIdAsync(pet1.getId(), getCallback1); + api.getPetByIdAsync(pet2.getId(), getCallback2); + // Get nonexistent pet + api.getPetByIdAsync(-10000L, getCallback3); + + // wait for all asynchronous calls to finish (at most 10 seconds) + assertTrue(getLatch.await(10, TimeUnit.SECONDS)); + + assertTrue(getCallback1.isDone()); + assertTrue(getCallback2.isDone()); + assertTrue(getCallback3.isDone()); + + if (!getCallback1.isSuccess()) throw getCallback1.getException(); + if (!getCallback2.isSuccess()) throw getCallback2.getException(); + + assertPetMatches(pet1, getCallback1.getResult()); + assertPetMatches(pet2, getCallback2.getResult()); + + assertValidProgress(getCallback1.getDownloadProgress()); + assertValidProgress(getCallback2.getDownloadProgress()); + + // Last callback should fail with ApiException + assertFalse(getCallback3.isSuccess()); + final ApiException exception = getCallback3.getException(); + assertNotNull(exception); + assertEquals(404, exception.getCode()); + api.deletePet(pet1.getId(), null); + api.deletePet(pet2.getId(), null); + } + + @Test + public void testUpdatePet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + pet.setName("programmer"); + + api.updatePet(pet); + + Pet fetched = api.getPetById(pet.getId()); + assertPetMatches(pet, fetched); + api.deletePet(pet.getId(), null); + } + + @Test + public void testFindPetsByStatus() throws Exception { + assertEquals(basePath, api.getApiClient().getBasePath()); + Pet pet = createPet(); + api.addPet(pet); + pet.setName("programmer"); + pet.setStatus(Pet.StatusEnum.PENDING); + api.updatePet(pet); + + List pets = api.findPetsByStatus(Arrays.asList("pending")); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + @Disabled + public void testFindPetsByTags() throws Exception { + Pet pet = createPet(); + pet.setName("monster"); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + + List tags = new ArrayList(); + org.openapitools.client.model.Tag tag1 = new org.openapitools.client.model.Tag(); + tag1.setName("friendly"); + tags.add(tag1); + pet.setTags(tags); + + api.updatePet(pet); + + List pets = api.findPetsByTags((Arrays.asList("friendly"))); + assertNotNull(pets); + + boolean found = false; + for (Pet fetched : pets) { + if (fetched.getId().equals(pet.getId())) { + found = true; + break; + } + } + assertTrue(found); + + api.deletePet(pet.getId(), null); + } + + @Test + public void testUpdatePetWithForm() throws Exception { + Pet pet = createPet(); + pet.setName("frank"); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + + api.updatePetWithForm(fetched.getId(), "furt", null); + Pet updated = api.getPetById(fetched.getId()); + + assertEquals(updated.getName(), "furt"); + api.deletePet(pet.getId(), null); + } + + @Test + @Disabled + public void testDeletePet() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + Pet fetched = api.getPetById(pet.getId()); + api.deletePet(pet.getId(), null); + + try { + fetched = api.getPetById(fetched.getId()); + fail("expected an error"); + } catch (ApiException e) { + LOG.info("Code: {}. Message: {}", e.getCode(), e.getMessage()); + assertEquals(404, e.getCode()); + } + } + + @Test + public void testUploadFile() throws Exception { + Pet pet = createPet(); + api.addPet(pet); + + File file = new File("hello.txt"); + BufferedWriter writer = new BufferedWriter(new FileWriter(file)); + writer.write("Hello world!"); + writer.close(); + + api.uploadFile(pet.getId(), "a test file", new File(file.getAbsolutePath())); + api.deletePet(pet.getId(), null); + } + + @Test + public void testEqualsAndHashCode() { + Pet pet1 = new Pet(); + Pet pet2 = new Pet(); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + + pet2.setName("really-happy"); + pet2.setPhotoUrls( + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"))); + assertFalse(pet1.equals(pet2)); + assertFalse(pet2.equals(pet1)); + assertFalse(pet1.hashCode() == (pet2.hashCode())); + assertTrue(pet2.equals(pet2)); + assertTrue(pet2.hashCode() == pet2.hashCode()); + + pet1.setName("really-happy"); + pet1.setPhotoUrls( + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2"))); + assertTrue(pet1.equals(pet2)); + assertTrue(pet2.equals(pet1)); + assertTrue(pet1.hashCode() == pet2.hashCode()); + assertTrue(pet1.equals(pet1)); + assertTrue(pet1.hashCode() == pet1.hashCode()); + } + + private Pet createPet() { + Pet pet = new Pet(); + pet.setId(ThreadLocalRandom.current().nextLong(Long.MAX_VALUE)); + pet.setName("gorilla"); + + Category category = new Category(); + category.setName("really-happy"); + + pet.setCategory(category); + pet.setStatus(Pet.StatusEnum.AVAILABLE); + List photos = + (Arrays.asList("http://foo.bar.com/1", "http://foo.bar.com/2")); + pet.setPhotoUrls(photos); + + return pet; + } + + private String serializeJson(Object o, ApiClient apiClient) { + return apiClient.getJSON().serialize(o); + } + + private T deserializeJson(String json, Type type, ApiClient apiClient) { + return (T) apiClient.getJSON().deserialize(json, type); + } + + private void assertPetMatches(Pet expected, Pet actual) { + assertNotNull(actual); + assertEquals(expected.getId(), actual.getId()); + assertNotNull(actual.getCategory()); + assertEquals(expected.getCategory().getName(), actual.getCategory().getName()); + } + + /** + * Assert that the given upload/download progress list satisfies the following constraints: + * + *

              - List is not empty - Byte count should be nondecreasing - The last element, and only the + * last element, should have done=true + */ + private void assertValidProgress(List progressList) { + assertFalse(progressList.isEmpty()); + + Progress prev = null; + int index = 0; + for (Progress progress : progressList) { + if (prev != null) { + if (prev.done || prev.bytes > progress.bytes) { + fail("Progress list out of order at index " + index + ": " + progressList); + } + } + prev = progress; + index += 1; + } + + if (!prev.done) { + fail("Last progress item should have done=true: " + progressList); + } + } + + private static class TestApiCallback implements ApiCallback { + + private final CountDownLatch latch; + private final ConcurrentLinkedQueue uploadProgress = + new ConcurrentLinkedQueue(); + private final ConcurrentLinkedQueue downloadProgress = + new ConcurrentLinkedQueue(); + + private boolean done; + private boolean success; + private ApiException exception; + private T result; + + public TestApiCallback(CountDownLatch latch) { + this.latch = latch; + this.done = false; + } + + @Override + public void onFailure( + ApiException e, int statusCode, Map> responseHeaders) { + exception = e; + this.done = true; + this.success = false; + latch.countDown(); + } + + @Override + public void onSuccess(T result, int statusCode, Map> responseHeaders) { + this.result = result; + this.done = true; + this.success = true; + latch.countDown(); + } + + @Override + public void onUploadProgress(long bytesWritten, long contentLength, boolean done) { + uploadProgress.add(new Progress(bytesWritten, contentLength, done)); + } + + @Override + public void onDownloadProgress(long bytesRead, long contentLength, boolean done) { + downloadProgress.add(new Progress(bytesRead, contentLength, done)); + } + + public boolean isDone() { + return done; + } + + public boolean isSuccess() { + return success; + } + + public ApiException getException() { + return exception; + } + + public T getResult() { + return result; + } + + public List getUploadProgress() { + return new ArrayList(uploadProgress); + } + + public List getDownloadProgress() { + return new ArrayList(downloadProgress); + } + } + + private static class Progress { + public final long bytes; + public final long contentLength; + public final boolean done; + + public Progress(long bytes, long contentLength, boolean done) { + this.bytes = bytes; + this.contentLength = contentLength; + this.done = done; + } + + @Override + public String toString() { + return ""; + } + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/StoreApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/StoreApiTest.java index 98354ba10c08..b9c5785e5ca3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/StoreApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/StoreApiTest.java @@ -2,30 +2,24 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * The version of the OpenAPI document: 1.0.0 - * + * OpenAPI spec version: 1.0.0 + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - package org.openapitools.client.api; -import org.openapitools.client.ApiException; -import org.openapitools.client.model.Order; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; import java.util.Map; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.Order; -/** - * API tests for StoreApi - */ +/** API tests for StoreApi */ @Disabled public class StoreApiTest { @@ -34,7 +28,8 @@ public class StoreApiTest { /** * Delete purchase order by ID * - * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + *

              For valid response try integer IDs with value < 1000. Anything above 1000 or + * nonintegers will generate API errors * * @throws ApiException if the Api call fails */ @@ -42,26 +37,29 @@ public class StoreApiTest { public void deleteOrderTest() throws ApiException { String orderId = null; api.deleteOrder(orderId); + // TODO: test validations } /** * Returns pet inventories by status * - * Returns a map of status codes to quantities + *

              Returns a map of status codes to quantities * * @throws ApiException if the Api call fails */ @Test public void getInventoryTest() throws ApiException { Map response = api.getInventory(); + // TODO: test validations } /** * Find purchase order by ID * - * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + *

              For valid response try integer IDs with value <= 5 or > 10. Other values will + * generated exceptions * * @throws ApiException if the Api call fails */ @@ -69,21 +67,20 @@ public void getInventoryTest() throws ApiException { public void getOrderByIdTest() throws ApiException { Long orderId = null; Order response = api.getOrderById(orderId); + // TODO: test validations } /** * Place an order for a pet * - * - * * @throws ApiException if the Api call fails */ @Test public void placeOrderTest() throws ApiException { - Order order = null; - Order response = api.placeOrder(order); + Order body = null; + Order response = api.placeOrder(body); + // TODO: test validations } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/UserApiTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/UserApiTest.java index aa9aff49b4df..50a958f2fd01 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/UserApiTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/api/UserApiTest.java @@ -2,31 +2,24 @@ * OpenAPI Petstore * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ * - * The version of the OpenAPI document: 1.0.0 - * + * OpenAPI spec version: 1.0.0 + * * * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). * https://openapi-generator.tech * Do not edit the class manually. */ - package org.openapitools.client.api; -import org.openapitools.client.ApiException; -import java.time.OffsetDateTime; -import org.openapitools.client.model.User; -import org.junit.jupiter.api.Disabled; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.HashMap; import java.util.List; -import java.util.Map; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; +import org.openapitools.client.ApiException; +import org.openapitools.client.model.User; -/** - * API tests for UserApi - */ +/** API tests for UserApi */ @Disabled public class UserApiTest { @@ -35,49 +28,48 @@ public class UserApiTest { /** * Create user * - * This can only be done by the logged in user. + *

              This can only be done by the logged in user. * * @throws ApiException if the Api call fails */ @Test public void createUserTest() throws ApiException { - User user = null; - api.createUser(user); + User body = null; + api.createUser(body); + // TODO: test validations } /** * Creates list of users with given input array * - * - * * @throws ApiException if the Api call fails */ @Test public void createUsersWithArrayInputTest() throws ApiException { - List user = null; - api.createUsersWithArrayInput(user); + List body = null; + api.createUsersWithArrayInput(body); + // TODO: test validations } /** * Creates list of users with given input array * - * - * * @throws ApiException if the Api call fails */ @Test public void createUsersWithListInputTest() throws ApiException { - List user = null; - api.createUsersWithListInput(user); + List body = null; + api.createUsersWithListInput(body); + // TODO: test validations } /** * Delete user * - * This can only be done by the logged in user. + *

              This can only be done by the logged in user. * * @throws ApiException if the Api call fails */ @@ -85,28 +77,26 @@ public void createUsersWithListInputTest() throws ApiException { public void deleteUserTest() throws ApiException { String username = null; api.deleteUser(username); + // TODO: test validations } /** * Get user by user name * - * - * * @throws ApiException if the Api call fails */ @Test public void getUserByNameTest() throws ApiException { String username = null; User response = api.getUserByName(username); + // TODO: test validations } /** * Logs user into the system * - * - * * @throws ApiException if the Api call fails */ @Test @@ -114,35 +104,35 @@ public void loginUserTest() throws ApiException { String username = null; String password = null; String response = api.loginUser(username, password); + // TODO: test validations } /** * Logs out current logged in user session * - * - * * @throws ApiException if the Api call fails */ @Test public void logoutUserTest() throws ApiException { api.logoutUser(); + // TODO: test validations } /** * Updated user * - * This can only be done by the logged in user. + *

              This can only be done by the logged in user. * * @throws ApiException if the Api call fails */ @Test public void updateUserTest() throws ApiException { String username = null; - User user = null; - api.updateUser(username, user); + User body = null; + api.updateUser(username, body); + // TODO: test validations } - } diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java new file mode 100644 index 000000000000..c4b8362967d0 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/ApiKeyAuthTest.java @@ -0,0 +1,119 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class ApiKeyAuthTest { + @Test + public void testApplyToParamsInQuery() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey("my-api-key"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + assertEquals(1, queryParams.size()); + for (Pair queryParam : queryParams) { + assertEquals("my-api-key", queryParam.getValue()); + } + + // no changes to header or cookie parameters + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInQueryWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("query", "api_key"); + auth.setApiKey(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(0, cookieParams.size()); + } + + @Test + public void testApplyToParamsInHeaderWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + assertEquals("Token my-api-token", headerParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInHeaderWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("header", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } + + @Test + public void testApplyToParamsInCookieWithPrefix() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey("my-api-token"); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or header parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + assertEquals(1, cookieParams.size()); + assertEquals("Token my-api-token", cookieParams.get("X-API-TOKEN")); + } + + @Test + public void testApplyToParamsInCookieWithNullValue() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + ApiKeyAuth auth = new ApiKeyAuth("cookie", "X-API-TOKEN"); + auth.setApiKey(null); + auth.setApiKeyPrefix("Token"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java new file mode 100644 index 000000000000..1230a9d9d2e9 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/HttpBasicAuthTest.java @@ -0,0 +1,65 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.*; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.*; +import org.openapitools.client.ApiException; +import org.openapitools.client.Pair; + +public class HttpBasicAuthTest { + HttpBasicAuth auth = null; + + @BeforeEach + public void setup() { + auth = new HttpBasicAuth(); + } + + @Test + public void testApplyToParams() throws ApiException { + List queryParams = new ArrayList(); + Map headerParams = new HashMap(); + Map cookieParams = new HashMap(); + + auth.setUsername("my-username"); + auth.setPassword("my-password"); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + + // no changes to query or cookie parameters + assertEquals(0, queryParams.size()); + assertEquals(0, cookieParams.size()); + assertEquals(1, headerParams.size()); + // the string below is base64-encoded result of "my-username:my-password" with the "Basic " + // prefix + String expected = "Basic bXktdXNlcm5hbWU6bXktcGFzc3dvcmQ="; + assertEquals(expected, headerParams.get("Authorization")); + + // null username should be treated as empty string + auth.setUsername(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of ":my-password" with the "Basic " prefix + expected = "Basic Om15LXBhc3N3b3Jk"; + assertEquals(expected, headerParams.get("Authorization")); + + // null password should be treated as empty string + auth.setUsername("my-username"); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // the string below is base64-encoded result of "my-username:" with the "Basic " prefix + expected = "Basic bXktdXNlcm5hbWU6"; + assertEquals(expected, headerParams.get("Authorization")); + + // null username and password should be ignored + queryParams = new ArrayList(); + headerParams = new HashMap(); + auth.setUsername(null); + auth.setPassword(null); + auth.applyToParams(queryParams, headerParams, cookieParams, null, null, null); + // no changes to parameters + assertEquals(0, queryParams.size()); + assertEquals(0, headerParams.size()); + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java new file mode 100644 index 000000000000..13d9276a7874 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/auth/RetryingOAuthTest.java @@ -0,0 +1,124 @@ +package org.openapitools.client.auth; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.net.HttpURLConnection; +import java.util.Collections; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.Future; + +import okhttp3.*; +import okhttp3.Interceptor.Chain; +import okhttp3.Response.Builder; +import org.apache.commons.lang3.reflect.FieldUtils; +import org.apache.oltu.oauth2.client.OAuthClient; +import org.apache.oltu.oauth2.client.request.OAuthClientRequest; +import org.apache.oltu.oauth2.client.response.OAuthJSONAccessTokenResponse; +import org.apache.oltu.oauth2.common.exception.OAuthProblemException; +import org.apache.oltu.oauth2.common.exception.OAuthSystemException; +import org.junit.jupiter.api.*; +import org.junit.jupiter.api.Test; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +public class RetryingOAuthTest { + + private RetryingOAuth oauth; + + @BeforeEach + public void setUp() throws Exception { + oauth = + new RetryingOAuth( + "_clientId", + "_clientSecret", + OAuthFlow.ACCESS_CODE, + "https://token.example.com", + Collections.emptyMap()); + oauth.setAccessToken("expired-access-token"); + FieldUtils.writeField(oauth, "oAuthClient", mockOAuthClient(), true); + } + + @Test + public void testSingleRequestUnauthorized() throws Exception { + Response response = oauth.intercept(mockChain()); + assertEquals(HttpURLConnection.HTTP_OK, response.code()); + } + + @Test + public void testTwoConcurrentRequestsUnauthorized() throws Exception { + + Callable callable = + new Callable() { + @Override + public Response call() throws Exception { + return oauth.intercept(mockChain()); + } + }; + ExecutorService executor = Executors.newFixedThreadPool(2); + try { + Future response1 = executor.submit(callable); + Future response2 = executor.submit(callable); + + assertEquals(HttpURLConnection.HTTP_OK, response1.get().code()); + assertEquals(HttpURLConnection.HTTP_OK, response2.get().code()); + } finally { + executor.shutdown(); + } + } + + private OAuthClient mockOAuthClient() throws OAuthProblemException, OAuthSystemException { + OAuthJSONAccessTokenResponse response = mock(OAuthJSONAccessTokenResponse.class); + when(response.getAccessToken()) + .thenAnswer( + new Answer() { + @Override + public String answer(InvocationOnMock invocation) throws Throwable { + // sleep ensures that the bug is triggered. + Thread.sleep(1000); + return "new-access-token"; + } + }); + + OAuthClient client = mock(OAuthClient.class); + when(client.accessToken(any(OAuthClientRequest.class))).thenReturn(response); + return client; + } + + private Chain mockChain() throws IOException { + Chain chain = mock(Chain.class); + + final Request request = new Request.Builder().url("https://api.example.com").build(); + when(chain.request()).thenReturn(request); + + when(chain.proceed(any(Request.class))) + .thenAnswer( + new Answer() { + @Override + public Response answer(InvocationOnMock inv) { + Request r = inv.getArgument(0); + int responseCode = + "Bearer new-access-token".equals(r.header("Authorization")) + ? HttpURLConnection.HTTP_OK + : HttpURLConnection.HTTP_UNAUTHORIZED; + return new Builder() + .protocol(Protocol.HTTP_1_0) + .message("sup") + .request(request) + .body( + ResponseBody.create( + new byte[0], + MediaType.get("application/test"))) + .code(responseCode) + .build(); + } + }); + + return chain; + } +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java index 4d17345a18e7..074e6add3cc7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AdditionalPropertiesClassTest.java @@ -19,13 +19,13 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.openapitools.jackson.nullable.JsonNullable; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for AdditionalPropertiesClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java new file mode 100644 index 000000000000..089fe1a41581 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesCTest.java @@ -0,0 +1,127 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.time.OffsetDateTime; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Order; +import org.openapitools.client.model.Pet; +import org.openapitools.client.model.Tag; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfAttributesC + */ +public class AllOfModelArrayAnyOfAllOfAttributesCTest { + private final AllOfModelArrayAnyOfAllOfAttributesC model = new AllOfModelArrayAnyOfAllOfAttributesC(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfAttributesC + */ + @Test + public void testAllOfModelArrayAnyOfAllOfAttributesC() { + // TODO: test AllOfModelArrayAnyOfAllOfAttributesC + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + + /** + * Test the property 'petId' + */ + @Test + public void petIdTest() { + // TODO: test petId + } + + /** + * Test the property 'quantity' + */ + @Test + public void quantityTest() { + // TODO: test quantity + } + + /** + * Test the property 'shipDate' + */ + @Test + public void shipDateTest() { + // TODO: test shipDate + } + + /** + * Test the property 'complete' + */ + @Test + public void completeTest() { + // TODO: test complete + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java new file mode 100644 index 000000000000..f8f0bf62726b --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfAttributesTest.java @@ -0,0 +1,49 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfAttributesC; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfAttributes + */ +public class AllOfModelArrayAnyOfAllOfAttributesTest { + private final AllOfModelArrayAnyOfAllOfAttributes model = new AllOfModelArrayAnyOfAllOfAttributes(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfAttributes + */ + @Test + public void testAllOfModelArrayAnyOfAllOfAttributes() { + // TODO: test AllOfModelArrayAnyOfAllOfAttributes + } + + /** + * Test the property 'C' + */ + @Test + public void CTest() { + // TODO: test C + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java new file mode 100644 index 000000000000..26c849b8bc32 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1Test.java @@ -0,0 +1,51 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1Value; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ +public class AllOfModelArrayAnyOfAllOfLinkListColumn1Test { + private final AllOfModelArrayAnyOfAllOfLinkListColumn1 model = new AllOfModelArrayAnyOfAllOfLinkListColumn1(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1 + */ + @Test + public void testAllOfModelArrayAnyOfAllOfLinkListColumn1() { + // TODO: test AllOfModelArrayAnyOfAllOfLinkListColumn1 + } + + /** + * Test the property 'value' + */ + @Test + public void valueTest() { + // TODO: test value + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java new file mode 100644 index 000000000000..23dc059e6fce --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest.java @@ -0,0 +1,147 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.Tag; +import org.openapitools.client.model.User; +import org.openapitools.jackson.nullable.JsonNullable; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ +public class AllOfModelArrayAnyOfAllOfLinkListColumn1ValueTest { + private final AllOfModelArrayAnyOfAllOfLinkListColumn1Value model = new AllOfModelArrayAnyOfAllOfLinkListColumn1Value(); + + /** + * Model tests for AllOfModelArrayAnyOfAllOfLinkListColumn1Value + */ + @Test + public void testAllOfModelArrayAnyOfAllOfLinkListColumn1Value() { + // TODO: test AllOfModelArrayAnyOfAllOfLinkListColumn1Value + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'username' + */ + @Test + public void usernameTest() { + // TODO: test username + } + + /** + * Test the property 'firstName' + */ + @Test + public void firstNameTest() { + // TODO: test firstName + } + + /** + * Test the property 'lastName' + */ + @Test + public void lastNameTest() { + // TODO: test lastName + } + + /** + * Test the property 'email' + */ + @Test + public void emailTest() { + // TODO: test email + } + + /** + * Test the property 'password' + */ + @Test + public void passwordTest() { + // TODO: test password + } + + /** + * Test the property 'phone' + */ + @Test + public void phoneTest() { + // TODO: test phone + } + + /** + * Test the property 'userStatus' + */ + @Test + public void userStatusTest() { + // TODO: test userStatus + } + + /** + * Test the property 'objectWithNoDeclaredProps' + */ + @Test + public void objectWithNoDeclaredPropsTest() { + // TODO: test objectWithNoDeclaredProps + } + + /** + * Test the property 'objectWithNoDeclaredPropsNullable' + */ + @Test + public void objectWithNoDeclaredPropsNullableTest() { + // TODO: test objectWithNoDeclaredPropsNullable + } + + /** + * Test the property 'anyTypeProp' + */ + @Test + public void anyTypePropTest() { + // TODO: test anyTypeProp + } + + /** + * Test the property 'anyTypePropNullable' + */ + @Test + public void anyTypePropNullableTest() { + // TODO: test anyTypePropNullable + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java new file mode 100644 index 000000000000..15cde8b947b5 --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AllOfModelArrayAnyOfTest.java @@ -0,0 +1,65 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.Arrays; +import org.openapitools.client.model.AllOfModelArrayAnyOfAllOfLinkListColumn1; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + +/** + * Model tests for AllOfModelArrayAnyOf + */ +public class AllOfModelArrayAnyOfTest { + private final AllOfModelArrayAnyOf model = new AllOfModelArrayAnyOf(); + + /** + * Model tests for AllOfModelArrayAnyOf + */ + @Test + public void testAllOfModelArrayAnyOf() { + // TODO: test AllOfModelArrayAnyOf + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'linkListColumn1' + */ + @Test + public void linkListColumn1Test() { + // TODO: test linkListColumn1 + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AnimalTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AnimalTest.java index f30075833858..cc4678583018 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AnimalTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AnimalTest.java @@ -19,10 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; +import org.openapitools.client.model.Cat; +import org.openapitools.client.model.Dog; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Animal */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleReqTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleReqTest.java index ab1caf49d1bb..772c2ac24bf3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleReqTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleReqTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for AppleReq */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleTest.java index 0cde246f3dd8..1b9fd1706d46 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/AppleTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Apple */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java index 0be94bcc3466..15817f98e222 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfArrayAllofDogPropertyInnerTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ArrayOfInlineAllOfArrayAllofDogPropertyInner */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java index 385ead61ffe5..c887d6b4bc39 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfInlineAllOfTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.ArrayOfInlineAllOfArrayAllofDogPropertyInner; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ArrayOfInlineAllOf */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java index 7121b15da89f..8eb0bf5acd59 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayOfNumberOnlyTest.java @@ -21,11 +21,11 @@ import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ArrayOfNumberOnly */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayTestTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayTestTest.java index da72462ec73d..63a98fbeff6d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayTestTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ArrayTestTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.ReadOnlyFirst; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ArrayTest */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaReqTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaReqTest.java index cf02d90b8c2c..30568207995f 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaReqTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaReqTest.java @@ -20,10 +20,10 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for BananaReq */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaTest.java index 889087a653d4..10f407730718 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BananaTest.java @@ -20,10 +20,10 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Banana */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BasquePigTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BasquePigTest.java index b4e3ebde1882..0d9eec8e0f0b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BasquePigTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/BasquePigTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for BasquePig */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CapitalizationTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CapitalizationTest.java index c3c69e049af7..51745e8a2214 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CapitalizationTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CapitalizationTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Capitalization */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CatTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CatTest.java index 73309d4bec1f..23ab7c6c9045 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CatTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CatTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Animal; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Cat */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CategoryTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CategoryTest.java index 03f1c7ec1d53..30e7328449c0 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CategoryTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/CategoryTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Category */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClassModelTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClassModelTest.java index 1666ebc79969..0e6956b33269 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClassModelTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClassModelTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ClassModel */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClientTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClientTest.java index 140143b9573d..22c1e8596146 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClientTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ClientTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Client */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java index ae249afb2a59..c544a3da00cb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ComplexQuadrilateralTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ComplexQuadrilateral */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DanishPigTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DanishPigTest.java index f1a269899574..2a265236c260 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DanishPigTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DanishPigTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for DanishPig */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java index 1b298f1bd159..bf3e5f6e21da 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DeprecatedObjectTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for DeprecatedObject */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DogTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DogTest.java index 844e3e06f5e1..99c282235ce9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DogTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DogTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Animal; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Dog */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DrawingTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DrawingTest.java index d6834d1985e3..8232c871009b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DrawingTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/DrawingTest.java @@ -20,7 +20,6 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.Fruit; import org.openapitools.client.model.NullableShape; @@ -30,6 +29,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Drawing */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumArraysTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumArraysTest.java index 02954e6a6839..9ca44c3d5e53 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumArraysTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumArraysTest.java @@ -20,11 +20,11 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for EnumArrays */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumClassTest.java index bed8681219e8..88c982a61df2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumClassTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumClassTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for EnumClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java index ef8bbbfac3f2..9d4c8e553954 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumStringDiscriminatorTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for EnumStringDiscriminator */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumTestTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumTestTest.java index 320df9ad3ebf..79bd51ad8532 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumTestTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EnumTestTest.java @@ -19,7 +19,6 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.OuterEnum; import org.openapitools.client.model.OuterEnumDefaultValue; import org.openapitools.client.model.OuterEnumInteger; @@ -28,6 +27,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for EnumTest */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java index 181c439fa18c..edd7afe14210 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/EquilateralTriangleTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for EquilateralTriangle */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java index 79eccbf4beef..75af6c26a264 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FileSchemaTestClassTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.ModelFile; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for FileSchemaTestClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java index 83fc00cea450..4e9ebc39952c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooGetDefaultResponseTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Foo; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for FooGetDefaultResponse */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooTest.java index 8dd27992bc1c..562b545ffb65 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FooTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Foo */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FormatTestTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FormatTestTest.java index e2b6ed61d88b..9e091ac1614d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FormatTestTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FormatTestTest.java @@ -23,11 +23,11 @@ import java.math.BigDecimal; import java.time.LocalDate; import java.time.OffsetDateTime; -import java.util.Arrays; import java.util.UUID; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for FormatTest */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitReqTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitReqTest.java index d4bdb5f312ff..95ea123b1399 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitReqTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitReqTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.openapitools.client.model.AppleReq; import org.openapitools.client.model.BananaReq; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for FruitReq */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitTest.java index bc4e5e54130d..bd7cd5827a4b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/FruitTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.openapitools.client.model.Apple; import org.openapitools.client.model.Banana; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Fruit */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GmFruitTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GmFruitTest.java index 68c8179498de..03b9a54d490a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GmFruitTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GmFruitTest.java @@ -20,12 +20,12 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.openapitools.client.model.Apple; import org.openapitools.client.model.Banana; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for GmFruit */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java index 8247ad12829b..dccfda8c772d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/GrandparentAnimalTest.java @@ -19,10 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; +import org.openapitools.client.model.ParentPet; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for GrandparentAnimal */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java index f63bf66b1775..12879ebf3951 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HasOnlyReadOnlyTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for HasOnlyReadOnly */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java index a6e06e3dbd8c..c424fb717e8e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/HealthCheckResultTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for HealthCheckResult */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java index 728d1af34f26..b45919dadadd 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/IsoscelesTriangleTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for IsoscelesTriangle */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MammalTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MammalTest.java index af5250405311..a2682988c72e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MammalTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MammalTest.java @@ -19,13 +19,13 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Pig; import org.openapitools.client.model.Whale; import org.openapitools.client.model.Zebra; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Mammal */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MapTestTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MapTestTest.java index 0587a961b146..f2515c398b94 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MapTestTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MapTestTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for MapTest */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java index 1cc69bedcd83..03df28593f69 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/MixedPropertiesAndAdditionalPropertiesClassTest.java @@ -20,7 +20,6 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.time.OffsetDateTime; -import java.util.Arrays; import java.util.HashMap; import java.util.Map; import java.util.UUID; @@ -28,6 +27,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for MixedPropertiesAndAdditionalPropertiesClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/Model200ResponseTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/Model200ResponseTest.java index 01b44a53b4fa..aa3d6381861b 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/Model200ResponseTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/Model200ResponseTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Model200Response */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java index 9480c9ee0ff7..3f61010629ae 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelApiResponseTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ModelApiResponse */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelFileTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelFileTest.java index a84242272474..5e868346f88d 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelFileTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelFileTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ModelFile */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelListTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelListTest.java index ea5a55185989..8ec190bf5446 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelListTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelListTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ModelList */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelReturnTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelReturnTest.java index 10c7841ba3c1..dae92f89a6c4 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelReturnTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ModelReturnTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ModelReturn */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NameTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NameTest.java index 52eae7974bc1..7086457d5cf7 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NameTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NameTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Name */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableClassTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableClassTest.java index 0a0595ca0e65..1f72849e9f2e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableClassTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableClassTest.java @@ -23,7 +23,6 @@ import java.time.LocalDate; import java.time.OffsetDateTime; import java.util.ArrayList; -import java.util.Arrays; import java.util.HashMap; import java.util.List; import java.util.Map; @@ -31,6 +30,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for NullableClass */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableShapeTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableShapeTest.java index dbc420fae72d..0026a5188e53 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableShapeTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NullableShapeTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Quadrilateral; import org.openapitools.client.model.Triangle; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for NullableShape */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NumberOnlyTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NumberOnlyTest.java index 774200c9f6bc..b01e135a260c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NumberOnlyTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/NumberOnlyTest.java @@ -20,10 +20,10 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for NumberOnly */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java index 452495e83d31..0f59cf5baec5 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ObjectWithDeprecatedFieldsTest.java @@ -21,12 +21,12 @@ import java.io.IOException; import java.math.BigDecimal; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.DeprecatedObject; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ObjectWithDeprecatedFields */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OrderTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OrderTest.java index adcfde4a33d0..9dff581d403e 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OrderTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OrderTest.java @@ -20,10 +20,10 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.time.OffsetDateTime; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Order */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterCompositeTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterCompositeTest.java index 794328118065..3b6aa4c90338 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterCompositeTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterCompositeTest.java @@ -20,10 +20,10 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.math.BigDecimal; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for OuterComposite */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java index 6b324784e1d6..57ed09918adc 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumDefaultValueTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for OuterEnumDefaultValue */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java index ffb20a97973b..70cae81500e3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerDefaultValueTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for OuterEnumIntegerDefaultValue */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java index be0665bb740e..fc666e9da3bb 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumIntegerTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for OuterEnumInteger */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumTest.java index 8ab11b65cbde..61cb88bb3dba 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/OuterEnumTest.java @@ -17,6 +17,7 @@ import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for OuterEnum */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ParentPetTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ParentPetTest.java index 226366f49666..02011765f760 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ParentPetTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ParentPetTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.GrandparentAnimal; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ParentPet */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java new file mode 100644 index 000000000000..7939998e1a2f --- /dev/null +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetTest.java @@ -0,0 +1,92 @@ +/* + * OpenAPI Petstore + * This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ + + +package org.openapitools.client.model; + +import com.google.gson.TypeAdapter; +import com.google.gson.annotations.JsonAdapter; +import com.google.gson.annotations.SerializedName; +import com.google.gson.stream.JsonReader; +import com.google.gson.stream.JsonWriter; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import org.openapitools.client.model.Category; +import org.openapitools.client.model.Tag; +import org.junit.jupiter.api.Disabled; +import org.junit.jupiter.api.Test; + + +/** + * Model tests for Pet + */ +public class PetTest { + private final Pet model = new Pet(); + + /** + * Model tests for Pet + */ + @Test + public void testPet() { + // TODO: test Pet + } + + /** + * Test the property 'id' + */ + @Test + public void idTest() { + // TODO: test id + } + + /** + * Test the property 'category' + */ + @Test + public void categoryTest() { + // TODO: test category + } + + /** + * Test the property 'name' + */ + @Test + public void nameTest() { + // TODO: test name + } + + /** + * Test the property 'photoUrls' + */ + @Test + public void photoUrlsTest() { + // TODO: test photoUrls + } + + /** + * Test the property 'tags' + */ + @Test + public void tagsTest() { + // TODO: test tags + } + + /** + * Test the property 'status' + */ + @Test + public void statusTest() { + // TODO: test status + } + +} diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java index a338a337dc6d..e511e57ccd11 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PetWithRequiredTagsTest.java @@ -20,13 +20,13 @@ import com.google.gson.stream.JsonWriter; import java.io.IOException; import java.util.ArrayList; -import java.util.Arrays; import java.util.List; import org.openapitools.client.model.Category; import org.openapitools.client.model.Tag; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for PetWithRequiredTags */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PigTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PigTest.java index 43341a064965..c9682283bf91 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PigTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/PigTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.BasquePig; import org.openapitools.client.model.DanishPig; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Pig */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java index 09636aa063b8..ef395cadb635 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralInterfaceTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for QuadrilateralInterface */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralTest.java index 9615c3cddbee..ff4674d4cd38 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/QuadrilateralTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.ComplexQuadrilateral; import org.openapitools.client.model.SimpleQuadrilateral; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Quadrilateral */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java index c4b3c2a8d09d..28bbe600c7f3 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ReadOnlyFirstTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ReadOnlyFirst */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java index eaa8c5949fb2..38716e473983 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ScaleneTriangleTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ScaleneTriangle */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java index 5ca1df738506..bd20c12251af 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeInterfaceTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ShapeInterface */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java index c6897d03888f..0164b509cfd8 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeOrNullTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Quadrilateral; import org.openapitools.client.model.Triangle; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for ShapeOrNull */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeTest.java index 90dcd3533662..3343750c59c1 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ShapeTest.java @@ -19,12 +19,12 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.Quadrilateral; import org.openapitools.client.model.Triangle; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Shape */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java index 4479450f2a90..b794d1cf052c 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SimpleQuadrilateralTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for SimpleQuadrilateral */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java index 49c1845b64ca..a61cb4663f26 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/SpecialModelNameTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for SpecialModelName */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TagTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TagTest.java index 6f38d0223841..4642d1e931d2 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TagTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TagTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Tag */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java index 51c68d94db47..832f887bcf92 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleInterfaceTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for TriangleInterface */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleTest.java index 92acf4e566cb..26267f88100a 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/TriangleTest.java @@ -19,13 +19,13 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.client.model.EquilateralTriangle; import org.openapitools.client.model.IsoscelesTriangle; import org.openapitools.client.model.ScaleneTriangle; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Triangle */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/UserTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/UserTest.java index eea5bbb3866d..225980e83662 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/UserTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/UserTest.java @@ -19,11 +19,11 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.openapitools.jackson.nullable.JsonNullable; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for User */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/WhaleTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/WhaleTest.java index 97bcae4987b4..5ef53c4ee1c9 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/WhaleTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/WhaleTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Whale */ diff --git a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ZebraTest.java b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ZebraTest.java index 73aa9b2b4e7a..a893fca3fe31 100644 --- a/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ZebraTest.java +++ b/samples/client/petstore/java/okhttp-gson/src/test/java/org/openapitools/client/model/ZebraTest.java @@ -19,10 +19,10 @@ import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; import java.io.IOException; -import java.util.Arrays; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; + /** * Model tests for Zebra */ diff --git a/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION b/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/java/rest-assured-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/rest-assured-jackson/build.gradle b/samples/client/petstore/java/rest-assured-jackson/build.gradle index e20b0dc87079..b112fc390a84 100644 --- a/samples/client/petstore/java/rest-assured-jackson/build.gradle +++ b/samples/client/petstore/java/rest-assured-jackson/build.gradle @@ -97,18 +97,16 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.6.6" - rest_assured_version = "4.5.1" + rest_assured_version = "5.3.2" junit_version = "4.13.2" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" jakarta_annotation_version = "1.3.5" - okio_version = "1.17.5" + okio_version = "3.6.0" } dependencies { - implementation "io.swagger:swagger-annotations:$swagger_annotations_version" implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "io.rest-assured:rest-assured:$rest_assured_version" implementation "com.fasterxml.jackson.core:jackson-core:$jackson_version" diff --git a/samples/client/petstore/java/rest-assured-jackson/docs/ArrayTest.md b/samples/client/petstore/java/rest-assured-jackson/docs/ArrayTest.md index 36077c9df300..ae2672809aa9 100644 --- a/samples/client/petstore/java/rest-assured-jackson/docs/ArrayTest.md +++ b/samples/client/petstore/java/rest-assured-jackson/docs/ArrayTest.md @@ -9,7 +9,7 @@ |------------ | ------------- | ------------- | -------------| |**arrayOfString** | **List<String>** | | [optional] | |**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | -|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<@Valid ReadOnlyFirst>>** | | [optional] | diff --git a/samples/client/petstore/java/rest-assured-jackson/docs/UserApi.md b/samples/client/petstore/java/rest-assured-jackson/docs/UserApi.md index 8d4dfba9ff41..87fb20faa572 100644 --- a/samples/client/petstore/java/rest-assured-jackson/docs/UserApi.md +++ b/samples/client/petstore/java/rest-assured-jackson/docs/UserApi.md @@ -81,7 +81,7 @@ api.createUsersWithArrayInput() | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type @@ -121,7 +121,7 @@ api.createUsersWithListInput() | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type diff --git a/samples/client/petstore/java/rest-assured-jackson/pom.xml b/samples/client/petstore/java/rest-assured-jackson/pom.xml index aac46a3cf569..0a0c91d0e4d3 100644 --- a/samples/client/petstore/java/rest-assured-jackson/pom.xml +++ b/samples/client/petstore/java/rest-assured-jackson/pom.xml @@ -277,15 +277,15 @@ UTF-8 - 4.5.1 + 5.3.2 2.10.1 - 1.8.5 + 1.9.0 2.15.2 2.15.2 0.2.6 1.3.5 2.0.2 - 1.17.5 + 3.6.0 4.13.2 diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index 4beb2b367149..4dfb005c9938 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -28,6 +28,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeApi.java index 47e5b6b62cdd..76fce0633b27 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeApi.java @@ -35,6 +35,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 7df98f1d91d4..d00177e63313 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -27,6 +27,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/PetApi.java index cf5a6a11f415..2bebdbf853cd 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/PetApi.java @@ -30,6 +30,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/StoreApi.java index 730db2d87b7a..2894f03e56b2 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/StoreApi.java @@ -27,6 +27,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/UserApi.java index da04feeb5372..ec2869045566 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/api/UserApi.java @@ -28,6 +28,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; @@ -204,10 +207,10 @@ public T execute(Function handler) { } /** - * @param body (List<User>) List of user object (required) + * @param body (List<@Valid User>) List of user object (required) * @return operation */ - public CreateUsersWithArrayInputOper body(List body) { + public CreateUsersWithArrayInputOper body(List<@Valid User> body) { reqSpec.setBody(body); return this; } @@ -265,10 +268,10 @@ public T execute(Function handler) { } /** - * @param body (List<User>) List of user object (required) + * @param body (List<@Valid User>) List of user object (required) * @return operation */ - public CreateUsersWithListInputOper body(List body) { + public CreateUsersWithListInputOper body(List<@Valid User> body) { reqSpec.setBody(body); return this; } diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java index c6de0aba2175..fb4fd954d50c 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest() { } @@ -123,13 +123,13 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -147,14 +147,14 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index baf04c9f83e6..2ec49a7e8b0b 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -43,7 +43,7 @@ public class FileSchemaTestClass { private ModelFile _file; public static final String JSON_PROPERTY_FILES = "files"; - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass() { } @@ -76,7 +76,7 @@ public void setFile(ModelFile _file) { } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; @@ -100,14 +100,14 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java index 24c613991cf1..683681c3f5f0 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/FormatTest.java @@ -541,7 +541,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java index d7f9218f5eae..dd787c5dd702 100644 --- a/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/rest-assured-jackson/src/main/java/org/openapitools/client/model/Pet.java @@ -60,7 +60,7 @@ public class Pet { private Set photoUrls = new LinkedHashSet<>(); public static final String JSON_PROPERTY_TAGS = "tags"; - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -225,7 +225,7 @@ public void setPhotoUrls(Set photoUrls) { } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; @@ -249,14 +249,14 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION +++ b/samples/client/petstore/java/rest-assured/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/rest-assured/build.gradle b/samples/client/petstore/java/rest-assured/build.gradle index 1465cdb209c9..d0fc73dd3431 100644 --- a/samples/client/petstore/java/rest-assured/build.gradle +++ b/samples/client/petstore/java/rest-assured/build.gradle @@ -97,16 +97,14 @@ if(hasProperty('target') && target == 'android') { } ext { - swagger_annotations_version = "1.6.6" - rest_assured_version = "4.5.1" + rest_assured_version = "5.3.2" junit_version = "4.13.2" - gson_version = "2.8.9" - gson_fire_version = "1.8.5" - okio_version = "1.17.5" + gson_version = "2.10.1" + gson_fire_version = "1.9.0" + okio_version = "3.6.0" } dependencies { - implementation "io.swagger:swagger-annotations:$swagger_annotations_version" implementation "com.google.code.findbugs:jsr305:3.0.2" implementation "io.rest-assured:rest-assured:$rest_assured_version" implementation "io.gsonfire:gson-fire:$gson_fire_version" diff --git a/samples/client/petstore/java/rest-assured/build.sbt b/samples/client/petstore/java/rest-assured/build.sbt index 8e36f1674930..a82aa7da30b9 100644 --- a/samples/client/petstore/java/rest-assured/build.sbt +++ b/samples/client/petstore/java/rest-assured/build.sbt @@ -14,7 +14,7 @@ lazy val root = (project in file(".")). "io.rest-assured" % "scala-support" % "4.5.1", "com.google.code.findbugs" % "jsr305" % "3.0.2", "com.google.code.gson" % "gson" % "2.8.9", - "io.gsonfire" % "gson-fire" % "1.8.5" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "com.squareup.okio" % "okio" % "1.17.5" % "compile", "jakarta.validation" % "jakarta.validation-api" % "2.0.2" % "compile", "org.hibernate" % "hibernate-validator" % "6.0.19.Final" % "compile", diff --git a/samples/client/petstore/java/rest-assured/docs/ArrayTest.md b/samples/client/petstore/java/rest-assured/docs/ArrayTest.md index 36077c9df300..ae2672809aa9 100644 --- a/samples/client/petstore/java/rest-assured/docs/ArrayTest.md +++ b/samples/client/petstore/java/rest-assured/docs/ArrayTest.md @@ -9,7 +9,7 @@ |------------ | ------------- | ------------- | -------------| |**arrayOfString** | **List<String>** | | [optional] | |**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | -|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<@Valid ReadOnlyFirst>>** | | [optional] | diff --git a/samples/client/petstore/java/rest-assured/docs/UserApi.md b/samples/client/petstore/java/rest-assured/docs/UserApi.md index 8d4dfba9ff41..87fb20faa572 100644 --- a/samples/client/petstore/java/rest-assured/docs/UserApi.md +++ b/samples/client/petstore/java/rest-assured/docs/UserApi.md @@ -81,7 +81,7 @@ api.createUsersWithArrayInput() | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type @@ -121,7 +121,7 @@ api.createUsersWithListInput() | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type diff --git a/samples/client/petstore/java/rest-assured/pom.xml b/samples/client/petstore/java/rest-assured/pom.xml index cefff2ae19e7..4ba82ad7c648 100644 --- a/samples/client/petstore/java/rest-assured/pom.xml +++ b/samples/client/petstore/java/rest-assured/pom.xml @@ -254,12 +254,12 @@ UTF-8 - 4.5.1 + 5.3.2 2.10.1 - 1.8.5 + 1.9.0 1.3.5 2.0.2 - 1.17.5 + 3.6.0 4.13.2 diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index dcf36d88183e..52e88b2db2bd 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -28,6 +28,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeApi.java index 850217b7edc1..842d9fa2bc80 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeApi.java @@ -35,6 +35,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index 12178fc04bd4..0447c8a88c67 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -27,6 +27,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/PetApi.java index 24567d7becf4..8846a084ec08 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/PetApi.java @@ -30,6 +30,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/StoreApi.java index fd1abe4db3c5..e6281a0a34e8 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/StoreApi.java @@ -27,6 +27,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/UserApi.java index f2babb7cb22b..dfd991dc96c1 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/api/UserApi.java @@ -28,6 +28,9 @@ import io.restassured.http.Method; import io.restassured.response.Response; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.lang.reflect.Type; import java.util.function.Consumer; import java.util.function.Function; @@ -205,10 +208,10 @@ public T execute(Function handler) { } /** - * @param body (List<User>) List of user object (required) + * @param body (List<@Valid User>) List of user object (required) * @return operation */ - public CreateUsersWithArrayInputOper body(List body) { + public CreateUsersWithArrayInputOper body(List<@Valid User> body) { reqSpec.setBody(body); return this; } @@ -266,10 +269,10 @@ public T execute(Function handler) { } /** - * @param body (List<User>) List of user object (required) + * @param body (List<@Valid User>) List of user object (required) * @return operation */ - public CreateUsersWithListInputOper body(List body) { + public CreateUsersWithListInputOper body(List<@Valid User> body) { reqSpec.setBody(body); return this; } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java index 2898e700a4a5..a29dbe5b7d91 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -44,7 +44,7 @@ public class ArrayTest { public static final String SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @SerializedName(SERIALIZED_NAME_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest() { } @@ -112,13 +112,13 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -134,12 +134,12 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 997bf161b873..a121bcfca136 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { public static final String SERIALIZED_NAME_FILES = "files"; @SerializedName(SERIALIZED_NAME_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass() { } @@ -69,7 +69,7 @@ public void setFile(ModelFile _file) { } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; @@ -91,12 +91,12 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java index 595f75f15ced..cdabf3d2d57e 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/FormatTest.java @@ -481,7 +481,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java index 76aaad0bab8c..b0d3770ba8dd 100644 --- a/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/rest-assured/src/main/java/org/openapitools/client/model/Pet.java @@ -55,7 +55,7 @@ public class Pet { public static final String SERIALIZED_NAME_TAGS = "tags"; @SerializedName(SERIALIZED_NAME_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -216,7 +216,7 @@ public void setPhotoUrls(Set photoUrls) { } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; @@ -238,12 +238,12 @@ public Pet addTagsItem(Tag tagsItem) { @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resteasy/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resteasy/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resteasy/README.md b/samples/client/petstore/java/resteasy/README.md index 88c593489c7a..f436b871632f 100644 --- a/samples/client/petstore/java/resteasy/README.md +++ b/samples/client/petstore/java/resteasy/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/resteasy/api/openapi.yaml b/samples/client/petstore/java/resteasy/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/resteasy/api/openapi.yaml +++ b/samples/client/petstore/java/resteasy/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/resteasy/docs/FakeApi.md b/samples/client/petstore/java/resteasy/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/resteasy/docs/FakeApi.md +++ b/samples/client/petstore/java/resteasy/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java index e8d560a255cc..b484f563509f 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/ApiClient.java @@ -493,7 +493,7 @@ public Entity serialize(Object obj, Map formParams, String co if (param.getValue() instanceof File) { File file = (File) param.getValue(); try { - multipart.addFormData(param.getKey(),new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM_TYPE); + multipart.addFormData(param.getKey(),new FileInputStream(file),MediaType.APPLICATION_OCTET_STREAM_TYPE, file.getName()); } catch (FileNotFoundException e) { throw new ApiException("Could not serialize multipart/form-data "+e.getMessage()); } diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/api/FakeApi.java index f9093377f76e..cceced91b3a3 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/api/FakeApi.java @@ -364,6 +364,48 @@ public OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(OuterObjectW GenericType localVarReturnType = new GenericType() {}; return apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException if fails to make API call + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + Object localVarPostBody = requestBody; + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + // create path and map variables + String localVarPath = "/fake/additionalProperties-reference".replaceAll("\\{format\\}","json"); + + // query params + List localVarQueryParams = new ArrayList(); + Map localVarHeaderParams = new HashMap(); + Map localVarCookieParams = new HashMap(); + Map localVarFormParams = new HashMap(); + + + + + + final String[] localVarAccepts = { + + }; + final String localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + + final String[] localVarContentTypes = { + "application/json" + }; + final String localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, null); + } /** * * For this test, the body has to be a binary file. diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index e9d4c678963a..a0083b8cf989 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -15,13 +15,15 @@ import org.openapitools.client.Pair; -import java.util.Map; import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Supplier; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaClientCodegen") public class HttpBearerAuth implements Authentication { private final String scheme; - private String bearerToken; + private Supplier tokenSupplier; public HttpBearerAuth(String scheme) { this.scheme = scheme; @@ -33,7 +35,7 @@ public HttpBearerAuth(String scheme) { * @return The bearer token */ public String getBearerToken() { - return bearerToken; + return tokenSupplier.get(); } /** @@ -42,12 +44,22 @@ public String getBearerToken() { * @param bearerToken The bearer token to send in the Authorization header */ public void setBearerToken(String bearerToken) { - this.bearerToken = bearerToken; + this.tokenSupplier = () -> bearerToken; + } + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ + public void setBearerToken(Supplier tokenSupplier) { + this.tokenSupplier = tokenSupplier; } @Override public void applyToParams(List queryParams, Map headerParams, Map cookieParams) { - if(bearerToken == null) { + String bearerToken = Optional.ofNullable(tokenSupplier).map(Supplier::get).orElse(null); + if (bearerToken == null) { return; } diff --git a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java index 1efd4270dd5d..f9ddc4d4d294 100644 --- a/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resteasy/src/main/java/org/openapitools/client/model/FormatTest.java @@ -577,7 +577,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/resttemplate-jakarta/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-jakarta/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resttemplate-jakarta/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-jakarta/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/ApiClient.java index a58613e725a7..b575260a330c 100644 --- a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/ApiClient.java @@ -22,6 +22,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -79,6 +81,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://petstore.swagger.io/v2"; private RestTemplate restTemplate; @@ -136,6 +142,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -629,7 +675,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -737,7 +812,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/PetApi.java index 75ba2cf8eed5..732527c10e5e 100644 --- a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/PetApi.java @@ -185,7 +185,7 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" @@ -240,7 +240,7 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(List tags) t final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/UserApi.java index 3853d9f8eb01..46b2a0835cd6 100644 --- a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/api/UserApi.java @@ -327,7 +327,7 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 45ef724bd645..e78b00018017 100644 --- a/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resttemplate-jakarta/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/petstore/java/resttemplate-swagger1/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-swagger1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resttemplate-swagger1/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-swagger1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/ApiClient.java index cfa530eaca27..274f0b0cc970 100644 --- a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/ApiClient.java @@ -22,6 +22,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -79,6 +81,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://petstore.swagger.io/v2"; private RestTemplate restTemplate; @@ -136,6 +142,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -629,7 +675,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -737,7 +812,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/PetApi.java index c83dcced6b89..5690a4560a0d 100644 --- a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/PetApi.java @@ -185,7 +185,7 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" @@ -240,7 +240,7 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(List tags) t final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/UserApi.java index 61837f12d6ed..9c958bd5e8a2 100644 --- a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/api/UserApi.java @@ -327,7 +327,7 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 51d5e3278ef7..4678c06efd7c 100644 --- a/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resttemplate-swagger1/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/petstore/java/resttemplate-swagger2/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-swagger2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resttemplate-swagger2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-swagger2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/ApiClient.java index cfa530eaca27..274f0b0cc970 100644 --- a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -22,6 +22,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -79,6 +81,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://petstore.swagger.io/v2"; private RestTemplate restTemplate; @@ -136,6 +142,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -629,7 +675,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -737,7 +812,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/PetApi.java index c83dcced6b89..5690a4560a0d 100644 --- a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/PetApi.java @@ -185,7 +185,7 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" @@ -240,7 +240,7 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(List tags) t final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/UserApi.java index 61837f12d6ed..9c958bd5e8a2 100644 --- a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/api/UserApi.java @@ -327,7 +327,7 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 51d5e3278ef7..4678c06efd7c 100644 --- a/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resttemplate-swagger2/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate-withXml/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate-withXml/README.md b/samples/client/petstore/java/resttemplate-withXml/README.md index aef90cd7fba9..08a46fad4882 100644 --- a/samples/client/petstore/java/resttemplate-withXml/README.md +++ b/samples/client/petstore/java/resttemplate-withXml/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml b/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml +++ b/samples/client/petstore/java/resttemplate-withXml/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md b/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md +++ b/samples/client/petstore/java/resttemplate-withXml/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java index 0a73b802d4c2..9736bae543c6 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/ApiClient.java @@ -27,6 +27,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -86,6 +88,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://petstore.swagger.io:80/v2"; private RestTemplate restTemplate; @@ -146,6 +152,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -166,18 +212,18 @@ public Authentication getAuthentication(String authName) { } /** - * Helper method to set token for HTTP bearer authentication. + * Helper method to set access token for the first Bearer authentication. * - * @param bearerToken the token + * @param bearerToken Bearer token */ public void setBearerToken(String bearerToken) { setBearerToken(() -> bearerToken); } /** - * Helper method to set the token supplier for HTTP bearer authentication. + * Helper method to set the supplier of access tokens for Bearer authentication. * - * @param tokenSupplier the token supplier function + * @param tokenSupplier The supplier of bearer tokens */ public void setBearerToken(Supplier tokenSupplier) { for (Authentication auth : authentications.values()) { @@ -692,7 +738,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -808,7 +883,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java index c816078d2480..88425e86cea1 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/FakeApi.java @@ -175,7 +175,7 @@ public ResponseEntity fakeHttpSignatureTestWithHttpInfo(Pet pet, String qu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_1", query1)); - + if (header1 != null) localVarHeaderParams.add("header_1", apiClient.parameterToString(header1)); @@ -412,6 +412,51 @@ public ResponseEntity fakePropertyEnumIntegerSerial ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/property/enum-int", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); } + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void testAdditionalPropertiesReference(Map requestBody) throws RestClientException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws RestClientException { + Object localVarPostBody = requestBody; + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/fake/additionalProperties-reference", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } /** * * For this test, the body has to be a binary file. @@ -543,7 +588,7 @@ public ResponseEntity testBodyWithQueryParamsWithHttpInfo(String query, Us final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query", query)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); @@ -773,7 +818,7 @@ public ResponseEntity testEnumParametersWithHttpInfo(List enumHead localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "enum_query_model_array", enumQueryModelArray)); - + if (enumHeaderStringArray != null) localVarHeaderParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); @@ -854,7 +899,7 @@ public ResponseEntity testGroupParametersWithHttpInfo(Integer requiredStri localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "required_int64_group", requiredInt64Group)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_group", stringGroup)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "int64_group", int64Group)); - + if (requiredBooleanGroup != null) localVarHeaderParams.add("required_boolean_group", apiClient.parameterToString(requiredBooleanGroup)); @@ -1140,7 +1185,7 @@ public ResponseEntity testQueryParameterCollectionFormatWithHttpInfo(List< localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "context", context)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "language", language)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "allowEmpty", allowEmpty)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java index 75b0825e2e59..59ee44d69d1d 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/PetApi.java @@ -185,7 +185,7 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" @@ -240,7 +240,7 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(Set tags) thr final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java index 72054f302d68..dabcb91b76ed 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/api/UserApi.java @@ -327,7 +327,7 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 51d5e3278ef7..4678c06efd7c 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java index 8caa23796092..209238514014 100644 --- a/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resttemplate-withXml/src/main/java/org/openapitools/client/model/FormatTest.java @@ -633,7 +633,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION +++ b/samples/client/petstore/java/resttemplate/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/resttemplate/README.md b/samples/client/petstore/java/resttemplate/README.md index 24053b816edb..046c1d47e35d 100644 --- a/samples/client/petstore/java/resttemplate/README.md +++ b/samples/client/petstore/java/resttemplate/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/resttemplate/api/openapi.yaml b/samples/client/petstore/java/resttemplate/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/resttemplate/api/openapi.yaml +++ b/samples/client/petstore/java/resttemplate/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/resttemplate/docs/FakeApi.md b/samples/client/petstore/java/resttemplate/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/resttemplate/docs/FakeApi.md +++ b/samples/client/petstore/java/resttemplate/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java index d6e6a8b07d2f..7bd45e6b4867 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/ApiClient.java @@ -22,6 +22,8 @@ import org.springframework.util.LinkedMultiValueMap; import org.springframework.util.MultiValueMap; import org.springframework.util.StringUtils; +import org.springframework.web.client.HttpClientErrorException; +import org.springframework.web.client.HttpServerErrorException; import org.springframework.web.client.RestClientException; import org.springframework.web.client.RestTemplate; import org.springframework.web.util.UriComponentsBuilder; @@ -81,6 +83,10 @@ private String collectionToString(Collection collection) { private HttpHeaders defaultHeaders = new HttpHeaders(); private MultiValueMap defaultCookies = new LinkedMultiValueMap(); + private int maxAttemptsForRetry = 1; + + private long waitTimeMillis = 10; + private String basePath = "http://petstore.swagger.io:80/v2"; private RestTemplate restTemplate; @@ -141,6 +147,46 @@ public ApiClient setBasePath(String basePath) { return this; } + /** + * Get the max attempts for retry + * + * @return int the max attempts + */ + public int getMaxAttemptsForRetry() { + return maxAttemptsForRetry; + } + + /** + * Set the max attempts for retry + * + * @param maxAttemptsForRetry the max attempts for retry + * @return ApiClient this client + */ + public ApiClient setMaxAttemptsForRetry(int maxAttemptsForRetry) { + this.maxAttemptsForRetry = maxAttemptsForRetry; + return this; + } + + /** + * Get the wait time in milliseconds + * + * @return long wait time in milliseconds + */ + public long getWaitTimeMillis() { + return waitTimeMillis; + } + + /** + * Set the wait time in milliseconds + * + * @param waitTimeMillis the wait time in milliseconds + * @return ApiClient this client + */ + public ApiClient setWaitTimeMillis(long waitTimeMillis) { + this.waitTimeMillis = waitTimeMillis; + return this; + } + /** * Get authentications (key: authentication name, value: authentication). * @@ -161,18 +207,18 @@ public Authentication getAuthentication(String authName) { } /** - * Helper method to set token for HTTP bearer authentication. + * Helper method to set access token for the first Bearer authentication. * - * @param bearerToken the token + * @param bearerToken Bearer token */ public void setBearerToken(String bearerToken) { setBearerToken(() -> bearerToken); } /** - * Helper method to set the token supplier for HTTP bearer authentication. + * Helper method to set the supplier of access tokens for Bearer authentication. * - * @param tokenSupplier the token supplier function + * @param tokenSupplier The supplier of bearer tokens */ public void setBearerToken(Supplier tokenSupplier) { for (Authentication auth : authentications.values()) { @@ -687,7 +733,36 @@ public ResponseEntity invokeAPI(String path, HttpMethod method, Map requestEntity = requestBuilder.body(selectBody(body, formParams, contentType)); - ResponseEntity responseEntity = restTemplate.exchange(requestEntity, returnType); + ResponseEntity responseEntity = null; + int attempts = 0; + while (attempts < maxAttemptsForRetry) { + try { + responseEntity = restTemplate.exchange(requestEntity, returnType); + break; + } catch (HttpServerErrorException | HttpClientErrorException ex) { + if (ex instanceof HttpServerErrorException + || ((HttpClientErrorException) ex) + .getStatusCode() + .equals(HttpStatus.TOO_MANY_REQUESTS)) { + attempts++; + if (attempts < maxAttemptsForRetry) { + try { + Thread.sleep(waitTimeMillis); + } catch (InterruptedException e) { + Thread.currentThread().interrupt(); + } + } else { + throw ex; + } + } else { + throw ex; + } + } + } + + if (responseEntity == null) { + throw new RestClientException("ResponseEntity is null"); + } if (responseEntity.getStatusCode().is2xxSuccessful()) { return responseEntity; @@ -795,7 +870,7 @@ private void logRequest(HttpRequest request, byte[] body) throws UnsupportedEnco } private void logResponse(ClientHttpResponse response) throws IOException { - log.info("HTTP Status Code: " + response.getRawStatusCode()); + log.info("HTTP Status Code: " + response.getStatusCode().value()); log.info("Status Text: " + response.getStatusText()); log.info("HTTP Headers: " + headersToString(response.getHeaders())); log.info("Response Body: " + bodyToString(response.getBody())); diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java index c816078d2480..88425e86cea1 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/FakeApi.java @@ -175,7 +175,7 @@ public ResponseEntity fakeHttpSignatureTestWithHttpInfo(Pet pet, String qu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_1", query1)); - + if (header1 != null) localVarHeaderParams.add("header_1", apiClient.parameterToString(header1)); @@ -412,6 +412,51 @@ public ResponseEntity fakePropertyEnumIntegerSerial ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; return apiClient.invokeAPI("/fake/property/enum-int", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); } + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body (required) + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public void testAdditionalPropertiesReference(Map requestBody) throws RestClientException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body (required) + * @return ResponseEntity<Void> + * @throws RestClientException if an error occurs while attempting to invoke the API + */ + public ResponseEntity testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws RestClientException { + Object localVarPostBody = requestBody; + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new HttpClientErrorException(HttpStatus.BAD_REQUEST, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + + final MultiValueMap localVarQueryParams = new LinkedMultiValueMap(); + final HttpHeaders localVarHeaderParams = new HttpHeaders(); + final MultiValueMap localVarCookieParams = new LinkedMultiValueMap(); + final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/fake/additionalProperties-reference", HttpMethod.POST, Collections.emptyMap(), localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccept, localVarContentType, localVarAuthNames, localReturnType); + } /** * * For this test, the body has to be a binary file. @@ -543,7 +588,7 @@ public ResponseEntity testBodyWithQueryParamsWithHttpInfo(String query, Us final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "query", query)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); @@ -773,7 +818,7 @@ public ResponseEntity testEnumParametersWithHttpInfo(List enumHead localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "enum_query_model_array", enumQueryModelArray)); - + if (enumHeaderStringArray != null) localVarHeaderParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); @@ -854,7 +899,7 @@ public ResponseEntity testGroupParametersWithHttpInfo(Integer requiredStri localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "required_int64_group", requiredInt64Group)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_group", stringGroup)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "int64_group", int64Group)); - + if (requiredBooleanGroup != null) localVarHeaderParams.add("required_boolean_group", apiClient.parameterToString(requiredBooleanGroup)); @@ -1140,7 +1185,7 @@ public ResponseEntity testQueryParameterCollectionFormatWithHttpInfo(List< localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "context", context)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "language", language)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "allowEmpty", allowEmpty)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java index 75b0825e2e59..59ee44d69d1d 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/PetApi.java @@ -185,7 +185,7 @@ public ResponseEntity> findPetsByStatusWithHttpInfo(List statu final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" @@ -240,7 +240,7 @@ public ResponseEntity> findPetsByTagsWithHttpInfo(Set tags) thr final MultiValueMap localVarFormParams = new LinkedMultiValueMap(); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java index 72054f302d68..dabcb91b76ed 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/api/UserApi.java @@ -327,7 +327,7 @@ public ResponseEntity loginUserWithHttpInfo(String username, String pass localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); localVarQueryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java index 51d5e3278ef7..4678c06efd7c 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/auth/HttpBearerAuth.java @@ -14,14 +14,29 @@ public HttpBearerAuth(String scheme) { this.scheme = scheme; } + /** + * Gets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @return The bearer token + */ public String getBearerToken() { return tokenSupplier.get(); } + /** + * Sets the token, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param bearerToken The bearer token to send in the Authorization header + */ public void setBearerToken(String bearerToken) { this.tokenSupplier = () -> bearerToken; } - + + /** + * Sets the supplier of tokens, which together with the scheme, will be sent as the value of the Authorization header. + * + * @param tokenSupplier The supplier of bearer tokens to send in the Authorization header + */ public void setBearerToken(Supplier tokenSupplier) { this.tokenSupplier = tokenSupplier; } diff --git a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java index 1efd4270dd5d..f9ddc4d4d294 100644 --- a/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/resttemplate/src/main/java/org/openapitools/client/model/FormatTest.java @@ -577,7 +577,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2-play26/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2-play26/build.gradle b/samples/client/petstore/java/retrofit2-play26/build.gradle index b065d686774b..51ea8801fbb7 100644 --- a/samples/client/petstore/java/retrofit2-play26/build.gradle +++ b/samples/client/petstore/java/retrofit2-play26/build.gradle @@ -106,7 +106,7 @@ ext { jakarta_annotation_version = "1.3.5" swagger_annotations_version = "1.5.22" junit_version = "4.13.2" - json_fire_version = "1.8.0" + json_fire_version = "1.9.0" } dependencies { diff --git a/samples/client/petstore/java/retrofit2-play26/build.sbt b/samples/client/petstore/java/retrofit2-play26/build.sbt index b7a8550348b9..f4f37c3c94d8 100644 --- a/samples/client/petstore/java/retrofit2-play26/build.sbt +++ b/samples/client/petstore/java/retrofit2-play26/build.sbt @@ -19,7 +19,7 @@ lazy val root = (project in file(".")). "com.fasterxml.jackson.core" % "jackson-databind" % "2.15.2" % "compile", "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", - "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "junit" % "junit" % "4.13.2" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" diff --git a/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md b/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md index 36077c9df300..ae2672809aa9 100644 --- a/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md +++ b/samples/client/petstore/java/retrofit2-play26/docs/ArrayTest.md @@ -9,7 +9,7 @@ |------------ | ------------- | ------------- | -------------| |**arrayOfString** | **List<String>** | | [optional] | |**arrayArrayOfInteger** | **List<List<Long>>** | | [optional] | -|**arrayArrayOfModel** | **List<List<ReadOnlyFirst>>** | | [optional] | +|**arrayArrayOfModel** | **List<List<@Valid ReadOnlyFirst>>** | | [optional] | diff --git a/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md b/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md index 8425a5f810ed..c562981ef7f7 100644 --- a/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md +++ b/samples/client/petstore/java/retrofit2-play26/docs/UserApi.md @@ -102,7 +102,7 @@ public class Example { defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); UserApi apiInstance = new UserApi(defaultClient); - List body = Arrays.asList(); // List | List of user object + List<@Valid User> body = Arrays.asList(); // List<@Valid User> | List of user object try { apiInstance.createUsersWithArrayInput(body); } catch (ApiException e) { @@ -121,7 +121,7 @@ public class Example { | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type @@ -165,7 +165,7 @@ public class Example { defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); UserApi apiInstance = new UserApi(defaultClient); - List body = Arrays.asList(); // List | List of user object + List<@Valid User> body = Arrays.asList(); // List<@Valid User> | List of user object try { apiInstance.createUsersWithListInput(body); } catch (ApiException e) { @@ -184,7 +184,7 @@ public class Example { | Name | Type | Description | Notes | |------------- | ------------- | ------------- | -------------| -| **body** | [**List<User>**](User.md)| List of user object | | +| **body** | [**List<@Valid User>**](User.md)| List of user object | | ### Return type diff --git a/samples/client/petstore/java/retrofit2-play26/pom.xml b/samples/client/petstore/java/retrofit2-play26/pom.xml index ea9ecd85326f..3101a86f19a9 100644 --- a/samples/client/petstore/java/retrofit2-play26/pom.xml +++ b/samples/client/petstore/java/retrofit2-play26/pom.xml @@ -301,7 +301,7 @@ 1.8 ${java.version} ${java.version} - 1.8.3 + 1.9.0 1.6.3 2.15.2 2.15.2 diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java index e613b9b8e09f..05c24d6bdb53 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/AnotherFakeApi.java @@ -12,6 +12,9 @@ import org.openapitools.client.model.Client; import java.util.UUID; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java index 6279aae50c8b..3f72d5f3c634 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeApi.java @@ -19,6 +19,9 @@ import org.openapitools.client.model.User; import org.openapitools.client.model.XmlItem; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java index af53baad6ab2..8eda86928f53 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/FakeClassnameTags123Api.java @@ -11,6 +11,9 @@ import org.openapitools.client.model.Client; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java index ecc66db936ae..b6814c9e916e 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/PetApi.java @@ -14,6 +14,9 @@ import org.openapitools.client.model.Pet; import java.util.Set; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java index 361ae3560b54..9904c1fb871e 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/StoreApi.java @@ -11,6 +11,9 @@ import org.openapitools.client.model.Order; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java index b3729f27abee..e28e7e4f3d42 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/api/UserApi.java @@ -12,6 +12,9 @@ import java.time.OffsetDateTime; import org.openapitools.client.model.User; +import javax.validation.constraints.*; +import javax.validation.Valid; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -40,7 +43,7 @@ CompletionStage> createUser( */ @POST("user/createWithArray") CompletionStage> createUsersWithArrayInput( - @retrofit2.http.Body List body + @retrofit2.http.Body List<@Valid User> body ); /** @@ -51,7 +54,7 @@ CompletionStage> createUsersWithArrayInput( */ @POST("user/createWithList") CompletionStage> createUsersWithListInput( - @retrofit2.http.Body List body + @retrofit2.http.Body List<@Valid User> body ); /** diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java index 7c664f0ed7c5..0676b9eb693a 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/ArrayTest.java @@ -46,7 +46,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest() { } @@ -122,13 +122,13 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -146,14 +146,14 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java index 03cbf4eafabe..f8821d021eb9 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FileSchemaTestClass.java @@ -42,7 +42,7 @@ public class FileSchemaTestClass { private ModelFile _file; public static final String JSON_PROPERTY_FILES = "files"; - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass() { } @@ -75,7 +75,7 @@ public void setFile(ModelFile _file) { } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; @@ -99,14 +99,14 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } @JsonProperty(JSON_PROPERTY_FILES) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java index 2b21678a0f3a..8db64fb12909 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/FormatTest.java @@ -540,7 +540,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java index 467c931fb45e..b937cc816dcd 100644 --- a/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java +++ b/samples/client/petstore/java/retrofit2-play26/src/main/java/org/openapitools/client/model/Pet.java @@ -59,7 +59,7 @@ public class Pet { private Set photoUrls = new LinkedHashSet<>(); public static final String JSON_PROPERTY_TAGS = "tags"; - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -224,7 +224,7 @@ public void setPhotoUrls(Set photoUrls) { } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; @@ -248,14 +248,14 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2/build.gradle b/samples/client/petstore/java/retrofit2/build.gradle index 3bd9b7df21ec..1a891a2ef800 100644 --- a/samples/client/petstore/java/retrofit2/build.gradle +++ b/samples/client/petstore/java/retrofit2/build.gradle @@ -102,7 +102,7 @@ ext { jakarta_annotation_version = "1.3.5" swagger_annotations_version = "1.5.22" junit_version = "4.13.2" - json_fire_version = "1.8.0" + json_fire_version = "1.9.0" } dependencies { diff --git a/samples/client/petstore/java/retrofit2/build.sbt b/samples/client/petstore/java/retrofit2/build.sbt index bd72ef8472c0..1a2ae1ec441d 100644 --- a/samples/client/petstore/java/retrofit2/build.sbt +++ b/samples/client/petstore/java/retrofit2/build.sbt @@ -14,7 +14,7 @@ lazy val root = (project in file(".")). "com.squareup.retrofit2" % "converter-gson" % "2.3.0" % "compile", "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", - "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "junit" % "junit" % "4.13.2" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" diff --git a/samples/client/petstore/java/retrofit2/pom.xml b/samples/client/petstore/java/retrofit2/pom.xml index 167ccff09191..d3247005cc28 100644 --- a/samples/client/petstore/java/retrofit2/pom.xml +++ b/samples/client/petstore/java/retrofit2/pom.xml @@ -260,7 +260,7 @@ 1.8 ${java.version} ${java.version} - 1.8.3 + 1.9.0 1.6.3 2.5.0 1.3.5 diff --git a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java index 4a67a31ec94e..c702eb130e2f 100644 --- a/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2/src/main/java/org/openapitools/client/model/FormatTest.java @@ -454,7 +454,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx2/build.gradle b/samples/client/petstore/java/retrofit2rx2/build.gradle index 892538e0a194..4bad500d2424 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.gradle +++ b/samples/client/petstore/java/retrofit2rx2/build.gradle @@ -103,7 +103,7 @@ ext { swagger_annotations_version = "1.5.22" junit_version = "4.13.2" rx_java_version = "2.1.1" - json_fire_version = "1.8.0" + json_fire_version = "1.9.0" } dependencies { diff --git a/samples/client/petstore/java/retrofit2rx2/build.sbt b/samples/client/petstore/java/retrofit2rx2/build.sbt index e663d1574d3d..872d126e7c5f 100644 --- a/samples/client/petstore/java/retrofit2rx2/build.sbt +++ b/samples/client/petstore/java/retrofit2rx2/build.sbt @@ -16,7 +16,7 @@ lazy val root = (project in file(".")). "io.reactivex.rxjava2" % "rxjava" % "2.1.1" % "compile", "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", - "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "junit" % "junit" % "4.13.2" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" diff --git a/samples/client/petstore/java/retrofit2rx2/pom.xml b/samples/client/petstore/java/retrofit2rx2/pom.xml index 31d58e496e74..fcec0a8541f0 100644 --- a/samples/client/petstore/java/retrofit2rx2/pom.xml +++ b/samples/client/petstore/java/retrofit2rx2/pom.xml @@ -270,7 +270,7 @@ 1.8 ${java.version} ${java.version} - 1.8.3 + 1.9.0 1.6.3 2.5.0 2.1.1 diff --git a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java index 4a67a31ec94e..c702eb130e2f 100644 --- a/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx2/src/main/java/org/openapitools/client/model/FormatTest.java @@ -454,7 +454,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/java/retrofit2rx3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/retrofit2rx3/build.gradle b/samples/client/petstore/java/retrofit2rx3/build.gradle index 98bc4e019a4b..29bfb6738e9d 100644 --- a/samples/client/petstore/java/retrofit2rx3/build.gradle +++ b/samples/client/petstore/java/retrofit2rx3/build.gradle @@ -103,7 +103,7 @@ ext { swagger_annotations_version = "1.5.22" junit_version = "4.13.2" rx_java_version = "3.0.4" - json_fire_version = "1.8.0" + json_fire_version = "1.9.0" } dependencies { diff --git a/samples/client/petstore/java/retrofit2rx3/build.sbt b/samples/client/petstore/java/retrofit2rx3/build.sbt index 1dcb6b3a3097..d95ca2d5e890 100644 --- a/samples/client/petstore/java/retrofit2rx3/build.sbt +++ b/samples/client/petstore/java/retrofit2rx3/build.sbt @@ -16,7 +16,7 @@ lazy val root = (project in file(".")). "io.reactivex.rxjava3" % "rxjava" % "3.0.4" % "compile", "io.swagger" % "swagger-annotations" % "1.5.21" % "compile", "org.apache.oltu.oauth2" % "org.apache.oltu.oauth2.client" % "1.0.1" % "compile", - "io.gsonfire" % "gson-fire" % "1.8.0" % "compile", + "io.gsonfire" % "gson-fire" % "1.9.0" % "compile", "jakarta.annotation" % "jakarta.annotation-api" % "1.3.5" % "compile", "junit" % "junit" % "4.13.2" % "test", "com.novocode" % "junit-interface" % "0.11" % "test" diff --git a/samples/client/petstore/java/retrofit2rx3/pom.xml b/samples/client/petstore/java/retrofit2rx3/pom.xml index cc5948ce6be5..d1a000cf6796 100644 --- a/samples/client/petstore/java/retrofit2rx3/pom.xml +++ b/samples/client/petstore/java/retrofit2rx3/pom.xml @@ -270,7 +270,7 @@ 1.8 ${java.version} ${java.version} - 1.8.3 + 1.9.0 1.6.3 2.5.0 3.0.4 diff --git a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java index 4a67a31ec94e..c702eb130e2f 100644 --- a/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/retrofit2rx3/src/main/java/org/openapitools/client/model/FormatTest.java @@ -454,7 +454,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION b/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/java/vertx-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java index ce7dc954214c..5c3dda075600 100644 --- a/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/vertx-no-nullable/src/main/java/org/openapitools/client/model/FormatTest.java @@ -514,7 +514,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/java/vertx/.openapi-generator/VERSION b/samples/client/petstore/java/vertx/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/vertx/.openapi-generator/VERSION +++ b/samples/client/petstore/java/vertx/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/vertx/README.md b/samples/client/petstore/java/vertx/README.md index 1cab57b4f6ca..c022185a73c7 100644 --- a/samples/client/petstore/java/vertx/README.md +++ b/samples/client/petstore/java/vertx/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/vertx/api/openapi.yaml b/samples/client/petstore/java/vertx/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/vertx/api/openapi.yaml +++ b/samples/client/petstore/java/vertx/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/vertx/docs/FakeApi.md b/samples/client/petstore/java/vertx/docs/FakeApi.md index b9dc1bfbd928..8aec7cab4285 100644 --- a/samples/client/petstore/java/vertx/docs/FakeApi.md +++ b/samples/client/petstore/java/vertx/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApi.java index f0768854f800..e3717cf8f8c7 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApi.java @@ -56,6 +56,10 @@ public interface FakeApi { void fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty, ApiClient.AuthInfo authInfo, Handler> handler); + void testAdditionalPropertiesReference(Map requestBody, Handler> handler); + + void testAdditionalPropertiesReference(Map requestBody, ApiClient.AuthInfo authInfo, Handler> handler); + void testBodyWithBinary(AsyncFile body, Handler> handler); void testBodyWithBinary(AsyncFile body, ApiClient.AuthInfo authInfo, Handler> handler); diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApiImpl.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApiImpl.java index 88734181cfc0..c1375f95b403 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApiImpl.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/FakeApiImpl.java @@ -406,6 +406,54 @@ public void fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerOb apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, authInfo, localVarReturnType, resultHandler); } /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param resultHandler Asynchronous result handler + */ + public void testAdditionalPropertiesReference(Map requestBody, Handler> resultHandler) { + testAdditionalPropertiesReference(requestBody, null, resultHandler); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param authInfo per call authentication override. + * @param resultHandler Asynchronous result handler + */ + public void testAdditionalPropertiesReference(Map requestBody, ApiClient.AuthInfo authInfo, Handler> resultHandler) { + Object localVarBody = requestBody; + + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + resultHandler.handle(ApiException.fail(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference")); + return; + } + + // create path and map variables + String localVarPath = "/fake/additionalProperties-reference"; + + // query params + List localVarQueryParams = new ArrayList<>(); + + // header params + MultiMap localVarHeaderParams = MultiMap.caseInsensitiveMultiMap(); + + // cookie params + MultiMap localVarCookieParams = MultiMap.caseInsensitiveMultiMap(); + + // form params + // TODO: sending files within multipart/form-data is not supported yet (because of vertx web-client) + Map localVarFormParams = new HashMap<>(); + + String[] localVarAccepts = { }; + String[] localVarContentTypes = { "application/json" }; + String[] localVarAuthNames = new String[] { }; + + apiClient.invokeAPI(localVarPath, "POST", localVarQueryParams, localVarBody, localVarHeaderParams, localVarCookieParams, localVarFormParams, localVarAccepts, localVarContentTypes, localVarAuthNames, authInfo, null, resultHandler); + } + /** * * For this test, the body has to be a binary file. * @param body image to upload (required) diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/rxjava/FakeApi.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/rxjava/FakeApi.java index f5537a272c92..8980ce3c1afb 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/rxjava/FakeApi.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/api/rxjava/FakeApi.java @@ -397,6 +397,51 @@ public Single rxFakePropertyEnumIntegerSerialize(Ou )); } /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param resultHandler Asynchronous result handler + */ + public void testAdditionalPropertiesReference(Map requestBody, Handler> resultHandler) { + delegate.testAdditionalPropertiesReference(requestBody, resultHandler); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param authInfo call specific auth overrides + * @param resultHandler Asynchronous result handler + */ + public void testAdditionalPropertiesReference(Map requestBody, ApiClient.AuthInfo authInfo, Handler> resultHandler) { + delegate.testAdditionalPropertiesReference(requestBody, authInfo, resultHandler); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return Asynchronous result handler (RxJava Single) + */ + public Single rxTestAdditionalPropertiesReference(Map requestBody) { + return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> + delegate.testAdditionalPropertiesReference(requestBody, fut) + )); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @param authInfo call specific auth overrides + * @return Asynchronous result handler (RxJava Single) + */ + public Single rxTestAdditionalPropertiesReference(Map requestBody, ApiClient.AuthInfo authInfo) { + return Single.create(new io.vertx.rx.java.SingleOnSubscribeAdapter<>(fut -> + delegate.testAdditionalPropertiesReference(requestBody, authInfo, fut) + )); + } + /** * * For this test, the body has to be a binary file. * @param body image to upload (required) diff --git a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java index 9589f801ac9e..9e86b3628756 100644 --- a/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/vertx/src/main/java/org/openapitools/client/model/FormatTest.java @@ -577,7 +577,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/webclient-jakarta/.openapi-generator/VERSION b/samples/client/petstore/java/webclient-jakarta/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/webclient-jakarta/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient-jakarta/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-jakarta/README.md b/samples/client/petstore/java/webclient-jakarta/README.md index a88a5413c4f8..65b06fccc8de 100644 --- a/samples/client/petstore/java/webclient-jakarta/README.md +++ b/samples/client/petstore/java/webclient-jakarta/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/webclient-jakarta/api/openapi.yaml b/samples/client/petstore/java/webclient-jakarta/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/webclient-jakarta/api/openapi.yaml +++ b/samples/client/petstore/java/webclient-jakarta/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/webclient-jakarta/build.gradle b/samples/client/petstore/java/webclient-jakarta/build.gradle index 71ee7b668b7a..9e82e0e32b5c 100644 --- a/samples/client/petstore/java/webclient-jakarta/build.gradle +++ b/samples/client/petstore/java/webclient-jakarta/build.gradle @@ -112,10 +112,10 @@ if(hasProperty('target') && target == 'android') { } ext { - spring_boot_version = "3.0.1" + spring_boot_version = "3.0.12" jakarta_annotation_version = "2.1.1" - reactor_version = "3.5.1" - reactor_netty_version = "1.1.1" + reactor_version = "3.5.12" + reactor_netty_version = "1.1.13" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" diff --git a/samples/client/petstore/java/webclient-jakarta/docs/FakeApi.md b/samples/client/petstore/java/webclient-jakarta/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/webclient-jakarta/docs/FakeApi.md +++ b/samples/client/petstore/java/webclient-jakarta/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/webclient-jakarta/pom.xml b/samples/client/petstore/java/webclient-jakarta/pom.xml index c0ee7564416d..877afeb2de53 100644 --- a/samples/client/petstore/java/webclient-jakarta/pom.xml +++ b/samples/client/petstore/java/webclient-jakarta/pom.xml @@ -123,10 +123,10 @@ 2.15.2 2.15.2 0.2.6 - 3.0.1 + 3.0.12 2.1.1 - 3.5.1 - 1.1.1 + 3.5.12 + 1.1.13 4.13.2 diff --git a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/ApiClient.java index 63234665a04b..3265438f902e 100644 --- a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/ApiClient.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.jackson.nullable.JsonNullableModule; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/FakeApi.java index 4eda70f5a0c2..7b435264e5ef 100644 --- a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/FakeApi.java @@ -212,6 +212,7 @@ private ResponseSpec fakeHttpSignatureTestRequestCreation(Pet pet, String query1 final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_1", query1)); + if (header1 != null) headerParams.add("header_1", apiClient.parameterToString(header1)); @@ -623,6 +624,75 @@ public Mono> fakePropertyEnumInteger public ResponseSpec fakePropertyEnumIntegerSerializeWithResponseSpec(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws WebClientResponseException { return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty); } + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec testAdditionalPropertiesReferenceRequestCreation(Map requestBody) throws WebClientResponseException { + Object postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new WebClientResponseException("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/fake/additionalProperties-reference", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testAdditionalPropertiesReference(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).bodyToMono(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono> testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).toEntity(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testAdditionalPropertiesReferenceWithResponseSpec(Map requestBody) throws WebClientResponseException { + return testAdditionalPropertiesReferenceRequestCreation(requestBody); + } /** * * For this test, the body has to be a binary file. @@ -788,7 +858,7 @@ private ResponseSpec testBodyWithQueryParamsRequestCreation(String query, User u final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query", query)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { @@ -1111,6 +1181,7 @@ private ResponseSpec testEnumParametersRequestCreation(List enumHeaderSt queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble)); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "enum_query_model_array", enumQueryModelArray)); + if (enumHeaderStringArray != null) headerParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); @@ -1234,6 +1305,7 @@ private ResponseSpec testGroupParametersRequestCreation(Integer requiredStringGr queryParams.putAll(apiClient.parameterToMultiValueMap(null, "required_int64_group", requiredInt64Group)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_group", stringGroup)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "int64_group", int64Group)); + if (requiredBooleanGroup != null) headerParams.add("required_boolean_group", apiClient.parameterToString(requiredBooleanGroup)); @@ -1643,7 +1715,7 @@ private ResponseSpec testQueryParameterCollectionFormatRequestCreation(List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; diff --git a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/PetApi.java index f9ae47490280..45389ee255c1 100644 --- a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/PetApi.java @@ -147,6 +147,7 @@ private ResponseSpec deletePetRequestCreation(Long petId, String apiKey) throws final MultiValueMap cookieParams = new LinkedMultiValueMap(); final MultiValueMap formParams = new LinkedMultiValueMap(); + if (apiKey != null) headerParams.add("api_key", apiClient.parameterToString(apiKey)); final String[] localVarAccepts = { }; @@ -225,7 +226,7 @@ private ResponseSpec findPetsByStatusRequestCreation(List status) throws final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; @@ -305,7 +306,7 @@ private ResponseSpec findPetsByTagsRequestCreation(Set tags) throws WebC final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/UserApi.java index ebb82cc15b9a..68346059e913 100644 --- a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/api/UserApi.java @@ -439,7 +439,7 @@ private ResponseSpec loginUserRequestCreation(String username, String password) queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/model/FormatTest.java index b223a7bbea00..d0e2ff8b961b 100644 --- a/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/webclient-jakarta/src/main/java/org/openapitools/client/model/FormatTest.java @@ -577,7 +577,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/webclient-nullable-arrays/.openapi-generator/VERSION b/samples/client/petstore/java/webclient-nullable-arrays/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/webclient-nullable-arrays/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient-nullable-arrays/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-nullable-arrays/build.gradle b/samples/client/petstore/java/webclient-nullable-arrays/build.gradle index 6e36612f7023..690b3ea79966 100644 --- a/samples/client/petstore/java/webclient-nullable-arrays/build.gradle +++ b/samples/client/petstore/java/webclient-nullable-arrays/build.gradle @@ -112,10 +112,10 @@ if(hasProperty('target') && target == 'android') { } ext { - spring_boot_version = "2.6.6" + spring_boot_version = "2.7.17" jakarta_annotation_version = "1.3.5" - reactor_version = "3.4.3" - reactor_netty_version = "1.0.4" + reactor_version = "3.4.34" + reactor_netty_version = "1.0.39" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" diff --git a/samples/client/petstore/java/webclient-nullable-arrays/pom.xml b/samples/client/petstore/java/webclient-nullable-arrays/pom.xml index ece14e13171b..898a6952def9 100644 --- a/samples/client/petstore/java/webclient-nullable-arrays/pom.xml +++ b/samples/client/petstore/java/webclient-nullable-arrays/pom.xml @@ -123,10 +123,10 @@ 2.15.2 2.15.2 0.2.6 - 2.6.6 + 2.7.17 1.3.5 - 3.4.3 - 1.0.4 + 3.4.34 + 1.0.39 4.13.2 diff --git a/samples/client/petstore/java/webclient-nullable-arrays/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient-nullable-arrays/src/main/java/org/openapitools/client/ApiClient.java index cba5137810b8..07ce47ab2cde 100644 --- a/samples/client/petstore/java/webclient-nullable-arrays/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient-nullable-arrays/src/main/java/org/openapitools/client/ApiClient.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.jackson.nullable.JsonNullableModule; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/samples/client/petstore/java/webclient-swagger2/.openapi-generator/VERSION b/samples/client/petstore/java/webclient-swagger2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/webclient-swagger2/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient-swagger2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient-swagger2/README.md b/samples/client/petstore/java/webclient-swagger2/README.md index a88a5413c4f8..65b06fccc8de 100644 --- a/samples/client/petstore/java/webclient-swagger2/README.md +++ b/samples/client/petstore/java/webclient-swagger2/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/webclient-swagger2/api/openapi.yaml b/samples/client/petstore/java/webclient-swagger2/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/webclient-swagger2/api/openapi.yaml +++ b/samples/client/petstore/java/webclient-swagger2/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/webclient-swagger2/build.gradle b/samples/client/petstore/java/webclient-swagger2/build.gradle index 96475de4b16f..9052967eaba1 100644 --- a/samples/client/petstore/java/webclient-swagger2/build.gradle +++ b/samples/client/petstore/java/webclient-swagger2/build.gradle @@ -113,10 +113,10 @@ if(hasProperty('target') && target == 'android') { ext { swagger_annotations_version = "2.2.9" - spring_boot_version = "2.6.6" + spring_boot_version = "2.7.17" jakarta_annotation_version = "1.3.5" - reactor_version = "3.4.3" - reactor_netty_version = "1.0.4" + reactor_version = "3.4.34" + reactor_netty_version = "1.0.39" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" diff --git a/samples/client/petstore/java/webclient-swagger2/docs/FakeApi.md b/samples/client/petstore/java/webclient-swagger2/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/webclient-swagger2/docs/FakeApi.md +++ b/samples/client/petstore/java/webclient-swagger2/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/webclient-swagger2/pom.xml b/samples/client/petstore/java/webclient-swagger2/pom.xml index 760405970e7a..e8297f3e9547 100644 --- a/samples/client/petstore/java/webclient-swagger2/pom.xml +++ b/samples/client/petstore/java/webclient-swagger2/pom.xml @@ -129,10 +129,10 @@ 2.15.2 2.15.2 0.2.6 - 2.6.6 + 2.7.17 1.3.5 - 3.4.3 - 1.0.4 + 3.4.34 + 1.0.39 4.13.2 diff --git a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/ApiClient.java index d582b89eece9..e379ae2db788 100644 --- a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/ApiClient.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.jackson.nullable.JsonNullableModule; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/FakeApi.java index a7602fbaff3d..3e209c2ff620 100644 --- a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/FakeApi.java @@ -212,6 +212,7 @@ private ResponseSpec fakeHttpSignatureTestRequestCreation(Pet pet, String query1 final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_1", query1)); + if (header1 != null) headerParams.add("header_1", apiClient.parameterToString(header1)); @@ -623,6 +624,75 @@ public Mono> fakePropertyEnumInteger public ResponseSpec fakePropertyEnumIntegerSerializeWithResponseSpec(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws WebClientResponseException { return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty); } + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec testAdditionalPropertiesReferenceRequestCreation(Map requestBody) throws WebClientResponseException { + Object postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new WebClientResponseException("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/fake/additionalProperties-reference", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testAdditionalPropertiesReference(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).bodyToMono(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono> testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).toEntity(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testAdditionalPropertiesReferenceWithResponseSpec(Map requestBody) throws WebClientResponseException { + return testAdditionalPropertiesReferenceRequestCreation(requestBody); + } /** * * For this test, the body has to be a binary file. @@ -788,7 +858,7 @@ private ResponseSpec testBodyWithQueryParamsRequestCreation(String query, User u final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query", query)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { @@ -1111,6 +1181,7 @@ private ResponseSpec testEnumParametersRequestCreation(List enumHeaderSt queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble)); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "enum_query_model_array", enumQueryModelArray)); + if (enumHeaderStringArray != null) headerParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); @@ -1234,6 +1305,7 @@ private ResponseSpec testGroupParametersRequestCreation(Integer requiredStringGr queryParams.putAll(apiClient.parameterToMultiValueMap(null, "required_int64_group", requiredInt64Group)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_group", stringGroup)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "int64_group", int64Group)); + if (requiredBooleanGroup != null) headerParams.add("required_boolean_group", apiClient.parameterToString(requiredBooleanGroup)); @@ -1643,7 +1715,7 @@ private ResponseSpec testQueryParameterCollectionFormatRequestCreation(List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; diff --git a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/PetApi.java index c5588dff9700..9be0a49522a3 100644 --- a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/PetApi.java @@ -147,6 +147,7 @@ private ResponseSpec deletePetRequestCreation(Long petId, String apiKey) throws final MultiValueMap cookieParams = new LinkedMultiValueMap(); final MultiValueMap formParams = new LinkedMultiValueMap(); + if (apiKey != null) headerParams.add("api_key", apiClient.parameterToString(apiKey)); final String[] localVarAccepts = { }; @@ -225,7 +226,7 @@ private ResponseSpec findPetsByStatusRequestCreation(List status) throws final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; @@ -305,7 +306,7 @@ private ResponseSpec findPetsByTagsRequestCreation(Set tags) throws WebC final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/UserApi.java index ad76ef2ea733..dab56cb7a2c0 100644 --- a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/api/UserApi.java @@ -439,7 +439,7 @@ private ResponseSpec loginUserRequestCreation(String username, String password) queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/model/FormatTest.java index ac72dce3f118..e97f03e2726f 100644 --- a/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/webclient-swagger2/src/main/java/org/openapitools/client/model/FormatTest.java @@ -594,7 +594,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/java/webclient/.openapi-generator/VERSION b/samples/client/petstore/java/webclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/java/webclient/.openapi-generator/VERSION +++ b/samples/client/petstore/java/webclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/java/webclient/README.md b/samples/client/petstore/java/webclient/README.md index a88a5413c4f8..65b06fccc8de 100644 --- a/samples/client/petstore/java/webclient/README.md +++ b/samples/client/petstore/java/webclient/README.md @@ -123,6 +123,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/java/webclient/api/openapi.yaml b/samples/client/petstore/java/webclient/api/openapi.yaml index 991caf590017..d02433c791c2 100644 --- a/samples/client/petstore/java/webclient/api/openapi.yaml +++ b/samples/client/petstore/java/webclient/api/openapi.yaml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/client/petstore/java/webclient/build.gradle b/samples/client/petstore/java/webclient/build.gradle index a804139148d9..e34609ac6301 100644 --- a/samples/client/petstore/java/webclient/build.gradle +++ b/samples/client/petstore/java/webclient/build.gradle @@ -112,10 +112,10 @@ if(hasProperty('target') && target == 'android') { } ext { - spring_boot_version = "2.6.6" + spring_boot_version = "2.7.17" jakarta_annotation_version = "1.3.5" - reactor_version = "3.4.3" - reactor_netty_version = "1.0.4" + reactor_version = "3.4.34" + reactor_netty_version = "1.0.39" jackson_version = "2.13.4" jackson_databind_version = "2.13.4.2" jackson_databind_nullable_version = "0.2.6" diff --git a/samples/client/petstore/java/webclient/docs/FakeApi.md b/samples/client/petstore/java/webclient/docs/FakeApi.md index e442af92c3b7..148fc7a22ddd 100644 --- a/samples/client/petstore/java/webclient/docs/FakeApi.md +++ b/samples/client/petstore/java/webclient/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -548,6 +549,71 @@ No authorization required | **200** | Output enum (int) | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.models.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | [**Map<String, Object>**](Object.md)| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/java/webclient/pom.xml b/samples/client/petstore/java/webclient/pom.xml index fbfc0947328b..475fc63d50d6 100644 --- a/samples/client/petstore/java/webclient/pom.xml +++ b/samples/client/petstore/java/webclient/pom.xml @@ -123,10 +123,10 @@ 2.15.2 2.15.2 0.2.6 - 2.6.6 + 2.7.17 1.3.5 - 3.4.3 - 1.0.4 + 3.4.34 + 1.0.39 4.13.2 diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java index d582b89eece9..e379ae2db788 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/ApiClient.java @@ -4,8 +4,6 @@ import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import org.openapitools.jackson.nullable.JsonNullableModule; -import org.apache.commons.logging.Log; -import org.apache.commons.logging.LogFactory; import org.springframework.core.ParameterizedTypeReference; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpMethod; diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java index a7602fbaff3d..3e209c2ff620 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/FakeApi.java @@ -212,6 +212,7 @@ private ResponseSpec fakeHttpSignatureTestRequestCreation(Pet pet, String query1 final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query_1", query1)); + if (header1 != null) headerParams.add("header_1", apiClient.parameterToString(header1)); @@ -623,6 +624,75 @@ public Mono> fakePropertyEnumInteger public ResponseSpec fakePropertyEnumIntegerSerializeWithResponseSpec(OuterObjectWithEnumProperty outerObjectWithEnumProperty) throws WebClientResponseException { return fakePropertyEnumIntegerSerializeRequestCreation(outerObjectWithEnumProperty); } + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + private ResponseSpec testAdditionalPropertiesReferenceRequestCreation(Map requestBody) throws WebClientResponseException { + Object postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody == null) { + throw new WebClientResponseException("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference", HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase(), null, null, null); + } + // create path and map variables + final Map pathParams = new HashMap(); + + final MultiValueMap queryParams = new LinkedMultiValueMap(); + final HttpHeaders headerParams = new HttpHeaders(); + final MultiValueMap cookieParams = new LinkedMultiValueMap(); + final MultiValueMap formParams = new LinkedMultiValueMap(); + + final String[] localVarAccepts = { }; + final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); + final String[] localVarContentTypes = { + "application/json" + }; + final MediaType localVarContentType = apiClient.selectHeaderContentType(localVarContentTypes); + + String[] localVarAuthNames = new String[] { }; + + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return apiClient.invokeAPI("/fake/additionalProperties-reference", HttpMethod.POST, pathParams, queryParams, postBody, headerParams, cookieParams, formParams, localVarAccept, localVarContentType, localVarAuthNames, localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono testAdditionalPropertiesReference(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).bodyToMono(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public Mono> testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws WebClientResponseException { + ParameterizedTypeReference localVarReturnType = new ParameterizedTypeReference() {}; + return testAdditionalPropertiesReferenceRequestCreation(requestBody).toEntity(localVarReturnType); + } + + /** + * test referenced additionalProperties + * + *

              200 - successful operation + * @param requestBody request body + * @return ResponseSpec + * @throws WebClientResponseException if an error occurs while attempting to invoke the API + */ + public ResponseSpec testAdditionalPropertiesReferenceWithResponseSpec(Map requestBody) throws WebClientResponseException { + return testAdditionalPropertiesReferenceRequestCreation(requestBody); + } /** * * For this test, the body has to be a binary file. @@ -788,7 +858,7 @@ private ResponseSpec testBodyWithQueryParamsRequestCreation(String query, User u final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "query", query)); - + final String[] localVarAccepts = { }; final List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { @@ -1111,6 +1181,7 @@ private ResponseSpec testEnumParametersRequestCreation(List enumHeaderSt queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_integer", enumQueryInteger)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "enum_query_double", enumQueryDouble)); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("multi".toUpperCase(Locale.ROOT)), "enum_query_model_array", enumQueryModelArray)); + if (enumHeaderStringArray != null) headerParams.add("enum_header_string_array", apiClient.parameterToString(enumHeaderStringArray)); @@ -1234,6 +1305,7 @@ private ResponseSpec testGroupParametersRequestCreation(Integer requiredStringGr queryParams.putAll(apiClient.parameterToMultiValueMap(null, "required_int64_group", requiredInt64Group)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "string_group", stringGroup)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "int64_group", int64Group)); + if (requiredBooleanGroup != null) headerParams.add("required_boolean_group", apiClient.parameterToString(requiredBooleanGroup)); @@ -1643,7 +1715,7 @@ private ResponseSpec testQueryParameterCollectionFormatRequestCreation(List localVarAccept = apiClient.selectHeaderAccept(localVarAccepts); final String[] localVarContentTypes = { }; diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java index c5588dff9700..9be0a49522a3 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/PetApi.java @@ -147,6 +147,7 @@ private ResponseSpec deletePetRequestCreation(Long petId, String apiKey) throws final MultiValueMap cookieParams = new LinkedMultiValueMap(); final MultiValueMap formParams = new LinkedMultiValueMap(); + if (apiKey != null) headerParams.add("api_key", apiClient.parameterToString(apiKey)); final String[] localVarAccepts = { }; @@ -225,7 +226,7 @@ private ResponseSpec findPetsByStatusRequestCreation(List status) throws final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "status", status)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; @@ -305,7 +306,7 @@ private ResponseSpec findPetsByTagsRequestCreation(Set tags) throws WebC final MultiValueMap formParams = new LinkedMultiValueMap(); queryParams.putAll(apiClient.parameterToMultiValueMap(ApiClient.CollectionFormat.valueOf("csv".toUpperCase(Locale.ROOT)), "tags", tags)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java index ad76ef2ea733..dab56cb7a2c0 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/api/UserApi.java @@ -439,7 +439,7 @@ private ResponseSpec loginUserRequestCreation(String username, String password) queryParams.putAll(apiClient.parameterToMultiValueMap(null, "username", username)); queryParams.putAll(apiClient.parameterToMultiValueMap(null, "password", password)); - + final String[] localVarAccepts = { "application/xml", "application/json" }; diff --git a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java index 1efd4270dd5d..f9ddc4d4d294 100644 --- a/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/client/petstore/java/webclient/src/main/java/org/openapitools/client/model/FormatTest.java @@ -577,7 +577,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION b/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-apollo/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-apollo/README.md b/samples/client/petstore/javascript-apollo/README.md index 96969380ac20..cc9221bf4653 100644 --- a/samples/client/petstore/javascript-apollo/README.md +++ b/samples/client/petstore/javascript-apollo/README.md @@ -129,6 +129,7 @@ Class | Method | HTTP request | Description *OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/javascript-apollo/docs/FakeApi.md b/samples/client/petstore/javascript-apollo/docs/FakeApi.md index b67ae97ad0d6..140ff85a048d 100644 --- a/samples/client/petstore/javascript-apollo/docs/FakeApi.md +++ b/samples/client/petstore/javascript-apollo/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | @@ -347,6 +348,51 @@ No authorization required - **Accept**: */* +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let requestBody = {key: null}; // {String: Object} | request body +apiInstance.testAdditionalPropertiesReference(requestBody, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**{String: Object}**](Object.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/javascript-apollo/src/api/FakeApi.js b/samples/client/petstore/javascript-apollo/src/api/FakeApi.js index 3cd150371997..1699e697ffaa 100644 --- a/samples/client/petstore/javascript-apollo/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-apollo/src/api/FakeApi.js @@ -279,6 +279,42 @@ export default class FakeApi extends ApiClient { ); } + /** + * test referenced additionalProperties + * + * @param {Object.} requestBody request body + * @param requestInit Dynamic configuration. @see {@link https://github.com/apollographql/apollo-server/pull/1277} + * @return {Promise} + */ + async testAdditionalPropertiesReference(requestBody, requestInit) { + let postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody === undefined || requestBody === null) { + throw new Error("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + 'User-Agent': 'OpenAPI-Generator/1.0.0/Javascript', + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + + return this.callApi( + '/fake/additionalProperties-reference', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, requestInit + ); + } + /** * For this test, the body has to be a binary file. * @param {File} body image to upload diff --git a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/javascript-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-es6/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-es6/README.md b/samples/client/petstore/javascript-es6/README.md index f3aec1c96bf0..8b628d8ea909 100644 --- a/samples/client/petstore/javascript-es6/README.md +++ b/samples/client/petstore/javascript-es6/README.md @@ -129,6 +129,7 @@ Class | Method | HTTP request | Description *OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/javascript-es6/docs/FakeApi.md b/samples/client/petstore/javascript-es6/docs/FakeApi.md index f19950114455..6ed67beb69f7 100644 --- a/samples/client/petstore/javascript-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | @@ -347,6 +348,51 @@ No authorization required - **Accept**: */* +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let requestBody = {key: null}; // {String: Object} | request body +apiInstance.testAdditionalPropertiesReference(requestBody, (error, data, response) => { + if (error) { + console.error(error); + } else { + console.log('API called successfully.'); + } +}); +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**{String: Object}**](Object.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/javascript-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-es6/src/api/FakeApi.js index 4d5bcd0b826f..c47f7247b7b3 100644 --- a/samples/client/petstore/javascript-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-es6/src/api/FakeApi.js @@ -321,6 +321,47 @@ export default class FakeApi { ); } + /** + * Callback function to receive the result of the testAdditionalPropertiesReference operation. + * @callback module:api/FakeApi~testAdditionalPropertiesReferenceCallback + * @param {String} error Error message, if any. + * @param data This operation does not return a value. + * @param {String} response The complete HTTP response. + */ + + /** + * test referenced additionalProperties + * + * @param {Object.} requestBody request body + * @param {module:api/FakeApi~testAdditionalPropertiesReferenceCallback} callback The callback function, accepting three arguments: error, data, response + */ + testAdditionalPropertiesReference(requestBody, callback) { + let postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody === undefined || requestBody === null) { + throw new Error("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/additionalProperties-reference', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null, callback + ); + } + /** * Callback function to receive the result of the testBodyWithBinary operation. * @callback module:api/FakeApi~testBodyWithBinaryCallback diff --git a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION +++ b/samples/client/petstore/javascript-promise-es6/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/javascript-promise-es6/README.md b/samples/client/petstore/javascript-promise-es6/README.md index cbe9da562f0a..b538c6edc33c 100644 --- a/samples/client/petstore/javascript-promise-es6/README.md +++ b/samples/client/petstore/javascript-promise-es6/README.md @@ -127,6 +127,7 @@ Class | Method | HTTP request | Description *OpenApiPetstore.FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *OpenApiPetstore.FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *OpenApiPetstore.FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +*OpenApiPetstore.FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *OpenApiPetstore.FakeApi* | [**testBodyWithBinary**](docs/FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | *OpenApiPetstore.FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *OpenApiPetstore.FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md index 91964dffaa70..c04cb9b9057f 100644 --- a/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md +++ b/samples/client/petstore/javascript-promise-es6/docs/FakeApi.md @@ -11,6 +11,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | @@ -340,6 +341,50 @@ No authorization required - **Accept**: */* +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```javascript +import OpenApiPetstore from 'open_api_petstore'; + +let apiInstance = new OpenApiPetstore.FakeApi(); +let requestBody = {key: null}; // {String: Object} | request body +apiInstance.testAdditionalPropertiesReference(requestBody).then(() => { + console.log('API called successfully.'); +}, (error) => { + console.error(error); +}); + +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**{String: Object}**](Object.md)| request body | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## testBodyWithBinary > testBodyWithBinary(body) diff --git a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js index 15a2f60eb1dc..67f8f1b2d286 100644 --- a/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js +++ b/samples/client/petstore/javascript-promise-es6/src/api/FakeApi.js @@ -357,6 +357,53 @@ export default class FakeApi { } + /** + * test referenced additionalProperties + * + * @param {Object.} requestBody request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise}, with an object containing HTTP response + */ + testAdditionalPropertiesReferenceWithHttpInfo(requestBody) { + let postBody = requestBody; + // verify the required parameter 'requestBody' is set + if (requestBody === undefined || requestBody === null) { + throw new Error("Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + let pathParams = { + }; + let queryParams = { + }; + let headerParams = { + }; + let formParams = { + }; + + let authNames = []; + let contentTypes = ['application/json']; + let accepts = []; + let returnType = null; + return this.apiClient.callApi( + '/fake/additionalProperties-reference', 'POST', + pathParams, queryParams, headerParams, formParams, postBody, + authNames, contentTypes, accepts, returnType, null + ); + } + + /** + * test referenced additionalProperties + * + * @param {Object.} requestBody request body + * @return {Promise} a {@link https://www.promisejs.org/|Promise} + */ + testAdditionalPropertiesReference(requestBody) { + return this.testAdditionalPropertiesReferenceWithHttpInfo(requestBody) + .then(function(response_and_data) { + return response_and_data.data; + }); + } + + /** * For this test, the body has to be a binary file. * @param {File} body image to upload diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/.openapi-generator/VERSION b/samples/client/petstore/jaxrs-cxf-client-jackson/.openapi-generator/VERSION index 0984c4c1ad21..fff4bdd7ab59 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -5.4.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml b/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml index 8c7d5814eb3a..9f9b7a96fadb 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/pom.xml @@ -87,6 +87,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -147,7 +155,7 @@ com.fasterxml.jackson.datatype - jackson-datatype-joda + jackson-datatype-jsr310 ${jackson-jaxrs-version} @@ -156,6 +164,11 @@ ${jakarta-annotation-version} provided + + joda-time + joda-time + 2.10.13 + @@ -167,16 +180,16 @@ - 1.7 + 1.8 ${java.version} ${java.version} 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.10 + 1.4.14 3.3.0 - 2.9.9 - 1.3.5 + 2.15.2 + 1.3.5 UTF-8 diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Category.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Category.java index 385d6324ae44..dccf1f3db9c5 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Category.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Category.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A category for a pet **/ @ApiModel(description="A category for a pet") + public class Category { @ApiModelProperty(value = "") @@ -52,6 +54,23 @@ public Category name(String name) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/ModelApiResponse.java index d37f40980d36..af32c823d47a 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -1,14 +1,17 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes the result of uploading an image resource **/ @ApiModel(description="Describes the result of uploading an image resource") + public class ModelApiResponse { @ApiModelProperty(value = "") @@ -73,6 +76,24 @@ public ModelApiResponse message(String message) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Order.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Order.java index aa0f0ce80b84..327e990d676d 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Order.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Order.java @@ -6,12 +6,14 @@ import java.util.Date; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * An order for a pets from the pet store **/ @ApiModel(description="An order for a pets from the pet store") + public class Order { @ApiModelProperty(value = "") @@ -177,6 +179,27 @@ public Order complete(Boolean complete) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Pet.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Pet.java index c151c3733984..539ef8a6722f 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Pet.java @@ -4,17 +4,20 @@ import com.fasterxml.jackson.annotation.JsonValue; import io.swagger.annotations.ApiModel; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.Category; import org.openapitools.model.Tag; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A pet for sale in the pet store **/ @ApiModel(description="A pet for sale in the pet store") + public class Pet { @ApiModelProperty(value = "") @@ -27,10 +30,10 @@ public class Pet { private String name; @ApiModelProperty(required = true, value = "") - private List photoUrls = new ArrayList(); + private List photoUrls = new ArrayList<>(); @ApiModelProperty(value = "") - private List tags = null; + private List tags; public enum StatusEnum { @@ -190,6 +193,27 @@ public Pet status(StatusEnum status) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Tag.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Tag.java index 49680fe48a4a..9c011ae12b41 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/Tag.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A tag for a pet **/ @ApiModel(description="A tag for a pet") + public class Tag { @ApiModelProperty(value = "") @@ -52,6 +54,23 @@ public Tag name(String name) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/User.java b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/User.java index bab06ed1f71c..001a0b7437b4 100644 --- a/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/User.java +++ b/samples/client/petstore/jaxrs-cxf-client-jackson/src/gen/java/org/openapitools/model/User.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A User who is purchasing from the pet store **/ @ApiModel(description="A User who is purchasing from the pet store") + public class User { @ApiModelProperty(value = "") @@ -181,6 +183,29 @@ public User userStatus(Integer userStatus) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION b/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION index 0984c4c1ad21..fff4bdd7ab59 100644 --- a/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION +++ b/samples/client/petstore/jaxrs-cxf-client/.openapi-generator/VERSION @@ -1 +1 @@ -5.4.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jaxrs-cxf-client/pom.xml b/samples/client/petstore/jaxrs-cxf-client/pom.xml index d0b8597d5f3d..283b696df7fe 100644 --- a/samples/client/petstore/jaxrs-cxf-client/pom.xml +++ b/samples/client/petstore/jaxrs-cxf-client/pom.xml @@ -87,6 +87,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -147,7 +155,7 @@ com.fasterxml.jackson.datatype - jackson-datatype-joda + jackson-datatype-jsr310 ${jackson-jaxrs-version} @@ -156,6 +164,11 @@ ${jakarta-annotation-version} provided + + joda-time + joda-time + 2.10.13 + @@ -167,16 +180,16 @@ - 1.7 + 1.8 ${java.version} ${java.version} 1.5.18 9.2.9.v20150224 4.13.2 - 1.2.10 + 1.4.14 3.3.0 - 2.9.9 - 1.3.5 + 2.15.2 + 1.3.5 UTF-8 diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Category.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Category.java index 385d6324ae44..dccf1f3db9c5 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Category.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Category.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A category for a pet **/ @ApiModel(description="A category for a pet") + public class Category { @ApiModelProperty(value = "") @@ -52,6 +54,23 @@ public Category name(String name) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/ModelApiResponse.java index d37f40980d36..43e7bd9e4329 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * Describes the result of uploading an image resource **/ @ApiModel(description="Describes the result of uploading an image resource") + public class ModelApiResponse { @ApiModelProperty(value = "") @@ -73,6 +75,24 @@ public ModelApiResponse message(String message) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Order.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Order.java index 76f002502406..ab98465791c0 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Order.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Order.java @@ -4,12 +4,14 @@ import java.util.Date; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * An order for a pets from the pet store **/ @ApiModel(description="An order for a pets from the pet store") + public class Order { @ApiModelProperty(value = "") @@ -173,6 +175,27 @@ public Order complete(Boolean complete) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Pet.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Pet.java index baf8f5a9d7b0..d9bc1cbd1979 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Pet.java @@ -2,17 +2,20 @@ import io.swagger.annotations.ApiModel; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.Category; import org.openapitools.model.Tag; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A pet for sale in the pet store **/ @ApiModel(description="A pet for sale in the pet store") + public class Pet { @ApiModelProperty(value = "") @@ -25,10 +28,10 @@ public class Pet { private String name; @ApiModelProperty(required = true, value = "") - private List photoUrls = new ArrayList(); + private List photoUrls = new ArrayList<>(); @ApiModelProperty(value = "") - private List tags = null; + private List tags; public enum StatusEnum { @@ -186,6 +189,27 @@ public Pet status(StatusEnum status) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Tag.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Tag.java index 49680fe48a4a..9c011ae12b41 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/Tag.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A tag for a pet **/ @ApiModel(description="A tag for a pet") + public class Tag { @ApiModelProperty(value = "") @@ -52,6 +54,23 @@ public Tag name(String name) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } @Override public String toString() { diff --git a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/User.java b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/User.java index bab06ed1f71c..001a0b7437b4 100644 --- a/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/User.java +++ b/samples/client/petstore/jaxrs-cxf-client/src/gen/java/org/openapitools/model/User.java @@ -3,12 +3,14 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; +import java.util.Objects; import com.fasterxml.jackson.annotation.JsonProperty; /** * A User who is purchasing from the pet store **/ @ApiModel(description="A User who is purchasing from the pet store") + public class User { @ApiModelProperty(value = "") @@ -181,6 +183,29 @@ public User userStatus(Integer userStatus) { return this; } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } @Override public String toString() { diff --git a/samples/client/petstore/jetbrains/http/client/.openapi-generator/VERSION b/samples/client/petstore/jetbrains/http/client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/jetbrains/http/client/.openapi-generator/VERSION +++ b/samples/client/petstore/jetbrains/http/client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jmeter/.openapi-generator/FILES b/samples/client/petstore/jmeter/.openapi-generator/FILES index 87541f4daaa9..0377bec67288 100644 --- a/samples/client/petstore/jmeter/.openapi-generator/FILES +++ b/samples/client/petstore/jmeter/.openapi-generator/FILES @@ -1,3 +1,5 @@ +FakeApi.csv +FakeApi.jmx PetApi.csv PetApi.jmx StoreApi.csv diff --git a/samples/client/petstore/jmeter/.openapi-generator/VERSION b/samples/client/petstore/jmeter/.openapi-generator/VERSION index c30f0ec2be7f..fff4bdd7ab59 100644 --- a/samples/client/petstore/jmeter/.openapi-generator/VERSION +++ b/samples/client/petstore/jmeter/.openapi-generator/VERSION @@ -1 +1 @@ -5.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/jmeter/FakeApi.csv b/samples/client/petstore/jmeter/FakeApi.csv new file mode 100644 index 000000000000..48a90826d529 --- /dev/null +++ b/samples/client/petstore/jmeter/FakeApi.csv @@ -0,0 +1,2 @@ +testCase,httpStatusCode +Success,200 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/FakeApi.jmx b/samples/client/petstore/jmeter/FakeApi.jmx new file mode 100644 index 000000000000..918182e4e1c5 --- /dev/null +++ b/samples/client/petstore/jmeter/FakeApi.jmx @@ -0,0 +1,171 @@ + + + + + + false + false + + + + + + + + + + threads + ${__P(threads,1)} + = + + + rampup + ${__P(rampup,1)} + = + + + duration + ${__P(duration,1)} + = + + + testCases + ${__P(testCases,10)} + = + + + host + ${__P(host,localhost)} + = + + + port + ${__P(port,8080)} + = + + + testData.operationId_DollarSignFile + ${__P(testData.operationId_DollarSignFile,FakeApi.csv)} + = + + + + + + + + + ${host} + ${port} + + + + + + 4 + + + + continue + + false + ${testCases} + + ${threads} + ${rampup} + 1448391617000 + 1448391617000 + true + ${duration} + 5 + + + + + + + + + + + + + + + + + + + + /v2/fake/operation_id_dollar_sign + GET + true + false + true + false + + false + + operationId dollar sign operationId dollar sign + + + + , + + ${testData.operationId_DollarSignFile} + true + true + shareMode.group + false + + true + + + + + + ${httpStatusCode} + + Assertion.response_code + false + 8 + + + + + + false + + saveConfig + + + true + true + true + + true + true + true + true + false + true + true + false + false + false + false + false + false + false + false + 0 + true + true + + + + + + + + diff --git a/samples/client/petstore/jmeter/PetApi.csv b/samples/client/petstore/jmeter/PetApi.csv index 29b09a1715de..2ab795b50f75 100644 --- a/samples/client/petstore/jmeter/PetApi.csv +++ b/samples/client/petstore/jmeter/PetApi.csv @@ -1,2 +1,2 @@ -testCase,httpStatusCode,body,petId,apiKey,status,tags,petId,body,petId,name,status,petId,additionalMetadata,file +testCase,httpStatusCode,pet,petId,apiKey,status,tags,petId,pet,petId,name,status,petId,additionalMetadata,file Success,200,0,0,0,0,0,0,0,0,0,0,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/PetApi.jmx b/samples/client/petstore/jmeter/PetApi.jmx index 69c4866afab6..15efcf2b2849 100644 --- a/samples/client/petstore/jmeter/PetApi.jmx +++ b/samples/client/petstore/jmeter/PetApi.jmx @@ -121,6 +121,10 @@ Content-Type application/json + + accept + application/xml + Bearer ${__P(oathToken,token)} @@ -132,9 +136,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${pet}".replace(/'/g\, '"'),)} = @@ -515,6 +519,10 @@ Content-Type application/json + + accept + application/xml + Bearer ${__P(oathToken,token)} @@ -526,9 +534,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${pet}".replace(/'/g\, '"'),)} = diff --git a/samples/client/petstore/jmeter/StoreApi.csv b/samples/client/petstore/jmeter/StoreApi.csv index 70fd54e2b204..2ccf8884aff0 100644 --- a/samples/client/petstore/jmeter/StoreApi.csv +++ b/samples/client/petstore/jmeter/StoreApi.csv @@ -1,2 +1,2 @@ -testCase,httpStatusCode,orderId,orderId,body +testCase,httpStatusCode,orderId,orderId,order Success,200,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/StoreApi.jmx b/samples/client/petstore/jmeter/StoreApi.jmx index a30bca1219ee..7cb9f20967f2 100644 --- a/samples/client/petstore/jmeter/StoreApi.jmx +++ b/samples/client/petstore/jmeter/StoreApi.jmx @@ -310,6 +310,10 @@ + + Content-Type + application/json + accept application/xml @@ -321,9 +325,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${order}".replace(/'/g\, '"'),)} = diff --git a/samples/client/petstore/jmeter/UserApi.csv b/samples/client/petstore/jmeter/UserApi.csv index 92242d4077c7..66fcc84a5901 100644 --- a/samples/client/petstore/jmeter/UserApi.csv +++ b/samples/client/petstore/jmeter/UserApi.csv @@ -1,2 +1,2 @@ -testCase,httpStatusCode,body,body,body,username,username,username,password,username,body +testCase,httpStatusCode,user,user,user,username,username,username,password,username,user Success,200,0,0,0,0,0,0,0,0,0 \ No newline at end of file diff --git a/samples/client/petstore/jmeter/UserApi.jmx b/samples/client/petstore/jmeter/UserApi.jmx index 0ab9b304880d..47eb9867b304 100644 --- a/samples/client/petstore/jmeter/UserApi.jmx +++ b/samples/client/petstore/jmeter/UserApi.jmx @@ -117,6 +117,14 @@ + + Content-Type + application/json + + + api_key + ${__P(apiKey,key)} + @@ -124,9 +132,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${user}".replace(/'/g\, '"'),)} = @@ -189,6 +197,14 @@ + + Content-Type + application/json + + + api_key + ${__P(apiKey,key)} + @@ -196,9 +212,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${user}".replace(/'/g\, '"'),)} = @@ -261,6 +277,14 @@ + + Content-Type + application/json + + + api_key + ${__P(apiKey,key)} + @@ -268,9 +292,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${user}".replace(/'/g\, '"'),)} = @@ -333,6 +357,10 @@ + + api_key + ${__P(apiKey,key)} + @@ -556,6 +584,10 @@ + + api_key + ${__P(apiKey,key)} + @@ -623,6 +655,14 @@ + + Content-Type + application/json + + + api_key + ${__P(apiKey,key)} + @@ -630,9 +670,9 @@ true - + false - ${__javaScript("${body}".replace(/'/g\, '"'),)} + ${__javaScript("${user}".replace(/'/g\, '"'),)} = diff --git a/samples/client/petstore/julia/.openapi-generator/VERSION b/samples/client/petstore/julia/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/julia/.openapi-generator/VERSION +++ b/samples/client/petstore/julia/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/k6/.openapi-generator/VERSION b/samples/client/petstore/k6/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/k6/.openapi-generator/VERSION +++ b/samples/client/petstore/k6/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/k6/script.js b/samples/client/petstore/k6/script.js index 8ccd72bcf920..d2f55a29daec 100644 --- a/samples/client/petstore/k6/script.js +++ b/samples/client/petstore/k6/script.js @@ -7,7 +7,7 @@ * NOTE: This class is auto generated by OpenAPI Generator. * https://github.com/OpenAPITools/openapi-generator * - * OpenAPI generator version: 7.1.0-SNAPSHOT + * OpenAPI generator version: 7.3.0-SNAPSHOT */ @@ -409,6 +409,20 @@ export default function() { } }); + group("/fake/additionalProperties-reference", () => { + + // Request No. 1: testAdditionalPropertiesReference + { + let url = BASE_URL + `/fake/additionalProperties-reference`; + let params = {headers: {"Content-Type": "application/json", "Accept": "application/json"}}; + let request = http.post(url, params); + + check(request, { + "successful operation": (r) => r.status === 200 + }); + } + }); + group("/pet/findByStatus", () => { let status = 'TODO_EDIT_THE_STATUS'; // specify value as there is no example value for this parameter in OpenAPI spec diff --git a/samples/client/petstore/kotlin-allOff-discriminator/.openapi-generator/VERSION b/samples/client/petstore/kotlin-allOff-discriminator/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-allOff-discriminator/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-allOff-discriminator/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 81cbdad3ec33..d03a7c7d066b 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -26,6 +26,7 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -198,6 +199,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code(), diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/.openapi-generator/VERSION b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/VERSION b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-array-simple-string-jvm-volley/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts index 2aaf14f1d7c2..60a1d4bbf117 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/build.gradle.kts @@ -1,17 +1,17 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform") version "1.7.21" // kotlin_version - kotlin("plugin.serialization") version "1.7.21" // kotlin_version + kotlin("multiplatform") version "1.9.20" // kotlin_version + kotlin("plugin.serialization") version "1.9.20" // kotlin_version } group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.7.21" -val coroutines_version = "1.6.4" -val serialization_version = "1.3.3" -val ktor_version = "2.1.3" +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" repositories { mavenCentral() @@ -19,14 +19,16 @@ repositories { kotlin { jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + iosX64() + iosArm64() + iosSimulatorArm64() js { browser() nodejs() } sourceSets { - val commonMain by getting { + commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") @@ -35,45 +37,43 @@ kotlin { api("io.ktor:ktor-client-serialization:$ktor_version") api("io.ktor:ktor-client-content-negotiation:$ktor_version") api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") } } - val commonTest by getting { + commonTest { dependencies { implementation(kotlin("test")) implementation("io.ktor:ktor-client-mock:$ktor_version") } } - val jvmMain by getting { + jvmMain { dependencies { implementation(kotlin("stdlib-jdk7")) implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") } } - val jvmTest by getting { + jvmTest { dependencies { implementation(kotlin("test-junit")) } } - val iosMain by getting { + iosMain { dependencies { api("io.ktor:ktor-client-ios:$ktor_version") } } - val iosTest by getting - - val jsMain by getting { + jsMain { dependencies { api("io.ktor:ktor-client-js:$ktor_version") } } - val jsTest by getting - all { languageSettings.apply { optIn("kotlin.Experimental") diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 70d03d97b87e..471ea9d97e7e 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -10,9 +10,11 @@ import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.serialization.kotlinx.json.json import io.ktor.http.* import io.ktor.http.content.PartData +import io.ktor.http.contentType import kotlin.Unit import kotlinx.serialization.json.Json @@ -154,6 +156,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) this.setBody(body) } } diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt index 5aeea0894894..b5b7054f9092 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(Base64ByteArray.Companion::class) class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt index af8caa633ccb..df72899875bd 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -82,6 +82,7 @@ private fun ByteReadPacket.encodeBase64(): String = buildString { * * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt */ +@Suppress("DEPRECATION") private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { val data = ByteArray(4) diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt index d10d7c506523..96339312ada4 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(OctetByteArray.Companion::class) class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) diff --git a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-array-simple-string-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts index 2aaf14f1d7c2..60a1d4bbf117 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/build.gradle.kts @@ -1,17 +1,17 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform") version "1.7.21" // kotlin_version - kotlin("plugin.serialization") version "1.7.21" // kotlin_version + kotlin("multiplatform") version "1.9.20" // kotlin_version + kotlin("plugin.serialization") version "1.9.20" // kotlin_version } group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.7.21" -val coroutines_version = "1.6.4" -val serialization_version = "1.3.3" -val ktor_version = "2.1.3" +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" repositories { mavenCentral() @@ -19,14 +19,16 @@ repositories { kotlin { jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + iosX64() + iosArm64() + iosSimulatorArm64() js { browser() nodejs() } sourceSets { - val commonMain by getting { + commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") @@ -35,45 +37,43 @@ kotlin { api("io.ktor:ktor-client-serialization:$ktor_version") api("io.ktor:ktor-client-content-negotiation:$ktor_version") api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") } } - val commonTest by getting { + commonTest { dependencies { implementation(kotlin("test")) implementation("io.ktor:ktor-client-mock:$ktor_version") } } - val jvmMain by getting { + jvmMain { dependencies { implementation(kotlin("stdlib-jdk7")) implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") } } - val jvmTest by getting { + jvmTest { dependencies { implementation(kotlin("test-junit")) } } - val iosMain by getting { + iosMain { dependencies { api("io.ktor:ktor-client-ios:$ktor_version") } } - val iosTest by getting - - val jsMain by getting { + jsMain { dependencies { api("io.ktor:ktor-client-js:$ktor_version") } } - val jsTest by getting - all { languageSettings.apply { optIn("kotlin.Experimental") diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 70d03d97b87e..471ea9d97e7e 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -10,9 +10,11 @@ import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.serialization.kotlinx.json.json import io.ktor.http.* import io.ktor.http.content.PartData +import io.ktor.http.contentType import kotlin.Unit import kotlinx.serialization.json.Json @@ -154,6 +156,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) this.setBody(body) } } diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt index 5aeea0894894..b5b7054f9092 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(Base64ByteArray.Companion::class) class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt index af8caa633ccb..df72899875bd 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -82,6 +82,7 @@ private fun ByteReadPacket.encodeBase64(): String = buildString { * * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt */ +@Suppress("DEPRECATION") private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { val data = ByteArray(4) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt index d10d7c506523..96339312ada4 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(OctetByteArray.Companion::class) class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) diff --git a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/.openapi-generator/VERSION b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-bigdecimal-default-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 81cbdad3ec33..d03a7c7d066b 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -26,6 +26,7 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -198,6 +199,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code(), diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/.openapi-generator/VERSION b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-default-values-jvm-okhttp4/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/.openapi-generator/VERSION b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-default-values-jvm-retrofit2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/VERSION b/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-default-values-jvm-volley/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-default-values-multiplatform/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts index 2aaf14f1d7c2..60a1d4bbf117 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-default-values-multiplatform/build.gradle.kts @@ -1,17 +1,17 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform") version "1.7.21" // kotlin_version - kotlin("plugin.serialization") version "1.7.21" // kotlin_version + kotlin("multiplatform") version "1.9.20" // kotlin_version + kotlin("plugin.serialization") version "1.9.20" // kotlin_version } group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.7.21" -val coroutines_version = "1.6.4" -val serialization_version = "1.3.3" -val ktor_version = "2.1.3" +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" repositories { mavenCentral() @@ -19,14 +19,16 @@ repositories { kotlin { jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + iosX64() + iosArm64() + iosSimulatorArm64() js { browser() nodejs() } sourceSets { - val commonMain by getting { + commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") @@ -35,45 +37,43 @@ kotlin { api("io.ktor:ktor-client-serialization:$ktor_version") api("io.ktor:ktor-client-content-negotiation:$ktor_version") api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") } } - val commonTest by getting { + commonTest { dependencies { implementation(kotlin("test")) implementation("io.ktor:ktor-client-mock:$ktor_version") } } - val jvmMain by getting { + jvmMain { dependencies { implementation(kotlin("stdlib-jdk7")) implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") } } - val jvmTest by getting { + jvmTest { dependencies { implementation(kotlin("test-junit")) } } - val iosMain by getting { + iosMain { dependencies { api("io.ktor:ktor-client-ios:$ktor_version") } } - val iosTest by getting - - val jsMain by getting { + jsMain { dependencies { api("io.ktor:ktor-client-js:$ktor_version") } } - val jsTest by getting - all { languageSettings.apply { optIn("kotlin.Experimental") diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 70d03d97b87e..471ea9d97e7e 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -10,9 +10,11 @@ import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.serialization.kotlinx.json.json import io.ktor.http.* import io.ktor.http.content.PartData +import io.ktor.http.contentType import kotlin.Unit import kotlinx.serialization.json.Json @@ -154,6 +156,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) this.setBody(body) } } diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt index 5aeea0894894..b5b7054f9092 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(Base64ByteArray.Companion::class) class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt index af8caa633ccb..df72899875bd 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -82,6 +82,7 @@ private fun ByteReadPacket.encodeBase64(): String = buildString { * * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt */ +@Suppress("DEPRECATION") private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { val data = ByteArray(4) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt index d10d7c506523..96339312ada4 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(OctetByteArray.Companion::class) class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) diff --git a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-default-values-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-enum-default-value/.openapi-generator/VERSION b/samples/client/petstore/kotlin-enum-default-value/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-enum-default-value/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-enum-default-value/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/PropertyOfDay.kt b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/PropertyOfDay.kt index b00e68b75928..87a592b41cce 100644 --- a/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/PropertyOfDay.kt +++ b/samples/client/petstore/kotlin-enum-default-value/src/main/kotlin/org/openapitools/client/models/PropertyOfDay.kt @@ -106,7 +106,7 @@ data class PropertyOfDay ( /** * Holiday types * - * Values: nOTHOLIDAY,lOCALHOLIDAY,nATIONALHOLIDAY,aNYHOLIDAY,wORKINGDAY,aNYDAY,nEWYEARSDAY,pALMSUNDAY,mAUNDYTHURSDAY,gOODFRIDAY,eASTERSUNDAY,eASTERMONDAY,lABOURDAY,cONSTITUTIONDAY,aSCENSIONDAY,wHITSUNDAY,wHITMONDAY,cHRISTMASDAY,bOXINGDAY,unknownDefaultOpenApi + * Values: nOTHOLIDAY,lOCALHOLIDAY,nATIONALHOLIDAY,aNYHOLIDAY,wORKINGDAY,aNYDAY,nEWYEARSDAY,pALMSUNDAY,mAUNDYTHURSDAY,gOODFRIDAY,eASTERSUNDAY,eASTERMONDAY,lABOURDAY,cONSTITUTIONDAY,aSCENSIONDAY,wHITSUNDAY,wHITMONDAY,XMAS_DAY,bOXINGDAY,unknownDefaultOpenApi */ @JsonClass(generateAdapter = false) enum class HolidayTypes(val value: kotlin.Any) { @@ -127,7 +127,7 @@ data class PropertyOfDay ( @Json(name = "ASCENSION_DAY") aSCENSIONDAY("ASCENSION_DAY"), @Json(name = "WHIT_SUNDAY") wHITSUNDAY("WHIT_SUNDAY"), @Json(name = "WHIT_MONDAY") wHITMONDAY("WHIT_MONDAY"), - @Json(name = "CHRISTMAS_DAY") cHRISTMASDAY("CHRISTMAS_DAY"), + @Json(name = "CHRISTMAS_DAY") XMAS_DAY("CHRISTMAS_DAY"), @Json(name = "BOXING_DAY") bOXINGDAY("BOXING_DAY"), @Json(name = "11184809") unknownDefaultOpenApi("11184809"); } diff --git a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index a01ca44bbbb8..9f4495c4dcf2 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.google.gson.reflect.TypeToken + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -218,6 +219,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 031dc8522916..bcafbbef17c7 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -193,7 +193,7 @@ class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = A enum class StatusFindPetsByStatus(val value: kotlin.String) { @JsonProperty(value = "available") AVAILABLE("available"), @JsonProperty(value = "pending") PENDING("pending"), - @JsonProperty(value = "sold") SOLD("sold") + @JsonProperty(value = "sold") SOLD("sold"), } /** diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 45b072f82784..73a5859dd959 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.fasterxml.jackson.core.type.TypeReference + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -218,6 +219,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..6a09fd57f301 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -10,5 +11,6 @@ object Serializer { val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt index 71a7d74b06f1..ff41aedca0bf 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5590e88cd83e..2a59a8f3acdb 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt index ae6f6bc3b9f9..5d72e185d7f3 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -56,12 +57,13 @@ data class Order ( /** * Order Status * - * Values: PLACED,APPROVED,DELIVERED + * Values: PLACED,APPROVED,DELIVERED,UNKNOWN_DEFAULT_OPEN_API */ enum class Status(val value: kotlin.String) { @JsonProperty(value = "placed") PLACED("placed"), @JsonProperty(value = "approved") APPROVED("approved"), - @JsonProperty(value = "delivered") DELIVERED("delivered"); + @JsonProperty(value = "delivered") DELIVERED("delivered"), + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue UNKNOWN_DEFAULT_OPEN_API("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt index ea5a3dce8c40..c9863eb6c326 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,6 +18,7 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -58,12 +59,13 @@ data class Pet ( /** * pet status in the store * - * Values: AVAILABLE,PENDING,SOLD + * Values: AVAILABLE,PENDING,SOLD,UNKNOWN_DEFAULT_OPEN_API */ enum class Status(val value: kotlin.String) { @JsonProperty(value = "available") AVAILABLE("available"), @JsonProperty(value = "pending") PENDING("pending"), - @JsonProperty(value = "sold") SOLD("sold"); + @JsonProperty(value = "sold") SOLD("sold"), + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue UNKNOWN_DEFAULT_OPEN_API("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt index f5f600cc3745..bfff056241ca 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt index 7872ed7da4df..48cabe858981 100644 --- a/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-json-request-string/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5f684f2428ad..0855652e45e7 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -16,7 +16,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -31,6 +30,8 @@ import java.util.Locale import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -224,6 +225,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-json-request-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-jackson/build.gradle b/samples/client/petstore/kotlin-jvm-jackson/build.gradle index 303a58910c4e..7517d03fe473 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jvm-jackson/build.gradle @@ -61,6 +61,7 @@ dependencies { implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-jackson:$retrofitVersion" implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" } diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 4621cb35f4fb..1a1b4fd85fa9 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -16,6 +16,7 @@ import retrofit2.Converter import retrofit2.CallAdapter import retrofit2.converter.scalars.ScalarsConverterFactory import com.fasterxml.jackson.databind.ObjectMapper +import retrofit2.converter.jackson.JacksonConverterFactory class ApiClient( @@ -27,6 +28,7 @@ class ApiClient( ), private val converterFactories: List = listOf( ScalarsConverterFactory.create(), + JacksonConverterFactory.create(), ) ) { private val apiAuthorizations = mutableMapOf() @@ -70,7 +72,7 @@ class ApiClient( authNames: Array ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { authNames.forEach { authName -> - val auth = when (authName) { + val auth: Interceptor? = when (authName) { "petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") "api_key" -> ApiKeyAuth("header", "api_key") diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..6a09fd57f301 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -10,5 +11,6 @@ object Serializer { val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) } diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt index 71a7d74b06f1..ff41aedca0bf 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5590e88cd83e..2a59a8f3acdb 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt index bfedd1b52845..01008523bcb8 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -62,7 +63,7 @@ data class Order ( @JsonProperty(value = "placed") placed("placed"), @JsonProperty(value = "approved") approved("approved"), @JsonProperty(value = "delivered") delivered("delivered"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt index 1da246bb31de..17abefb22caf 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,6 +18,7 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -65,7 +66,7 @@ data class Pet ( @JsonProperty(value = "available") available("available"), @JsonProperty(value = "pending") pending("pending"), @JsonProperty(value = "sold") sold("sold"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt index f5f600cc3745..bfff056241ca 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/User.kt index 7872ed7da4df..48cabe858981 100644 --- a/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-ktor-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle b/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle index 0acb298375be..4bc5603fb837 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/build.gradle @@ -8,7 +8,7 @@ wrapper { buildscript { ext.kotlin_version = '1.8.10' - ext.ktor_version = '2.1.3' + ext.ktor_version = '2.2.3' ext.spotless_version = "6.13.0" repositories { diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 6e9f06023343..9dcc43abd0c7 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -13,6 +13,7 @@ import io.ktor.client.request.request import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.http.contentType +import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.Parameters @@ -156,6 +157,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) setBody(body) } } diff --git a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-gson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-ktor-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle b/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle index 7843999a8ff5..ac940c8653b2 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/build.gradle @@ -8,7 +8,7 @@ wrapper { buildscript { ext.kotlin_version = '1.8.10' - ext.ktor_version = '2.1.3' + ext.ktor_version = '2.2.3' ext.spotless_version = "6.13.0" repositories { diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 69fcc0ab8547..bf6a87e2a71a 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -13,6 +13,7 @@ import io.ktor.client.request.request import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.http.contentType +import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.Parameters @@ -164,6 +165,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) setBody(body) } } diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt index 71a7d74b06f1..ff41aedca0bf 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5590e88cd83e..2a59a8f3acdb 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt index bfedd1b52845..01008523bcb8 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -62,7 +63,7 @@ data class Order ( @JsonProperty(value = "placed") placed("placed"), @JsonProperty(value = "approved") approved("approved"), @JsonProperty(value = "delivered") delivered("delivered"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt index ba5fd69df76e..aa4e724e0e69 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,6 +18,7 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -64,7 +65,7 @@ data class Pet ( @JsonProperty(value = "available") available("available"), @JsonProperty(value = "pending") pending("pending"), @JsonProperty(value = "sold") sold("sold"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt index f5f600cc3745..bfff056241ca 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt index 7872ed7da4df..48cabe858981 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/build.gradle b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/build.gradle index 602a3d7d96e3..8a3f1d30e520 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/build.gradle +++ b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/build.gradle @@ -8,7 +8,7 @@ wrapper { buildscript { ext.kotlin_version = '1.8.10' - ext.ktor_version = '2.1.3' + ext.ktor_version = '2.2.3' ext.spotless_version = "6.13.0" repositories { diff --git a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 762dad7221a4..a87053c087ca 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -13,6 +13,7 @@ import io.ktor.client.request.request import io.ktor.client.request.setBody import io.ktor.client.statement.HttpResponse import io.ktor.http.contentType +import io.ktor.http.ContentType import io.ktor.http.HttpHeaders import io.ktor.http.HttpMethod import io.ktor.http.Parameters @@ -147,6 +148,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) setBody(body) } } diff --git a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-ktor-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 77aa25ca8060..3870d97065bb 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -32,6 +31,8 @@ import kotlin.coroutines.resumeWithException import kotlinx.coroutines.suspendCancellableCoroutine import com.google.gson.reflect.TypeToken + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -232,6 +233,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-okhttp4-coroutines/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-spring-2-webclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 543d5add69ef..25416732825a 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -63,9 +64,13 @@ class PetApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/xml" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/pet", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -75,28 +80,33 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?): Mono { + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String? = null): Mono { return deletePetWithHttpInfo(petId = petId, apiKey = apiKey) .map { it.body } } @Throws(WebClientResponseException::class) - fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String?): Mono> { + fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String? = null): Mono> { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) return request( localVariableConfig ) } - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String? = null) : RequestConfig { val localVariableBody = null val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -137,9 +147,13 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -174,9 +188,13 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -205,9 +223,14 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -238,9 +261,13 @@ class PetApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/xml" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.PUT, path = "/pet", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -250,29 +277,34 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?): Mono { + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): Mono { return updatePetWithFormWithHttpInfo(petId = petId, name = name, status = status) .map { it.body } } @Throws(WebClientResponseException::class) - fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?): Mono> { + fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): Mono> { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) return request>, Unit>( localVariableConfig ) } - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig>> { + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null) : RequestConfig>> { val localVariableBody = mapOf( "name" to PartConfig(body = name, headers = mutableMapOf()), "status" to PartConfig(body = status, headers = mutableMapOf()),) val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -282,20 +314,20 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?): Mono { + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): Mono { return uploadFileWithHttpInfo(petId = petId, additionalMetadata = additionalMetadata, file = file) .map { it.body } } @Throws(WebClientResponseException::class) - fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?): Mono> { + fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): Mono> { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) return request>, ModelApiResponse>( localVariableConfig ) } - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig>> { + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null) : RequestConfig>> { val localVariableBody = mapOf( "additionalMetadata" to PartConfig(body = additionalMetadata, headers = mutableMapOf()), "file" to PartConfig(body = file, headers = mutableMapOf()),) @@ -303,9 +335,14 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") localVariableHeaders["Accept"] = "application/json" + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}/uploadImage", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index b19ffd526016..c4431bade120 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.Order import org.openapitools.client.infrastructure.* @@ -59,9 +60,14 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + "orderId" to orderId, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + path = "/store/order/{orderId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -90,9 +96,13 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -121,9 +131,14 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "orderId" to orderId, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + path = "/store/order/{orderId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -153,9 +168,13 @@ class StoreApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/store/order", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 8c95187c619e..17caea45e594 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.User import org.openapitools.client.infrastructure.* @@ -60,9 +61,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -91,9 +96,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -122,9 +131,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -152,9 +165,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -183,9 +201,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -218,9 +241,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/user/login", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -248,9 +275,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -279,9 +310,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index d49ddb28e2ef..b8acccd3de12 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -4,9 +4,9 @@ import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType -import org.springframework.web.util.UriUtils import org.springframework.web.reactive.function.client.WebClient import org.springframework.http.ResponseEntity +import org.springframework.util.LinkedMultiValueMap import reactor.core.publisher.Mono open class ApiClient(protected val client: WebClient) { @@ -33,19 +33,15 @@ open class ApiClient(protected val client: WebClient) { } } - protected fun encodeURIComponent(uriComponent: kotlin.String) = - UriUtils.encodeFragment(uriComponent, Charsets.UTF_8) - private fun WebClient.method(requestConfig: RequestConfig)= method(HttpMethod.valueOf(requestConfig.method.name)) private fun WebClient.RequestBodyUriSpec.uri(requestConfig: RequestConfig) = uri { builder -> - builder.path(requestConfig.path).apply { - requestConfig.query.forEach { (name, value) -> - queryParam(name, value) - } - }.build() + builder + .path(requestConfig.path) + .queryParams(LinkedMultiValueMap(requestConfig.query)) + .build(requestConfig.params) } private fun WebClient.RequestBodySpec.headers(requestConfig: RequestConfig) = diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..6a09fd57f301 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -10,5 +11,6 @@ object Serializer { val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) } diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt index 71a7d74b06f1..ff41aedca0bf 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5590e88cd83e..2a59a8f3acdb 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt index bfedd1b52845..01008523bcb8 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -62,7 +63,7 @@ data class Order ( @JsonProperty(value = "placed") placed("placed"), @JsonProperty(value = "approved") approved("approved"), @JsonProperty(value = "delivered") delivered("delivered"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt index 1da246bb31de..17abefb22caf 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,6 +18,7 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -65,7 +66,7 @@ data class Pet ( @JsonProperty(value = "available") available("available"), @JsonProperty(value = "pending") pending("pending"), @JsonProperty(value = "sold") sold("sold"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt index f5f600cc3745..bfff056241ca 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/User.kt index 7872ed7da4df..48cabe858981 100644 --- a/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-spring-2-webclient/src/main/kotlin/org/openapitools/client/models/User.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator-ignore b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/FILES b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/FILES new file mode 100644 index 000000000000..f45aec7675da --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/FILES @@ -0,0 +1,31 @@ +README.md +build.gradle +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +settings.gradle +src/main/kotlin/org/openapitools/client/apis/PetApi.kt +src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +src/main/kotlin/org/openapitools/client/apis/UserApi.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/models/Category.kt +src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +src/main/kotlin/org/openapitools/client/models/Order.kt +src/main/kotlin/org/openapitools/client/models/Pet.kt +src/main/kotlin/org/openapitools/client/models/Tag.kt +src/main/kotlin/org/openapitools/client/models/User.kt diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/README.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/README.md new file mode 100644 index 000000000000..c97b251aba1e --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/README.md @@ -0,0 +1,101 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + +## Requires + +* Kotlin 1.7.21 +* Gradle 7.5 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.ModelApiResponse](docs/ModelApiResponse.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/build.gradle b/samples/client/petstore/kotlin-jvm-spring-3-restclient/build.gradle new file mode 100644 index 000000000000..a650f5ebf2d5 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/build.gradle @@ -0,0 +1,68 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '7.5' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.8.10' + ext.spring_boot_version = "3.2.0" + ext.spotless_version = "6.13.0" + + repositories { + maven { url "https://repo1.maven.org/maven2" } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "com.diffplug.spotless:spotless-plugin-gradle:$spotless_version" + } +} + +apply plugin: 'kotlin' +apply plugin: 'maven-publish' +apply plugin: 'com.diffplug.spotless' + +repositories { + maven { url "https://repo1.maven.org/maven2" } +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + kotlin { + ktfmt() + } +} + +test { + useJUnitPlatform() +} + +kotlin { + jvmToolchain { + languageVersion.set(JavaLanguageVersion.of(17)) + } +} +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.14.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.3" + implementation "org.springframework.boot:spring-boot-starter-web:$spring_boot_version" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/ApiResponse.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/ApiResponse.md new file mode 100644 index 000000000000..12f08d5cdef0 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Category.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Category.md new file mode 100644 index 000000000000..2c28a670fc79 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Order.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Order.md new file mode 100644 index 000000000000..c0c951b22d33 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**java.time.OffsetDateTime**](java.time.OffsetDateTime.md) | | [optional] +**status** | [**inline**](#Status) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Pet.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Pet.md new file mode 100644 index 000000000000..da70fca06e65 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.collections.List<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.collections.List<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#Status) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/PetApi.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/PetApi.md new file mode 100644 index 000000000000..000d91fd381e --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/PetApi.md @@ -0,0 +1,417 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> Pet addPet(pet) + +Add a new pet to the store + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val pet : Pet = // Pet | Pet object that needs to be added to the store +try { + val result : Pet = apiInstance.addPet(pet) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> kotlin.collections.List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val status : kotlin.collections.List = // kotlin.collections.List | Status values that need to be considered for filter +try { + val result : kotlin.collections.List = apiInstance.findPetsByStatus(status) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> kotlin.collections.List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.collections.List = // kotlin.collections.List | Tags to filter by +try { + val result : kotlin.collections.List = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> Pet updatePet(pet) + +Update an existing pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val pet : Pet = // Pet | Pet object that needs to be added to the store +try { + val result : Pet = apiInstance.updatePet(pet) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload +try { + val result : ModelApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/StoreApi.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/StoreApi.md new file mode 100644 index 000000000000..76ca75818c63 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/StoreApi.md @@ -0,0 +1,198 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(order) + +Place an order for a pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val order : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(order) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Tag.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Tag.md new file mode 100644 index 000000000000..60ce1bcdbad3 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/User.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/User.md new file mode 100644 index 000000000000..e801729b5ed1 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/UserApi.md b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/UserApi.md new file mode 100644 index 000000000000..cc033aebee6c --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/docs/UserApi.md @@ -0,0 +1,404 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(user) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val user : User = // User | Created user object +try { + apiInstance.createUser(user) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(user) + +Creates list of users with given input array + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val user : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithArrayInput(user) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(user) + +Creates list of users with given input array + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val user : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithListInput(user) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, user) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val user : User = // User | Updated user object +try { + apiInstance.updateUser(username, user) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..c1962a79e29d Binary files /dev/null and b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..8707e8b5067f --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-all.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew new file mode 100644 index 000000000000..aeb74cbb43e3 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew.bat b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew.bat new file mode 100644 index 000000000000..93e3f59f135d --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/settings.gradle b/samples/client/petstore/kotlin-jvm-spring-3-restclient/settings.gradle new file mode 100644 index 000000000000..df5429b3bbef --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-spring-restclient' diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 000000000000..6764aa89175c --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,349 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import com.fasterxml.jackson.annotation.JsonProperty + +import org.springframework.web.client.RestClient +import org.springframework.web.client.RestClientResponseException + +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter +import org.springframework.http.ResponseEntity +import org.springframework.http.MediaType + + +import org.openapitools.client.models.ModelApiResponse +import org.openapitools.client.models.Pet +import org.openapitools.client.infrastructure.* + +class PetApi(client: RestClient) : ApiClient(client) { + + constructor(baseUrl: String) : this(RestClient.builder() + .baseUrl(baseUrl) + .messageConverters { it.add(MappingJackson2HttpMessageConverter()) } + .build() + ) + + + @Throws(RestClientResponseException::class) + fun addPet(pet: Pet): Pet { + return addPetWithHttpInfo(pet = pet) + .body!! + } + + @Throws(RestClientResponseException::class) + fun addPetWithHttpInfo(pet: Pet): ResponseEntity { + val localVariableConfig = addPetRequestConfig(pet = pet) + return request( + localVariableConfig + ) + } + + fun addPetRequestConfig(pet: Pet) : RequestConfig { + val localVariableBody = pet + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Content-Type"] = "application/xml" + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String? = null): Unit { + return deletePetWithHttpInfo(petId = petId, apiKey = apiKey) + .body!! + } + + @Throws(RestClientResponseException::class) + fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String? = null): ResponseEntity { + val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) + return request( + localVariableConfig + ) + } + + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String? = null) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } + + val params = mutableMapOf( + "petId" to petId, + ) + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/pet/{petId}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * enum for parameter status + */ + enum class StatusFindPetsByStatus(val value: kotlin.String) { + @JsonProperty(value = "available") available("available"), + @JsonProperty(value = "pending") pending("pending"), + @JsonProperty(value = "sold") sold("sold"), + } + + + @Throws(RestClientResponseException::class) + fun findPetsByStatus(status: kotlin.collections.List): kotlin.collections.List { + return findPetsByStatusWithHttpInfo(status = status) + .body!! + } + + @Throws(RestClientResponseException::class) + fun findPetsByStatusWithHttpInfo(status: kotlin.collections.List): ResponseEntity> { + val localVariableConfig = findPetsByStatusRequestConfig(status = status) + return request>( + localVariableConfig + ) + } + + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + .apply { + put("status", toMultiValue(status.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/findByStatus", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List): kotlin.collections.List { + return findPetsByTagsWithHttpInfo(tags = tags) + .body!! + } + + @Throws(RestClientResponseException::class) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTagsWithHttpInfo(tags: kotlin.collections.List): ResponseEntity> { + val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) + return request>( + localVariableConfig + ) + } + + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + .apply { + put("tags", toMultiValue(tags.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/findByTags", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun getPetById(petId: kotlin.Long): Pet { + return getPetByIdWithHttpInfo(petId = petId) + .body!! + } + + @Throws(RestClientResponseException::class) + fun getPetByIdWithHttpInfo(petId: kotlin.Long): ResponseEntity { + val localVariableConfig = getPetByIdRequestConfig(petId = petId) + return request( + localVariableConfig + ) + } + + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + "petId" to petId, + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/{petId}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun updatePet(pet: Pet): Pet { + return updatePetWithHttpInfo(pet = pet) + .body!! + } + + @Throws(RestClientResponseException::class) + fun updatePetWithHttpInfo(pet: Pet): ResponseEntity { + val localVariableConfig = updatePetRequestConfig(pet = pet) + return request( + localVariableConfig + ) + } + + fun updatePetRequestConfig(pet: Pet) : RequestConfig { + val localVariableBody = pet + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Content-Type"] = "application/xml" + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.PUT, + path = "/pet", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): Unit { + return updatePetWithFormWithHttpInfo(petId = petId, name = name, status = status) + .body!! + } + + @Throws(RestClientResponseException::class) + fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): ResponseEntity { + val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) + return request>, Unit>( + localVariableConfig + ) + } + + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null) : RequestConfig>> { + val localVariableBody = mapOf( + "name" to PartConfig(body = name, headers = mutableMapOf()), + "status" to PartConfig(body = status, headers = mutableMapOf()),) + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") + + val params = mutableMapOf( + "petId" to petId, + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet/{petId}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): ModelApiResponse { + return uploadFileWithHttpInfo(petId = petId, additionalMetadata = additionalMetadata, file = file) + .body!! + } + + @Throws(RestClientResponseException::class) + fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): ResponseEntity { + val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) + return request>, ModelApiResponse>( + localVariableConfig + ) + } + + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null) : RequestConfig>> { + val localVariableBody = mapOf( + "additionalMetadata" to PartConfig(body = additionalMetadata, headers = mutableMapOf()), + "file" to PartConfig(body = file, headers = mutableMapOf()),) + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") + localVariableHeaders["Accept"] = "application/json" + + val params = mutableMapOf( + "petId" to petId, + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet/{petId}/uploadImage", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 000000000000..db6575d3f111 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,181 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import com.fasterxml.jackson.annotation.JsonProperty + +import org.springframework.web.client.RestClient +import org.springframework.web.client.RestClientResponseException + +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter +import org.springframework.http.ResponseEntity +import org.springframework.http.MediaType + + +import org.openapitools.client.models.Order +import org.openapitools.client.infrastructure.* + +class StoreApi(client: RestClient) : ApiClient(client) { + + constructor(baseUrl: String) : this(RestClient.builder() + .baseUrl(baseUrl) + .messageConverters { it.add(MappingJackson2HttpMessageConverter()) } + .build() + ) + + + @Throws(RestClientResponseException::class) + fun deleteOrder(orderId: kotlin.String): Unit { + return deleteOrderWithHttpInfo(orderId = orderId) + .body!! + } + + @Throws(RestClientResponseException::class) + fun deleteOrderWithHttpInfo(orderId: kotlin.String): ResponseEntity { + val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) + return request( + localVariableConfig + ) + } + + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + + val params = mutableMapOf( + "orderId" to orderId, + ) + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/store/order/{orderId}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun getInventory(): kotlin.collections.Map { + return getInventoryWithHttpInfo() + .body!! + } + + @Throws(RestClientResponseException::class) + fun getInventoryWithHttpInfo(): ResponseEntity> { + val localVariableConfig = getInventoryRequestConfig() + return request>( + localVariableConfig + ) + } + + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/store/inventory", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun getOrderById(orderId: kotlin.Long): Order { + return getOrderByIdWithHttpInfo(orderId = orderId) + .body!! + } + + @Throws(RestClientResponseException::class) + fun getOrderByIdWithHttpInfo(orderId: kotlin.Long): ResponseEntity { + val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) + return request( + localVariableConfig + ) + } + + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + "orderId" to orderId, + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/store/order/{orderId}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun placeOrder(order: Order): Order { + return placeOrderWithHttpInfo(order = order) + .body!! + } + + @Throws(RestClientResponseException::class) + fun placeOrderWithHttpInfo(order: Order): ResponseEntity { + val localVariableConfig = placeOrderRequestConfig(order = order) + return request( + localVariableConfig + ) + } + + fun placeOrderRequestConfig(order: Order) : RequestConfig { + val localVariableBody = order + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/store/order", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 000000000000..ee57ffe08617 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,324 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import com.fasterxml.jackson.annotation.JsonProperty + +import org.springframework.web.client.RestClient +import org.springframework.web.client.RestClientResponseException + +import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter +import org.springframework.http.ResponseEntity +import org.springframework.http.MediaType + + +import org.openapitools.client.models.User +import org.openapitools.client.infrastructure.* + +class UserApi(client: RestClient) : ApiClient(client) { + + constructor(baseUrl: String) : this(RestClient.builder() + .baseUrl(baseUrl) + .messageConverters { it.add(MappingJackson2HttpMessageConverter()) } + .build() + ) + + + @Throws(RestClientResponseException::class) + fun createUser(user: User): Unit { + return createUserWithHttpInfo(user = user) + .body!! + } + + @Throws(RestClientResponseException::class) + fun createUserWithHttpInfo(user: User): ResponseEntity { + val localVariableConfig = createUserRequestConfig(user = user) + return request( + localVariableConfig + ) + } + + fun createUserRequestConfig(user: User) : RequestConfig { + val localVariableBody = user + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/user", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun createUsersWithArrayInput(user: kotlin.collections.List): Unit { + return createUsersWithArrayInputWithHttpInfo(user = user) + .body!! + } + + @Throws(RestClientResponseException::class) + fun createUsersWithArrayInputWithHttpInfo(user: kotlin.collections.List): ResponseEntity { + val localVariableConfig = createUsersWithArrayInputRequestConfig(user = user) + return request, Unit>( + localVariableConfig + ) + } + + fun createUsersWithArrayInputRequestConfig(user: kotlin.collections.List) : RequestConfig> { + val localVariableBody = user + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/user/createWithArray", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun createUsersWithListInput(user: kotlin.collections.List): Unit { + return createUsersWithListInputWithHttpInfo(user = user) + .body!! + } + + @Throws(RestClientResponseException::class) + fun createUsersWithListInputWithHttpInfo(user: kotlin.collections.List): ResponseEntity { + val localVariableConfig = createUsersWithListInputRequestConfig(user = user) + return request, Unit>( + localVariableConfig + ) + } + + fun createUsersWithListInputRequestConfig(user: kotlin.collections.List) : RequestConfig> { + val localVariableBody = user + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.POST, + path = "/user/createWithList", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun deleteUser(username: kotlin.String): Unit { + return deleteUserWithHttpInfo(username = username) + .body!! + } + + @Throws(RestClientResponseException::class) + fun deleteUserWithHttpInfo(username: kotlin.String): ResponseEntity { + val localVariableConfig = deleteUserRequestConfig(username = username) + return request( + localVariableConfig + ) + } + + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + + val params = mutableMapOf( + "username" to username, + ) + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/user/{username}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun getUserByName(username: kotlin.String): User { + return getUserByNameWithHttpInfo(username = username) + .body!! + } + + @Throws(RestClientResponseException::class) + fun getUserByNameWithHttpInfo(username: kotlin.String): ResponseEntity { + val localVariableConfig = getUserByNameRequestConfig(username = username) + return request( + localVariableConfig + ) + } + + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + "username" to username, + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/{username}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun loginUser(username: kotlin.String, password: kotlin.String): kotlin.String { + return loginUserWithHttpInfo(username = username, password = password) + .body!! + } + + @Throws(RestClientResponseException::class) + fun loginUserWithHttpInfo(username: kotlin.String, password: kotlin.String): ResponseEntity { + val localVariableConfig = loginUserRequestConfig(username = username, password = password) + return request( + localVariableConfig + ) + } + + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + .apply { + put("username", listOf(username.toString())) + put("password", listOf(password.toString())) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/xml, application/json" + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/login", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun logoutUser(): Unit { + return logoutUserWithHttpInfo() + .body!! + } + + @Throws(RestClientResponseException::class) + fun logoutUserWithHttpInfo(): ResponseEntity { + val localVariableConfig = logoutUserRequestConfig() + return request( + localVariableConfig + ) + } + + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + + val params = mutableMapOf( + ) + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/logout", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + @Throws(RestClientResponseException::class) + fun updateUser(username: kotlin.String, user: User): Unit { + return updateUserWithHttpInfo(username = username, user = user) + .body!! + } + + @Throws(RestClientResponseException::class) + fun updateUserWithHttpInfo(username: kotlin.String, user: User): ResponseEntity { + val localVariableConfig = updateUserRequestConfig(username = username, user = user) + return request( + localVariableConfig + ) + } + + fun updateUserRequestConfig(username: kotlin.String, user: User) : RequestConfig { + val localVariableBody = user + val localVariableQuery = mutableMapOf>() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + val params = mutableMapOf( + "username" to username, + ) + + return RequestConfig( + method = RequestMethod.PUT, + path = "/user/{username}", + params = params, + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..a4a4491eac0d --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..64f843ed93be --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,61 @@ +package org.openapitools.client.infrastructure; + +import org.springframework.core.ParameterizedTypeReference +import org.springframework.http.HttpHeaders +import org.springframework.http.HttpMethod +import org.springframework.http.MediaType +import org.springframework.web.client.RestClient +import org.springframework.http.ResponseEntity +import org.springframework.util.LinkedMultiValueMap + +open class ApiClient(protected val client: RestClient) { + + protected inline fun request(requestConfig: RequestConfig): ResponseEntity { + return prepare(defaults(requestConfig)) + .retrieve() + .toEntity(object : ParameterizedTypeReference() {}) + } + + protected fun prepare(requestConfig: RequestConfig) = + client.method(requestConfig) + .uri(requestConfig) + .headers(requestConfig) + .nullableBody(requestConfig) + + protected fun defaults(requestConfig: RequestConfig) = + requestConfig.apply { + if (body != null && headers[HttpHeaders.CONTENT_TYPE].isNullOrEmpty()) { + headers[HttpHeaders.CONTENT_TYPE] = MediaType.APPLICATION_JSON_VALUE + } + if (headers[HttpHeaders.ACCEPT].isNullOrEmpty()) { + headers[HttpHeaders.ACCEPT] = MediaType.APPLICATION_JSON_VALUE + } + } + + private fun RestClient.method(requestConfig: RequestConfig)= + method(HttpMethod.valueOf(requestConfig.method.name)) + + private fun RestClient.RequestBodyUriSpec.uri(requestConfig: RequestConfig) = + uri { builder -> + builder + .path(requestConfig.path) + .queryParams(LinkedMultiValueMap(requestConfig.query)) + .build(requestConfig.params) + } + + private fun RestClient.RequestBodySpec.headers(requestConfig: RequestConfig) = + apply { requestConfig.headers.forEach { (name, value) -> header(name, value) } } + + private fun RestClient.RequestBodySpec.nullableBody(requestConfig: RequestConfig) = + apply { if (requestConfig.body != null) body(requestConfig.body) } +} + +inline fun parseDateToQueryString(value : T): String { + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + return Serializer.jacksonObjectMapper.writeValueAsString(value).replace("\"", "") + } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..6578b9381b78 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 000000000000..6a09fd57f301 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.infrastructure + +import com.fasterxml.jackson.databind.DeserializationFeature +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper + +object Serializer { + @JvmStatic + val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() + .findAndRegisterModules() + .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) +} diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 000000000000..ff41aedca0bf --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,39 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * A category for a pet + * + * @param id + * @param name + */ + + +data class Category ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("name") + val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt new file mode 100644 index 000000000000..2a59a8f3acdb --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -0,0 +1,43 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * Describes the result of uploading an image resource + * + * @param code + * @param type + * @param message + */ + + +data class ModelApiResponse ( + + @field:JsonProperty("code") + val code: kotlin.Int? = null, + + @field:JsonProperty("type") + val type: kotlin.String? = null, + + @field:JsonProperty("message") + val message: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 000000000000..01008523bcb8 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * An order for a pets from the pet store + * + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ + + +data class Order ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("petId") + val petId: kotlin.Long? = null, + + @field:JsonProperty("quantity") + val quantity: kotlin.Int? = null, + + @field:JsonProperty("shipDate") + val shipDate: java.time.OffsetDateTime? = null, + + /* Order Status */ + @field:JsonProperty("status") + val status: Order.Status? = null, + + @field:JsonProperty("complete") + val complete: kotlin.Boolean? = false + +) { + + /** + * Order Status + * + * Values: placed,approved,delivered,unknownDefaultOpenApi + */ + enum class Status(val value: kotlin.String) { + @JsonProperty(value = "placed") placed("placed"), + @JsonProperty(value = "approved") approved("approved"), + @JsonProperty(value = "delivered") delivered("delivered"), + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); + } +} + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 000000000000..17abefb22caf --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,72 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * A pet for sale in the pet store + * + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ + + +data class Pet ( + + @field:JsonProperty("name") + val name: kotlin.String, + + @field:JsonProperty("photoUrls") + val photoUrls: kotlin.collections.List, + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("category") + val category: Category? = null, + + @field:JsonProperty("tags") + val tags: kotlin.collections.List? = null, + + /* pet status in the store */ + @field:JsonProperty("status") + @Deprecated(message = "This property is deprecated.") + val status: Pet.Status? = null + +) { + + /** + * pet status in the store + * + * Values: available,pending,sold,unknownDefaultOpenApi + */ + enum class Status(val value: kotlin.String) { + @JsonProperty(value = "available") available("available"), + @JsonProperty(value = "pending") pending("pending"), + @JsonProperty(value = "sold") sold("sold"), + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); + } +} + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 000000000000..bfff056241ca --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,39 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * A tag for a pet + * + * @param id + * @param name + */ + + +data class Tag ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("name") + val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 000000000000..48cabe858981 --- /dev/null +++ b/samples/client/petstore/kotlin-jvm-spring-3-restclient/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,64 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue +import com.fasterxml.jackson.annotation.JsonProperty + +/** + * A User who is purchasing from the pet store + * + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ + + +data class User ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("username") + val username: kotlin.String? = null, + + @field:JsonProperty("firstName") + val firstName: kotlin.String? = null, + + @field:JsonProperty("lastName") + val lastName: kotlin.String? = null, + + @field:JsonProperty("email") + val email: kotlin.String? = null, + + @field:JsonProperty("password") + val password: kotlin.String? = null, + + @field:JsonProperty("phone") + val phone: kotlin.String? = null, + + /* User Status */ + @field:JsonProperty("userStatus") + val userStatus: kotlin.Int? = null + +) + diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-spring-3-webclient/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/build.gradle b/samples/client/petstore/kotlin-jvm-spring-3-webclient/build.gradle index ed53c80e4769..d594b8f80933 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/build.gradle +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/build.gradle @@ -8,7 +8,7 @@ wrapper { buildscript { ext.kotlin_version = '1.8.10' - ext.spring_boot_version = "3.1.0" + ext.spring_boot_version = "3.2.0" ext.reactor_version = "3.5.6" ext.spotless_version = "6.13.0" diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt index 543d5add69ef..25416732825a 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.ModelApiResponse import org.openapitools.client.models.Pet @@ -63,9 +64,13 @@ class PetApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/xml" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/pet", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -75,28 +80,33 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun deletePet(petId: kotlin.Long, apiKey: kotlin.String?): Mono { + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String? = null): Mono { return deletePetWithHttpInfo(petId = petId, apiKey = apiKey) .map { it.body } } @Throws(WebClientResponseException::class) - fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String?): Mono> { + fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String? = null): Mono> { val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) return request( localVariableConfig ) } - fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String? = null) : RequestConfig { val localVariableBody = null val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -137,9 +147,13 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByStatus", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -174,9 +188,13 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/pet/findByTags", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -205,9 +223,14 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -238,9 +261,13 @@ class PetApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/xml" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.PUT, path = "/pet", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -250,29 +277,34 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?): Mono { + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): Mono { return updatePetWithFormWithHttpInfo(petId = petId, name = name, status = status) .map { it.body } } @Throws(WebClientResponseException::class) - fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?): Mono> { + fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): Mono> { val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) return request>, Unit>( localVariableConfig ) } - fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig>> { + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null) : RequestConfig>> { val localVariableBody = mapOf( "name" to PartConfig(body = name, headers = mutableMapOf()), "status" to PartConfig(body = status, headers = mutableMapOf()),) val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -282,20 +314,20 @@ class PetApi(client: WebClient) : ApiClient(client) { @Throws(WebClientResponseException::class) - fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?): Mono { + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): Mono { return uploadFileWithHttpInfo(petId = petId, additionalMetadata = additionalMetadata, file = file) .map { it.body } } @Throws(WebClientResponseException::class) - fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?): Mono> { + fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null): Mono> { val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) return request>, ModelApiResponse>( localVariableConfig ) } - fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig>> { + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null) : RequestConfig>> { val localVariableBody = mapOf( "additionalMetadata" to PartConfig(body = additionalMetadata, headers = mutableMapOf()), "file" to PartConfig(body = file, headers = mutableMapOf()),) @@ -303,9 +335,14 @@ class PetApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") localVariableHeaders["Accept"] = "application/json" + val params = mutableMapOf( + "petId" to petId, + ) + return RequestConfig( method = RequestMethod.POST, - path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + path = "/pet/{petId}/uploadImage", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt index b19ffd526016..c4431bade120 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.Order import org.openapitools.client.infrastructure.* @@ -59,9 +60,14 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + "orderId" to orderId, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + path = "/store/order/{orderId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -90,9 +96,13 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/store/inventory", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -121,9 +131,14 @@ class StoreApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "orderId" to orderId, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + path = "/store/order/{orderId}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -153,9 +168,13 @@ class StoreApi(client: WebClient) : ApiClient(client) { localVariableHeaders["Content-Type"] = "application/json" localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/store/order", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt index 8c95187c619e..17caea45e594 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -24,6 +24,7 @@ import org.springframework.http.codec.json.Jackson2JsonEncoder import org.springframework.http.ResponseEntity import org.springframework.http.MediaType import reactor.core.publisher.Mono +import org.springframework.util.LinkedMultiValueMap import org.openapitools.client.models.User import org.openapitools.client.infrastructure.* @@ -60,9 +61,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -91,9 +96,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithArray", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -122,9 +131,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.POST, path = "/user/createWithList", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -152,9 +165,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.DELETE, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -183,9 +201,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.GET, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -218,9 +241,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Accept"] = "application/xml, application/json" + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/user/login", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = false, @@ -248,9 +275,13 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableQuery = mutableMapOf>() val localVariableHeaders: MutableMap = mutableMapOf() + val params = mutableMapOf( + ) + return RequestConfig( method = RequestMethod.GET, path = "/user/logout", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, @@ -279,9 +310,14 @@ class UserApi(client: WebClient) : ApiClient(client) { val localVariableHeaders: MutableMap = mutableMapOf() localVariableHeaders["Content-Type"] = "application/json" + val params = mutableMapOf( + "username" to username, + ) + return RequestConfig( method = RequestMethod.PUT, - path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + path = "/user/{username}", + params = params, query = localVariableQuery, headers = localVariableHeaders, requiresAuthentication = true, diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index d49ddb28e2ef..b8acccd3de12 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -4,9 +4,9 @@ import org.springframework.core.ParameterizedTypeReference import org.springframework.http.HttpHeaders import org.springframework.http.HttpMethod import org.springframework.http.MediaType -import org.springframework.web.util.UriUtils import org.springframework.web.reactive.function.client.WebClient import org.springframework.http.ResponseEntity +import org.springframework.util.LinkedMultiValueMap import reactor.core.publisher.Mono open class ApiClient(protected val client: WebClient) { @@ -33,19 +33,15 @@ open class ApiClient(protected val client: WebClient) { } } - protected fun encodeURIComponent(uriComponent: kotlin.String) = - UriUtils.encodeFragment(uriComponent, Charsets.UTF_8) - private fun WebClient.method(requestConfig: RequestConfig)= method(HttpMethod.valueOf(requestConfig.method.name)) private fun WebClient.RequestBodyUriSpec.uri(requestConfig: RequestConfig) = uri { builder -> - builder.path(requestConfig.path).apply { - requestConfig.query.forEach { (name, value) -> - queryParam(name, value) - } - }.build() + builder + .path(requestConfig.path) + .queryParams(LinkedMultiValueMap(requestConfig.query)) + .build(requestConfig.params) } private fun WebClient.RequestBodySpec.headers(requestConfig: RequestConfig) = diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt index ece5c413e124..6a09fd57f301 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -1,5 +1,6 @@ package org.openapitools.client.infrastructure +import com.fasterxml.jackson.databind.DeserializationFeature import com.fasterxml.jackson.databind.ObjectMapper import com.fasterxml.jackson.databind.SerializationFeature import com.fasterxml.jackson.annotation.JsonInclude @@ -10,5 +11,6 @@ object Serializer { val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() .findAndRegisterModules() .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(DeserializationFeature.READ_UNKNOWN_ENUM_VALUES_USING_DEFAULT_VALUE, true) .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt index 71a7d74b06f1..ff41aedca0bf 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt index 5590e88cd83e..2a59a8f3acdb 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt index bfedd1b52845..01008523bcb8 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -62,7 +63,7 @@ data class Order ( @JsonProperty(value = "placed") placed("placed"), @JsonProperty(value = "approved") approved("approved"), @JsonProperty(value = "delivered") delivered("delivered"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt index 1da246bb31de..17abefb22caf 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -18,6 +18,7 @@ package org.openapitools.client.models import org.openapitools.client.models.Category import org.openapitools.client.models.Tag +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** @@ -65,7 +66,7 @@ data class Pet ( @JsonProperty(value = "available") available("available"), @JsonProperty(value = "pending") pending("pending"), @JsonProperty(value = "sold") sold("sold"), - @JsonProperty(value = "unknown_default_open_api") unknownDefaultOpenApi("unknown_default_open_api"); + @JsonProperty(value = "unknown_default_open_api") @JsonEnumDefaultValue unknownDefaultOpenApi("unknown_default_open_api"); } } diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt index f5f600cc3745..bfff056241ca 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/User.kt index 7872ed7da4df..48cabe858981 100644 --- a/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/User.kt +++ b/samples/client/petstore/kotlin-jvm-spring-3-webclient/src/main/kotlin/org/openapitools/client/models/User.kt @@ -16,6 +16,7 @@ package org.openapitools.client.models +import com.fasterxml.jackson.annotation.JsonEnumDefaultValue import com.fasterxml.jackson.annotation.JsonProperty /** diff --git a/samples/client/petstore/kotlin-jvm-vertx-gson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-vertx-gson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-gson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-vertx-gson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-vertx-jackson-coroutines/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-vertx-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-vertx-jackson/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-jackson/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-vertx-jackson/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-vertx-moshi/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-vertx-moshi/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-vertx-moshi/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-vertx-moshi/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-jvm-volley/.openapi-generator/VERSION b/samples/client/petstore/kotlin-jvm-volley/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-jvm-volley/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-jvm-volley/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator-ignore b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES new file mode 100644 index 000000000000..b3104c03efb1 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/FILES @@ -0,0 +1,43 @@ +README.md +build.gradle +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +settings.gradle +src/main/kotlin/org/openapitools/client/apis/PetApi.kt +src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +src/main/kotlin/org/openapitools/client/apis/UserApi.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt +src/main/kotlin/org/openapitools/client/infrastructure/InstantAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt +src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt +src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt +src/main/kotlin/org/openapitools/client/models/Category.kt +src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +src/main/kotlin/org/openapitools/client/models/Order.kt +src/main/kotlin/org/openapitools/client/models/Pet.kt +src/main/kotlin/org/openapitools/client/models/Tag.kt +src/main/kotlin/org/openapitools/client/models/User.kt diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/VERSION b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/README.md b/samples/client/petstore/kotlin-kotlinx-datetime/README.md new file mode 100644 index 000000000000..c97b251aba1e --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/README.md @@ -0,0 +1,101 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + +## Requires + +* Kotlin 1.7.21 +* Gradle 7.5 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.ModelApiResponse](docs/ModelApiResponse.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/build.gradle b/samples/client/petstore/kotlin-kotlinx-datetime/build.gradle new file mode 100644 index 000000000000..e8c65ba06a9a --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/build.gradle @@ -0,0 +1,63 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '7.5' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.8.10' + ext.spotless_version = "6.13.0" + + repositories { + maven { url "https://repo1.maven.org/maven2" } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "com.diffplug.spotless:spotless-plugin-gradle:$spotless_version" + } +} + +apply plugin: 'kotlin' +apply plugin: 'maven-publish' +apply plugin: 'com.diffplug.spotless' + +repositories { + maven { url "https://repo1.maven.org/maven2" } +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + kotlin { + ktfmt() + } +} + +test { + useJUnitPlatform() +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.squareup.moshi:moshi-kotlin:1.14.0" + implementation "com.squareup.moshi:moshi-adapters:1.14.0" + implementation "com.squareup.okhttp3:okhttp:4.11.0" + implementation "org.jetbrains.kotlinx:kotlinx-datetime:0.4.0" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/ApiResponse.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/ApiResponse.md new file mode 100644 index 000000000000..12f08d5cdef0 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/Category.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Category.md new file mode 100644 index 000000000000..2c28a670fc79 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/Order.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Order.md new file mode 100644 index 000000000000..84e068bef3f8 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**kotlinx.datetime.Instant**](kotlinx.datetime.Instant.md) | | [optional] +**status** | [**inline**](#Status) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/Pet.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Pet.md new file mode 100644 index 000000000000..da70fca06e65 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.collections.List<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.collections.List<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#Status) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/PetApi.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/PetApi.md new file mode 100644 index 000000000000..bb8451def0df --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/PetApi.md @@ -0,0 +1,405 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> kotlin.collections.List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val status : kotlin.collections.List = // kotlin.collections.List | Status values that need to be considered for filter +try { + val result : kotlin.collections.List = apiInstance.findPetsByStatus(status) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **findPetsByTags** +> kotlin.collections.List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.collections.List = // kotlin.collections.List | Tags to filter by +try { + val result : kotlin.collections.List = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload +try { + val result : ModelApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/StoreApi.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/StoreApi.md new file mode 100644 index 000000000000..9515ccd6d0cb --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/StoreApi.md @@ -0,0 +1,196 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val body : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(body) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/Tag.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Tag.md new file mode 100644 index 000000000000..60ce1bcdbad3 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/User.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/User.md new file mode 100644 index 000000000000..e801729b5ed1 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/docs/UserApi.md b/samples/client/petstore/kotlin-kotlinx-datetime/docs/UserApi.md new file mode 100644 index 000000000000..fdf75275cb97 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : User = // User | Created user object +try { + apiInstance.createUser(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithArrayInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithListInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val body : User = // User | Updated user object +try { + apiInstance.updateUser(username, body) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..c1962a79e29d Binary files /dev/null and b/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..8707e8b5067f --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-all.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/gradlew b/samples/client/petstore/kotlin-kotlinx-datetime/gradlew new file mode 100644 index 000000000000..aeb74cbb43e3 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/gradlew.bat b/samples/client/petstore/kotlin-kotlinx-datetime/gradlew.bat new file mode 100644 index 000000000000..93e3f59f135d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/settings.gradle b/samples/client/petstore/kotlin-kotlinx-datetime/settings.gradle new file mode 100644 index 000000000000..e5cd54b824d6 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-threetenbp' diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 000000000000..3263d52ffeba --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,650 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import java.io.IOException +import okhttp3.OkHttpClient +import okhttp3.HttpUrl + +import org.openapitools.client.models.ModelApiResponse +import org.openapitools.client.models.Pet + +import com.squareup.moshi.Json + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ApiResponse +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.PartConfig +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class PetApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.baseUrlKey, "http://petstore.swagger.io/v2") + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun addPet(body: Pet) : Unit { + val localVarResponse = addPetWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun addPetWithHttpInfo(body: Pet) : ApiResponse { + val localVariableConfig = addPetRequestConfig(body = body) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation addPet + * + * @param body Pet object that needs to be added to the store + * @return RequestConfig + */ + fun addPetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deletePet(petId: kotlin.Long, apiKey: kotlin.String? = null) : Unit { + val localVarResponse = deletePetWithHttpInfo(petId = petId, apiKey = apiKey) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun deletePetWithHttpInfo(petId: kotlin.Long, apiKey: kotlin.String?) : ApiResponse { + val localVariableConfig = deletePetRequestConfig(petId = petId, apiKey = apiKey) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deletePet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return RequestConfig + */ + fun deletePetRequestConfig(petId: kotlin.Long, apiKey: kotlin.String?) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * enum for parameter status + */ + enum class StatusFindPetsByStatus(val value: kotlin.String) { + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold") + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @return kotlin.collections.List + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun findPetsByStatus(status: kotlin.collections.List) : kotlin.collections.List { + val localVarResponse = findPetsByStatusWithHttpInfo(status = status) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun findPetsByStatusWithHttpInfo(status: kotlin.collections.List) : ApiResponse?> { + val localVariableConfig = findPetsByStatusRequestConfig(status = status) + + return request>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation findPetsByStatus + * + * @param status Status values that need to be considered for filter + * @return RequestConfig + */ + fun findPetsByStatusRequestConfig(status: kotlin.collections.List) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("status", toMultiValue(status.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/findByStatus", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return kotlin.collections.List + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTags(tags: kotlin.collections.List) : kotlin.collections.List { + @Suppress("DEPRECATION") + val localVarResponse = findPetsByTagsWithHttpInfo(tags = tags) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.List + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTagsWithHttpInfo(tags: kotlin.collections.List) : ApiResponse?> { + @Suppress("DEPRECATION") + val localVariableConfig = findPetsByTagsRequestConfig(tags = tags) + + return request>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation findPetsByTags + * + * @param tags Tags to filter by + * @return RequestConfig + */ + @Deprecated(message = "This operation is deprecated.") + fun findPetsByTagsRequestConfig(tags: kotlin.collections.List) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("tags", toMultiValue(tags.toList(), "csv")) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/findByTags", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return Pet + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getPetById(petId: kotlin.Long) : Pet { + val localVarResponse = getPetByIdWithHttpInfo(petId = petId) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Pet + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun getPetByIdWithHttpInfo(petId: kotlin.Long) : ApiResponse { + val localVariableConfig = getPetByIdRequestConfig(petId = petId) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getPetById + * + * @param petId ID of pet to return + * @return RequestConfig + */ + fun getPetByIdRequestConfig(petId: kotlin.Long) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePet(body: Pet) : Unit { + val localVarResponse = updatePetWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun updatePetWithHttpInfo(body: Pet) : ApiResponse { + val localVariableConfig = updatePetRequestConfig(body = body) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updatePet + * + * @param body Pet object that needs to be added to the store + * @return RequestConfig + */ + fun updatePetRequestConfig(body: Pet) : RequestConfig { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Content-Type"] = "application/json" + + return RequestConfig( + method = RequestMethod.PUT, + path = "/pet", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null) : Unit { + val localVarResponse = updatePetWithFormWithHttpInfo(petId = petId, name = name, status = status) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun updatePetWithFormWithHttpInfo(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : ApiResponse { + val localVariableConfig = updatePetWithFormRequestConfig(petId = petId, name = name, status = status) + + return request>, Unit>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updatePetWithForm + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return RequestConfig + */ + fun updatePetWithFormRequestConfig(petId: kotlin.Long, name: kotlin.String?, status: kotlin.String?) : RequestConfig>> { + val localVariableBody = mapOf( + "name" to PartConfig(body = name, headers = mutableMapOf()), + "status" to PartConfig(body = status, headers = mutableMapOf()),) + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "application/x-www-form-urlencoded") + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet/{petId}".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: java.io.File? = null) : ModelApiResponse { + val localVarResponse = uploadFileWithHttpInfo(petId = petId, additionalMetadata = additionalMetadata, file = file) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as ModelApiResponse + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun uploadFileWithHttpInfo(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : ApiResponse { + val localVariableConfig = uploadFileRequestConfig(petId = petId, additionalMetadata = additionalMetadata, file = file) + + return request>, ModelApiResponse>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation uploadFile + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return RequestConfig + */ + fun uploadFileRequestConfig(petId: kotlin.Long, additionalMetadata: kotlin.String?, file: java.io.File?) : RequestConfig>> { + val localVariableBody = mapOf( + "additionalMetadata" to PartConfig(body = additionalMetadata, headers = mutableMapOf()), + "file" to PartConfig(body = file, headers = mutableMapOf()),) + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf("Content-Type" to "multipart/form-data") + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/pet/{petId}/uploadImage".replace("{"+"petId"+"}", encodeURIComponent(petId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 000000000000..9893947c1bec --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,329 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import java.io.IOException +import okhttp3.OkHttpClient +import okhttp3.HttpUrl + +import org.openapitools.client.models.Order + +import com.squareup.moshi.Json + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ApiResponse +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.PartConfig +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class StoreApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.baseUrlKey, "http://petstore.swagger.io/v2") + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteOrder(orderId: kotlin.String) : Unit { + val localVarResponse = deleteOrderWithHttpInfo(orderId = orderId) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun deleteOrderWithHttpInfo(orderId: kotlin.String) : ApiResponse { + val localVariableConfig = deleteOrderRequestConfig(orderId = orderId) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteOrder + * + * @param orderId ID of the order that needs to be deleted + * @return RequestConfig + */ + fun deleteOrderRequestConfig(orderId: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return kotlin.collections.Map + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getInventory() : kotlin.collections.Map { + val localVarResponse = getInventoryWithHttpInfo() + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.collections.Map + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return ApiResponse?> + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun getInventoryWithHttpInfo() : ApiResponse?> { + val localVariableConfig = getInventoryRequestConfig() + + return request>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getInventory + * + * @return RequestConfig + */ + fun getInventoryRequestConfig() : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/store/inventory", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + body = localVariableBody + ) + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getOrderById(orderId: kotlin.Long) : Order { + val localVarResponse = getOrderByIdWithHttpInfo(orderId = orderId) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun getOrderByIdWithHttpInfo(orderId: kotlin.Long) : ApiResponse { + val localVariableConfig = getOrderByIdRequestConfig(orderId = orderId) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getOrderById + * + * @param orderId ID of pet that needs to be fetched + * @return RequestConfig + */ + fun getOrderByIdRequestConfig(orderId: kotlin.Long) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/store/order/{orderId}".replace("{"+"orderId"+"}", encodeURIComponent(orderId.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun placeOrder(body: Order) : Order { + val localVarResponse = placeOrderWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as Order + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun placeOrderWithHttpInfo(body: Order) : ApiResponse { + val localVariableConfig = placeOrderRequestConfig(body = body) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation placeOrder + * + * @param body order placed for purchasing the pet + * @return RequestConfig + */ + fun placeOrderRequestConfig(body: Order) : RequestConfig { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.POST, + path = "/store/order", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 000000000000..7bd04e022216 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,608 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import java.io.IOException +import okhttp3.OkHttpClient +import okhttp3.HttpUrl + +import org.openapitools.client.models.User + +import com.squareup.moshi.Json + +import org.openapitools.client.infrastructure.ApiClient +import org.openapitools.client.infrastructure.ApiResponse +import org.openapitools.client.infrastructure.ClientException +import org.openapitools.client.infrastructure.ClientError +import org.openapitools.client.infrastructure.ServerException +import org.openapitools.client.infrastructure.ServerError +import org.openapitools.client.infrastructure.MultiValueMap +import org.openapitools.client.infrastructure.PartConfig +import org.openapitools.client.infrastructure.RequestConfig +import org.openapitools.client.infrastructure.RequestMethod +import org.openapitools.client.infrastructure.ResponseType +import org.openapitools.client.infrastructure.Success +import org.openapitools.client.infrastructure.toMultiValue + +class UserApi(basePath: kotlin.String = defaultBasePath, client: OkHttpClient = ApiClient.defaultClient) : ApiClient(basePath, client) { + companion object { + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(ApiClient.baseUrlKey, "http://petstore.swagger.io/v2") + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUser(body: User) : Unit { + val localVarResponse = createUserWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun createUserWithHttpInfo(body: User) : ApiResponse { + val localVariableConfig = createUserRequestConfig(body = body) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createUser + * + * @param body Created user object + * @return RequestConfig + */ + fun createUserRequestConfig(body: User) : RequestConfig { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.POST, + path = "/user", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithArrayInput(body: kotlin.collections.List) : Unit { + val localVarResponse = createUsersWithArrayInputWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun createUsersWithArrayInputWithHttpInfo(body: kotlin.collections.List) : ApiResponse { + val localVariableConfig = createUsersWithArrayInputRequestConfig(body = body) + + return request, Unit>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createUsersWithArrayInput + * + * @param body List of user object + * @return RequestConfig + */ + fun createUsersWithArrayInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.POST, + path = "/user/createWithArray", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun createUsersWithListInput(body: kotlin.collections.List) : Unit { + val localVarResponse = createUsersWithListInputWithHttpInfo(body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun createUsersWithListInputWithHttpInfo(body: kotlin.collections.List) : ApiResponse { + val localVariableConfig = createUsersWithListInputRequestConfig(body = body) + + return request, Unit>( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation createUsersWithListInput + * + * @param body List of user object + * @return RequestConfig + */ + fun createUsersWithListInputRequestConfig(body: kotlin.collections.List) : RequestConfig> { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.POST, + path = "/user/createWithList", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun deleteUser(username: kotlin.String) : Unit { + val localVarResponse = deleteUserWithHttpInfo(username = username) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun deleteUserWithHttpInfo(username: kotlin.String) : ApiResponse { + val localVariableConfig = deleteUserRequestConfig(username = username) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation deleteUser + * + * @param username The name that needs to be deleted + * @return RequestConfig + */ + fun deleteUserRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.DELETE, + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun getUserByName(username: kotlin.String) : User { + val localVarResponse = getUserByNameWithHttpInfo(username = username) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as User + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun getUserByNameWithHttpInfo(username: kotlin.String) : ApiResponse { + val localVariableConfig = getUserByNameRequestConfig(username = username) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation getUserByName + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return RequestConfig + */ + fun getUserByNameRequestConfig(username: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return kotlin.String + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun loginUser(username: kotlin.String, password: kotlin.String) : kotlin.String { + val localVarResponse = loginUserWithHttpInfo(username = username, password = password) + + return when (localVarResponse.responseType) { + ResponseType.Success -> (localVarResponse as Success<*>).data as kotlin.String + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Suppress("UNCHECKED_CAST") + @Throws(IllegalStateException::class, IOException::class) + fun loginUserWithHttpInfo(username: kotlin.String, password: kotlin.String) : ApiResponse { + val localVariableConfig = loginUserRequestConfig(username = username, password = password) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation loginUser + * + * @param username The user name for login + * @param password The password for login in clear text + * @return RequestConfig + */ + fun loginUserRequestConfig(username: kotlin.String, password: kotlin.String) : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf>() + .apply { + put("username", listOf(username.toString())) + put("password", listOf(password.toString())) + } + val localVariableHeaders: MutableMap = mutableMapOf() + localVariableHeaders["Accept"] = "application/json" + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/login", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Logs out current logged in user session + * + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun logoutUser() : Unit { + val localVarResponse = logoutUserWithHttpInfo() + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Logs out current logged in user session + * + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun logoutUserWithHttpInfo() : ApiResponse { + val localVariableConfig = logoutUserRequestConfig() + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation logoutUser + * + * @return RequestConfig + */ + fun logoutUserRequestConfig() : RequestConfig { + val localVariableBody = null + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.GET, + path = "/user/logout", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + * @throws UnsupportedOperationException If the API returns an informational or redirection response + * @throws ClientException If the API returns a client error response + * @throws ServerException If the API returns a server error response + */ + @Throws(IllegalStateException::class, IOException::class, UnsupportedOperationException::class, ClientException::class, ServerException::class) + fun updateUser(username: kotlin.String, body: User) : Unit { + val localVarResponse = updateUserWithHttpInfo(username = username, body = body) + + return when (localVarResponse.responseType) { + ResponseType.Success -> Unit + ResponseType.Informational -> throw UnsupportedOperationException("Client does not support Informational responses.") + ResponseType.Redirection -> throw UnsupportedOperationException("Client does not support Redirection responses.") + ResponseType.ClientError -> { + val localVarError = localVarResponse as ClientError<*> + throw ClientException("Client error : ${localVarError.statusCode} ${localVarError.message.orEmpty()}", localVarError.statusCode, localVarResponse) + } + ResponseType.ServerError -> { + val localVarError = localVarResponse as ServerError<*> + throw ServerException("Server error : ${localVarError.statusCode} ${localVarError.message.orEmpty()} ${localVarError.body}", localVarError.statusCode, localVarResponse) + } + } + } + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return ApiResponse + * @throws IllegalStateException If the request is not correctly configured + * @throws IOException Rethrows the OkHttp execute method exception + */ + @Throws(IllegalStateException::class, IOException::class) + fun updateUserWithHttpInfo(username: kotlin.String, body: User) : ApiResponse { + val localVariableConfig = updateUserRequestConfig(username = username, body = body) + + return request( + localVariableConfig + ) + } + + /** + * To obtain the request config of the operation updateUser + * + * @param username name that need to be deleted + * @param body Updated user object + * @return RequestConfig + */ + fun updateUserRequestConfig(username: kotlin.String, body: User) : RequestConfig { + val localVariableBody = body + val localVariableQuery: MultiValueMap = mutableMapOf() + val localVariableHeaders: MutableMap = mutableMapOf() + + return RequestConfig( + method = RequestMethod.PUT, + path = "/user/{username}".replace("{"+"username"+"}", encodeURIComponent(username.toString())), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + body = localVariableBody + ) + } + + + private fun encodeURIComponent(uriComponent: kotlin.String): kotlin.String = + HttpUrl.Builder().scheme("http").host("localhost").addPathSegment(uriComponent).build().encodedPathSegments[0] +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..a4a4491eac0d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..26f85869b681 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,272 @@ +package org.openapitools.client.infrastructure + +import okhttp3.OkHttpClient +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.asRequestBody +import okhttp3.RequestBody.Companion.toRequestBody +import okhttp3.FormBody +import okhttp3.HttpUrl.Companion.toHttpUrlOrNull +import okhttp3.ResponseBody +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.Request +import okhttp3.Headers +import okhttp3.Headers.Companion.toHeaders +import okhttp3.MultipartBody +import okhttp3.Call +import okhttp3.Callback +import okhttp3.Response +import java.io.BufferedWriter +import java.io.File +import java.io.FileWriter +import java.io.IOException +import java.net.URLConnection +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.LocalTime +import java.time.OffsetDateTime +import java.time.OffsetTime +import java.util.Locale +import com.squareup.moshi.adapter + + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + +open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { + companion object { + protected const val ContentType = "Content-Type" + protected const val Accept = "Accept" + protected const val Authorization = "Authorization" + protected const val JsonMediaType = "application/json" + protected const val FormDataMediaType = "multipart/form-data" + protected const val FormUrlEncMediaType = "application/x-www-form-urlencoded" + protected const val XmlMediaType = "application/xml" + protected const val OctetMediaType = "application/octet-stream" + + val apiKey: MutableMap = mutableMapOf() + val apiKeyPrefix: MutableMap = mutableMapOf() + var username: String? = null + var password: String? = null + var accessToken: String? = null + const val baseUrlKey = "org.openapitools.client.baseUrl" + + @JvmStatic + val defaultClient: OkHttpClient by lazy { + builder.build() + } + + @JvmStatic + val builder: OkHttpClient.Builder = OkHttpClient.Builder() + } + + /** + * Guess Content-Type header from the given file (defaults to "application/octet-stream"). + * + * @param file The given file + * @return The guessed Content-Type + */ + protected fun guessContentTypeFromFile(file: File): String { + val contentType = URLConnection.guessContentTypeFromName(file.name) + return contentType ?: "application/octet-stream" + } + + protected inline fun requestBody(content: T, mediaType: String?): RequestBody = + when { + content is File -> content.asRequestBody((mediaType ?: guessContentTypeFromFile(content)).toMediaTypeOrNull()) + mediaType == FormDataMediaType -> + MultipartBody.Builder() + .setType(MultipartBody.FORM) + .apply { + // content's type *must* be Map> + @Suppress("UNCHECKED_CAST") + (content as Map>).forEach { (name, part) -> + if (part.body is File) { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"; filename=\"${part.body.name}\"") + val fileMediaType = guessContentTypeFromFile(part.body).toMediaTypeOrNull() + addPart( + partHeaders.toHeaders(), + part.body.asRequestBody(fileMediaType) + ) + } else { + val partHeaders = part.headers.toMutableMap() + + ("Content-Disposition" to "form-data; name=\"$name\"") + addPart( + partHeaders.toHeaders(), + parameterToString(part.body).toRequestBody(null) + ) + } + } + }.build() + mediaType == FormUrlEncMediaType -> { + FormBody.Builder().apply { + // content's type *must* be Map> + @Suppress("UNCHECKED_CAST") + (content as Map>).forEach { (name, part) -> + add(name, parameterToString(part.body)) + } + }.build() + } + mediaType == null || mediaType.startsWith("application/") && mediaType.endsWith("json") -> + if (content == null) { + EMPTY_REQUEST + } else { + Serializer.moshi.adapter(T::class.java).toJson(content) + .toRequestBody((mediaType ?: JsonMediaType).toMediaTypeOrNull()) + } + mediaType == XmlMediaType -> throw UnsupportedOperationException("xml not currently supported.") + mediaType == OctetMediaType && content is ByteArray -> + content.toRequestBody(OctetMediaType.toMediaTypeOrNull()) + // TODO: this should be extended with other serializers + else -> throw UnsupportedOperationException("requestBody currently only supports JSON body, byte body and File body.") + } + + @OptIn(ExperimentalStdlibApi::class) + protected inline fun responseBody(body: ResponseBody?, mediaType: String? = JsonMediaType): T? { + if(body == null) { + return null + } + if (T::class.java == File::class.java) { + // return tempFile + // Attention: if you are developing an android app that supports API Level 25 and bellow, please check flag supportAndroidApiLevel25AndBelow in https://openapi-generator.tech/docs/generators/kotlin#config-options + val tempFile = java.nio.file.Files.createTempFile("tmp.org.openapitools.client", null).toFile() + tempFile.deleteOnExit() + body.byteStream().use { inputStream -> + tempFile.outputStream().use { tempFileOutputStream -> + inputStream.copyTo(tempFileOutputStream) + } + } + return tempFile as T + } + + return when { + mediaType == null || (mediaType.startsWith("application/") && mediaType.endsWith("json")) -> { + val bodyContent = body.string() + if (bodyContent.isEmpty()) { + return null + } + Serializer.moshi.adapter().fromJson(bodyContent) + } + mediaType == OctetMediaType -> body.bytes() as? T + else -> throw UnsupportedOperationException("responseBody currently only supports JSON body.") + } + } + + protected fun updateAuthParams(requestConfig: RequestConfig) { + if (requestConfig.headers[Authorization].isNullOrEmpty()) { + accessToken?.let { accessToken -> + requestConfig.headers[Authorization] = "Bearer $accessToken " + } + } + if (requestConfig.headers["api_key"].isNullOrEmpty()) { + if (apiKey["api_key"] != null) { + if (apiKeyPrefix["api_key"] != null) { + requestConfig.headers["api_key"] = apiKeyPrefix["api_key"]!! + " " + apiKey["api_key"]!! + } else { + requestConfig.headers["api_key"] = apiKey["api_key"]!! + } + } + } + } + + protected inline fun request(requestConfig: RequestConfig): ApiResponse { + val httpUrl = baseUrl.toHttpUrlOrNull() ?: throw IllegalStateException("baseUrl is invalid.") + + // take authMethod from operation + updateAuthParams(requestConfig) + + val url = httpUrl.newBuilder() + .addEncodedPathSegments(requestConfig.path.trimStart('/')) + .apply { + requestConfig.query.forEach { query -> + query.value.forEach { queryValue -> + addQueryParameter(query.key, queryValue) + } + } + }.build() + + // take content-type/accept from spec or set to default (application/json) if not defined + if (requestConfig.body != null && requestConfig.headers[ContentType].isNullOrEmpty()) { + requestConfig.headers[ContentType] = JsonMediaType + } + if (requestConfig.headers[Accept].isNullOrEmpty()) { + requestConfig.headers[Accept] = JsonMediaType + } + val headers = requestConfig.headers + + if (headers[Accept].isNullOrEmpty()) { + throw kotlin.IllegalStateException("Missing Accept header. This is required.") + } + + val contentType = if (headers[ContentType] != null) { + // TODO: support multiple contentType options here. + (headers[ContentType] as String).substringBefore(";").lowercase(Locale.US) + } else { + null + } + + val request = when (requestConfig.method) { + RequestMethod.DELETE -> Request.Builder().url(url).delete(requestBody(requestConfig.body, contentType)) + RequestMethod.GET -> Request.Builder().url(url) + RequestMethod.HEAD -> Request.Builder().url(url).head() + RequestMethod.PATCH -> Request.Builder().url(url).patch(requestBody(requestConfig.body, contentType)) + RequestMethod.PUT -> Request.Builder().url(url).put(requestBody(requestConfig.body, contentType)) + RequestMethod.POST -> Request.Builder().url(url).post(requestBody(requestConfig.body, contentType)) + RequestMethod.OPTIONS -> Request.Builder().url(url).method("OPTIONS", null) + }.apply { + headers.forEach { header -> addHeader(header.key, header.value) } + }.build() + + val response = client.newCall(request).execute() + + val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) + + // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") + return when { + response.isRedirect -> Redirection( + response.code, + response.headers.toMultimap() + ) + response.isInformational -> Informational( + response.message, + response.code, + response.headers.toMultimap() + ) + response.isSuccessful -> Success( + responseBody(response.body, accept), + response.code, + response.headers.toMultimap() + ) + response.isClientError -> ClientError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + else -> ServerError( + response.message, + response.body?.string(), + response.code, + response.headers.toMultimap() + ) + } + } + + protected fun parameterToString(value: Any?): String = when (value) { + null -> "" + is Array<*> -> toMultiValue(value, "csv").toString() + is Iterable<*> -> toMultiValue(value, "csv").toString() + is OffsetDateTime, is OffsetTime, is LocalDateTime, is LocalDate, is LocalTime -> + parseDateToQueryString(value) + else -> value.toString() + } + + protected inline fun parseDateToQueryString(value : T): String { + /* + .replace("\"", "") converts the json object string to an actual string for the query parameter. + The moshi or gson adapter allows a more generic solution instead of trying to use a native + formatter. It also easily allows to provide a simple way to define a custom date format pattern + inside a gson/moshi adapter. + */ + return Serializer.moshi.adapter(T::class.java).toJson(value).replace("\"", "") + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt new file mode 100644 index 000000000000..cf2cfaa95d91 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ApiResponse.kt @@ -0,0 +1,43 @@ +package org.openapitools.client.infrastructure + +enum class ResponseType { + Success, Informational, Redirection, ClientError, ServerError +} + +interface Response + +abstract class ApiResponse(val responseType: ResponseType): Response { + abstract val statusCode: Int + abstract val headers: Map> +} + +class Success( + val data: T, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +): ApiResponse(ResponseType.Success) + +class Informational( + val statusText: String, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Informational) + +class Redirection( + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.Redirection) + +class ClientError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> = mapOf() +) : ApiResponse(ResponseType.ClientError) + +class ServerError( + val message: String? = null, + val body: Any? = null, + override val statusCode: Int = -1, + override val headers: Map> +): ApiResponse(ResponseType.ServerError) diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt new file mode 100644 index 000000000000..064b57fc6b82 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigDecimalAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigDecimal + +class BigDecimalAdapter { + @ToJson + fun toJson(value: BigDecimal): String { + return value.toPlainString() + } + + @FromJson + fun fromJson(value: String): BigDecimal { + return BigDecimal(value) + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt new file mode 100644 index 000000000000..7df6057b4503 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/BigIntegerAdapter.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.math.BigInteger + +class BigIntegerAdapter { + @ToJson + fun toJson(value: BigInteger): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): BigInteger { + return BigInteger(value) + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt new file mode 100644 index 000000000000..ff5e2a81ee8c --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ByteArrayAdapter.kt @@ -0,0 +1,12 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson + +class ByteArrayAdapter { + @ToJson + fun toJson(data: ByteArray): String = String(data) + + @FromJson + fun fromJson(data: String): ByteArray = data.toByteArray() +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt new file mode 100644 index 000000000000..c83993b9055c --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Errors.kt @@ -0,0 +1,18 @@ +@file:Suppress("unused") +package org.openapitools.client.infrastructure + +import java.lang.RuntimeException + +open class ClientException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 123L + } +} + +open class ServerException(message: kotlin.String? = null, val statusCode: Int = -1, val response: Response? = null) : RuntimeException(message) { + + companion object { + private const val serialVersionUID: Long = 456L + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/InstantAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/InstantAdapter.kt new file mode 100644 index 000000000000..0e155923ee82 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/InstantAdapter.kt @@ -0,0 +1,18 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import kotlinx.datetime.Instant + +class InstantAdapter { + @ToJson + fun toJson(value: Instant): String { + return value.toString() + } + + @FromJson + fun fromJson(value: String): Instant { + return Instant.parse(value) + } + +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt new file mode 100644 index 000000000000..b2e1654479a0 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDate +import java.time.format.DateTimeFormatter + +class LocalDateAdapter { + @ToJson + fun toJson(value: LocalDate): String { + return DateTimeFormatter.ISO_LOCAL_DATE.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDate { + return LocalDate.parse(value, DateTimeFormatter.ISO_LOCAL_DATE) + } + +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt new file mode 100644 index 000000000000..e082db94811d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/LocalDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.LocalDateTime +import java.time.format.DateTimeFormatter + +class LocalDateTimeAdapter { + @ToJson + fun toJson(value: LocalDateTime): String { + return DateTimeFormatter.ISO_LOCAL_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): LocalDateTime { + return LocalDateTime.parse(value, DateTimeFormatter.ISO_LOCAL_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt new file mode 100644 index 000000000000..87437871a31e --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/OffsetDateTimeAdapter.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.time.OffsetDateTime +import java.time.format.DateTimeFormatter + +class OffsetDateTimeAdapter { + @ToJson + fun toJson(value: OffsetDateTime): String { + return DateTimeFormatter.ISO_OFFSET_DATE_TIME.format(value) + } + + @FromJson + fun fromJson(value: String): OffsetDateTime { + return OffsetDateTime.parse(value, DateTimeFormatter.ISO_OFFSET_DATE_TIME) + } + +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..6578b9381b78 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt new file mode 100644 index 000000000000..9bd2790dc144 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExtensions.kt @@ -0,0 +1,24 @@ +package org.openapitools.client.infrastructure + +import okhttp3.Response + +/** + * Provides an extension to evaluation whether the response is a 1xx code + */ +val Response.isInformational : Boolean get() = this.code in 100..199 + +/** + * Provides an extension to evaluation whether the response is a 3xx code + */ +@Suppress("EXTENSION_SHADOWED_BY_MEMBER") +val Response.isRedirect : Boolean get() = this.code in 300..399 + +/** + * Provides an extension to evaluation whether the response is a 4xx code + */ +val Response.isClientError : Boolean get() = this.code in 400..499 + +/** + * Provides an extension to evaluation whether the response is a 5xx (Standard) through 999 (non-standard) code + */ +val Response.isServerError : Boolean get() = this.code in 500..999 diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 000000000000..d191eb67d45d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,24 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.Moshi +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory + +object Serializer { + @JvmStatic + val moshiBuilder: Moshi.Builder = Moshi.Builder() + .add(OffsetDateTimeAdapter()) + .add(InstantAdapter()) + .add(LocalDateTimeAdapter()) + .add(LocalDateAdapter()) + .add(UUIDAdapter()) + .add(ByteArrayAdapter()) + .add(URIAdapter()) + .add(KotlinJsonAdapterFactory()) + .add(BigDecimalAdapter()) + .add(BigIntegerAdapter()) + + @JvmStatic + val moshi: Moshi by lazy { + moshiBuilder.build() + } +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt new file mode 100644 index 000000000000..927522757da9 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/URIAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.net.URI + +class URIAdapter { + @ToJson + fun toJson(uri: URI) = uri.toString() + + @FromJson + fun fromJson(s: String): URI = URI.create(s) +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt new file mode 100644 index 000000000000..7ccf7dc25d2d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/infrastructure/UUIDAdapter.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.infrastructure + +import com.squareup.moshi.FromJson +import com.squareup.moshi.ToJson +import java.util.UUID + +class UUIDAdapter { + @ToJson + fun toJson(uuid: UUID) = uuid.toString() + + @FromJson + fun fromJson(s: String): UUID = UUID.fromString(s) +} diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 000000000000..4d74348ecd01 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,39 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * A category for a pet + * + * @param id + * @param name + */ + + +data class Category ( + + @Json(name = "id") + val id: kotlin.Long? = null, + + @Json(name = "name") + val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt new file mode 100644 index 000000000000..e9e9fe4870d1 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -0,0 +1,43 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * Describes the result of uploading an image resource + * + * @param code + * @param type + * @param message + */ + + +data class ModelApiResponse ( + + @Json(name = "code") + val code: kotlin.Int? = null, + + @Json(name = "type") + val type: kotlin.String? = null, + + @Json(name = "message") + val message: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 000000000000..bbfae8a8b2da --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * An order for a pets from the pet store + * + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ + + +data class Order ( + + @Json(name = "id") + val id: kotlin.Long? = null, + + @Json(name = "petId") + val petId: kotlin.Long? = null, + + @Json(name = "quantity") + val quantity: kotlin.Int? = null, + + @Json(name = "shipDate") + val shipDate: kotlinx.datetime.Instant? = null, + + /* Order Status */ + @Json(name = "status") + val status: Order.Status? = null, + + @Json(name = "complete") + val complete: kotlin.Boolean? = false + +) { + + /** + * Order Status + * + * Values: placed,approved,delivered + */ + @JsonClass(generateAdapter = false) + enum class Status(val value: kotlin.String) { + @Json(name = "placed") placed("placed"), + @Json(name = "approved") approved("approved"), + @Json(name = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 000000000000..cc35b5164c51 --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,71 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * A pet for sale in the pet store + * + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ + + +data class Pet ( + + @Json(name = "name") + val name: kotlin.String, + + @Json(name = "photoUrls") + val photoUrls: kotlin.collections.List, + + @Json(name = "id") + val id: kotlin.Long? = null, + + @Json(name = "category") + val category: Category? = null, + + @Json(name = "tags") + val tags: kotlin.collections.List? = null, + + /* pet status in the store */ + @Json(name = "status") + val status: Pet.Status? = null + +) { + + /** + * pet status in the store + * + * Values: available,pending,sold + */ + @JsonClass(generateAdapter = false) + enum class Status(val value: kotlin.String) { + @Json(name = "available") available("available"), + @Json(name = "pending") pending("pending"), + @Json(name = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 000000000000..b21fbab6580d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,39 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * A tag for a pet + * + * @param id + * @param name + */ + + +data class Tag ( + + @Json(name = "id") + val id: kotlin.Long? = null, + + @Json(name = "name") + val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 000000000000..e5269f5d5d3d --- /dev/null +++ b/samples/client/petstore/kotlin-kotlinx-datetime/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,64 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.squareup.moshi.Json +import com.squareup.moshi.JsonClass + +/** + * A User who is purchasing from the pet store + * + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ + + +data class User ( + + @Json(name = "id") + val id: kotlin.Long? = null, + + @Json(name = "username") + val username: kotlin.String? = null, + + @Json(name = "firstName") + val firstName: kotlin.String? = null, + + @Json(name = "lastName") + val lastName: kotlin.String? = null, + + @Json(name = "email") + val email: kotlin.String? = null, + + @Json(name = "password") + val password: kotlin.String? = null, + + @Json(name = "phone") + val phone: kotlin.String? = null, + + /* User Status */ + @Json(name = "userStatus") + val userStatus: kotlin.Int? = null + +) + diff --git a/samples/client/petstore/kotlin-modelMutable/.openapi-generator/VERSION b/samples/client/petstore/kotlin-modelMutable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-modelMutable/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-modelMutable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5b2c0ad376a1..26f85869b681 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-modelMutable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-moshi-codegen/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5b2c0ad376a1..26f85869b681 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-moshi-codegen/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator-ignore b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/FILES b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/FILES new file mode 100644 index 000000000000..ae11a0430af1 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/FILES @@ -0,0 +1,43 @@ +README.md +build.gradle.kts +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +settings.gradle.kts +src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt +src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt +src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt +src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt +src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt +src/commonMain/kotlin/org/openapitools/client/models/Category.kt +src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt +src/commonMain/kotlin/org/openapitools/client/models/Order.kt +src/commonMain/kotlin/org/openapitools/client/models/Pet.kt +src/commonMain/kotlin/org/openapitools/client/models/Tag.kt +src/commonMain/kotlin/org/openapitools/client/models/User.kt +src/commonTest/kotlin/util/Coroutine.kt +src/iosTest/kotlin/util/Coroutine.kt +src/jsTest/kotlin/util/Coroutine.kt +src/jvmTest/kotlin/util/Coroutine.kt diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/VERSION b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/README.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/README.md new file mode 100644 index 000000000000..bdc31197a607 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/README.md @@ -0,0 +1,92 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + +## Requires + +* Kotlin 1.5.10 + +## Build + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. + + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** /user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.ModelApiResponse](docs/ModelApiResponse.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/build.gradle.kts new file mode 100644 index 000000000000..60a1d4bbf117 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/build.gradle.kts @@ -0,0 +1,101 @@ +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget + +plugins { + kotlin("multiplatform") version "1.9.20" // kotlin_version + kotlin("plugin.serialization") version "1.9.20" // kotlin_version +} + +group = "org.openapitools" +version = "1.0.0" + +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" + +repositories { + mavenCentral() +} + +kotlin { + jvm() + iosX64() + iosArm64() + iosSimulatorArm64() + js { + browser() + nodejs() + } + + sourceSets { + commonMain { + dependencies { + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") + implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") + + api("io.ktor:ktor-client-core:$ktor_version") + api("io.ktor:ktor-client-serialization:$ktor_version") + api("io.ktor:ktor-client-content-negotiation:$ktor_version") + api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") + } + } + + commonTest { + dependencies { + implementation(kotlin("test")) + implementation("io.ktor:ktor-client-mock:$ktor_version") + } + } + + jvmMain { + dependencies { + implementation(kotlin("stdlib-jdk7")) + implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") + } + } + + jvmTest { + dependencies { + implementation(kotlin("test-junit")) + } + } + + iosMain { + dependencies { + api("io.ktor:ktor-client-ios:$ktor_version") + } + } + + jsMain { + dependencies { + api("io.ktor:ktor-client-js:$ktor_version") + } + } + + all { + languageSettings.apply { + optIn("kotlin.Experimental") + } + } + } +} + +tasks { + register("iosTest") { + val device = project.findProperty("device")?.toString() ?: "iPhone 8" + dependsOn("linkDebugTestIosX64") + group = JavaBasePlugin.VERIFICATION_GROUP + description = "Execute unit tests on ${device} simulator" + doLast { + val binary = kotlin.targets.getByName("iosX64").binaries.getTest("DEBUG") + exec { + commandLine("xcrun", "simctl", "spawn", device, binary.outputFile) + } + } + } + register("test") { + dependsOn("allTests") + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/ApiResponse.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/ApiResponse.md new file mode 100644 index 000000000000..12f08d5cdef0 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Category.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Category.md new file mode 100644 index 000000000000..2c28a670fc79 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Order.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Order.md new file mode 100644 index 000000000000..84e068bef3f8 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**kotlinx.datetime.Instant**](kotlinx.datetime.Instant.md) | | [optional] +**status** | [**inline**](#Status) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Pet.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Pet.md new file mode 100644 index 000000000000..da70fca06e65 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.collections.List<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.collections.List<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#Status) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/PetApi.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/PetApi.md new file mode 100644 index 000000000000..851879ed2f4d --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/PetApi.md @@ -0,0 +1,405 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +# **addPet** +> addPet(body) + +Add a new pet to the store + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.addPet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#addPet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#addPet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **deletePet** +> deletePet(petId, apiKey) + +Deletes a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | +try { + apiInstance.deletePet(petId, apiKey) +} catch (e: ClientException) { + println("4xx response calling PetApi#deletePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#deletePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **findPetsByStatus** +> kotlin.collections.List<Pet> findPetsByStatus(status) + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val status : kotlin.collections.List = // kotlin.collections.List | Status values that need to be considered for filter +try { + val result : kotlin.collections.List = apiInstance.findPetsByStatus(status) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByStatus") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **findPetsByTags** +> kotlin.collections.List<Pet> findPetsByTags(tags) + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val tags : kotlin.collections.List = // kotlin.collections.List | Tags to filter by +try { + val result : kotlin.collections.List = apiInstance.findPetsByTags(tags) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#findPetsByTags") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **getPetById** +> Pet getPetById(petId) + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return +try { + val result : Pet = apiInstance.getPetById(petId) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#getPetById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#getPetById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **updatePet** +> updatePet(body) + +Update an existing pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val body : Pet = // Pet | Pet object that needs to be added to the store +try { + apiInstance.updatePet(body) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePet") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePet") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: Not defined + + +# **updatePetWithForm** +> updatePetWithForm(petId, name, status) + +Updates a pet in the store with form data + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet +try { + apiInstance.updatePetWithForm(petId, name, status) +} catch (e: ClientException) { + println("4xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#updatePetWithForm") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +# **uploadFile** +> ModelApiResponse uploadFile(petId, additionalMetadata, file) + +uploads an image + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = PetApi() +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : io.ktor.client.request.forms.InputProvider = BINARY_DATA_HERE // io.ktor.client.request.forms.InputProvider | file to upload +try { + val result : ModelApiResponse = apiInstance.uploadFile(petId, additionalMetadata, file) + println(result) +} catch (e: ClientException) { + println("4xx response calling PetApi#uploadFile") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling PetApi#uploadFile") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **io.ktor.client.request.forms.InputProvider**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + + +Configure petstore_auth: + ApiClient.accessToken = "" + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/StoreApi.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/StoreApi.md new file mode 100644 index 000000000000..d111b2911d7e --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/StoreApi.md @@ -0,0 +1,196 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet + + + +# **deleteOrder** +> deleteOrder(orderId) + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted +try { + apiInstance.deleteOrder(orderId) +} catch (e: ClientException) { + println("4xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#deleteOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getInventory** +> kotlin.collections.Map<kotlin.String, kotlin.Int> getInventory() + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +try { + val result : kotlin.collections.Map = apiInstance.getInventory() + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getInventory") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getInventory") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + +Configure api_key: + ApiClient.apiKey["api_key"] = "" + ApiClient.apiKeyPrefix["api_key"] = "" + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +# **getOrderById** +> Order getOrderById(orderId) + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched +try { + val result : Order = apiInstance.getOrderById(orderId) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#getOrderById") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#getOrderById") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **placeOrder** +> Order placeOrder(body) + +Place an order for a pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = StoreApi() +val body : Order = // Order | order placed for purchasing the pet +try { + val result : Order = apiInstance.placeOrder(body) + println(result) +} catch (e: ClientException) { + println("4xx response calling StoreApi#placeOrder") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling StoreApi#placeOrder") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Tag.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Tag.md new file mode 100644 index 000000000000..60ce1bcdbad3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/User.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/User.md new file mode 100644 index 000000000000..e801729b5ed1 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/UserApi.md b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/UserApi.md new file mode 100644 index 000000000000..afcdb070dbbd --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/docs/UserApi.md @@ -0,0 +1,376 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + + +# **createUser** +> createUser(body) + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : User = // User | Created user object +try { + apiInstance.createUser(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithArrayInput** +> createUsersWithArrayInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithArrayInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithArrayInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **createUsersWithListInput** +> createUsersWithListInput(body) + +Creates list of users with given input array + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val body : kotlin.collections.List = // kotlin.collections.List | List of user object +try { + apiInstance.createUsersWithListInput(body) +} catch (e: ClientException) { + println("4xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#createUsersWithListInput") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **body** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **deleteUser** +> deleteUser(username) + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted +try { + apiInstance.deleteUser(username) +} catch (e: ClientException) { + println("4xx response calling UserApi#deleteUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#deleteUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **getUserByName** +> User getUserByName(username) + +Get user by user name + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. +try { + val result : User = apiInstance.getUserByName(username) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#getUserByName") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#getUserByName") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **loginUser** +> kotlin.String loginUser(username, password) + +Logs user into the system + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text +try { + val result : kotlin.String = apiInstance.loginUser(username, password) + println(result) +} catch (e: ClientException) { + println("4xx response calling UserApi#loginUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#loginUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +# **logoutUser** +> logoutUser() + +Logs out current logged in user session + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +try { + apiInstance.logoutUser() +} catch (e: ClientException) { + println("4xx response calling UserApi#logoutUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#logoutUser") + e.printStackTrace() +} +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +# **updateUser** +> updateUser(username, body) + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiInstance = UserApi() +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val body : User = // User | Updated user object +try { + apiInstance.updateUser(username, body) +} catch (e: ClientException) { + println("4xx response calling UserApi#updateUser") + e.printStackTrace() +} catch (e: ServerException) { + println("5xx response calling UserApi#updateUser") + e.printStackTrace() +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **body** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..c1962a79e29d Binary files /dev/null and b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..8707e8b5067f --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-all.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew new file mode 100644 index 000000000000..aeb74cbb43e3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew.bat b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew.bat new file mode 100644 index 000000000000..93e3f59f135d --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/settings.gradle.kts b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/settings.gradle.kts new file mode 100644 index 000000000000..845247195531 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/settings.gradle.kts @@ -0,0 +1 @@ +rootProject.name = "kotlin-client-petstore-multiplatform-kotlinx-datetime" diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 000000000000..ec709473d75a --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,356 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import org.openapitools.client.models.ModelApiResponse +import org.openapitools.client.models.Pet + +import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.request.forms.formData +import io.ktor.client.engine.HttpClientEngine +import kotlinx.serialization.json.Json +import io.ktor.http.ParametersBuilder +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +open class PetApi : ApiClient { + + constructor( + baseUrl: String = ApiClient.BASE_URL, + httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonSerializer: Json = ApiClient.JSON_DEFAULT + ) : super(baseUrl = baseUrl, httpClientEngine = httpClientEngine, httpClientConfig = httpClientConfig, jsonBlock = jsonSerializer) + + constructor( + baseUrl: String, + httpClient: HttpClient + ): super(baseUrl = baseUrl, httpClient = httpClient) + + /** + * Add a new pet to the store + * + * @param body Pet object that needs to be added to the store + * @return void + */ + open suspend fun addPet(body: Pet): HttpResponse { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = body + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + + /** + * Deletes a pet + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return void + */ + open suspend fun deletePet(petId: kotlin.Long, apiKey: kotlin.String? = null): HttpResponse { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + apiKey?.apply { localVariableHeaders["api_key"] = this.toString() } + + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + + /** + * enum for parameter status + */ + @Serializable + enum class StatusFindPetsByStatus(val value: kotlin.String) { + + @SerialName(value = "available") + available("available"), + + @SerialName(value = "pending") + pending("pending"), + + @SerialName(value = "sold") + sold("sold") + + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * @param status Status values that need to be considered for filter + * @return kotlin.collections.List + */ + @Suppress("UNCHECKED_CAST") + open suspend fun findPetsByStatus(status: kotlin.collections.List): HttpResponse> { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + status?.apply { localVariableQuery["status"] = toMultiValue(this, "csv") } + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/findByStatus", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap().map { value } + } + + @Serializable(FindPetsByStatusResponse.Companion::class) + private class FindPetsByStatusResponse(val value: List) { + companion object : KSerializer { + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: FindPetsByStatusResponse) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = FindPetsByStatusResponse(serializer.deserialize(decoder)) + } + } + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * @param tags Tags to filter by + * @return kotlin.collections.List + */ + @Suppress("UNCHECKED_CAST") + open suspend fun findPetsByTags(tags: kotlin.collections.List): HttpResponse> { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + tags?.apply { localVariableQuery["tags"] = toMultiValue(this, "csv") } + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/findByTags", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap().map { value } + } + + @Serializable(FindPetsByTagsResponse.Companion::class) + private class FindPetsByTagsResponse(val value: List) { + companion object : KSerializer { + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: FindPetsByTagsResponse) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = FindPetsByTagsResponse(serializer.deserialize(decoder)) + } + } + + /** + * Find pet by ID + * Returns a single pet + * @param petId ID of pet to return + * @return Pet + */ + @Suppress("UNCHECKED_CAST") + open suspend fun getPetById(petId: kotlin.Long): HttpResponse { + + val localVariableAuthNames = listOf("api_key") + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Update an existing pet + * + * @param body Pet object that needs to be added to the store + * @return void + */ + open suspend fun updatePet(body: Pet): HttpResponse { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = body + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/pet", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + + /** + * Updates a pet in the store with form data + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return void + */ + open suspend fun updatePetWithForm(petId: kotlin.Long, name: kotlin.String? = null, status: kotlin.String? = null): HttpResponse { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = + ParametersBuilder().also { + name?.apply { it.append("name", name.toString()) } + status?.apply { it.append("status", status.toString()) } + }.build() + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}".replace("{" + "petId" + "}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return urlEncodedFormRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * uploads an image + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return ModelApiResponse + */ + @Suppress("UNCHECKED_CAST") + open suspend fun uploadFile(petId: kotlin.Long, additionalMetadata: kotlin.String? = null, file: io.ktor.client.request.forms.InputProvider? = null): HttpResponse { + + val localVariableAuthNames = listOf("petstore_auth") + + val localVariableBody = + formData { + additionalMetadata?.apply { append("additionalMetadata", additionalMetadata) } + file?.apply { append("file", file) } + } + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/pet/{petId}/uploadImage".replace("{" + "petId" + "}", "$petId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return multipartFormRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 000000000000..83a909297ee7 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,184 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import org.openapitools.client.models.Order + +import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.request.forms.formData +import io.ktor.client.engine.HttpClientEngine +import kotlinx.serialization.json.Json +import io.ktor.http.ParametersBuilder +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +open class StoreApi : ApiClient { + + constructor( + baseUrl: String = ApiClient.BASE_URL, + httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonSerializer: Json = ApiClient.JSON_DEFAULT + ) : super(baseUrl = baseUrl, httpClientEngine = httpClientEngine, httpClientConfig = httpClientConfig, jsonBlock = jsonSerializer) + + constructor( + baseUrl: String, + httpClient: HttpClient + ): super(baseUrl = baseUrl, httpClient = httpClient) + + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * @param orderId ID of the order that needs to be deleted + * @return void + */ + open suspend fun deleteOrder(orderId: kotlin.String): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/store/order/{orderId}".replace("{" + "orderId" + "}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * @return kotlin.collections.Map + */ + @Suppress("UNCHECKED_CAST") + open suspend fun getInventory(): HttpResponse> { + + val localVariableAuthNames = listOf("api_key") + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/inventory", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = true, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap().map { value } + } + + @Serializable(GetInventoryResponse.Companion::class) + private class GetInventoryResponse(val value: Map) { + companion object : KSerializer { + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: GetInventoryResponse) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = GetInventoryResponse(serializer.deserialize(decoder)) + } + } + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * @param orderId ID of pet that needs to be fetched + * @return Order + */ + @Suppress("UNCHECKED_CAST") + open suspend fun getOrderById(orderId: kotlin.Long): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/store/order/{orderId}".replace("{" + "orderId" + "}", "$orderId"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Place an order for a pet + * + * @param body order placed for purchasing the pet + * @return Order + */ + @Suppress("UNCHECKED_CAST") + open suspend fun placeOrder(body: Order): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = body + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/store/order", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 000000000000..305871ff4ef2 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,322 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.apis + +import org.openapitools.client.models.User + +import org.openapitools.client.infrastructure.* +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.request.forms.formData +import io.ktor.client.engine.HttpClientEngine +import kotlinx.serialization.json.Json +import io.ktor.http.ParametersBuilder +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +open class UserApi : ApiClient { + + constructor( + baseUrl: String = ApiClient.BASE_URL, + httpClientEngine: HttpClientEngine? = null, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonSerializer: Json = ApiClient.JSON_DEFAULT + ) : super(baseUrl = baseUrl, httpClientEngine = httpClientEngine, httpClientConfig = httpClientConfig, jsonBlock = jsonSerializer) + + constructor( + baseUrl: String, + httpClient: HttpClient + ): super(baseUrl = baseUrl, httpClient = httpClient) + + /** + * Create user + * This can only be done by the logged in user. + * @param body Created user object + * @return void + */ + open suspend fun createUser(body: User): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = body + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + open suspend fun createUsersWithArrayInput(body: kotlin.collections.List): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = CreateUsersWithArrayInputRequest(body) + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithArray", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + @Serializable(CreateUsersWithArrayInputRequest.Companion::class) + private class CreateUsersWithArrayInputRequest(val value: List) { + companion object : KSerializer { + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: CreateUsersWithArrayInputRequest) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = CreateUsersWithArrayInputRequest(serializer.deserialize(decoder)) + } + } + + /** + * Creates list of users with given input array + * + * @param body List of user object + * @return void + */ + open suspend fun createUsersWithListInput(body: kotlin.collections.List): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = CreateUsersWithListInputRequest(body) + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.POST, + "/user/createWithList", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + @Serializable(CreateUsersWithListInputRequest.Companion::class) + private class CreateUsersWithListInputRequest(val value: List) { + companion object : KSerializer { + private val serializer: KSerializer> = serializer>() + override val descriptor = serializer.descriptor + override fun serialize(encoder: Encoder, obj: CreateUsersWithListInputRequest) = serializer.serialize(encoder, obj.value) + override fun deserialize(decoder: Decoder) = CreateUsersWithListInputRequest(serializer.deserialize(decoder)) + } + } + + /** + * Delete user + * This can only be done by the logged in user. + * @param username The name that needs to be deleted + * @return void + */ + open suspend fun deleteUser(username: kotlin.String): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.DELETE, + "/user/{username}".replace("{" + "username" + "}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Get user by user name + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return User + */ + @Suppress("UNCHECKED_CAST") + open suspend fun getUserByName(username: kotlin.String): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/{username}".replace("{" + "username" + "}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Logs user into the system + * + * @param username The user name for login + * @param password The password for login in clear text + * @return kotlin.String + */ + @Suppress("UNCHECKED_CAST") + open suspend fun loginUser(username: kotlin.String, password: kotlin.String): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + username?.apply { localVariableQuery["username"] = listOf("$username") } + password?.apply { localVariableQuery["password"] = listOf("$password") } + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/login", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Logs out current logged in user session + * + * @return void + */ + open suspend fun logoutUser(): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = + io.ktor.client.utils.EmptyContent + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.GET, + "/user/logout", + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return request( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + /** + * Updated user + * This can only be done by the logged in user. + * @param username name that need to be deleted + * @param body Updated user object + * @return void + */ + open suspend fun updateUser(username: kotlin.String, body: User): HttpResponse { + + val localVariableAuthNames = listOf() + + val localVariableBody = body + + val localVariableQuery = mutableMapOf>() + val localVariableHeaders = mutableMapOf() + + val localVariableConfig = RequestConfig( + RequestMethod.PUT, + "/user/{username}".replace("{" + "username" + "}", "$username"), + query = localVariableQuery, + headers = localVariableHeaders, + requiresAuthentication = false, + ) + + return jsonRequest( + localVariableConfig, + localVariableBody, + localVariableAuthNames + ).wrap() + } + + + +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 000000000000..8bd8b59a8f82 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,16 @@ +package org.openapitools.client.auth + +class ApiKeyAuth(private val location: String, val paramName: String) : Authentication { + var apiKey: String? = null + var apiKeyPrefix: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val key: String = apiKey ?: return + val prefix: String? = apiKeyPrefix + val value: String = if (prefix != null) "$prefix $key" else key + when (location) { + "query" -> query[paramName] = listOf(value) + "header" -> headers[paramName] = value + } + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt new file mode 100644 index 000000000000..2c5dfb4acc56 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/Authentication.kt @@ -0,0 +1,13 @@ +package org.openapitools.client.auth + +interface Authentication { + + /** + * Apply authentication settings to header and query params. + * + * @param query Query parameters. + * @param headers Header parameters. + */ + fun apply(query: MutableMap>, headers: MutableMap) + +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt new file mode 100644 index 000000000000..40276dbb985e --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBasicAuth.kt @@ -0,0 +1,17 @@ +package org.openapitools.client.auth + +import io.ktor.util.InternalAPI +import io.ktor.util.encodeBase64 + +class HttpBasicAuth : Authentication { + var username: String? = null + var password: String? = null + + @OptIn(InternalAPI::class) + override fun apply(query: MutableMap>, headers: MutableMap) { + if (username == null && password == null) return + val str = (username ?: "") + ":" + (password ?: "") + val auth = str.encodeBase64() + headers["Authorization"] = "Basic $auth" + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt new file mode 100644 index 000000000000..a6fb285af5c3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/HttpBearerAuth.kt @@ -0,0 +1,14 @@ +package org.openapitools.client.auth + +class HttpBearerAuth(private val scheme: String?) : Authentication { + var bearerToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = bearerToken ?: return + headers["Authorization"] = (if (scheme != null) upperCaseBearer(scheme)!! + " " else "") + token + } + + private fun upperCaseBearer(scheme: String): String? { + return if ("bearer".equals(scheme, ignoreCase = true)) "Bearer" else scheme + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 000000000000..0e8f30f39383 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,10 @@ +package org.openapitools.client.auth + +class OAuth : Authentication { + var accessToken: String? = null + + override fun apply(query: MutableMap>, headers: MutableMap) { + val token: String = accessToken ?: return + headers["Authorization"] = "Bearer $token" + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt new file mode 100644 index 000000000000..a4a4491eac0d --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiAbstractions.kt @@ -0,0 +1,23 @@ +package org.openapitools.client.infrastructure + +typealias MultiValueMap = MutableMap> + +fun collectionDelimiter(collectionFormat: String) = when(collectionFormat) { + "csv" -> "," + "tsv" -> "\t" + "pipe" -> "|" + "space" -> " " + else -> "" +} + +val defaultMultiValueConverter: (item: Any?) -> String = { item -> "$item" } + +fun toMultiValue(items: Array, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter) + = toMultiValue(items.asIterable(), collectionFormat, map) + +fun toMultiValue(items: Iterable, collectionFormat: String, map: (item: T) -> String = defaultMultiValueConverter): List { + return when(collectionFormat) { + "multi" -> items.map(map) + else -> listOf(items.joinToString(separator = collectionDelimiter(collectionFormat), transform = map)) + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..2e1e946ec8a3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,192 @@ +package org.openapitools.client.infrastructure + +import io.ktor.client.HttpClient +import io.ktor.client.HttpClientConfig +import io.ktor.client.engine.HttpClientEngine +import io.ktor.client.plugins.contentnegotiation.ContentNegotiation +import io.ktor.client.request.* +import io.ktor.client.request.forms.FormDataContent +import io.ktor.client.request.forms.MultiPartFormDataContent +import io.ktor.client.request.header +import io.ktor.client.request.parameter +import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType +import io.ktor.serialization.kotlinx.json.json +import io.ktor.http.* +import io.ktor.http.content.PartData +import io.ktor.http.contentType +import kotlin.Unit +import kotlinx.serialization.json.Json + +import org.openapitools.client.auth.* + +open class ApiClient( + private val baseUrl: String +) { + + private lateinit var client: HttpClient + + constructor( + baseUrl: String, + httpClientEngine: HttpClientEngine?, + httpClientConfig: ((HttpClientConfig<*>) -> Unit)? = null, + jsonBlock: Json, + ) : this(baseUrl = baseUrl) { + val clientConfig: (HttpClientConfig<*>) -> Unit by lazy { + { + it.install(ContentNegotiation) { json(jsonBlock) } + httpClientConfig?.invoke(it) + } + } + + client = httpClientEngine?.let { HttpClient(it, clientConfig) } ?: HttpClient(clientConfig) + } + + constructor( + baseUrl: String, + httpClient: HttpClient + ): this(baseUrl = baseUrl) { + this.client = httpClient + } + + private val authentications: kotlin.collections.Map by lazy { + mapOf( + "petstore_auth" to OAuth(), + "api_key" to ApiKeyAuth("header", "api_key")) + } + + companion object { + const val BASE_URL = "http://petstore.swagger.io/v2" + val JSON_DEFAULT = Json { + ignoreUnknownKeys = true + prettyPrint = true + isLenient = true + } + protected val UNSAFE_HEADERS = listOf(HttpHeaders.ContentType) + } + + /** + * Set the username for the first HTTP basic authentication. + * + * @param username Username + */ + fun setUsername(username: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.username = username + } + + /** + * Set the password for the first HTTP basic authentication. + * + * @param password Password + */ + fun setPassword(password: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBasicAuth } as HttpBasicAuth? + ?: throw Exception("No HTTP basic authentication configured") + auth.password = password + } + + /** + * Set the API key value for the first API key authentication. + * + * @param apiKey API key + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKey(apiKey: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName)} as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKey = apiKey + } + + /** + * Set the API key prefix for the first API key authentication. + * + * @param apiKeyPrefix API key prefix + * @param paramName The name of the API key parameter, or null or set the first key. + */ + fun setApiKeyPrefix(apiKeyPrefix: String, paramName: String? = null) { + val auth = authentications?.values?.firstOrNull { it is ApiKeyAuth && (paramName == null || paramName == it.paramName) } as ApiKeyAuth? + ?: throw Exception("No API key authentication configured") + auth.apiKeyPrefix = apiKeyPrefix + } + + /** + * Set the access token for the first OAuth2 authentication. + * + * @param accessToken Access token + */ + fun setAccessToken(accessToken: String) { + val auth = authentications?.values?.firstOrNull { it is OAuth } as OAuth? + ?: throw Exception("No OAuth2 authentication configured") + auth.accessToken = accessToken + } + + /** + * Set the access token for the first Bearer authentication. + * + * @param bearerToken The bearer token. + */ + fun setBearerToken(bearerToken: String) { + val auth = authentications?.values?.firstOrNull { it is HttpBearerAuth } as HttpBearerAuth? + ?: throw Exception("No Bearer authentication configured") + auth.bearerToken = bearerToken + } + + protected suspend fun multipartFormRequest(requestConfig: RequestConfig, body: kotlin.collections.List?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, MultiPartFormDataContent(body ?: listOf()), authNames) + } + + protected suspend fun urlEncodedFormRequest(requestConfig: RequestConfig, body: Parameters?, authNames: kotlin.collections.List): HttpResponse { + return request(requestConfig, FormDataContent(body ?: Parameters.Empty), authNames) + } + + protected suspend fun jsonRequest(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse = request(requestConfig, body, authNames) + + protected suspend fun request(requestConfig: RequestConfig, body: Any? = null, authNames: kotlin.collections.List): HttpResponse { + requestConfig.updateForAuth(authNames) + val headers = requestConfig.headers + + return client.request { + this.url { + this.takeFrom(URLBuilder(baseUrl)) + appendPath(requestConfig.path.trimStart('/').split('/')) + requestConfig.query.forEach { query -> + query.value.forEach { value -> + parameter(query.key, value) + } + } + } + this.method = requestConfig.method.httpMethod + headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } + if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) + this.setBody(body) + } + } + } + + private fun RequestConfig.updateForAuth(authNames: kotlin.collections.List) { + for (authName in authNames) { + val auth = authentications?.get(authName) ?: throw Exception("Authentication undefined: $authName") + auth.apply(query, headers) + } + } + + private fun URLBuilder.appendPath(components: kotlin.collections.List): URLBuilder = apply { + encodedPath = encodedPath.trimEnd('/') + components.joinToString("/", prefix = "/") { it.encodeURLQueryComponent() } + } + + private val RequestMethod.httpMethod: HttpMethod + get() = when (this) { + RequestMethod.DELETE -> HttpMethod.Delete + RequestMethod.GET -> HttpMethod.Get + RequestMethod.HEAD -> HttpMethod.Head + RequestMethod.PATCH -> HttpMethod.Patch + RequestMethod.PUT -> HttpMethod.Put + RequestMethod.POST -> HttpMethod.Post + RequestMethod.OPTIONS -> HttpMethod.Options + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt new file mode 100644 index 000000000000..b5b7054f9092 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable(Base64ByteArray.Companion::class) +class Base64ByteArray(val value: ByteArray) { + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) + override fun deserialize(decoder: Decoder) = Base64ByteArray(decoder.decodeString().decodeBase64Bytes()) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as Base64ByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "Base64ByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt new file mode 100644 index 000000000000..df72899875bd --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -0,0 +1,101 @@ +package org.openapitools.client.infrastructure + +import io.ktor.utils.io.core.* +import kotlin.experimental.and + +private val digits = "0123456789abcdef".toCharArray() +private const val BASE64_ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/" +private const val BASE64_MASK: Byte = 0x3f +private const val BASE64_PAD = '=' +private val BASE64_INVERSE_ALPHABET = IntArray(256) { BASE64_ALPHABET.indexOf(it.toChar()) } + +private fun String.toCharArray(): CharArray = CharArray(length) { get(it) } +private fun ByteArray.clearFrom(from: Int) = (from until size).forEach { this[it] = 0 } +private fun Int.toBase64(): Char = BASE64_ALPHABET[this] +private fun Byte.fromBase64(): Byte = BASE64_INVERSE_ALPHABET[toInt() and 0xff].toByte() and BASE64_MASK +internal fun ByteArray.encodeBase64(): String = buildPacket { writeFully(this@encodeBase64) }.encodeBase64() +internal fun String.decodeBase64Bytes(): ByteArray = buildPacket { writeText(dropLastWhile { it == BASE64_PAD }) }.decodeBase64Bytes().readBytes() + +/** + * Encode [bytes] as a HEX string with no spaces, newlines and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(bytes: ByteArray): String { + val result = CharArray(bytes.size * 2) + var resultIndex = 0 + val digits = digits + + for (element in bytes) { + val b = element.toInt() and 0xff + result[resultIndex++] = digits[b shr 4] + result[resultIndex++] = digits[b and 0x0f] + } + + return result.concatToString() +} + +/** + * Decode bytes from HEX string. It should be no spaces and `0x` prefixes. + * + * Taken from https://github.com/ktorio/ktor/blob/master/ktor-utils/common/src/io/ktor/util/Crypto.kt + */ +internal fun hex(s: String): ByteArray { + val result = ByteArray(s.length / 2) + for (idx in result.indices) { + val srcIdx = idx * 2 + val high = s[srcIdx].toString().toInt(16) shl 4 + val low = s[srcIdx + 1].toString().toInt(16) + result[idx] = (high or low).toByte() + } + + return result +} + +/** + * Encode [ByteReadPacket] in base64 format. + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +private fun ByteReadPacket.encodeBase64(): String = buildString { + val data = ByteArray(3) + while (remaining > 0) { + val read = readAvailable(data) + data.clearFrom(read) + + val padSize = (data.size - read) * 8 / 6 + val chunk = ((data[0].toInt() and 0xFF) shl 16) or + ((data[1].toInt() and 0xFF) shl 8) or + (data[2].toInt() and 0xFF) + + for (index in data.size downTo padSize) { + val char = (chunk shr (6 * index)) and BASE64_MASK.toInt() + append(char.toBase64()) + } + + repeat(padSize) { append(BASE64_PAD) } + } +} + +/** + * Decode [ByteReadPacket] from base64 format + * + * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt + */ +@Suppress("DEPRECATION") +private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { + val data = ByteArray(4) + + while (remaining > 0) { + val read = readAvailable(data) + + val chunk = data.foldIndexed(0) { index, result, current -> + result or (current.fromBase64().toInt() shl ((3 - index) * 6)) + } + + for (index in data.size - 2 downTo (data.size - read)) { + val origin = (chunk shr (8 * index)) and 0xff + writeByte(origin.toByte()) + } + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt new file mode 100644 index 000000000000..4285d605ea62 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/HttpResponse.kt @@ -0,0 +1,51 @@ +package org.openapitools.client.infrastructure + +import io.ktor.http.Headers +import io.ktor.http.isSuccess +import io.ktor.util.reflect.TypeInfo +import io.ktor.util.reflect.typeInfo + +open class HttpResponse(val response: io.ktor.client.statement.HttpResponse, val provider: BodyProvider) { + val status: Int = response.status.value + val success: Boolean = response.status.isSuccess() + val headers: Map> = response.headers.mapEntries() + suspend fun body(): T = provider.body(response) + suspend fun typedBody(type: TypeInfo): V = provider.typedBody(response, type) + + companion object { + private fun Headers.mapEntries(): Map> { + val result = mutableMapOf>() + entries().forEach { result[it.key] = it.value } + return result + } + } +} + +interface BodyProvider { + suspend fun body(response: io.ktor.client.statement.HttpResponse): T + suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V +} + +class TypedBodyProvider(private val type: TypeInfo) : BodyProvider { + @Suppress("UNCHECKED_CAST") + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + response.call.body(type) as T + + @Suppress("UNCHECKED_CAST") + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + response.call.body(type) as V +} + +class MappedBodyProvider(private val provider: BodyProvider, private val block: S.() -> T) : BodyProvider { + override suspend fun body(response: io.ktor.client.statement.HttpResponse): T = + block(provider.body(response)) + + override suspend fun typedBody(response: io.ktor.client.statement.HttpResponse, type: TypeInfo): V = + provider.typedBody(response, type) +} + +inline fun io.ktor.client.statement.HttpResponse.wrap(): HttpResponse = + HttpResponse(this, TypedBodyProvider(typeInfo())) + +fun HttpResponse.map(block: T.() -> V): HttpResponse = + HttpResponse(response, MappedBodyProvider(provider, block)) diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt new file mode 100644 index 000000000000..96339312ada4 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -0,0 +1,29 @@ +package org.openapitools.client.infrastructure + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +@Serializable(OctetByteArray.Companion::class) +class OctetByteArray(val value: ByteArray) { + companion object : KSerializer { + override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) + override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) + override fun deserialize(decoder: Decoder) = OctetByteArray(hex(decoder.decodeString())) + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as OctetByteArray + return value.contentEquals(other.value) + } + + override fun hashCode(): Int { + return value.contentHashCode() + } + + override fun toString(): String { + return "OctetByteArray(${hex(value)})" + } +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt new file mode 100644 index 000000000000..be00e38fbaee --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/PartConfig.kt @@ -0,0 +1,11 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given part of a multi-part request. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class PartConfig( + val headers: MutableMap = mutableMapOf(), + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt new file mode 100644 index 000000000000..6578b9381b78 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -0,0 +1,19 @@ +package org.openapitools.client.infrastructure + +/** + * Defines a config object for a given request. + * NOTE: This object doesn't include 'body' because it + * allows for caching of the constructed object + * for many request definitions. + * NOTE: Headers is a Map because rfc2616 defines + * multi-valued headers as csv-only. + */ +data class RequestConfig( + val method: RequestMethod, + val path: String, + val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), + val query: MutableMap> = mutableMapOf(), + val requiresAuthentication: Boolean, + val body: T? = null +) diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt new file mode 100644 index 000000000000..beb56f07cdde --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestMethod.kt @@ -0,0 +1,8 @@ +package org.openapitools.client.infrastructure + +/** + * Provides enumerated HTTP verbs + */ +enum class RequestMethod { + GET, DELETE, HEAD, OPTIONS, PATCH, POST, PUT +} diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 000000000000..2e16584b4e48 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,38 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * A category for a pet + * + * @param id + * @param name + */ +@Serializable + +data class Category ( + + @SerialName(value = "id") val id: kotlin.Long? = null, + + @SerialName(value = "name") val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt new file mode 100644 index 000000000000..c9c0a490824b --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -0,0 +1,41 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * Describes the result of uploading an image resource + * + * @param code + * @param type + * @param message + */ +@Serializable + +data class ModelApiResponse ( + + @SerialName(value = "code") val code: kotlin.Int? = null, + + @SerialName(value = "type") val type: kotlin.String? = null, + + @SerialName(value = "message") val message: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 000000000000..e82f1e3fd7cb --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,64 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * An order for a pets from the pet store + * + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +@Serializable + +data class Order ( + + @SerialName(value = "id") val id: kotlin.Long? = null, + + @SerialName(value = "petId") val petId: kotlin.Long? = null, + + @SerialName(value = "quantity") val quantity: kotlin.Int? = null, + + @SerialName(value = "shipDate") val shipDate: kotlinx.datetime.Instant? = null, + + /* Order Status */ + @SerialName(value = "status") val status: Order.Status? = null, + + @SerialName(value = "complete") val complete: kotlin.Boolean? = false + +) { + + /** + * Order Status + * + * Values: placed,approved,delivered + */ + @Serializable + enum class Status(val value: kotlin.String) { + @SerialName(value = "placed") placed("placed"), + @SerialName(value = "approved") approved("approved"), + @SerialName(value = "delivered") delivered("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 000000000000..a275dec03d79 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,66 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * A pet for sale in the pet store + * + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ +@Serializable + +data class Pet ( + + @SerialName(value = "name") @Required val name: kotlin.String, + + @SerialName(value = "photoUrls") @Required val photoUrls: kotlin.collections.List, + + @SerialName(value = "id") val id: kotlin.Long? = null, + + @SerialName(value = "category") val category: Category? = null, + + @SerialName(value = "tags") val tags: kotlin.collections.List? = null, + + /* pet status in the store */ + @SerialName(value = "status") val status: Pet.Status? = null + +) { + + /** + * pet status in the store + * + * Values: available,pending,sold + */ + @Serializable + enum class Status(val value: kotlin.String) { + @SerialName(value = "available") available("available"), + @SerialName(value = "pending") pending("pending"), + @SerialName(value = "sold") sold("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 000000000000..1bfe2f85978c --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,38 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * A tag for a pet + * + * @param id + * @param name + */ +@Serializable + +data class Tag ( + + @SerialName(value = "id") val id: kotlin.Long? = null, + + @SerialName(value = "name") val name: kotlin.String? = null + +) + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 000000000000..29413ad2b02c --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonMain/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,57 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import kotlinx.serialization.* +import kotlinx.serialization.descriptors.* +import kotlinx.serialization.encoding.* + +/** + * A User who is purchasing from the pet store + * + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +@Serializable + +data class User ( + + @SerialName(value = "id") val id: kotlin.Long? = null, + + @SerialName(value = "username") val username: kotlin.String? = null, + + @SerialName(value = "firstName") val firstName: kotlin.String? = null, + + @SerialName(value = "lastName") val lastName: kotlin.String? = null, + + @SerialName(value = "email") val email: kotlin.String? = null, + + @SerialName(value = "password") val password: kotlin.String? = null, + + @SerialName(value = "phone") val phone: kotlin.String? = null, + + /* User Status */ + @SerialName(value = "userStatus") val userStatus: kotlin.Int? = null + +) + diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonTest/kotlin/util/Coroutine.kt new file mode 100644 index 000000000000..4db267d629cc --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/commonTest/kotlin/util/Coroutine.kt @@ -0,0 +1,27 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + + +package util + +import kotlinx.coroutines.CoroutineScope + +/** +* Block the current thread until execution of the given coroutine is complete. +* +* @param block The coroutine code. +* @return The result of the coroutine. +*/ +internal expect fun runTest(block: suspend CoroutineScope.() -> T): T diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/iosTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/iosTest/kotlin/util/Coroutine.kt new file mode 100644 index 000000000000..e967e3993cf3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/iosTest/kotlin/util/Coroutine.kt @@ -0,0 +1,22 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + + +package util + +import kotlinx.coroutines.CoroutineScope +import kotlin.coroutines.EmptyCoroutineContext + +internal actual fun runTest(block: suspend CoroutineScope.() -> T): T = kotlinx.coroutines.runBlocking(EmptyCoroutineContext, block) diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jsTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jsTest/kotlin/util/Coroutine.kt new file mode 100644 index 000000000000..23f710816de7 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jsTest/kotlin/util/Coroutine.kt @@ -0,0 +1,7 @@ +package util + +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.GlobalScope +import kotlinx.coroutines.promise + +actual fun runTest(block: suspend (scope : CoroutineScope) -> T): dynamic = GlobalScope.promise { block(this) } diff --git a/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jvmTest/kotlin/util/Coroutine.kt b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jvmTest/kotlin/util/Coroutine.kt new file mode 100644 index 000000000000..e967e3993cf3 --- /dev/null +++ b/samples/client/petstore/kotlin-multiplatform-kotlinx-datetime/src/jvmTest/kotlin/util/Coroutine.kt @@ -0,0 +1,22 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + + +package util + +import kotlinx.coroutines.CoroutineScope +import kotlin.coroutines.EmptyCoroutineContext + +internal actual fun runTest(block: suspend CoroutineScope.() -> T): T = kotlinx.coroutines.runBlocking(EmptyCoroutineContext, block) diff --git a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-multiplatform/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts index 2aaf14f1d7c2..60a1d4bbf117 100644 --- a/samples/client/petstore/kotlin-multiplatform/build.gradle.kts +++ b/samples/client/petstore/kotlin-multiplatform/build.gradle.kts @@ -1,17 +1,17 @@ import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget plugins { - kotlin("multiplatform") version "1.7.21" // kotlin_version - kotlin("plugin.serialization") version "1.7.21" // kotlin_version + kotlin("multiplatform") version "1.9.20" // kotlin_version + kotlin("plugin.serialization") version "1.9.20" // kotlin_version } group = "org.openapitools" version = "1.0.0" -val kotlin_version = "1.7.21" -val coroutines_version = "1.6.4" -val serialization_version = "1.3.3" -val ktor_version = "2.1.3" +val kotlin_version = "1.9.20" +val coroutines_version = "1.7.3" +val serialization_version = "1.6.1" +val ktor_version = "2.3.6" repositories { mavenCentral() @@ -19,14 +19,16 @@ repositories { kotlin { jvm() - ios { binaries { framework { freeCompilerArgs += "-Xobjc-generics" } } } + iosX64() + iosArm64() + iosSimulatorArm64() js { browser() nodejs() } sourceSets { - val commonMain by getting { + commonMain { dependencies { implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:$coroutines_version") implementation("org.jetbrains.kotlinx:kotlinx-serialization-core:$serialization_version") @@ -35,45 +37,43 @@ kotlin { api("io.ktor:ktor-client-serialization:$ktor_version") api("io.ktor:ktor-client-content-negotiation:$ktor_version") api("io.ktor:ktor-serialization-kotlinx-json:$ktor_version") + + api("org.jetbrains.kotlinx:kotlinx-datetime:0.4.1") } } - val commonTest by getting { + commonTest { dependencies { implementation(kotlin("test")) implementation("io.ktor:ktor-client-mock:$ktor_version") } } - val jvmMain by getting { + jvmMain { dependencies { implementation(kotlin("stdlib-jdk7")) implementation("io.ktor:ktor-client-cio-jvm:$ktor_version") } } - val jvmTest by getting { + jvmTest { dependencies { implementation(kotlin("test-junit")) } } - val iosMain by getting { + iosMain { dependencies { api("io.ktor:ktor-client-ios:$ktor_version") } } - val iosTest by getting - - val jsMain by getting { + jsMain { dependencies { api("io.ktor:ktor-client-js:$ktor_version") } } - val jsTest by getting - all { languageSettings.apply { optIn("kotlin.Experimental") diff --git a/samples/client/petstore/kotlin-multiplatform/docs/Order.md b/samples/client/petstore/kotlin-multiplatform/docs/Order.md index f4dcee6911b4..84e068bef3f8 100644 --- a/samples/client/petstore/kotlin-multiplatform/docs/Order.md +++ b/samples/client/petstore/kotlin-multiplatform/docs/Order.md @@ -7,7 +7,7 @@ Name | Type | Description | Notes **id** | **kotlin.Long** | | [optional] **petId** | **kotlin.Long** | | [optional] **quantity** | **kotlin.Int** | | [optional] -**shipDate** | **kotlin.String** | | [optional] +**shipDate** | [**kotlinx.datetime.Instant**](kotlinx.datetime.Instant.md) | | [optional] **status** | [**inline**](#Status) | Order Status | [optional] **complete** | **kotlin.Boolean** | | [optional] diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt index 28cc788be291..ec709473d75a 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/PetApi.kt @@ -160,9 +160,8 @@ open class PetApi : ApiClient { ).wrap().map { value } } - @Serializable + @Serializable(FindPetsByStatusResponse.Companion::class) private class FindPetsByStatusResponse(val value: List) { - @Serializer(FindPetsByStatusResponse::class) companion object : KSerializer { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor @@ -204,9 +203,8 @@ open class PetApi : ApiClient { ).wrap().map { value } } - @Serializable + @Serializable(FindPetsByTagsResponse.Companion::class) private class FindPetsByTagsResponse(val value: List) { - @Serializer(FindPetsByTagsResponse::class) companion object : KSerializer { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt index f6b78d2262ef..83a909297ee7 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -105,9 +105,8 @@ open class StoreApi : ApiClient { ).wrap().map { value } } - @Serializable + @Serializable(GetInventoryResponse.Companion::class) private class GetInventoryResponse(val value: Map) { - @Serializer(GetInventoryResponse::class) companion object : KSerializer { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt index 510d4c46c7bb..305871ff4ef2 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/apis/UserApi.kt @@ -104,9 +104,8 @@ open class UserApi : ApiClient { ).wrap() } - @Serializable + @Serializable(CreateUsersWithArrayInputRequest.Companion::class) private class CreateUsersWithArrayInputRequest(val value: List) { - @Serializer(CreateUsersWithArrayInputRequest::class) companion object : KSerializer { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor @@ -145,9 +144,8 @@ open class UserApi : ApiClient { ).wrap() } - @Serializable + @Serializable(CreateUsersWithListInputRequest.Companion::class) private class CreateUsersWithListInputRequest(val value: List) { - @Serializer(CreateUsersWithListInputRequest::class) companion object : KSerializer { private val serializer: KSerializer> = serializer>() override val descriptor = serializer.descriptor diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index b22722a1fb38..2e1e946ec8a3 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -10,9 +10,11 @@ import io.ktor.client.request.forms.MultiPartFormDataContent import io.ktor.client.request.header import io.ktor.client.request.parameter import io.ktor.client.statement.HttpResponse +import io.ktor.http.ContentType import io.ktor.serialization.kotlinx.json.json import io.ktor.http.* import io.ktor.http.content.PartData +import io.ktor.http.contentType import kotlin.Unit import kotlinx.serialization.json.Json @@ -158,6 +160,9 @@ open class ApiClient( this.method = requestConfig.method.httpMethod headers.filter { header -> !UNSAFE_HEADERS.contains(header.key) }.forEach { header -> this.header(header.key, header.value) } if (requestConfig.method in listOf(RequestMethod.PUT, RequestMethod.POST, RequestMethod.PATCH)) { + val contentType = (requestConfig.headers[HttpHeaders.ContentType]?.let { ContentType.parse(it) } + ?: ContentType.Application.Json) + this.contentType(contentType) this.setBody(body) } } diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt index 5aeea0894894..b5b7054f9092 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Base64ByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(Base64ByteArray.Companion::class) class Base64ByteArray(val value: ByteArray) { - @Serializer(Base64ByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("Base64ByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: Base64ByteArray) = encoder.encodeString(obj.value.encodeBase64()) diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt index af8caa633ccb..df72899875bd 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/Bytes.kt @@ -82,6 +82,7 @@ private fun ByteReadPacket.encodeBase64(): String = buildString { * * Taken from https://github.com/ktorio/ktor/blob/424d1d2cfaa3281302c60af9500f738c8c2fc846/ktor-utils/common/src/io/ktor/util/Base64.kt */ +@Suppress("DEPRECATION") private fun ByteReadPacket.decodeBase64Bytes(): Input = buildPacket { val data = ByteArray(4) diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt index d10d7c506523..96339312ada4 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/OctetByteArray.kt @@ -4,9 +4,8 @@ import kotlinx.serialization.* import kotlinx.serialization.descriptors.* import kotlinx.serialization.encoding.* -@Serializable +@Serializable(OctetByteArray.Companion::class) class OctetByteArray(val value: ByteArray) { - @Serializer(OctetByteArray::class) companion object : KSerializer { override val descriptor = PrimitiveSerialDescriptor("OctetByteArray", PrimitiveKind.STRING) override fun serialize(encoder: Encoder, obj: OctetByteArray) = encoder.encodeString(hex(obj.value)) diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt index 0af1287f0770..e82f1e3fd7cb 100644 --- a/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt +++ b/samples/client/petstore/kotlin-multiplatform/src/commonMain/kotlin/org/openapitools/client/models/Order.kt @@ -40,7 +40,7 @@ data class Order ( @SerialName(value = "quantity") val quantity: kotlin.Int? = null, - @SerialName(value = "shipDate") val shipDate: kotlin.String? = null, + @SerialName(value = "shipDate") val shipDate: kotlinx.datetime.Instant? = null, /* Order Status */ @SerialName(value = "status") val status: Order.Status? = null, diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/VERSION b/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-name-parameter-mappings/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 8e899898f013..432e132033b9 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-name-parameter-mappings/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nonpublic/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index e8f2e7bb4899..16f9ff98fa75 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter +internal val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { internal companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ internal open class ApiClient(val baseUrl: String, val client: OkHttpClient = de val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index fade6b309ab3..582d4f96174c 100644 --- a/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-nonpublic/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ internal data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5b2c0ad376a1..26f85869b681 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-nullable/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-okhttp3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 0f1fae4e64a0..631082e905f4 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -26,6 +26,7 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -217,6 +218,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code(), diff --git a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-okhttp3/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator-ignore b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/FILES b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/FILES new file mode 100644 index 000000000000..12080e58a135 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/FILES @@ -0,0 +1,33 @@ +README.md +build.gradle +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +gradle/wrapper/gradle-wrapper.jar +gradle/wrapper/gradle-wrapper.properties +gradlew +gradlew.bat +settings.gradle +src/main/kotlin/org/openapitools/client/apis/PetApi.kt +src/main/kotlin/org/openapitools/client/apis/StoreApi.kt +src/main/kotlin/org/openapitools/client/apis/UserApi.kt +src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt +src/main/kotlin/org/openapitools/client/auth/OAuth.kt +src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt +src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt +src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt +src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt +src/main/kotlin/org/openapitools/client/models/Category.kt +src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt +src/main/kotlin/org/openapitools/client/models/Order.kt +src/main/kotlin/org/openapitools/client/models/Pet.kt +src/main/kotlin/org/openapitools/client/models/Tag.kt +src/main/kotlin/org/openapitools/client/models/User.kt diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/README.md b/samples/client/petstore/kotlin-retrofit2-jackson/README.md new file mode 100644 index 000000000000..9d54fdd01c00 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/README.md @@ -0,0 +1,101 @@ +# org.openapitools.client - Kotlin client library for OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [openapi-spec](https://github.com/OAI/OpenAPI-Specification) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: +- Build package: org.openapitools.codegen.languages.KotlinClientCodegen + +## Requires + +* Kotlin 1.7.21 +* Gradle 7.5 + +## Build + +First, create the gradle wrapper script: + +``` +gradle wrapper +``` + +Then, run: + +``` +./gradlew check assemble +``` + +This runs all tests and packages the library. + +## Features/Implementation Notes + +* Supports JSON inputs/outputs, File inputs, and Form inputs. +* Supports collection formats for query parameters: csv, tsv, ssv, pipes. +* Some Kotlin and Java types are fully qualified to avoid conflicts with types defined in OpenAPI definitions. +* Implementation of ApiClient is intended to reduce method counts, specifically to benefit Android targets. + + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addpet) | **POST** pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletepet) | **DELETE** pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findpetsbystatus) | **GET** pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findpetsbytags) | **GET** pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getpetbyid) | **GET** pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatepet) | **PUT** pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatepetwithform) | **POST** pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadfile) | **POST** pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteorder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getinventory) | **GET** store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getorderbyid) | **GET** store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeorder) | **POST** store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createuser) | **POST** user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createuserswitharrayinput) | **POST** user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createuserswithlistinput) | **POST** user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteuser) | **DELETE** user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getuserbyname) | **GET** user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginuser) | **GET** user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutuser) | **GET** user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateuser) | **PUT** user/{username} | Updated user + + + +## Documentation for Models + + - [org.openapitools.client.models.Category](docs/Category.md) + - [org.openapitools.client.models.ModelApiResponse](docs/ModelApiResponse.md) + - [org.openapitools.client.models.Order](docs/Order.md) + - [org.openapitools.client.models.Pet](docs/Pet.md) + - [org.openapitools.client.models.Tag](docs/Tag.md) + - [org.openapitools.client.models.User](docs/User.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### petstore_auth + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - write:pets: modify pets in your account + - read:pets: read your pets + + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/build.gradle b/samples/client/petstore/kotlin-retrofit2-jackson/build.gradle new file mode 100644 index 000000000000..7517d03fe473 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/build.gradle @@ -0,0 +1,67 @@ +group 'org.openapitools' +version '1.0.0' + +wrapper { + gradleVersion = '7.5' + distributionUrl = "https://services.gradle.org/distributions/gradle-$gradleVersion-all.zip" +} + +buildscript { + ext.kotlin_version = '1.8.10' + ext.retrofitVersion = '2.9.0' + ext.spotless_version = "6.13.0" + + repositories { + maven { url "https://repo1.maven.org/maven2" } + } + dependencies { + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + classpath "com.diffplug.spotless:spotless-plugin-gradle:$spotless_version" + } +} + +apply plugin: 'kotlin' +apply plugin: 'maven-publish' +apply plugin: 'com.diffplug.spotless' + +repositories { + maven { url "https://repo1.maven.org/maven2" } +} + +// Use spotless plugin to automatically format code, remove unused import, etc +// To apply changes directly to the file, run `gradlew spotlessApply` +// Ref: https://github.com/diffplug/spotless/tree/main/plugin-gradle +spotless { + // comment out below to run spotless as part of the `check` task + enforceCheck false + + format 'misc', { + // define the files (e.g. '*.gradle', '*.md') to apply `misc` to + target '.gitignore' + + // define the steps to apply to those files + trimTrailingWhitespace() + indentWithSpaces() // Takes an integer argument if you don't like 4 + endWithNewline() + } + kotlin { + ktfmt() + } +} + +test { + useJUnitPlatform() +} + +dependencies { + implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version" + implementation "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version" + implementation "com.fasterxml.jackson.module:jackson-module-kotlin:2.14.3" + implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.14.3" + implementation "org.apache.oltu.oauth2:org.apache.oltu.oauth2.client:1.0.2" + implementation "com.squareup.okhttp3:logging-interceptor:4.10.0" + implementation "com.squareup.retrofit2:retrofit:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-jackson:$retrofitVersion" + implementation "com.squareup.retrofit2:converter-scalars:$retrofitVersion" + testImplementation "io.kotlintest:kotlintest-runner-junit5:3.4.2" +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/ApiResponse.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/ApiResponse.md new file mode 100644 index 000000000000..12f08d5cdef0 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/ApiResponse.md @@ -0,0 +1,12 @@ + +# ModelApiResponse + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **kotlin.Int** | | [optional] +**type** | **kotlin.String** | | [optional] +**message** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/Category.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Category.md new file mode 100644 index 000000000000..2c28a670fc79 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Category.md @@ -0,0 +1,11 @@ + +# Category + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/Order.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Order.md new file mode 100644 index 000000000000..c0c951b22d33 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Order.md @@ -0,0 +1,22 @@ + +# Order + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**petId** | **kotlin.Long** | | [optional] +**quantity** | **kotlin.Int** | | [optional] +**shipDate** | [**java.time.OffsetDateTime**](java.time.OffsetDateTime.md) | | [optional] +**status** | [**inline**](#Status) | Order Status | [optional] +**complete** | **kotlin.Boolean** | | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | placed, approved, delivered + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/Pet.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Pet.md new file mode 100644 index 000000000000..da70fca06e65 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Pet.md @@ -0,0 +1,22 @@ + +# Pet + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**name** | **kotlin.String** | | +**photoUrls** | **kotlin.collections.List<kotlin.String>** | | +**id** | **kotlin.Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**tags** | [**kotlin.collections.List<Tag>**](Tag.md) | | [optional] +**status** | [**inline**](#Status) | pet status in the store | [optional] + + + +## Enum: status +Name | Value +---- | ----- +status | available, pending, sold + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/PetApi.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/PetApi.md new file mode 100644 index 000000000000..0d9d5f4a8cb3 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/PetApi.md @@ -0,0 +1,330 @@ +# PetApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** pet/{petId}/uploadImage | uploads an image + + + +Add a new pet to the store + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val pet : Pet = // Pet | Pet object that needs to be added to the store + +val result : Pet = webService.addPet(pet) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +Deletes a pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val petId : kotlin.Long = 789 // kotlin.Long | Pet id to delete +val apiKey : kotlin.String = apiKey_example // kotlin.String | + +webService.deletePet(petId, apiKey) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| Pet id to delete | + **apiKey** | **kotlin.String**| | [optional] + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val status : kotlin.collections.List = // kotlin.collections.List | Status values that need to be considered for filter + +val result : kotlin.collections.List = webService.findPetsByStatus(status) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val tags : kotlin.collections.List = // kotlin.collections.List | Tags to filter by + +val result : kotlin.collections.List = webService.findPetsByTags(tags) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**kotlin.collections.List<kotlin.String>**](kotlin.String.md)| Tags to filter by | + +### Return type + +[**kotlin.collections.List<Pet>**](Pet.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Find pet by ID + +Returns a single pet + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to return + +val result : Pet = webService.getPetById(petId) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to return | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Update an existing pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val pet : Pet = // Pet | Pet object that needs to be added to the store + +val result : Pet = webService.updatePet(pet) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json, application/xml + - **Accept**: application/xml, application/json + + +Updates a pet in the store with form data + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be updated +val name : kotlin.String = name_example // kotlin.String | Updated name of the pet +val status : kotlin.String = status_example // kotlin.String | Updated status of the pet + +webService.updatePetWithForm(petId, name, status) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet that needs to be updated | + **name** | **kotlin.String**| Updated name of the pet | [optional] + **status** | **kotlin.String**| Updated status of the pet | [optional] + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/x-www-form-urlencoded + - **Accept**: Not defined + + +uploads an image + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(PetApi::class.java) +val petId : kotlin.Long = 789 // kotlin.Long | ID of pet to update +val additionalMetadata : kotlin.String = additionalMetadata_example // kotlin.String | Additional data to pass to server +val file : java.io.File = BINARY_DATA_HERE // java.io.File | file to upload + +val result : ModelApiResponse = webService.uploadFile(petId, additionalMetadata, file) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **kotlin.Long**| ID of pet to update | + **additionalMetadata** | **kotlin.String**| Additional data to pass to server | [optional] + **file** | **java.io.File**| file to upload | [optional] + +### Return type + +[**ModelApiResponse**](ModelApiResponse.md) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: multipart/form-data + - **Accept**: application/json + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/StoreApi.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/StoreApi.md new file mode 100644 index 000000000000..591623f8993a --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/StoreApi.md @@ -0,0 +1,160 @@ +# StoreApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** store/order | Place an order for a pet + + + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(StoreApi::class.java) +val orderId : kotlin.String = orderId_example // kotlin.String | ID of the order that needs to be deleted + +webService.deleteOrder(orderId) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.String**| ID of the order that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(StoreApi::class.java) + +val result : kotlin.collections.Map = webService.getInventory() +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +**kotlin.collections.Map<kotlin.String, kotlin.Int>** + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(StoreApi::class.java) +val orderId : kotlin.Long = 789 // kotlin.Long | ID of pet that needs to be fetched + +val result : Order = webService.getOrderById(orderId) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **kotlin.Long**| ID of pet that needs to be fetched | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Place an order for a pet + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(StoreApi::class.java) +val order : Order = // Order | order placed for purchasing the pet + +val result : Order = webService.placeOrder(order) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +[**Order**](Order.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: application/xml, application/json + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/Tag.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Tag.md new file mode 100644 index 000000000000..60ce1bcdbad3 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/Tag.md @@ -0,0 +1,11 @@ + +# Tag + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**name** | **kotlin.String** | | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/User.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/User.md new file mode 100644 index 000000000000..e801729b5ed1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/User.md @@ -0,0 +1,17 @@ + +# User + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **kotlin.Long** | | [optional] +**username** | **kotlin.String** | | [optional] +**firstName** | **kotlin.String** | | [optional] +**lastName** | **kotlin.String** | | [optional] +**email** | **kotlin.String** | | [optional] +**password** | **kotlin.String** | | [optional] +**phone** | **kotlin.String** | | [optional] +**userStatus** | **kotlin.Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/docs/UserApi.md b/samples/client/petstore/kotlin-retrofit2-jackson/docs/UserApi.md new file mode 100644 index 000000000000..0d238432fd61 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/docs/UserApi.md @@ -0,0 +1,320 @@ +# UserApi + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** user/{username} | Updated user + + + +Create user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val user : User = // User | Created user object + +webService.createUser(user) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +Creates list of users with given input array + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val user : kotlin.collections.List = // kotlin.collections.List | List of user object + +webService.createUsersWithArrayInput(user) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +Creates list of users with given input array + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val user : kotlin.collections.List = // kotlin.collections.List | List of user object + +webService.createUsersWithListInput(user) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**kotlin.collections.List<User>**](User.md)| List of user object | + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + + +Delete user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val username : kotlin.String = username_example // kotlin.String | The name that needs to be deleted + +webService.deleteUser(username) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be deleted | + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +Get user by user name + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val username : kotlin.String = username_example // kotlin.String | The name that needs to be fetched. Use user1 for testing. + +val result : User = webService.getUserByName(username) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +[**User**](User.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Logs user into the system + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val username : kotlin.String = username_example // kotlin.String | The user name for login +val password : kotlin.String = password_example // kotlin.String | The password for login in clear text + +val result : kotlin.String = webService.loginUser(username, password) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| The user name for login | + **password** | **kotlin.String**| The password for login in clear text | + +### Return type + +**kotlin.String** + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/xml, application/json + + +Logs out current logged in user session + + + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) + +webService.logoutUser() +``` + +### Parameters +This endpoint does not need any parameter. + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: Not defined + + +Updated user + +This can only be done by the logged in user. + +### Example +```kotlin +// Import classes: +//import org.openapitools.client.* +//import org.openapitools.client.infrastructure.* +//import org.openapitools.client.models.* + +val apiClient = ApiClient() +val webService = apiClient.createWebservice(UserApi::class.java) +val username : kotlin.String = username_example // kotlin.String | name that need to be deleted +val user : User = // User | Updated user object + +webService.updateUser(username, user) +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **kotlin.String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + +null (empty response body) + +### Authorization + + + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.jar b/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 000000000000..c1962a79e29d Binary files /dev/null and b/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.jar differ diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.properties b/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 000000000000..8707e8b5067f --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,6 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.1.1-all.zip +networkTimeout=10000 +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/gradlew b/samples/client/petstore/kotlin-retrofit2-jackson/gradlew new file mode 100644 index 000000000000..aeb74cbb43e3 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/gradlew @@ -0,0 +1,245 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/HEAD/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +# This is normally unused +# shellcheck disable=SC2034 +APP_BASE_NAME=${0##*/} +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + # In POSIX sh, ulimit -H is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + # In POSIX sh, ulimit -n is undefined. That's why the result is checked to see if it worked. + # shellcheck disable=SC3045 + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Stop when "xargs" is not available. +if ! command -v xargs >/dev/null 2>&1 +then + die "xargs is not available" +fi + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/gradlew.bat b/samples/client/petstore/kotlin-retrofit2-jackson/gradlew.bat new file mode 100644 index 000000000000..93e3f59f135d --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/gradlew.bat @@ -0,0 +1,92 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%"=="" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%"=="" set DIRNAME=. +@rem This is normally unused +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if %ERRORLEVEL% equ 0 goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if %ERRORLEVEL% equ 0 goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +set EXIT_CODE=%ERRORLEVEL% +if %EXIT_CODE% equ 0 set EXIT_CODE=1 +if not ""=="%GRADLE_EXIT_CONSOLE%" exit %EXIT_CODE% +exit /b %EXIT_CODE% + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/settings.gradle b/samples/client/petstore/kotlin-retrofit2-jackson/settings.gradle new file mode 100644 index 000000000000..113e1aafbe57 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/settings.gradle @@ -0,0 +1,2 @@ + +rootProject.name = 'kotlin-petstore-retrofit2-jackson' diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt new file mode 100644 index 000000000000..7b1a23ec5635 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/PetApi.kt @@ -0,0 +1,137 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import com.fasterxml.jackson.annotation.JsonProperty + +import org.openapitools.client.models.ModelApiResponse +import org.openapitools.client.models.Pet + +import okhttp3.MultipartBody + +interface PetApi { + /** + * Add a new pet to the store + * + * Responses: + * - 200: successful operation + * - 405: Invalid input + * + * @param pet Pet object that needs to be added to the store + * @return [Call]<[Pet]> + */ + @POST("pet") + fun addPet(@Body pet: Pet): Call + + /** + * Deletes a pet + * + * Responses: + * - 400: Invalid pet value + * + * @param petId Pet id to delete + * @param apiKey (optional) + * @return [Call]<[Unit]> + */ + @DELETE("pet/{petId}") + fun deletePet(@Path("petId") petId: kotlin.Long, @Header("api_key") apiKey: kotlin.String? = null): Call + + + /** + * enum for parameter status + */ + enum class StatusFindPetsByStatus(val value: kotlin.String) { + @JsonProperty(value = "available") AVAILABLE("available"), + @JsonProperty(value = "pending") PENDING("pending"), + @JsonProperty(value = "sold") SOLD("sold") + } + + /** + * Finds Pets by status + * Multiple status values can be provided with comma separated strings + * Responses: + * - 200: successful operation + * - 400: Invalid status value + * + * @param status Status values that need to be considered for filter + * @return [Call]<[kotlin.collections.List]> + */ + @GET("pet/findByStatus") + fun findPetsByStatus(@Query("status") status: CSVParams): Call> + + /** + * Finds Pets by tags + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * Responses: + * - 200: successful operation + * - 400: Invalid tag value + * + * @param tags Tags to filter by + * @return [Call]<[kotlin.collections.List]> + */ + @Deprecated("This api was deprecated") + @GET("pet/findByTags") + fun findPetsByTags(@Query("tags") tags: CSVParams): Call> + + /** + * Find pet by ID + * Returns a single pet + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Pet not found + * + * @param petId ID of pet to return + * @return [Call]<[Pet]> + */ + @GET("pet/{petId}") + fun getPetById(@Path("petId") petId: kotlin.Long): Call + + /** + * Update an existing pet + * + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Pet not found + * - 405: Validation exception + * + * @param pet Pet object that needs to be added to the store + * @return [Call]<[Pet]> + */ + @PUT("pet") + fun updatePet(@Body pet: Pet): Call + + /** + * Updates a pet in the store with form data + * + * Responses: + * - 405: Invalid input + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet (optional) + * @param status Updated status of the pet (optional) + * @return [Call]<[Unit]> + */ + @FormUrlEncoded + @POST("pet/{petId}") + fun updatePetWithForm(@Path("petId") petId: kotlin.Long, @Field("name") name: kotlin.String? = null, @Field("status") status: kotlin.String? = null): Call + + /** + * uploads an image + * + * Responses: + * - 200: successful operation + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server (optional) + * @param file file to upload (optional) + * @return [Call]<[ModelApiResponse]> + */ + @Multipart + @POST("pet/{petId}/uploadImage") + fun uploadFile(@Path("petId") petId: kotlin.Long, @Part("additionalMetadata") additionalMetadata: kotlin.String? = null, @Part file: MultipartBody.Part? = null): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt new file mode 100644 index 000000000000..e86db71017c2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/StoreApi.kt @@ -0,0 +1,63 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import com.fasterxml.jackson.annotation.JsonProperty + +import org.openapitools.client.models.Order + +interface StoreApi { + /** + * Delete purchase order by ID + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * Responses: + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of the order that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("store/order/{orderId}") + fun deleteOrder(@Path("orderId") orderId: kotlin.String): Call + + /** + * Returns pet inventories by status + * Returns a map of status codes to quantities + * Responses: + * - 200: successful operation + * + * @return [Call]<[kotlin.collections.Map]> + */ + @GET("store/inventory") + fun getInventory(): Call> + + /** + * Find purchase order by ID + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * Responses: + * - 200: successful operation + * - 400: Invalid ID supplied + * - 404: Order not found + * + * @param orderId ID of pet that needs to be fetched + * @return [Call]<[Order]> + */ + @GET("store/order/{orderId}") + fun getOrderById(@Path("orderId") orderId: kotlin.Long): Call + + /** + * Place an order for a pet + * + * Responses: + * - 200: successful operation + * - 400: Invalid Order + * + * @param order order placed for purchasing the pet + * @return [Call]<[Order]> + */ + @POST("store/order") + fun placeOrder(@Body order: Order): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt new file mode 100644 index 000000000000..207644c379b9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/apis/UserApi.kt @@ -0,0 +1,114 @@ +package org.openapitools.client.apis + +import org.openapitools.client.infrastructure.CollectionFormats.* +import retrofit2.http.* +import retrofit2.Call +import okhttp3.RequestBody +import com.fasterxml.jackson.annotation.JsonProperty + +import org.openapitools.client.models.User + +interface UserApi { + /** + * Create user + * This can only be done by the logged in user. + * Responses: + * - 0: successful operation + * + * @param user Created user object + * @return [Call]<[Unit]> + */ + @POST("user") + fun createUser(@Body user: User): Call + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param user List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithArray") + fun createUsersWithArrayInput(@Body user: kotlin.collections.List): Call + + /** + * Creates list of users with given input array + * + * Responses: + * - 0: successful operation + * + * @param user List of user object + * @return [Call]<[Unit]> + */ + @POST("user/createWithList") + fun createUsersWithListInput(@Body user: kotlin.collections.List): Call + + /** + * Delete user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be deleted + * @return [Call]<[Unit]> + */ + @DELETE("user/{username}") + fun deleteUser(@Path("username") username: kotlin.String): Call + + /** + * Get user by user name + * + * Responses: + * - 200: successful operation + * - 400: Invalid username supplied + * - 404: User not found + * + * @param username The name that needs to be fetched. Use user1 for testing. + * @return [Call]<[User]> + */ + @GET("user/{username}") + fun getUserByName(@Path("username") username: kotlin.String): Call + + /** + * Logs user into the system + * + * Responses: + * - 200: successful operation + * - 400: Invalid username/password supplied + * + * @param username The user name for login + * @param password The password for login in clear text + * @return [Call]<[kotlin.String]> + */ + @GET("user/login") + fun loginUser(@Query("username") username: kotlin.String, @Query("password") password: kotlin.String): Call + + /** + * Logs out current logged in user session + * + * Responses: + * - 0: successful operation + * + * @return [Call]<[Unit]> + */ + @GET("user/logout") + fun logoutUser(): Call + + /** + * Updated user + * This can only be done by the logged in user. + * Responses: + * - 400: Invalid user supplied + * - 404: User not found + * + * @param username name that need to be deleted + * @param user Updated user object + * @return [Call]<[Unit]> + */ + @PUT("user/{username}") + fun updateUser(@Path("username") username: kotlin.String, @Body user: User): Call + +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt new file mode 100644 index 000000000000..ddb369be5f8f --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/ApiKeyAuth.kt @@ -0,0 +1,50 @@ +package org.openapitools.client.auth + +import java.io.IOException +import java.net.URI +import java.net.URISyntaxException + +import okhttp3.Interceptor +import okhttp3.Response + +class ApiKeyAuth( + private val location: String = "", + private val paramName: String = "", + private var apiKey: String = "" +) : Interceptor { + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + var request = chain.request() + + if ("query" == location) { + var newQuery = request.url.toUri().query + val paramValue = "$paramName=$apiKey" + if (newQuery == null) { + newQuery = paramValue + } else { + newQuery += "&$paramValue" + } + + val newUri: URI + try { + val oldUri = request.url.toUri() + newUri = URI(oldUri.scheme, oldUri.authority, + oldUri.path, newQuery, oldUri.fragment) + } catch (e: URISyntaxException) { + throw IOException(e) + } + + request = request.newBuilder().url(newUri.toURL()).build() + } else if ("header" == location) { + request = request.newBuilder() + .addHeader(paramName, apiKey) + .build() + } else if ("cookie" == location) { + request = request.newBuilder() + .addHeader("Cookie", "$paramName=$apiKey") + .build() + } + return chain.proceed(request) + } +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuth.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuth.kt new file mode 100644 index 000000000000..69582551f376 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuth.kt @@ -0,0 +1,151 @@ +package org.openapitools.client.auth + +import java.net.HttpURLConnection.HTTP_UNAUTHORIZED +import java.net.HttpURLConnection.HTTP_FORBIDDEN + +import java.io.IOException + +import org.apache.oltu.oauth2.client.OAuthClient +import org.apache.oltu.oauth2.client.request.OAuthBearerClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException +import org.apache.oltu.oauth2.common.message.types.GrantType +import org.apache.oltu.oauth2.common.token.BasicOAuthToken + +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import okhttp3.Response + +class OAuth( + client: OkHttpClient, + var tokenRequestBuilder: TokenRequestBuilder +) : Interceptor { + + interface AccessTokenListener { + fun notify(token: BasicOAuthToken) + } + + private var oauthClient: OAuthClient = OAuthClient(OAuthOkHttpClient(client)) + + @Volatile + private var accessToken: String? = null + var authenticationRequestBuilder: AuthenticationRequestBuilder? = null + private var accessTokenListener: AccessTokenListener? = null + + constructor( + requestBuilder: TokenRequestBuilder + ) : this( + OkHttpClient(), + requestBuilder + ) + + constructor( + flow: OAuthFlow, + authorizationUrl: String, + tokenUrl: String, + scopes: String + ) : this( + OAuthClientRequest.tokenLocation(tokenUrl).setScope(scopes) + ) { + setFlow(flow) + authenticationRequestBuilder = OAuthClientRequest.authorizationLocation(authorizationUrl) + } + + fun setFlow(flow: OAuthFlow) { + when (flow) { + OAuthFlow.accessCode, OAuthFlow.implicit -> + tokenRequestBuilder.setGrantType(GrantType.AUTHORIZATION_CODE) + OAuthFlow.password -> + tokenRequestBuilder.setGrantType(GrantType.PASSWORD) + OAuthFlow.application -> + tokenRequestBuilder.setGrantType(GrantType.CLIENT_CREDENTIALS) + } + } + + @Throws(IOException::class) + override fun intercept(chain: Interceptor.Chain): Response { + return retryingIntercept(chain, true) + } + + @Throws(IOException::class) + private fun retryingIntercept(chain: Interceptor.Chain, updateTokenAndRetryOnAuthorizationFailure: Boolean): Response { + var request = chain.request() + + // If the request already have an authorization (eg. Basic auth), do nothing + if (request.header("Authorization") != null) { + return chain.proceed(request) + } + + // If first time, get the token + val oAuthRequest: OAuthClientRequest + if (accessToken == null) { + updateAccessToken(null) + } + + if (accessToken != null) { + // Build the request + val rb = request.newBuilder() + + val requestAccessToken = accessToken + try { + oAuthRequest = OAuthBearerClientRequest(request.url.toString()) + .setAccessToken(requestAccessToken) + .buildHeaderMessage() + } catch (e: OAuthSystemException) { + throw IOException(e) + } + + oAuthRequest.headers.entries.forEach { header -> + rb.addHeader(header.key, header.value) + } + rb.url(oAuthRequest.locationUri) + + //Execute the request + val response = chain.proceed(rb.build()) + + // 401/403 most likely indicates that access token has expired. Unless it happens two times in a row. + if ((response.code == HTTP_UNAUTHORIZED || response.code == HTTP_FORBIDDEN) && updateTokenAndRetryOnAuthorizationFailure) { + try { + if (updateAccessToken(requestAccessToken)) { + response.body?.close() + return retryingIntercept(chain, false) + } + } catch (e: Exception) { + response.body?.close() + throw e + } + } + return response + } else { + return chain.proceed(chain.request()) + } + } + + /** + * Returns true if the access token has been updated + */ + @Throws(IOException::class) + @Synchronized + fun updateAccessToken(requestAccessToken: String?): Boolean { + if (accessToken == null || accessToken.equals(requestAccessToken)) { + return try { + val accessTokenResponse = oauthClient.accessToken(this.tokenRequestBuilder.buildBodyMessage()) + if (accessTokenResponse != null && accessTokenResponse.accessToken != null) { + accessToken = accessTokenResponse.accessToken + accessTokenListener?.notify(accessTokenResponse.oAuthToken as BasicOAuthToken) + !accessToken.equals(requestAccessToken) + } else { + false + } + } catch (e: OAuthSystemException) { + throw IOException(e) + } catch (e: OAuthProblemException) { + throw IOException(e) + } + } + return true + } +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt new file mode 100644 index 000000000000..bcada9b7a6a2 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthFlow.kt @@ -0,0 +1,5 @@ +package org.openapitools.client.auth + +enum class OAuthFlow { + accessCode, implicit, password, application +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt new file mode 100644 index 000000000000..6680059d0536 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/auth/OAuthOkHttpClient.kt @@ -0,0 +1,61 @@ +package org.openapitools.client.auth + +import java.io.IOException + +import org.apache.oltu.oauth2.client.HttpClient +import org.apache.oltu.oauth2.client.request.OAuthClientRequest +import org.apache.oltu.oauth2.client.response.OAuthClientResponse +import org.apache.oltu.oauth2.client.response.OAuthClientResponseFactory +import org.apache.oltu.oauth2.common.exception.OAuthProblemException +import org.apache.oltu.oauth2.common.exception.OAuthSystemException + +import okhttp3.OkHttpClient +import okhttp3.Request +import okhttp3.MediaType.Companion.toMediaTypeOrNull +import okhttp3.RequestBody +import okhttp3.RequestBody.Companion.toRequestBody + + +class OAuthOkHttpClient( + private var client: OkHttpClient = OkHttpClient() +) : HttpClient { + + @Throws(OAuthSystemException::class, OAuthProblemException::class) + override fun execute( + request: OAuthClientRequest, + headers: Map?, + requestMethod: String, + responseClass: Class?): T { + + var mediaType = "application/json".toMediaTypeOrNull() + val requestBuilder = Request.Builder().url(request.locationUri) + + headers?.forEach { entry -> + if (entry.key.equals("Content-Type", true)) { + mediaType = entry.value.toMediaTypeOrNull() + } else { + requestBuilder.addHeader(entry.key, entry.value) + } + } + + val body: RequestBody? = if (request.body != null) request.body.toRequestBody(mediaType) else null + requestBuilder.method(requestMethod, body) + + try { + val response = client.newCall(requestBuilder.build()).execute() + return OAuthClientResponseFactory.createCustomResponse( + response.body?.string(), + response.body?.contentType()?.toString(), + response.code, + response.headers.toMultimap(), + responseClass) + } catch (e: IOException) { + throw OAuthSystemException(e) + } + } + + override fun shutdown() { + // Nothing to do here + } + +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt new file mode 100644 index 000000000000..1a1b4fd85fa9 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -0,0 +1,222 @@ +package org.openapitools.client.infrastructure + +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.AuthenticationRequestBuilder +import org.apache.oltu.oauth2.client.request.OAuthClientRequest.TokenRequestBuilder +import org.openapitools.client.auth.OAuth +import org.openapitools.client.auth.OAuth.AccessTokenListener +import org.openapitools.client.auth.OAuthFlow +import org.openapitools.client.auth.ApiKeyAuth + +import okhttp3.Call +import okhttp3.Interceptor +import okhttp3.OkHttpClient +import retrofit2.Retrofit +import okhttp3.logging.HttpLoggingInterceptor +import retrofit2.Converter +import retrofit2.CallAdapter +import retrofit2.converter.scalars.ScalarsConverterFactory +import com.fasterxml.jackson.databind.ObjectMapper +import retrofit2.converter.jackson.JacksonConverterFactory + + +class ApiClient( + private var baseUrl: String = defaultBasePath, + private val okHttpClientBuilder: OkHttpClient.Builder? = null, + private val serializerBuilder: ObjectMapper = Serializer.jacksonObjectMapper, + private val callFactory : Call.Factory? = null, + private val callAdapterFactories: List = listOf( + ), + private val converterFactories: List = listOf( + ScalarsConverterFactory.create(), + JacksonConverterFactory.create(), + ) +) { + private val apiAuthorizations = mutableMapOf() + var logger: ((String) -> Unit)? = null + + private val retrofitBuilder: Retrofit.Builder by lazy { + Retrofit.Builder() + .baseUrl(baseUrl) + .apply { + callAdapterFactories.forEach { + addCallAdapterFactory(it) + } + } + .apply { + converterFactories.forEach { + addConverterFactory(it) + } + } + } + + private val clientBuilder: OkHttpClient.Builder by lazy { + okHttpClientBuilder ?: defaultClientBuilder + } + + private val defaultClientBuilder: OkHttpClient.Builder by lazy { + OkHttpClient() + .newBuilder() + .addInterceptor(HttpLoggingInterceptor { message -> logger?.invoke(message) } + .apply { level = HttpLoggingInterceptor.Level.BODY } + ) + } + + init { + normalizeBaseUrl() + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: ObjectMapper = Serializer.jacksonObjectMapper, + authNames: Array + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { + authNames.forEach { authName -> + val auth: Interceptor? = when (authName) { + "petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") + + "api_key" -> ApiKeyAuth("header", "api_key") + + else -> throw RuntimeException("auth name $authName not found in available auth names") + } + if (auth != null) { + addAuthorization(authName, auth) + } + } + } + + constructor( + baseUrl: String = defaultBasePath, + okHttpClientBuilder: OkHttpClient.Builder? = null, + serializerBuilder: ObjectMapper = Serializer.jacksonObjectMapper, + authName: String, + clientId: String, + secret: String, + username: String, + password: String + ) : this(baseUrl, okHttpClientBuilder, serializerBuilder, arrayOf(authName)) { + getTokenEndPoint() + ?.setClientId(clientId) + ?.setClientSecret(secret) + ?.setUsername(username) + ?.setPassword(password) + } + + /** + * Helper method to configure the token endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Token request builder + */ + fun getTokenEndPoint(): TokenRequestBuilder? { + var result: TokenRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = tokenRequestBuilder + } + return result + } + + /** + * Helper method to configure authorization endpoint of the first oauth found in the apiAuthorizations (there should be only one) + * @return Authentication request builder + */ + fun getAuthorizationEndPoint(): AuthenticationRequestBuilder? { + var result: AuthenticationRequestBuilder? = null + apiAuthorizations.values.runOnFirst { + result = authenticationRequestBuilder + } + return result + } + + /** + * Helper method to pre-set the oauth access token of the first oauth found in the apiAuthorizations (there should be only one) + * @param accessToken Access token + * @return ApiClient + */ + fun setAccessToken(accessToken: String): ApiClient { + apiAuthorizations.values.runOnFirst { + setAccessToken(accessToken) + } + return this + } + + /** + * Helper method to configure the oauth accessCode/implicit flow parameters + * @param clientId Client ID + * @param clientSecret Client secret + * @param redirectURI Redirect URI + * @return ApiClient + */ + fun configureAuthorizationFlow(clientId: String, clientSecret: String, redirectURI: String): ApiClient { + apiAuthorizations.values.runOnFirst { + tokenRequestBuilder + .setClientId(clientId) + .setClientSecret(clientSecret) + .setRedirectURI(redirectURI) + authenticationRequestBuilder + ?.setClientId(clientId) + ?.setRedirectURI(redirectURI) + } + return this + } + + /** + * Configures a listener which is notified when a new access token is received. + * @param accessTokenListener Access token listener + * @return ApiClient + */ + fun registerAccessTokenListener(accessTokenListener: AccessTokenListener): ApiClient { + apiAuthorizations.values.runOnFirst { + registerAccessTokenListener(accessTokenListener) + } + return this + } + + /** + * Adds an authorization to be used by the client + * @param authName Authentication name + * @param authorization Authorization interceptor + * @return ApiClient + */ + fun addAuthorization(authName: String, authorization: Interceptor): ApiClient { + if (apiAuthorizations.containsKey(authName)) { + throw RuntimeException("auth name $authName already in api authorizations") + } + apiAuthorizations[authName] = authorization + clientBuilder.addInterceptor(authorization) + return this + } + + fun setLogger(logger: (String) -> Unit): ApiClient { + this.logger = logger + return this + } + + fun createService(serviceClass: Class): S { + val usedCallFactory = this.callFactory ?: clientBuilder.build() + return retrofitBuilder.callFactory(usedCallFactory).build().create(serviceClass) + } + + private fun normalizeBaseUrl() { + if (!baseUrl.endsWith("/")) { + baseUrl += "/" + } + } + + private inline fun Iterable.runOnFirst(callback: U.() -> Unit) { + for (element in this) { + if (element is U) { + callback.invoke(element) + break + } + } + } + + companion object { + @JvmStatic + protected val baseUrlKey = "org.openapitools.client.baseUrl" + + @JvmStatic + val defaultBasePath: String by lazy { + System.getProperties().getProperty(baseUrlKey, "http://petstore.swagger.io/v2") + } + } +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt new file mode 100644 index 000000000000..7f404da69ea0 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/CollectionFormats.kt @@ -0,0 +1,56 @@ +package org.openapitools.client.infrastructure + +class CollectionFormats { + + open class CSVParams { + + var params: List + + constructor(params: List) { + this.params = params + } + + constructor(vararg params: String) { + this.params = listOf(*params) + } + + override fun toString(): String { + return params.joinToString(",") + } + } + + open class SSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString(" ") + } + } + + class TSVParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("\t") + } + } + + class PIPESParams : CSVParams { + + constructor(params: List) : super(params) + + constructor(vararg params: String) : super(*params) + + override fun toString(): String { + return params.joinToString("|") + } + } + + class SPACEParams : SSVParams() +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt new file mode 100644 index 000000000000..0f121a95f5be --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/ResponseExt.kt @@ -0,0 +1,4 @@ +package org.openapitools.client.infrastructure + +import retrofit2.Response + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt new file mode 100644 index 000000000000..ece5c413e124 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/infrastructure/Serializer.kt @@ -0,0 +1,14 @@ +package org.openapitools.client.infrastructure + +import com.fasterxml.jackson.databind.ObjectMapper +import com.fasterxml.jackson.databind.SerializationFeature +import com.fasterxml.jackson.annotation.JsonInclude +import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper + +object Serializer { + @JvmStatic + val jacksonObjectMapper: ObjectMapper = jacksonObjectMapper() + .findAndRegisterModules() + .setSerializationInclusion(JsonInclude.Include.NON_ABSENT) + .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false) +} diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt new file mode 100644 index 000000000000..2694931cfe77 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Category.kt @@ -0,0 +1,44 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * A category for a pet + * + * @param id + * @param name + */ + + +data class Category ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("name") + val name: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt new file mode 100644 index 000000000000..1e466ac13e05 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/ModelApiResponse.kt @@ -0,0 +1,48 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * Describes the result of uploading an image resource + * + * @param code + * @param type + * @param message + */ + + +data class ModelApiResponse ( + + @field:JsonProperty("code") + val code: kotlin.Int? = null, + + @field:JsonProperty("type") + val type: kotlin.String? = null, + + @field:JsonProperty("message") + val message: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt new file mode 100644 index 000000000000..5a0e580f52a0 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Order.kt @@ -0,0 +1,71 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * An order for a pets from the pet store + * + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ + + +data class Order ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("petId") + val petId: kotlin.Long? = null, + + @field:JsonProperty("quantity") + val quantity: kotlin.Int? = null, + + @field:JsonProperty("shipDate") + val shipDate: java.time.OffsetDateTime? = null, + + /* Order Status */ + @field:JsonProperty("status") + val status: Order.Status? = null, + + @field:JsonProperty("complete") + val complete: kotlin.Boolean? = false + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * Order Status + * + * Values: PLACED,APPROVED,DELIVERED + */ + enum class Status(val value: kotlin.String) { + @JsonProperty(value = "placed") PLACED("placed"), + @JsonProperty(value = "approved") APPROVED("approved"), + @JsonProperty(value = "delivered") DELIVERED("delivered"); + } +} + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt new file mode 100644 index 000000000000..9f765699f1a1 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Pet.kt @@ -0,0 +1,74 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + +import org.openapitools.client.models.Category +import org.openapitools.client.models.Tag + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * A pet for sale in the pet store + * + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ + + +data class Pet ( + + @field:JsonProperty("name") + val name: kotlin.String, + + @field:JsonProperty("photoUrls") + val photoUrls: kotlin.collections.List, + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("category") + val category: Category? = null, + + @field:JsonProperty("tags") + val tags: kotlin.collections.List? = null, + + /* pet status in the store */ + @field:JsonProperty("status") + @Deprecated(message = "This property is deprecated.") + val status: Pet.Status? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + + /** + * pet status in the store + * + * Values: AVAILABLE,PENDING,SOLD + */ + enum class Status(val value: kotlin.String) { + @JsonProperty(value = "available") AVAILABLE("available"), + @JsonProperty(value = "pending") PENDING("pending"), + @JsonProperty(value = "sold") SOLD("sold"); + } +} + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt new file mode 100644 index 000000000000..edc30f52ae60 --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/Tag.kt @@ -0,0 +1,44 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * A tag for a pet + * + * @param id + * @param name + */ + + +data class Tag ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("name") + val name: kotlin.String? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/User.kt b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/User.kt new file mode 100644 index 000000000000..c0f8ad5788ed --- /dev/null +++ b/samples/client/petstore/kotlin-retrofit2-jackson/src/main/kotlin/org/openapitools/client/models/User.kt @@ -0,0 +1,69 @@ +/** + * + * Please note: + * This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * Do not edit this file manually. + * + */ + +@file:Suppress( + "ArrayInDataClass", + "EnumEntryName", + "RemoveRedundantQualifierName", + "UnusedImport" +) + +package org.openapitools.client.models + + +import com.fasterxml.jackson.annotation.JsonProperty +import java.io.Serializable + +/** + * A User who is purchasing from the pet store + * + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ + + +data class User ( + + @field:JsonProperty("id") + val id: kotlin.Long? = null, + + @field:JsonProperty("username") + val username: kotlin.String? = null, + + @field:JsonProperty("firstName") + val firstName: kotlin.String? = null, + + @field:JsonProperty("lastName") + val lastName: kotlin.String? = null, + + @field:JsonProperty("email") + val email: kotlin.String? = null, + + @field:JsonProperty("password") + val password: kotlin.String? = null, + + @field:JsonProperty("phone") + val phone: kotlin.String? = null, + + /* User Status */ + @field:JsonProperty("userStatus") + val userStatus: kotlin.Int? = null + +) : Serializable { + companion object { + private const val serialVersionUID: Long = 123 + } + +} + diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 884b2e66c281..d2a8cf9ce38a 100644 --- a/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-kotlinx_serialization/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -72,7 +72,7 @@ class ApiClient( authNames: Array ) : this(baseUrl, okHttpClientBuilder) { authNames.forEach { authName -> - val auth = when (authName) { + val auth: Interceptor? = when (authName) { "petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") "api_key" -> ApiKeyAuth("header", "api_key") diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2-rx3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 3c1dfd67345d..9dfc8903789a 100644 --- a/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2-rx3/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -74,7 +74,7 @@ class ApiClient( authNames: Array ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { authNames.forEach { authName -> - val auth = when (authName) { + val auth: Interceptor? = when (authName) { "petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") "api_key" -> ApiKeyAuth("header", "api_key") diff --git a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-retrofit2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 0d0605bbb602..e41d6a99f53e 100644 --- a/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-retrofit2/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -72,7 +72,7 @@ class ApiClient( authNames: Array ) : this(baseUrl, okHttpClientBuilder, serializerBuilder) { authNames.forEach { authName -> - val auth = when (authName) { + val auth: Interceptor? = when (authName) { "petstore_auth" -> OAuth(OAuthFlow.implicit, "http://petstore.swagger.io/api/oauth/dialog", "", "write:pets, read:pets") "api_key" -> ApiKeyAuth("header", "api_key") diff --git a/samples/client/petstore/kotlin-spring-cloud/.openapi-generator/VERSION b/samples/client/petstore/kotlin-spring-cloud/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-spring-cloud/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-spring-cloud/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/PetApi.kt index 041070035f28..23ebac764f2e 100644 --- a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/PetApi.kt +++ b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/StoreApi.kt index a40bc742e05b..cc4198b8a63d 100644 --- a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/StoreApi.kt +++ b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/UserApi.kt index 53b260d309dc..12b33d2a8cf8 100644 --- a/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/UserApi.kt +++ b/samples/client/petstore/kotlin-spring-cloud/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-string/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-string/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5b2c0ad376a1..26f85869b681 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-string/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-threetenbp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 7a9960d7e1f4..240690330d9a 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import org.threeten.bp.OffsetDateTime import org.threeten.bp.OffsetTime import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-threetenbp/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin-uppercase-enum/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 00e451fa20e7..e70bb9749554 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -30,6 +29,8 @@ import java.util.Locale import kotlinx.serialization.decodeFromString import kotlinx.serialization.encodeToString + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -200,6 +201,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin-uppercase-enum/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/kotlin/.openapi-generator/VERSION b/samples/client/petstore/kotlin/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/kotlin/.openapi-generator/VERSION +++ b/samples/client/petstore/kotlin/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt index 5b2c0ad376a1..26f85869b681 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/ApiClient.kt @@ -15,7 +15,6 @@ import okhttp3.MultipartBody import okhttp3.Call import okhttp3.Callback import okhttp3.Response -import okhttp3.internal.EMPTY_REQUEST import java.io.BufferedWriter import java.io.File import java.io.FileWriter @@ -29,6 +28,8 @@ import java.time.OffsetTime import java.util.Locale import com.squareup.moshi.adapter + val EMPTY_REQUEST: RequestBody = ByteArray(0).toRequestBody() + open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClient) { companion object { protected const val ContentType = "Content-Type" @@ -219,6 +220,7 @@ open class ApiClient(val baseUrl: String, val client: OkHttpClient = defaultClie val accept = response.header(ContentType)?.substringBefore(";")?.lowercase(Locale.US) // TODO: handle specific mapping types. e.g. Map> + @Suppress("UNNECESSARY_SAFE_CALL") return when { response.isRedirect -> Redirection( response.code, diff --git a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt index c3518a2d173c..6578b9381b78 100644 --- a/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt +++ b/samples/client/petstore/kotlin/src/main/kotlin/org/openapitools/client/infrastructure/RequestConfig.kt @@ -12,6 +12,7 @@ data class RequestConfig( val method: RequestMethod, val path: String, val headers: MutableMap = mutableMapOf(), + val params: MutableMap = mutableMapOf(), val query: MutableMap> = mutableMapOf(), val requiresAuthentication: Boolean, val body: T? = null diff --git a/samples/client/petstore/lua/.openapi-generator/VERSION b/samples/client/petstore/lua/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/lua/.openapi-generator/VERSION +++ b/samples/client/petstore/lua/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/n4js/.openapi-generator/VERSION b/samples/client/petstore/n4js/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/n4js/.openapi-generator/VERSION +++ b/samples/client/petstore/n4js/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/nim/.openapi-generator/VERSION b/samples/client/petstore/nim/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/nim/.openapi-generator/VERSION +++ b/samples/client/petstore/nim/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/objc/core-data/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/core-data/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m index d65b091f2e3c..5f9306219edd 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Core/SWGQueryParamCollection.m @@ -10,9 +10,9 @@ - (id)initWithValuesAndFormat:(NSArray *)values self = [super init]; if (self) { - _values = values; - _format = format; - } + _values = values; + _format = format; + } return self; } diff --git a/samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion b/samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion index c38112b62d2c..3a67e4c5a2a2 100644 --- a/samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion +++ b/samples/client/petstore/objc/core-data/SwaggerClient/Model/SWGModel.xcdatamodeld/.xccurrentversion @@ -2,7 +2,7 @@ - _XCCurrentVersionName - SWGModel.xcdatamodel + _XCCurrentVersionName + SWGModel.xcdatamodel diff --git a/samples/client/petstore/objc/default/.openapi-generator/VERSION b/samples/client/petstore/objc/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/objc/default/.openapi-generator/VERSION +++ b/samples/client/petstore/objc/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m index d65b091f2e3c..5f9306219edd 100644 --- a/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m +++ b/samples/client/petstore/objc/default/SwaggerClient/Core/SWGQueryParamCollection.m @@ -10,9 +10,9 @@ - (id)initWithValuesAndFormat:(NSArray *)values self = [super init]; if (self) { - _values = values; - _format = format; - } + _values = values; + _format = format; + } return self; } diff --git a/samples/client/petstore/perl/.openapi-generator/VERSION b/samples/client/petstore/perl/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/perl/.openapi-generator/VERSION +++ b/samples/client/petstore/perl/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/perl/README.md b/samples/client/petstore/perl/README.md index 6658f7e94699..414d9bfa2bb1 100644 --- a/samples/client/petstore/perl/README.md +++ b/samples/client/petstore/perl/README.md @@ -398,6 +398,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/perl/docs/FakeApi.md b/samples/client/petstore/perl/docs/FakeApi.md index fb3661a71a4e..41591b813c3a 100644 --- a/samples/client/petstore/perl/docs/FakeApi.md +++ b/samples/client/petstore/perl/docs/FakeApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | @@ -392,6 +393,51 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_additional_properties_reference** +> test_additional_properties_reference(request_body => $request_body) + +test referenced additionalProperties + + + +### Example +```perl +use Data::Dumper; +use WWW::OpenAPIClient::FakeApi; +my $api_instance = WWW::OpenAPIClient::FakeApi->new( +); + +my $request_body = WWW::OpenAPIClient::Object::HASH[string,AnyType]->new(); # HASH[string,AnyType] | request body + +eval { + $api_instance->test_additional_properties_reference(request_body => $request_body); +}; +if ($@) { + warn "Exception when calling FakeApi->test_additional_properties_reference: $@\n"; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**HASH[string,AnyType]**](AnyType.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_binary** > test_body_with_binary(body => $body) diff --git a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm index 376b9fdd2c51..1353b6f5b5a5 100644 --- a/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm +++ b/samples/client/petstore/perl/lib/WWW/OpenAPIClient/FakeApi.pm @@ -534,6 +534,67 @@ sub fake_property_enum_integer_serialize { return $_response_object; } +# +# test_additional_properties_reference +# +# test referenced additionalProperties +# +# @param HASH[string,AnyType] $request_body request body (required) +{ + my $params = { + 'request_body' => { + data_type => 'HASH[string,AnyType]', + description => 'request body', + required => '1', + }, + }; + __PACKAGE__->method_documentation->{ 'test_additional_properties_reference' } = { + summary => 'test referenced additionalProperties', + params => $params, + returns => undef, + }; +} +# @return void +# +sub test_additional_properties_reference { + my ($self, %args) = @_; + + # verify the required parameter 'request_body' is set + unless (exists $args{'request_body'}) { + croak("Missing the required parameter 'request_body' when calling test_additional_properties_reference"); + } + + # parse inputs + my $_resource_path = '/fake/additionalProperties-reference'; + + my $_method = 'POST'; + my $query_params = {}; + my $header_params = {}; + my $form_params = {}; + + # 'Accept' and 'Content-Type' header + my $_header_accept = $self->{api_client}->select_header_accept(); + if ($_header_accept) { + $header_params->{'Accept'} = $_header_accept; + } + $header_params->{'Content-Type'} = $self->{api_client}->select_header_content_type('application/json'); + + my $_body_data; + # body params + if ( exists $args{'request_body'}) { + $_body_data = $args{'request_body'}; + } + + # authentication setting, if any + my $auth_settings = [qw()]; + + # make the API Call + $self->{api_client}->call_api($_resource_path, $_method, + $query_params, $form_params, + $header_params, $_body_data, $auth_settings); + return; +} + # # test_body_with_binary # diff --git a/samples/client/petstore/php-dt-modern/.openapi-generator/VERSION b/samples/client/petstore/php-dt-modern/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/php-dt-modern/.openapi-generator/VERSION +++ b/samples/client/petstore/php-dt-modern/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php-dt/.openapi-generator/VERSION b/samples/client/petstore/php-dt/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/php-dt/.openapi-generator/VERSION +++ b/samples/client/petstore/php-dt/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/VERSION b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/VERSION +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md b/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md index 9fd66c9b427d..1f0bcb99bbb5 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/README.md @@ -81,6 +81,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/Api/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/Api/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/Api/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](docs/Api/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/Api/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/Api/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/Api/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Api/FakeApi.md index 3ff1c1b89d0e..48800159f242 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/docs/Api/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to http://petstore.swagger.io:80/v2, except if the operati | [**fakeOuterNumberSerialize()**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | +| [**testAdditionalPropertiesReference()**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -469,6 +470,61 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testAdditionalPropertiesReference()` + +```php +testAdditionalPropertiesReference($request_body) +``` + +test referenced additionalProperties + + + +### Example + +```php + | request body + +try { + $apiInstance->testAdditionalPropertiesReference($request_body); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testAdditionalPropertiesReference: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **request_body** | [**array**](../Model/mixed.md)| request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `application/json` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + ## `testBodyWithBinary()` ```php diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/AnotherFakeApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/AnotherFakeApi.php index fa6a21fd39b0..01d2e6cda979 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/AnotherFakeApi.php @@ -3,7 +3,6 @@ * AnotherFakeApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * AnotherFakeApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -132,7 +130,7 @@ public function getConfig(): Configuration * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -153,7 +151,7 @@ public function call123TestSpecialTags( * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -206,7 +204,19 @@ public function call123TestSpecialTagsWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -223,7 +233,19 @@ public function call123TestSpecialTagsWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/DefaultApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/DefaultApi.php index bf5de9837cc1..ac0177a75488 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/DefaultApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/DefaultApi.php @@ -3,7 +3,6 @@ * DefaultApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * DefaultApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -129,7 +127,7 @@ public function getConfig(): Configuration * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\FooGetDefaultResponse */ @@ -146,7 +144,7 @@ public function fooGet( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\FooGetDefaultResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -198,7 +196,19 @@ public function fooGetWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\FooGetDefaultResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -215,7 +225,19 @@ public function fooGetWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeApi.php index e61306561730..5adb962d1701 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeApi.php @@ -3,7 +3,6 @@ * FakeApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * FakeApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -98,6 +96,9 @@ class FakeApi 'fakePropertyEnumIntegerSerialize' => [ 'application/json', ], + 'testAdditionalPropertiesReference' => [ + 'application/json', + ], 'testBodyWithBinary' => [ 'image/png', ], @@ -187,7 +188,7 @@ public function getConfig(): Configuration * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeBigDecimalMap'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\FakeBigDecimalMap200Response */ @@ -204,7 +205,7 @@ public function fakeBigDecimalMap( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeBigDecimalMap'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\FakeBigDecimalMap200Response, HTTP status code, HTTP response headers (array of strings) */ @@ -256,7 +257,19 @@ public function fakeBigDecimalMapWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\FakeBigDecimalMap200Response' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -273,7 +286,19 @@ public function fakeBigDecimalMapWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -454,7 +479,7 @@ public function fakeBigDecimalMapRequest( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\HealthCheckResult */ @@ -473,7 +498,7 @@ public function fakeHealthGet( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\HealthCheckResult, HTTP status code, HTTP response headers (array of strings) */ @@ -525,7 +550,19 @@ public function fakeHealthGetWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\HealthCheckResult' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -542,7 +579,19 @@ public function fakeHealthGetWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -730,7 +779,7 @@ public function fakeHealthGetRequest( * @param string|null $header_1 header parameter (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -754,7 +803,7 @@ public function fakeHttpSignatureTest( * @param string|null $header_1 header parameter (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -1004,7 +1053,7 @@ public function fakeHttpSignatureTestRequest( * @param bool|null $body Input boolean as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return bool */ @@ -1023,7 +1072,7 @@ public function fakeOuterBooleanSerialize( * @param bool|null $body Input boolean as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of bool, HTTP status code, HTTP response headers (array of strings) */ @@ -1076,7 +1125,19 @@ public function fakeOuterBooleanSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ('bool' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1093,7 +1154,19 @@ public function fakeOuterBooleanSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1287,7 +1360,7 @@ public function fakeOuterBooleanSerializeRequest( * @param \OpenAPI\Client\Model\OuterComposite|null $outer_composite Input composite as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\OuterComposite */ @@ -1306,7 +1379,7 @@ public function fakeOuterCompositeSerialize( * @param \OpenAPI\Client\Model\OuterComposite|null $outer_composite Input composite as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\OuterComposite, HTTP status code, HTTP response headers (array of strings) */ @@ -1359,7 +1432,19 @@ public function fakeOuterCompositeSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\OuterComposite' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1376,7 +1461,19 @@ public function fakeOuterCompositeSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1570,7 +1667,7 @@ public function fakeOuterCompositeSerializeRequest( * @param float|null $body Input number as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return float */ @@ -1589,7 +1686,7 @@ public function fakeOuterNumberSerialize( * @param float|null $body Input number as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of float, HTTP status code, HTTP response headers (array of strings) */ @@ -1642,7 +1739,19 @@ public function fakeOuterNumberSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ('float' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1659,7 +1768,19 @@ public function fakeOuterNumberSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1853,7 +1974,7 @@ public function fakeOuterNumberSerializeRequest( * @param string|null $body Input string as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -1872,7 +1993,7 @@ public function fakeOuterStringSerialize( * @param string|null $body Input string as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1925,7 +2046,19 @@ public function fakeOuterStringSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1942,7 +2075,19 @@ public function fakeOuterStringSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2136,7 +2281,7 @@ public function fakeOuterStringSerializeRequest( * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\OuterObjectWithEnumProperty */ @@ -2155,7 +2300,7 @@ public function fakePropertyEnumIntegerSerialize( * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\OuterObjectWithEnumProperty, HTTP status code, HTTP response headers (array of strings) */ @@ -2208,7 +2353,19 @@ public function fakePropertyEnumIntegerSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\OuterObjectWithEnumProperty' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2225,7 +2382,19 @@ public function fakePropertyEnumIntegerSerializeWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2419,13 +2588,256 @@ public function fakePropertyEnumIntegerSerializeRequest( ); } + /** + * Operation testAdditionalPropertiesReference + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return void + */ + public function testAdditionalPropertiesReference( + array $request_body, + string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0] + ): void + { + $this->testAdditionalPropertiesReferenceWithHttpInfo($request_body, $contentType); + } + + /** + * Operation testAdditionalPropertiesReferenceWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws ApiException on non-2xx response or if the response body is not in the expected format + * @throws InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testAdditionalPropertiesReferenceWithHttpInfo( + array $request_body, + string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0] + ): array + { + $request = $this->testAdditionalPropertiesReferenceRequest($request_body, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testAdditionalPropertiesReferenceAsync + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testAdditionalPropertiesReferenceAsync( + array $request_body, + string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0] + ): PromiseInterface + { + return $this->testAdditionalPropertiesReferenceAsyncWithHttpInfo($request_body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testAdditionalPropertiesReferenceAsyncWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return PromiseInterface + */ + public function testAdditionalPropertiesReferenceAsyncWithHttpInfo( + $request_body, + string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0] + ): PromiseInterface + { + $returnType = ''; + $request = $this->testAdditionalPropertiesReferenceRequest($request_body, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testAdditionalPropertiesReference' + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testAdditionalPropertiesReferenceRequest( + $request_body, + string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0] + ): Request + { + + // verify the required parameter 'request_body' is set + if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) { + throw new InvalidArgumentException( + 'Missing the required parameter $request_body when calling testAdditionalPropertiesReference' + ); + } + + + $resourcePath = '/fake/additionalProperties-reference'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($request_body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($request_body)); + } else { + $httpBody = $request_body; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'POST', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + /** * Operation testBodyWithBinary * * @param \SplFileObject $body image to upload (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -2443,7 +2855,7 @@ public function testBodyWithBinary( * @param \SplFileObject $body image to upload (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2660,7 +3072,7 @@ public function testBodyWithBinaryRequest( * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class file_schema_test_class (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -2678,7 +3090,7 @@ public function testBodyWithFileSchema( * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2896,7 +3308,7 @@ public function testBodyWithFileSchemaRequest( * @param \OpenAPI\Client\Model\User $user user (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -2916,7 +3328,7 @@ public function testBodyWithQueryParams( * @param \OpenAPI\Client\Model\User $user (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -3158,7 +3570,7 @@ public function testBodyWithQueryParamsRequest( * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -3179,7 +3591,7 @@ public function testClientModel( * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -3232,7 +3644,19 @@ public function testClientModelWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -3249,7 +3673,19 @@ public function testClientModelWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -3468,7 +3904,7 @@ public function testClientModelRequest( * @param string|null $callback None (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -3514,7 +3950,7 @@ public function testEndpointParameters( * @param string|null $callback None (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -3967,7 +4403,7 @@ public function testEndpointParametersRequest( * @param string|null $enum_form_string Form parameter enum test (string) (optional, default to '-efg') * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -4003,7 +4439,7 @@ public function testEnumParameters( * @param string|null $enum_form_string Form parameter enum test (string) (optional, default to '-efg') * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4348,7 +4784,7 @@ public function testEnumParametersRequest( * @param int|null $int64_group Integer in group parameters (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -4374,7 +4810,7 @@ public function testGroupParameters( * @param int|null $int64_group Integer in group parameters (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4680,7 +5116,7 @@ public function testGroupParametersRequest( * @param array $request_body request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -4700,7 +5136,7 @@ public function testInlineAdditionalProperties( * @param array $request_body request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4923,7 +5359,7 @@ public function testInlineAdditionalPropertiesRequest( * @param \OpenAPI\Client\Model\TestInlineFreeformAdditionalPropertiesRequest $test_inline_freeform_additional_properties_request request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineFreeformAdditionalProperties'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -4943,7 +5379,7 @@ public function testInlineFreeformAdditionalProperties( * @param \OpenAPI\Client\Model\TestInlineFreeformAdditionalPropertiesRequest $test_inline_freeform_additional_properties_request request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineFreeformAdditionalProperties'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -5167,7 +5603,7 @@ public function testInlineFreeformAdditionalPropertiesRequest( * @param string $param2 field2 (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -5189,7 +5625,7 @@ public function testJsonFormData( * @param string $param2 field2 (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -5427,7 +5863,7 @@ public function testJsonFormDataRequest( * @param \OpenAPI\Client\Model\ChildWithNullable $child_with_nullable request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testNullable'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -5447,7 +5883,7 @@ public function testNullable( * @param \OpenAPI\Client\Model\ChildWithNullable $child_with_nullable request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testNullable'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -5674,7 +6110,7 @@ public function testNullableRequest( * @param array|null $language language (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -5704,7 +6140,7 @@ public function testQueryParameterCollectionFormat( * @param array|null $language (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeClassnameTags123Api.php index 27fe906fadea..c14be21e9713 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/FakeClassnameTags123Api.php @@ -3,7 +3,6 @@ * FakeClassnameTags123Api * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * FakeClassnameTags123Api Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -132,7 +130,7 @@ public function getConfig(): Configuration * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -153,7 +151,7 @@ public function testClassname( * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -206,7 +204,19 @@ public function testClassnameWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -223,7 +233,19 @@ public function testClassnameWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/PetApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/PetApi.php index e90831e0c556..d4162016cd54 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/PetApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/PetApi.php @@ -3,7 +3,6 @@ * PetApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * PetApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -176,7 +174,7 @@ public function getConfig(): Configuration * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -216,7 +214,7 @@ public function addPet( * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -558,7 +556,7 @@ protected function getHostSettingsForaddPet(): array * @param string|null $api_key api_key (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -580,7 +578,7 @@ public function deletePet( * @param string|null $api_key (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -820,7 +818,7 @@ public function deletePetRequest( * @param string[] $status Status values that need to be considered for filter (required) (deprecated) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Pet[] */ @@ -841,7 +839,7 @@ public function findPetsByStatus( * @param string[] $status Status values that need to be considered for filter (required) (deprecated) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ @@ -894,7 +892,19 @@ public function findPetsByStatusWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -911,7 +921,19 @@ public function findPetsByStatusWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1123,7 +1145,7 @@ public function findPetsByStatusRequest( * @param string[] $tags Tags to filter by (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Pet[] * @deprecated @@ -1145,7 +1167,7 @@ public function findPetsByTags( * @param string[] $tags Tags to filter by (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @deprecated @@ -1199,7 +1221,19 @@ public function findPetsByTagsWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1216,7 +1250,19 @@ public function findPetsByTagsWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1431,7 +1477,7 @@ public function findPetsByTagsRequest( * @param int $pet_id ID of pet to return (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Pet */ @@ -1452,7 +1498,7 @@ public function getPetById( * @param int $pet_id ID of pet to return (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ @@ -1505,7 +1551,19 @@ public function getPetByIdWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1522,7 +1580,19 @@ public function getPetByIdWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1752,7 +1822,7 @@ public function getPetByIdRequest( * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -1792,7 +1862,7 @@ public function updatePet( * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2135,7 +2205,7 @@ protected function getHostSettingsForupdatePet(): array * @param string|null $status Updated status of the pet (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -2159,7 +2229,7 @@ public function updatePetWithForm( * @param string|null $status Updated status of the pet (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2413,7 +2483,7 @@ public function updatePetWithFormRequest( * @param \SplFileObject|null $file file to upload (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\ApiResponse */ @@ -2438,7 +2508,7 @@ public function uploadFile( * @param \SplFileObject|null $file file to upload (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -2493,7 +2563,19 @@ public function uploadFileWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2510,7 +2592,19 @@ public function uploadFileWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2753,7 +2847,7 @@ public function uploadFileRequest( * @param string|null $additional_metadata Additional data to pass to server (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\ApiResponse */ @@ -2778,7 +2872,7 @@ public function uploadFileWithRequiredFile( * @param string|null $additional_metadata Additional data to pass to server (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -2833,7 +2927,19 @@ public function uploadFileWithRequiredFileWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2850,7 +2956,19 @@ public function uploadFileWithRequiredFileWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/StoreApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/StoreApi.php index 7af35028e6db..c61180ce49c1 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/StoreApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/StoreApi.php @@ -3,7 +3,6 @@ * StoreApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * StoreApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -141,7 +139,7 @@ public function getConfig(): Configuration * @param string $order_id ID of the order that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -161,7 +159,7 @@ public function deleteOrder( * @param string $order_id ID of the order that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -384,7 +382,7 @@ public function deleteOrderRequest( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array */ @@ -403,7 +401,7 @@ public function getInventory( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of array, HTTP status code, HTTP response headers (array of strings) */ @@ -455,7 +453,19 @@ public function getInventoryWithHttpInfo( } else { $content = (string) $response->getBody(); if ('array' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -472,7 +482,19 @@ public function getInventoryWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -663,7 +685,7 @@ public function getInventoryRequest( * @param int $order_id ID of pet that needs to be fetched (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Order */ @@ -684,7 +706,7 @@ public function getOrderById( * @param int $order_id ID of pet that needs to be fetched (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ @@ -737,7 +759,19 @@ public function getOrderByIdWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -754,7 +788,19 @@ public function getOrderByIdWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -967,7 +1013,7 @@ public function getOrderByIdRequest( * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\Order */ @@ -988,7 +1034,7 @@ public function placeOrder( * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ @@ -1041,7 +1087,19 @@ public function placeOrderWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1058,7 +1116,19 @@ public function placeOrderWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/UserApi.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/UserApi.php index 3c8c0b357ff3..aa283f7e3957 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/UserApi.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Api/UserApi.php @@ -3,7 +3,6 @@ * UserApi * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -44,7 +43,6 @@ /** * UserApi Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -153,7 +151,7 @@ public function getConfig(): Configuration * @param \OpenAPI\Client\Model\User $user Created user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -173,7 +171,7 @@ public function createUser( * @param \OpenAPI\Client\Model\User $user Created user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -396,7 +394,7 @@ public function createUserRequest( * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -416,7 +414,7 @@ public function createUsersWithArrayInput( * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -639,7 +637,7 @@ public function createUsersWithArrayInputRequest( * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -659,7 +657,7 @@ public function createUsersWithListInput( * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -882,7 +880,7 @@ public function createUsersWithListInputRequest( * @param string $username The name that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -902,7 +900,7 @@ public function deleteUser( * @param string $username The name that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -1126,7 +1124,7 @@ public function deleteUserRequest( * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return \OpenAPI\Client\Model\User */ @@ -1147,7 +1145,7 @@ public function getUserByName( * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of \OpenAPI\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ @@ -1200,7 +1198,19 @@ public function getUserByNameWithHttpInfo( } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\User' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1217,7 +1227,19 @@ public function getUserByNameWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1425,7 +1447,7 @@ public function getUserByNameRequest( * @param string $password The password for login in clear text (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return string */ @@ -1448,7 +1470,7 @@ public function loginUser( * @param string $password The password for login in clear text (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1502,7 +1524,19 @@ public function loginUserWithHttpInfo( } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1519,7 +1553,19 @@ public function loginUserWithHttpInfo( } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1748,7 +1794,7 @@ public function loginUserRequest( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -1766,7 +1812,7 @@ public function logoutUser( * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -1969,7 +2015,7 @@ public function logoutUserRequest( * @param \OpenAPI\Client\Model\User $user Updated user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return void */ @@ -1991,7 +2037,7 @@ public function updateUser( * @param \OpenAPI\Client\Model\User $user Updated user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation * - * @throws ApiException on non-2xx response + * @throws ApiException on non-2xx response or if the response body is not in the expected format * @throws InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ApiException.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ApiException.php index 88c1b37d8c92..4e7f202af60e 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ApiException.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ApiException.php @@ -3,7 +3,6 @@ * ApiException * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -33,7 +32,6 @@ /** * ApiException Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Configuration.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Configuration.php index c7202b6bb12a..1a034c8c1c05 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Configuration.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Configuration.php @@ -3,7 +3,6 @@ * Configuration * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -32,7 +31,6 @@ /** * Configuration Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/HeaderSelector.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/HeaderSelector.php index fd1f9f042799..51e9ea3f257e 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/HeaderSelector.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/HeaderSelector.php @@ -3,7 +3,6 @@ * HeaderSelector * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -16,7 +15,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -30,7 +29,6 @@ /** * HeaderSelector Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AdditionalPropertiesClass.php index 13dc3268a5e0..30c54f344c61 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AdditionalPropertiesClass.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * AdditionalPropertiesClass Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, JsonSeri */ protected static array $openAPINullables = [ 'map_property' => false, - 'map_of_map_property' => false + 'map_of_map_property' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AllOfWithSingleRef.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AllOfWithSingleRef.php index f3704c5f302c..76bf4988f245 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AllOfWithSingleRef.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/AllOfWithSingleRef.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * AllOfWithSingleRef Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, JsonSerializabl */ protected static array $openAPINullables = [ 'username' => false, - 'single_ref_type' => false + 'single_ref_type' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Animal.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Animal.php index 4c30cdbf1d1c..4a3905617f3f 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Animal.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Animal.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Animal Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class Animal implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'class_name' => false, - 'color' => false + 'color' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ApiResponse.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ApiResponse.php index 408d7a2f9f43..143948131b79 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ApiResponse.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ApiResponse.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ApiResponse Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -83,8 +81,8 @@ class ApiResponse implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'code' => false, - 'type' => false, - 'message' => false + 'type' => false, + 'message' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfArrayOfNumberOnly.php index aec8828606e9..8df1ab8da2ef 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfArrayOfNumberOnly.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ArrayOfArrayOfNumberOnly Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfNumberOnly.php index 7e4c442de376..f7b4be924c1f 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayOfNumberOnly.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ArrayOfNumberOnly Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayTest.php index 766f7d5a64b8..ac4452d089c4 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ArrayTest.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ArrayTest Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -83,8 +81,8 @@ class ArrayTest implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'array_of_string' => false, - 'array_array_of_integer' => false, - 'array_array_of_model' => false + 'array_array_of_integer' => false, + 'array_array_of_model' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Capitalization.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Capitalization.php index 55a214417633..0651c23da321 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Capitalization.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Capitalization.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Capitalization Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -89,11 +87,11 @@ class Capitalization implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'small_camel' => false, - 'capital_camel' => false, - 'small_snake' => false, - 'capital_snake' => false, - 'sca_eth_flow_points' => false, - 'att_name' => false + 'capital_camel' => false, + 'small_snake' => false, + 'capital_snake' => false, + 'sca_eth_flow_points' => false, + 'att_name' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Cat.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Cat.php index 8994d747c3eb..a1abf51b2f09 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Cat.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Cat.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * Cat Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Category.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Category.php index fc73f177de12..7753fbf64363 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Category.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Category.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Category Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class Category implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ChildWithNullable.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ChildWithNullable.php index 735c7b17c275..b65c498cb42d 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ChildWithNullable.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ChildWithNullable.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * ChildWithNullable Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ClassModel.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ClassModel.php index 9b260e9e0660..65abf0c39302 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ClassModel.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ClassModel.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ClassModel Class Doc Comment * - * @category Class * @description Model for testing model with \"_class\" property * @package OpenAPI\Client * @author OpenAPI Generator team diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Client.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Client.php index 9a30c41345a9..b8150f4d3f94 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Client.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Client.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Client Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DeprecatedObject.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DeprecatedObject.php index 9f49c669ded9..7160f5af46f0 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DeprecatedObject.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/DeprecatedObject.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * DeprecatedObject Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Dog.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Dog.php index 8f8350c36ded..6788709322e4 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Dog.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Dog.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * Dog Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumArrays.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumArrays.php index b674fe3d44e3..e7b062ae5e34 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumArrays.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumArrays.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * EnumArrays Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class EnumArrays implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'just_symbol' => false, - 'array_enum' => false + 'array_enum' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php index f70350f9e5ee..5669a8f77c15 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumClass.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * EnumClass Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php index 85dd60ae7a0d..3b402b28b420 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/EnumTest.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * EnumTest Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -93,13 +91,13 @@ class EnumTest implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'enum_string' => false, - 'enum_string_required' => false, - 'enum_integer' => false, - 'enum_number' => false, - 'outer_enum' => true, - 'outer_enum_integer' => false, - 'outer_enum_default_value' => false, - 'outer_enum_integer_default_value' => false + 'enum_string_required' => false, + 'enum_integer' => false, + 'enum_number' => false, + 'outer_enum' => true, + 'outer_enum_integer' => false, + 'outer_enum_default_value' => false, + 'outer_enum_integer_default_value' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FakeBigDecimalMap200Response.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FakeBigDecimalMap200Response.php index 981805f9ac61..2a34eeb92b87 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FakeBigDecimalMap200Response.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FakeBigDecimalMap200Response.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * FakeBigDecimalMap200Response Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class FakeBigDecimalMap200Response implements ModelInterface, ArrayAccess, JsonS */ protected static array $openAPINullables = [ 'some_id' => false, - 'some_map' => false + 'some_map' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/File.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/File.php index 6e257b536e07..7d79b291773e 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/File.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/File.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * File Class Doc Comment * - * @category Class * @description Must be named `File` for test. * @package OpenAPI\Client * @author OpenAPI Generator team diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FileSchemaTestClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FileSchemaTestClass.php index 0757d8da48ec..6b8199220cde 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FileSchemaTestClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FileSchemaTestClass.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * FileSchemaTestClass Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class FileSchemaTestClass implements ModelInterface, ArrayAccess, JsonSerializab */ protected static array $openAPINullables = [ 'file' => false, - 'files' => false + 'files' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Foo.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Foo.php index 9caa980649d1..d0bfea189aaf 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Foo.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Foo.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Foo Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FooGetDefaultResponse.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FooGetDefaultResponse.php index 3919c5199d32..57411fe6cc00 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FooGetDefaultResponse.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FooGetDefaultResponse.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * FooGetDefaultResponse Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FormatTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FormatTest.php index b6a6aa09c4b2..714c1b2a9d71 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FormatTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/FormatTest.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * FormatTest Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -109,21 +107,21 @@ class FormatTest implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'integer' => false, - 'int32' => false, - 'int64' => false, - 'number' => false, - 'float' => false, - 'double' => false, - 'decimal' => false, - 'string' => false, - 'byte' => false, - 'binary' => false, - 'date' => false, - 'date_time' => false, - 'uuid' => false, - 'password' => false, - 'pattern_with_digits' => false, - 'pattern_with_digits_and_delimiter' => false + 'int32' => false, + 'int64' => false, + 'number' => false, + 'float' => false, + 'double' => false, + 'decimal' => false, + 'string' => false, + 'byte' => false, + 'binary' => false, + 'date' => false, + 'date_time' => false, + 'uuid' => false, + 'password' => false, + 'pattern_with_digits' => false, + 'pattern_with_digits_and_delimiter' => false ]; /** @@ -718,7 +716,7 @@ public function setString(?string $string): static throw new InvalidArgumentException('non-nullable string cannot be null'); } - if ((!preg_match("/[a-z]/i", $string))) { + if ((!preg_match("/[a-z]/i", ObjectSerializer::toString($string)))) { throw new InvalidArgumentException("invalid value for \$string when calling FormatTest., must conform to the pattern /[a-z]/i."); } @@ -919,7 +917,7 @@ public function setPatternWithDigits(?string $pattern_with_digits): static throw new InvalidArgumentException('non-nullable pattern_with_digits cannot be null'); } - if ((!preg_match("/^\\d{10}$/", $pattern_with_digits))) { + if ((!preg_match("/^\\d{10}$/", ObjectSerializer::toString($pattern_with_digits)))) { throw new InvalidArgumentException("invalid value for \$pattern_with_digits when calling FormatTest., must conform to the pattern /^\\d{10}$/."); } @@ -951,7 +949,7 @@ public function setPatternWithDigitsAndDelimiter(?string $pattern_with_digits_an throw new InvalidArgumentException('non-nullable pattern_with_digits_and_delimiter cannot be null'); } - if ((!preg_match("/^image_\\d{1,3}$/i", $pattern_with_digits_and_delimiter))) { + if ((!preg_match("/^image_\\d{1,3}$/i", ObjectSerializer::toString($pattern_with_digits_and_delimiter)))) { throw new InvalidArgumentException("invalid value for \$pattern_with_digits_and_delimiter when calling FormatTest., must conform to the pattern /^image_\\d{1,3}$/i."); } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HasOnlyReadOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HasOnlyReadOnly.php index 9f6c1c91bb10..6b47e9e10488 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HasOnlyReadOnly.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * HasOnlyReadOnly Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class HasOnlyReadOnly implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'foo' => false + 'foo' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HealthCheckResult.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HealthCheckResult.php index 1e05b18c382c..bba8be6216f0 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HealthCheckResult.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/HealthCheckResult.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * HealthCheckResult Class Doc Comment * - * @category Class * @description Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. * @package OpenAPI\Client * @author OpenAPI Generator team diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MapTest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MapTest.php index 78d2c154dd3b..1f08fcea3079 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MapTest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MapTest.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * MapTest Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -85,9 +83,9 @@ class MapTest implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'map_map_of_string' => false, - 'map_of_enum_string' => false, - 'direct_map' => false, - 'indirect_map' => false + 'map_of_enum_string' => false, + 'direct_map' => false, + 'indirect_map' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MixedPropertiesAndAdditionalPropertiesClass.php index d5d27cb6e401..7eeb03bc14c7 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * MixedPropertiesAndAdditionalPropertiesClass Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -83,8 +81,8 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ModelInterface, Arr */ protected static array $openAPINullables = [ 'uuid' => false, - 'date_time' => false, - 'map' => false + 'date_time' => false, + 'map' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Model200Response.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Model200Response.php index a92c2708f740..b43d3c751f95 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Model200Response.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Model200Response.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Model200Response Class Doc Comment * - * @category Class * @description Model for testing model name starting with number * @package OpenAPI\Client * @author OpenAPI Generator team @@ -82,7 +80,7 @@ class Model200Response implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'class' => false + 'class' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelInterface.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelInterface.php index 1a92077ed27e..8f63717ccedb 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelInterface.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelInterface.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client\Model * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelList.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelList.php index e7c8107883f5..c2facb89eea1 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelList.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelList.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ModelList Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelReturn.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelReturn.php index 580fb80d0c21..c8f3ef9dc515 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelReturn.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ModelReturn.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ModelReturn Class Doc Comment * - * @category Class * @description Model for testing reserved words * @package OpenAPI\Client * @author OpenAPI Generator team diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Name.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Name.php index 12bc2cdefae1..63487b1d21a7 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Name.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Name.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Name Class Doc Comment * - * @category Class * @description Model for testing model name same as property name * @package OpenAPI\Client * @author OpenAPI Generator team @@ -86,9 +84,9 @@ class Name implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'snake_case' => false, - 'property' => false, - '_123_number' => false + 'snake_case' => false, + 'property' => false, + '_123_number' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NullableClass.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NullableClass.php index d0c8abb21010..ae9a9ba44070 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NullableClass.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NullableClass.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * NullableClass Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -101,17 +99,17 @@ class NullableClass implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'integer_prop' => true, - 'number_prop' => true, - 'boolean_prop' => true, - 'string_prop' => true, - 'date_prop' => true, - 'datetime_prop' => true, - 'array_nullable_prop' => true, - 'array_and_items_nullable_prop' => true, - 'array_items_nullable' => false, - 'object_nullable_prop' => true, - 'object_and_items_nullable_prop' => true, - 'object_items_nullable' => false + 'number_prop' => true, + 'boolean_prop' => true, + 'string_prop' => true, + 'date_prop' => true, + 'datetime_prop' => true, + 'array_nullable_prop' => true, + 'array_and_items_nullable_prop' => true, + 'array_items_nullable' => false, + 'object_nullable_prop' => true, + 'object_and_items_nullable_prop' => true, + 'object_items_nullable' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NumberOnly.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NumberOnly.php index a0ec0b8dc545..0c099d1a1d1e 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NumberOnly.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/NumberOnly.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * NumberOnly Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ObjectWithDeprecatedFields.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ObjectWithDeprecatedFields.php index 61fba31e85fe..25de6087e8af 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ObjectWithDeprecatedFields.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ObjectWithDeprecatedFields.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ObjectWithDeprecatedFields Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -85,9 +83,9 @@ class ObjectWithDeprecatedFields implements ModelInterface, ArrayAccess, JsonSer */ protected static array $openAPINullables = [ 'uuid' => false, - 'id' => false, - 'deprecated_ref' => false, - 'bars' => false + 'id' => false, + 'deprecated_ref' => false, + 'bars' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Order.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Order.php index fc675fc9d89b..eec35d3fe68b 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Order.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Order.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Order Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -89,11 +87,11 @@ class Order implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'pet_id' => false, - 'quantity' => false, - 'ship_date' => false, - 'status' => false, - 'complete' => false + 'pet_id' => false, + 'quantity' => false, + 'ship_date' => false, + 'status' => false, + 'complete' => false ]; /** @@ -261,7 +259,7 @@ public function getModelName(): string public const STATUS_PLACED = 'placed'; public const STATUS_APPROVED = 'approved'; - public const STATUS_DELIVERED = 'delivered'; + public const STATUS_SHIPPED = 'delivered'; /** * Gets allowable values of the enum @@ -273,7 +271,7 @@ public function getStatusAllowableValues() return [ self::STATUS_PLACED, self::STATUS_APPROVED, - self::STATUS_DELIVERED, + self::STATUS_SHIPPED, ]; } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterComposite.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterComposite.php index 17f5c90b1a7e..7ec38553c6ec 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterComposite.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterComposite.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * OuterComposite Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -83,8 +81,8 @@ class OuterComposite implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'my_number' => false, - 'my_string' => false, - 'my_boolean' => false + 'my_string' => false, + 'my_boolean' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnum.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnum.php index e3ec69053d86..6242e28aee27 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnum.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnum.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * OuterEnum Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -42,7 +40,7 @@ enum OuterEnum: string case APPROVED = 'approved'; - case DELIVERED = 'delivered'; + case SHIPPED = 'delivered'; } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumDefaultValue.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumDefaultValue.php index e0df59031a3e..8c8aca1e0391 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumDefaultValue.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumDefaultValue.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * OuterEnumDefaultValue Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -42,7 +40,7 @@ enum OuterEnumDefaultValue: string case APPROVED = 'approved'; - case DELIVERED = 'delivered'; + case SHIPPED = 'delivered'; } diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumInteger.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumInteger.php index 9c574c141177..d5c4c763d518 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumInteger.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumInteger.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * OuterEnumInteger Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumIntegerDefaultValue.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumIntegerDefaultValue.php index 66c4338b09ab..3eb5d5f801c9 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumIntegerDefaultValue.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterEnumIntegerDefaultValue.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * OuterEnumIntegerDefaultValue Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterObjectWithEnumProperty.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterObjectWithEnumProperty.php index ad4499db229a..709e329f600a 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterObjectWithEnumProperty.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/OuterObjectWithEnumProperty.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * OuterObjectWithEnumProperty Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ParentWithNullable.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ParentWithNullable.php index 92632528609e..36eed43835ed 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ParentWithNullable.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ParentWithNullable.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ParentWithNullable Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class ParentWithNullable implements ModelInterface, ArrayAccess, JsonSerializabl */ protected static array $openAPINullables = [ 'type' => false, - 'nullable_property' => true + 'nullable_property' => true ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Pet.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Pet.php index 3a6c79c2a1e3..029f09bdc679 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Pet.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Pet.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Pet Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -89,11 +87,11 @@ class Pet implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'category' => false, - 'name' => false, - 'photo_urls' => false, - 'tags' => false, - 'status' => false + 'category' => false, + 'name' => false, + 'photo_urls' => false, + 'tags' => false, + 'status' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ReadOnlyFirst.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ReadOnlyFirst.php index 69452b685ac8..9ae5877d1217 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/ReadOnlyFirst.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * ReadOnlyFirst Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class ReadOnlyFirst implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'baz' => false + 'baz' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SingleRefType.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SingleRefType.php index 219f65052bd9..c4465941e174 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SingleRefType.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SingleRefType.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -31,7 +30,6 @@ /** * SingleRefType Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SpecialModelName.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SpecialModelName.php index 1f35355de149..c330a5a031d6 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SpecialModelName.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/SpecialModelName.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * SpecialModelName Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Tag.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Tag.php index a7e84e742124..847c5d7312d0 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Tag.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/Tag.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * Tag Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -81,7 +79,7 @@ class Tag implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/TestInlineFreeformAdditionalPropertiesRequest.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/TestInlineFreeformAdditionalPropertiesRequest.php index 3f0c28ec8d1c..ba57d9863e0c 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/TestInlineFreeformAdditionalPropertiesRequest.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/TestInlineFreeformAdditionalPropertiesRequest.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * TestInlineFreeformAdditionalPropertiesRequest Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/User.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/User.php index 96e8ed3a9904..b548169e2259 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/User.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/Model/User.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -37,7 +36,6 @@ /** * User Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -93,13 +91,13 @@ class User implements ModelInterface, ArrayAccess, JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'username' => false, - 'first_name' => false, - 'last_name' => false, - 'email' => false, - 'password' => false, - 'phone' => false, - 'user_status' => false + 'username' => false, + 'first_name' => false, + 'last_name' => false, + 'email' => false, + 'password' => false, + 'phone' => false, + 'user_status' => false ]; /** diff --git a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ObjectSerializer.php b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ObjectSerializer.php index 47bedf3a5417..5665456ca428 100644 --- a/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ObjectSerializer.php +++ b/samples/client/petstore/php-nextgen/OpenAPIClient-php/src/ObjectSerializer.php @@ -4,7 +4,6 @@ * * PHP version 8.1 * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -17,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * @generated Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -36,7 +35,6 @@ /** * ObjectSerializer Class Doc Comment * - * @category Class * @package OpenAPI\Client * @author OpenAPI Generator team * @link https://openapi-generator.tech @@ -428,10 +426,7 @@ public static function deserialize(mixed $data, string $class, array $httpHeader return $deserialized; } - if ($class === 'object') { - settype($data, 'array'); - return $data; - } elseif ($class === 'mixed') { + if ($class === 'mixed') { settype($data, gettype($data)); return $data; } diff --git a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION +++ b/samples/client/petstore/php/OpenAPIClient-php/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php/OpenAPIClient-php/README.md b/samples/client/petstore/php/OpenAPIClient-php/README.md index 8a10479d27a3..91218feed664 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/README.md +++ b/samples/client/petstore/php/OpenAPIClient-php/README.md @@ -83,6 +83,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterStringSerialize**](docs/Api/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/Api/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | *FakeApi* | [**getParameterNameMapping**](docs/Api/FakeApi.md#getparameternamemapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*FakeApi* | [**testAdditionalPropertiesReference**](docs/Api/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/Api/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/Api/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/Api/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md index 2b5343f2b1b6..7c84b0c17d51 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/OpenAPIClient-php/docs/Api/FakeApi.md @@ -13,6 +13,7 @@ All URIs are relative to http://petstore.swagger.io:80/v2, except if the operati | [**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | | | [**getParameterNameMapping()**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | +| [**testAdditionalPropertiesReference()**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | | | [**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | @@ -530,6 +531,61 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testAdditionalPropertiesReference()` + +```php +testAdditionalPropertiesReference($request_body) +``` + +test referenced additionalProperties + + + +### Example + +```php + | request body + +try { + $apiInstance->testAdditionalPropertiesReference($request_body); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testAdditionalPropertiesReference: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +| Name | Type | Description | Notes | +| ------------- | ------------- | ------------- | ------------- | +| **request_body** | [**array**](../Model/mixed.md)| request body | | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `application/json` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + ## `testBodyWithBinary()` ```php diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php index d93207e06b3f..e179939fc466 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/AnotherFakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -76,7 +76,7 @@ class AnotherFakeApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -130,7 +130,7 @@ public function getConfig() * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -148,7 +148,7 @@ public function call123TestSpecialTags($client, string $contentType = self::cont * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['call123TestSpecialTags'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -198,7 +198,19 @@ public function call123TestSpecialTagsWithHttpInfo($client, string $contentType } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -215,7 +227,19 @@ public function call123TestSpecialTagsWithHttpInfo($client, string $contentType } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php index e947bae0eebb..e1a173695858 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/DefaultApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -76,7 +76,7 @@ class DefaultApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -127,7 +127,7 @@ public function getConfig() * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\FooGetDefaultResponse */ @@ -142,7 +142,7 @@ public function fooGet(string $contentType = self::contentTypes['fooGet'][0]) * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fooGet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\FooGetDefaultResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -192,7 +192,19 @@ public function fooGetWithHttpInfo(string $contentType = self::contentTypes['foo } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\FooGetDefaultResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -209,7 +221,19 @@ public function fooGetWithHttpInfo(string $contentType = self::contentTypes['foo } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php index a1bb31cbe6f8..f4cf34537d80 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -99,6 +99,9 @@ class FakeApi 'getParameterNameMapping' => [ 'application/json', ], + 'testAdditionalPropertiesReference' => [ + 'application/json', + ], 'testBodyWithBinary' => [ 'image/png', ], @@ -134,7 +137,7 @@ class FakeApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -185,7 +188,7 @@ public function getConfig() * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeBigDecimalMap'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\FakeBigDecimalMap200Response */ @@ -200,7 +203,7 @@ public function fakeBigDecimalMap(string $contentType = self::contentTypes['fake * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeBigDecimalMap'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\FakeBigDecimalMap200Response, HTTP status code, HTTP response headers (array of strings) */ @@ -250,7 +253,19 @@ public function fakeBigDecimalMapWithHttpInfo(string $contentType = self::conten } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\FakeBigDecimalMap200Response' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -267,7 +282,19 @@ public function fakeBigDecimalMapWithHttpInfo(string $contentType = self::conten } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -442,7 +469,7 @@ public function fakeBigDecimalMapRequest(string $contentType = self::contentType * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\HealthCheckResult */ @@ -459,7 +486,7 @@ public function fakeHealthGet(string $contentType = self::contentTypes['fakeHeal * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHealthGet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\HealthCheckResult, HTTP status code, HTTP response headers (array of strings) */ @@ -509,7 +536,19 @@ public function fakeHealthGetWithHttpInfo(string $contentType = self::contentTyp } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\HealthCheckResult' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -526,7 +565,19 @@ public function fakeHealthGetWithHttpInfo(string $contentType = self::contentTyp } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -708,7 +759,7 @@ public function fakeHealthGetRequest(string $contentType = self::contentTypes['f * @param string $header_1 header parameter (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -727,7 +778,7 @@ public function fakeHttpSignatureTest($pet, $query_1 = null, $header_1 = null, s * @param string $header_1 header parameter (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeHttpSignatureTest'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -957,7 +1008,7 @@ public function fakeHttpSignatureTestRequest($pet, $query_1 = null, $header_1 = * @param bool $body Input boolean as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return bool */ @@ -973,7 +1024,7 @@ public function fakeOuterBooleanSerialize($body = null, string $contentType = se * @param bool $body Input boolean as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterBooleanSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of bool, HTTP status code, HTTP response headers (array of strings) */ @@ -1023,7 +1074,19 @@ public function fakeOuterBooleanSerializeWithHttpInfo($body = null, string $cont } else { $content = (string) $response->getBody(); if ('bool' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1040,7 +1103,19 @@ public function fakeOuterBooleanSerializeWithHttpInfo($body = null, string $cont } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1225,7 +1300,7 @@ public function fakeOuterBooleanSerializeRequest($body = null, string $contentTy * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\OuterComposite */ @@ -1241,7 +1316,7 @@ public function fakeOuterCompositeSerialize($outer_composite = null, string $con * @param \OpenAPI\Client\Model\OuterComposite $outer_composite Input composite as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterCompositeSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\OuterComposite, HTTP status code, HTTP response headers (array of strings) */ @@ -1291,7 +1366,19 @@ public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null, } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\OuterComposite' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1308,7 +1395,19 @@ public function fakeOuterCompositeSerializeWithHttpInfo($outer_composite = null, } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1493,7 +1592,7 @@ public function fakeOuterCompositeSerializeRequest($outer_composite = null, stri * @param float $body Input number as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return float */ @@ -1509,7 +1608,7 @@ public function fakeOuterNumberSerialize($body = null, string $contentType = sel * @param float $body Input number as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterNumberSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of float, HTTP status code, HTTP response headers (array of strings) */ @@ -1559,7 +1658,19 @@ public function fakeOuterNumberSerializeWithHttpInfo($body = null, string $conte } else { $content = (string) $response->getBody(); if ('float' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1576,7 +1687,19 @@ public function fakeOuterNumberSerializeWithHttpInfo($body = null, string $conte } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1761,7 +1884,7 @@ public function fakeOuterNumberSerializeRequest($body = null, string $contentTyp * @param string $body Input string as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return string */ @@ -1777,7 +1900,7 @@ public function fakeOuterStringSerialize($body = null, string $contentType = sel * @param string $body Input string as post body (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakeOuterStringSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1827,7 +1950,19 @@ public function fakeOuterStringSerializeWithHttpInfo($body = null, string $conte } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1844,7 +1979,19 @@ public function fakeOuterStringSerializeWithHttpInfo($body = null, string $conte } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2029,7 +2176,7 @@ public function fakeOuterStringSerializeRequest($body = null, string $contentTyp * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\OuterObjectWithEnumProperty */ @@ -2045,7 +2192,7 @@ public function fakePropertyEnumIntegerSerialize($outer_object_with_enum_propert * @param \OpenAPI\Client\Model\OuterObjectWithEnumProperty $outer_object_with_enum_property Input enum (int) as post body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['fakePropertyEnumIntegerSerialize'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\OuterObjectWithEnumProperty, HTTP status code, HTTP response headers (array of strings) */ @@ -2095,7 +2242,19 @@ public function fakePropertyEnumIntegerSerializeWithHttpInfo($outer_object_with_ } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\OuterObjectWithEnumProperty' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2112,7 +2271,19 @@ public function fakePropertyEnumIntegerSerializeWithHttpInfo($outer_object_with_ } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2309,7 +2480,7 @@ public function fakePropertyEnumIntegerSerializeRequest($outer_object_with_enum_ * @param string $http_debug_option http debug option (to test parameter naming option) (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getParameterNameMapping'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -2330,7 +2501,7 @@ public function getParameterNameMapping($underscore_type, $type, $type_with_unde * @param string $http_debug_option http debug option (to test parameter naming option) (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getParameterNameMapping'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2596,13 +2767,241 @@ public function getParameterNameMappingRequest($underscore_type, $type, $type_wi ); } + /** + * Operation testAdditionalPropertiesReference + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return void + */ + public function testAdditionalPropertiesReference($request_body, string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0]) + { + $this->testAdditionalPropertiesReferenceWithHttpInfo($request_body, $contentType); + } + + /** + * Operation testAdditionalPropertiesReferenceWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testAdditionalPropertiesReferenceWithHttpInfo($request_body, string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0]) + { + $request = $this->testAdditionalPropertiesReferenceRequest($request_body, $contentType); + + try { + $options = $this->createHttpClientOption(); + try { + $response = $this->client->send($request, $options); + } catch (RequestException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + $e->getResponse() ? $e->getResponse()->getHeaders() : null, + $e->getResponse() ? (string) $e->getResponse()->getBody() : null + ); + } catch (ConnectException $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + (int) $e->getCode(), + null, + null + ); + } + + $statusCode = $response->getStatusCode(); + + if ($statusCode < 200 || $statusCode > 299) { + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + (string) $request->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testAdditionalPropertiesReferenceAsync + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testAdditionalPropertiesReferenceAsync($request_body, string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0]) + { + return $this->testAdditionalPropertiesReferenceAsyncWithHttpInfo($request_body, $contentType) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testAdditionalPropertiesReferenceAsyncWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Promise\PromiseInterface + */ + public function testAdditionalPropertiesReferenceAsyncWithHttpInfo($request_body, string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0]) + { + $returnType = ''; + $request = $this->testAdditionalPropertiesReferenceRequest($request_body, $contentType); + + return $this->client + ->sendAsync($request, $this->createHttpClientOption()) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function ($exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $statusCode, + $response->getHeaders(), + (string) $response->getBody() + ); + } + ); + } + + /** + * Create request for operation 'testAdditionalPropertiesReference' + * + * @param array $request_body request body (required) + * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testAdditionalPropertiesReference'] to see the possible values for this operation + * + * @throws \InvalidArgumentException + * @return \GuzzleHttp\Psr7\Request + */ + public function testAdditionalPropertiesReferenceRequest($request_body, string $contentType = self::contentTypes['testAdditionalPropertiesReference'][0]) + { + + // verify the required parameter 'request_body' is set + if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $request_body when calling testAdditionalPropertiesReference' + ); + } + + + $resourcePath = '/fake/additionalProperties-reference'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = ''; + $multipart = false; + + + + + + $headers = $this->headerSelector->selectHeaders( + [], + $contentType, + $multipart + ); + + // for model (json/xml) + if (isset($request_body)) { + if (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the body + $httpBody = \GuzzleHttp\Utils::jsonEncode(ObjectSerializer::sanitizeForSerialization($request_body)); + } else { + $httpBody = $request_body; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif (stripos($headers['Content-Type'], 'application/json') !== false) { + # if Content-Type contains "application/json", json_encode the form parameters + $httpBody = \GuzzleHttp\Utils::jsonEncode($formParams); + } else { + // for HTTP post (form) + $httpBody = ObjectSerializer::buildQuery($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + $query = ObjectSerializer::buildQuery($queryParams); + return new Request( + 'POST', + $operationHost . $resourcePath . ($query ? "?{$query}" : ''), + $headers, + $httpBody + ); + } + /** * Operation testBodyWithBinary * * @param \SplFileObject $body image to upload (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -2617,7 +3016,7 @@ public function testBodyWithBinary($body, string $contentType = self::contentTyp * @param \SplFileObject $body image to upload (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithBinary'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2822,7 +3221,7 @@ public function testBodyWithBinaryRequest($body, string $contentType = self::con * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class file_schema_test_class (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -2837,7 +3236,7 @@ public function testBodyWithFileSchema($file_schema_test_class, string $contentT * @param \OpenAPI\Client\Model\FileSchemaTestClass $file_schema_test_class (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithFileSchema'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -3043,7 +3442,7 @@ public function testBodyWithFileSchemaRequest($file_schema_test_class, string $c * @param \OpenAPI\Client\Model\User $user user (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -3059,7 +3458,7 @@ public function testBodyWithQueryParams($query, $user, string $contentType = sel * @param \OpenAPI\Client\Model\User $user (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testBodyWithQueryParams'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -3285,7 +3684,7 @@ public function testBodyWithQueryParamsRequest($query, $user, string $contentTyp * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -3303,7 +3702,7 @@ public function testClientModel($client, string $contentType = self::contentType * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClientModel'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -3353,7 +3752,19 @@ public function testClientModelWithHttpInfo($client, string $contentType = self: } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -3370,7 +3781,19 @@ public function testClientModelWithHttpInfo($client, string $contentType = self: } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -3580,7 +4003,7 @@ public function testClientModelRequest($client, string $contentType = self::cont * @param string $callback None (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -3610,7 +4033,7 @@ public function testEndpointParameters($number, $double, $pattern_without_delimi * @param string $callback None (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEndpointParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -3999,7 +4422,7 @@ public function testEndpointParametersRequest($number, $double, $pattern_without * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -4024,7 +4447,7 @@ public function testEnumParameters($enum_header_string_array = null, $enum_heade * @param string $enum_form_string Form parameter enum test (string) (optional, default to '-efg') * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testEnumParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4325,7 +4748,7 @@ public function testEnumParametersRequest($enum_header_string_array = null, $enu * @param int $int64_group Integer in group parameters (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -4349,7 +4772,7 @@ public function testGroupParameters($associative_array) * @param int $int64_group Integer in group parameters (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testGroupParameters'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4647,7 +5070,7 @@ public function testGroupParametersRequest($associative_array) * @param array $request_body request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -4664,7 +5087,7 @@ public function testInlineAdditionalProperties($request_body, string $contentTyp * @param array $request_body request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineAdditionalProperties'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -4875,7 +5298,7 @@ public function testInlineAdditionalPropertiesRequest($request_body, string $con * @param \OpenAPI\Client\Model\TestInlineFreeformAdditionalPropertiesRequest $test_inline_freeform_additional_properties_request request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineFreeformAdditionalProperties'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -4892,7 +5315,7 @@ public function testInlineFreeformAdditionalProperties($test_inline_freeform_add * @param \OpenAPI\Client\Model\TestInlineFreeformAdditionalPropertiesRequest $test_inline_freeform_additional_properties_request request body (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testInlineFreeformAdditionalProperties'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -5104,7 +5527,7 @@ public function testInlineFreeformAdditionalPropertiesRequest($test_inline_freef * @param string $param2 field2 (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -5122,7 +5545,7 @@ public function testJsonFormData($param, $param2, string $contentType = self::co * @param string $param2 field2 (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testJsonFormData'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -5348,7 +5771,7 @@ public function testJsonFormDataRequest($param, $param2, string $contentType = s * @param array $language language (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -5369,7 +5792,7 @@ public function testQueryParameterCollectionFormat($pipe, $ioutil, $http, $url, * @param array $language (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testQueryParameterCollectionFormat'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php index 965f6491cd50..d8606f1f0e36 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/FakeClassnameTags123Api.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -76,7 +76,7 @@ class FakeClassnameTags123Api ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -130,7 +130,7 @@ public function getConfig() * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Client */ @@ -148,7 +148,7 @@ public function testClassname($client, string $contentType = self::contentTypes[ * @param \OpenAPI\Client\Model\Client $client client model (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['testClassname'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Client, HTTP status code, HTTP response headers (array of strings) */ @@ -198,7 +198,19 @@ public function testClassnameWithHttpInfo($client, string $contentType = self::c } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Client' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -215,7 +227,19 @@ public function testClassnameWithHttpInfo($client, string $contentType = self::c } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php index 735bd078f5c4..06c1e58d1978 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/PetApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -102,7 +102,7 @@ class PetApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -174,7 +174,7 @@ public function getConfig() * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -209,7 +209,7 @@ public function addPet($pet, ?int $hostIndex = null, array $variables = [], stri * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['addPet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -531,7 +531,7 @@ protected function getHostSettingsForaddPet(): array * @param string $api_key api_key (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -549,7 +549,7 @@ public function deletePet($pet_id, $api_key = null, string $contentType = self:: * @param string $api_key (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deletePet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -773,7 +773,7 @@ public function deletePetRequest($pet_id, $api_key = null, string $contentType = * @param string[] $status Status values that need to be considered for filter (required) (deprecated) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Pet[] */ @@ -791,7 +791,7 @@ public function findPetsByStatus($status, string $contentType = self::contentTyp * @param string[] $status Status values that need to be considered for filter (required) (deprecated) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByStatus'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) */ @@ -841,7 +841,19 @@ public function findPetsByStatusWithHttpInfo($status, string $contentType = self } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -858,7 +870,19 @@ public function findPetsByStatusWithHttpInfo($status, string $contentType = self } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1061,7 +1085,7 @@ public function findPetsByStatusRequest($status, string $contentType = self::con * @param string[] $tags Tags to filter by (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Pet[] * @deprecated @@ -1080,7 +1104,7 @@ public function findPetsByTags($tags, string $contentType = self::contentTypes[' * @param string[] $tags Tags to filter by (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['findPetsByTags'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet[], HTTP status code, HTTP response headers (array of strings) * @deprecated @@ -1131,7 +1155,19 @@ public function findPetsByTagsWithHttpInfo($tags, string $contentType = self::co } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet[]' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1148,7 +1184,19 @@ public function findPetsByTagsWithHttpInfo($tags, string $contentType = self::co } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1354,7 +1402,7 @@ public function findPetsByTagsRequest($tags, string $contentType = self::content * @param int $pet_id ID of pet to return (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Pet */ @@ -1372,7 +1420,7 @@ public function getPetById($pet_id, string $contentType = self::contentTypes['ge * @param int $pet_id ID of pet to return (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getPetById'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Pet, HTTP status code, HTTP response headers (array of strings) */ @@ -1422,7 +1470,19 @@ public function getPetByIdWithHttpInfo($pet_id, string $contentType = self::cont } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Pet' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1439,7 +1499,19 @@ public function getPetByIdWithHttpInfo($pet_id, string $contentType = self::cont } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1660,7 +1732,7 @@ public function getPetByIdRequest($pet_id, string $contentType = self::contentTy * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -1695,7 +1767,7 @@ public function updatePet($pet, ?int $hostIndex = null, array $variables = [], s * @param array $variables Associative array of variables to pass to the host. Defaults to empty array. * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePet'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2018,7 +2090,7 @@ protected function getHostSettingsForupdatePet(): array * @param string $status Updated status of the pet (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -2037,7 +2109,7 @@ public function updatePetWithForm($pet_id, $name = null, $status = null, string * @param string $status Updated status of the pet (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updatePetWithForm'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -2271,7 +2343,7 @@ public function updatePetWithFormRequest($pet_id, $name = null, $status = null, * @param \SplFileObject $file file to upload (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\ApiResponse */ @@ -2291,7 +2363,7 @@ public function uploadFile($pet_id, $additional_metadata = null, $file = null, s * @param \SplFileObject $file file to upload (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFile'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -2341,7 +2413,19 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2358,7 +2442,19 @@ public function uploadFileWithHttpInfo($pet_id, $additional_metadata = null, $fi } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2586,7 +2682,7 @@ public function uploadFileRequest($pet_id, $additional_metadata = null, $file = * @param string $additional_metadata Additional data to pass to server (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\ApiResponse */ @@ -2606,7 +2702,7 @@ public function uploadFileWithRequiredFile($pet_id, $required_file, $additional_ * @param string $additional_metadata Additional data to pass to server (optional) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['uploadFileWithRequiredFile'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\ApiResponse, HTTP status code, HTTP response headers (array of strings) */ @@ -2656,7 +2752,19 @@ public function uploadFileWithRequiredFileWithHttpInfo($pet_id, $required_file, } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\ApiResponse' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -2673,7 +2781,19 @@ public function uploadFileWithRequiredFileWithHttpInfo($pet_id, $required_file, } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php index 712c7fbb6235..6da16c9b08d2 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/StoreApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -85,7 +85,7 @@ class StoreApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -139,7 +139,7 @@ public function getConfig() * @param string $order_id ID of the order that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -156,7 +156,7 @@ public function deleteOrder($order_id, string $contentType = self::contentTypes[ * @param string $order_id ID of the order that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteOrder'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -367,7 +367,7 @@ public function deleteOrderRequest($order_id, string $contentType = self::conten * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array */ @@ -384,7 +384,7 @@ public function getInventory(string $contentType = self::contentTypes['getInvent * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getInventory'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of array, HTTP status code, HTTP response headers (array of strings) */ @@ -434,7 +434,19 @@ public function getInventoryWithHttpInfo(string $contentType = self::contentType } else { $content = (string) $response->getBody(); if ('array' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -451,7 +463,19 @@ public function getInventoryWithHttpInfo(string $contentType = self::contentType } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -636,7 +660,7 @@ public function getInventoryRequest(string $contentType = self::contentTypes['ge * @param int $order_id ID of pet that needs to be fetched (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Order */ @@ -654,7 +678,7 @@ public function getOrderById($order_id, string $contentType = self::contentTypes * @param int $order_id ID of pet that needs to be fetched (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getOrderById'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ @@ -704,7 +728,19 @@ public function getOrderByIdWithHttpInfo($order_id, string $contentType = self:: } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -721,7 +757,19 @@ public function getOrderByIdWithHttpInfo($order_id, string $contentType = self:: } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -925,7 +973,7 @@ public function getOrderByIdRequest($order_id, string $contentType = self::conte * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\Order */ @@ -943,7 +991,7 @@ public function placeOrder($order, string $contentType = self::contentTypes['pla * @param \OpenAPI\Client\Model\Order $order order placed for purchasing the pet (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['placeOrder'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\Order, HTTP status code, HTTP response headers (array of strings) */ @@ -993,7 +1041,19 @@ public function placeOrderWithHttpInfo($order, string $contentType = self::conte } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\Order' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1010,7 +1070,19 @@ public function placeOrderWithHttpInfo($order, string $contentType = self::conte } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php index d808edb0f887..d9f4a3f0a56e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Api/UserApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -97,7 +97,7 @@ class UserApi ], ]; -/** + /** * @param ClientInterface $client * @param Configuration $config * @param HeaderSelector $selector @@ -151,7 +151,7 @@ public function getConfig() * @param \OpenAPI\Client\Model\User $user Created user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -168,7 +168,7 @@ public function createUser($user, string $contentType = self::contentTypes['crea * @param \OpenAPI\Client\Model\User $user Created user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -379,7 +379,7 @@ public function createUserRequest($user, string $contentType = self::contentType * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -396,7 +396,7 @@ public function createUsersWithArrayInput($user, string $contentType = self::con * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithArrayInput'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -607,7 +607,7 @@ public function createUsersWithArrayInputRequest($user, string $contentType = se * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -624,7 +624,7 @@ public function createUsersWithListInput($user, string $contentType = self::cont * @param \OpenAPI\Client\Model\User[] $user List of user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['createUsersWithListInput'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -835,7 +835,7 @@ public function createUsersWithListInputRequest($user, string $contentType = sel * @param string $username The name that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -852,7 +852,7 @@ public function deleteUser($username, string $contentType = self::contentTypes[' * @param string $username The name that needs to be deleted (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['deleteUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -1064,7 +1064,7 @@ public function deleteUserRequest($username, string $contentType = self::content * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return \OpenAPI\Client\Model\User */ @@ -1082,7 +1082,7 @@ public function getUserByName($username, string $contentType = self::contentType * @param string $username The name that needs to be fetched. Use user1 for testing. (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['getUserByName'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of \OpenAPI\Client\Model\User, HTTP status code, HTTP response headers (array of strings) */ @@ -1132,7 +1132,19 @@ public function getUserByNameWithHttpInfo($username, string $contentType = self: } else { $content = (string) $response->getBody(); if ('\OpenAPI\Client\Model\User' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1149,7 +1161,19 @@ public function getUserByNameWithHttpInfo($username, string $contentType = self: } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1348,7 +1372,7 @@ public function getUserByNameRequest($username, string $contentType = self::cont * @param string $password The password for login in clear text (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return string */ @@ -1367,7 +1391,7 @@ public function loginUser($username, $password, string $contentType = self::cont * @param string $password The password for login in clear text (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['loginUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of string, HTTP status code, HTTP response headers (array of strings) */ @@ -1417,7 +1441,19 @@ public function loginUserWithHttpInfo($username, $password, string $contentType } else { $content = (string) $response->getBody(); if ('string' !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1434,7 +1470,19 @@ public function loginUserWithHttpInfo($username, $password, string $contentType } else { $content = (string) $response->getBody(); if ($returnType !== 'string') { - $content = json_decode($content); + try { + $content = json_decode($content, false, 512, JSON_THROW_ON_ERROR); + } catch (\JsonException $exception) { + throw new ApiException( + sprintf( + 'Error JSON decoding server response (%s)', + $request->getUri() + ), + $statusCode, + $response->getHeaders(), + $content + ); + } } } @@ -1651,7 +1699,7 @@ public function loginUserRequest($username, $password, string $contentType = sel * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -1667,7 +1715,7 @@ public function logoutUser(string $contentType = self::contentTypes['logoutUser' * * @param string $contentType The value for the Content-Type header. Check self::contentTypes['logoutUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ @@ -1862,7 +1910,7 @@ public function logoutUserRequest(string $contentType = self::contentTypes['logo * @param \OpenAPI\Client\Model\User $user Updated user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return void */ @@ -1880,7 +1928,7 @@ public function updateUser($username, $user, string $contentType = self::content * @param \OpenAPI\Client\Model\User $user Updated user object (required) * @param string $contentType The value for the Content-Type header. Check self::contentTypes['updateUser'] to see the possible values for this operation * - * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \OpenAPI\Client\ApiException on non-2xx response or if the response body is not in the expected format * @throws \InvalidArgumentException * @return array of null, HTTP status code, HTTP response headers (array of strings) */ diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php index f1b4b4bbf6db..0f630c5d50a0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ApiException.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php index c8a68ba11552..97d1c6410320 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Configuration.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -209,7 +209,7 @@ public function getAccessToken() /** * Sets boolean format for query string. * - * @param string $booleanFormatForQueryString Boolean format for query string + * @param string $booleanFormat Boolean format for query string * * @return $this */ @@ -523,18 +523,18 @@ public function getHostSettings() * @param array|null $variables hash of variable and the corresponding value (optional) * @return string URL based on host settings */ - public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) + public static function getHostString(array $hostSettings, $hostIndex, array $variables = null) { if (null === $variables) { $variables = []; } // check array index out of bound - if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { - throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostSettings)); } - $host = $hostsSettings[$hostIndex]; + $host = $hostSettings[$hostIndex]; $url = $host["url"]; // go through variable and assign a value diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php index 98c657508c13..b72454566efa 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/HeaderSelector.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php index 7ad01ecd87a5..7bb06678f294 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSer */ protected static array $openAPINullables = [ 'map_property' => false, - 'map_of_map_property' => false + 'map_of_map_property' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php index b9d8b96c7ace..5dea8b080c79 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/AllOfWithSingleRef.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializab */ protected static array $openAPINullables = [ 'username' => false, - 'single_ref_type' => false + 'single_ref_type' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php index 2578fe0fdcde..b3b6a5751319 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Animal.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Animal implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'class_name' => false, - 'color' => false + 'color' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php index 2c48180de022..d4bd245cb3d9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ApiResponse.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class ApiResponse implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'code' => false, - 'type' => false, - 'message' => false + 'type' => false, + 'message' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php index 8a88346fef3c..404f500a1fbc 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php index 2bd26e01a049..ec45dfd24d69 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php index 4775338d3be3..5cfe29402892 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ArrayTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class ArrayTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'array_of_string' => false, - 'array_array_of_integer' => false, - 'array_array_of_model' => false + 'array_array_of_integer' => false, + 'array_array_of_model' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php index ac9039f763f1..d1e87653db0c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Capitalization.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Capitalization implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'small_camel' => false, - 'capital_camel' => false, - 'small_snake' => false, - 'capital_snake' => false, - 'sca_eth_flow_points' => false, - 'att_name' => false + 'capital_camel' => false, + 'small_snake' => false, + 'capital_snake' => false, + 'sca_eth_flow_points' => false, + 'att_name' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php index 330cd4445738..0909b36c91f3 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Cat.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php index ca975413f2c7..dded1fa6709d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Category.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Category implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php index 3126e15e0dff..7cca16e90a7a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ClassModel.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php index fab8874792bb..eaac47ce3f1d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Client.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php index 0b7794b5602d..46441e24d565 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/DeprecatedObject.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php index 91ae32cd75c6..88d90035ee73 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Dog.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php index 76548ed1e732..3fad01d16053 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumArrays.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class EnumArrays implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'just_symbol' => false, - 'array_enum' => false + 'array_enum' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php index 564dad7bf507..78f7f518cf24 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php index 8dbd8ad634d2..e4151df41e69 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/EnumTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -92,13 +92,13 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'enum_string' => false, - 'enum_string_required' => false, - 'enum_integer' => false, - 'enum_number' => false, - 'outer_enum' => true, - 'outer_enum_integer' => false, - 'outer_enum_default_value' => false, - 'outer_enum_integer_default_value' => false + 'enum_string_required' => false, + 'enum_integer' => false, + 'enum_number' => false, + 'outer_enum' => true, + 'outer_enum_integer' => false, + 'outer_enum_default_value' => false, + 'outer_enum_integer_default_value' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FakeBigDecimalMap200Response.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FakeBigDecimalMap200Response.php index 204e9af87d7b..fe007f393e35 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FakeBigDecimalMap200Response.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FakeBigDecimalMap200Response.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class FakeBigDecimalMap200Response implements ModelInterface, ArrayAccess, \Json */ protected static array $openAPINullables = [ 'some_id' => false, - 'some_map' => false + 'some_map' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php index 6f8e747ee27f..cf3878d434e8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/File.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php index 597666bf3e0a..9e2189892261 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FileSchemaTestClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class FileSchemaTestClass implements ModelInterface, ArrayAccess, \JsonSerializa */ protected static array $openAPINullables = [ 'file' => false, - 'files' => false + 'files' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php index 1c062093489e..fef941fd6c0d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Foo.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php index 6eb0f77907da..9021eab4ce9a 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FooGetDefaultResponse.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php index f61d401cbe69..76ec9093fdda 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/FormatTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -108,21 +108,21 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'integer' => false, - 'int32' => false, - 'int64' => false, - 'number' => false, - 'float' => false, - 'double' => false, - 'decimal' => false, - 'string' => false, - 'byte' => false, - 'binary' => false, - 'date' => false, - 'date_time' => false, - 'uuid' => false, - 'password' => false, - 'pattern_with_digits' => false, - 'pattern_with_digits_and_delimiter' => false + 'int32' => false, + 'int64' => false, + 'number' => false, + 'float' => false, + 'double' => false, + 'decimal' => false, + 'string' => false, + 'byte' => false, + 'binary' => false, + 'date' => false, + 'date_time' => false, + 'uuid' => false, + 'password' => false, + 'pattern_with_digits' => false, + 'pattern_with_digits_and_delimiter' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php index 3904eeb5b931..453a3ae01eb0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HasOnlyReadOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class HasOnlyReadOnly implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'foo' => false + 'foo' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php index d5ead08d64b4..2d3e3b1aa32c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/HealthCheckResult.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php index 957c8d631014..c2037d565244 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MapTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class MapTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'map_map_of_string' => false, - 'map_of_enum_string' => false, - 'direct_map' => false, - 'indirect_map' => false + 'map_of_enum_string' => false, + 'direct_map' => false, + 'indirect_map' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 9ee00c9ef0f7..70d36e08b3ef 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ModelInterface, Arr */ protected static array $openAPINullables = [ 'uuid' => false, - 'date_time' => false, - 'map' => false + 'date_time' => false, + 'map' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php index ea45ce3dc86d..51f70024ac4c 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Model200Response.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -81,7 +81,7 @@ class Model200Response implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'class' => false + 'class' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php index a76ce2e767ba..d64722206235 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelInterface.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php index 1b1cc8987a2c..28d4feb65ac0 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelList.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php index 5337c680bb35..12efa46b600e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ModelReturn.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php index d87e2df9b50f..e8b2c991bf10 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Name.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -85,9 +85,9 @@ class Name implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'snake_case' => false, - 'property' => false, - '_123_number' => false + 'snake_case' => false, + 'property' => false, + '_123_number' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php index 30c50185b2c8..c7d86dada96e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NullableClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -100,17 +100,17 @@ class NullableClass implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'integer_prop' => true, - 'number_prop' => true, - 'boolean_prop' => true, - 'string_prop' => true, - 'date_prop' => true, - 'datetime_prop' => true, - 'array_nullable_prop' => true, - 'array_and_items_nullable_prop' => true, - 'array_items_nullable' => false, - 'object_nullable_prop' => true, - 'object_and_items_nullable_prop' => true, - 'object_items_nullable' => false + 'number_prop' => true, + 'boolean_prop' => true, + 'string_prop' => true, + 'date_prop' => true, + 'datetime_prop' => true, + 'array_nullable_prop' => true, + 'array_and_items_nullable_prop' => true, + 'array_items_nullable' => false, + 'object_nullable_prop' => true, + 'object_and_items_nullable_prop' => true, + 'object_items_nullable' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php index bb529455e718..24c28259ba95 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/NumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php index 3f0c6a61c8bb..54cc48135f33 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ObjectWithDeprecatedFields.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class ObjectWithDeprecatedFields implements ModelInterface, ArrayAccess, \JsonSe */ protected static array $openAPINullables = [ 'uuid' => false, - 'id' => false, - 'deprecated_ref' => false, - 'bars' => false + 'id' => false, + 'deprecated_ref' => false, + 'bars' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php index 502b8bbc944a..f56b6c308f75 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Order.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Order implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'pet_id' => false, - 'quantity' => false, - 'ship_date' => false, - 'status' => false, - 'complete' => false + 'pet_id' => false, + 'quantity' => false, + 'ship_date' => false, + 'status' => false, + 'complete' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php index 4d8bc042776a..ddc9c396dfa9 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterComposite.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class OuterComposite implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'my_number' => false, - 'my_string' => false, - 'my_boolean' => false + 'my_string' => false, + 'my_boolean' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php index 1853560c9003..c7c2c614f678 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnum.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php index 7fab44f133f9..664e5914401f 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php index cd1f81768b34..859de958fc5b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumInteger.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php index fdfd64c90050..c196c08dfd61 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterEnumIntegerDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php index dc1ae0ca9977..ba475165e28e 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/OuterObjectWithEnumProperty.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php index 8075da54d28c..c1f9f7304a7d 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Pet.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Pet implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'category' => false, - 'name' => false, - 'photo_urls' => false, - 'tags' => false, - 'status' => false + 'category' => false, + 'name' => false, + 'photo_urls' => false, + 'tags' => false, + 'status' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/PropertyNameMapping.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/PropertyNameMapping.php index e97fa27d01b4..93507a5fddeb 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/PropertyNameMapping.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/PropertyNameMapping.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class PropertyNameMapping implements ModelInterface, ArrayAccess, \JsonSerializa */ protected static array $openAPINullables = [ 'http_debug_operation' => false, - 'underscore_type' => false, - 'type' => false, - 'type_with_underscore' => false + 'underscore_type' => false, + 'type' => false, + 'type_with_underscore' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php index 9d0e8cd97a8a..1fab9ca08b86 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/ReadOnlyFirst.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class ReadOnlyFirst implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'baz' => false + 'baz' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SingleRefType.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SingleRefType.php index 5f579dcbc944..cc490edd942b 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SingleRefType.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SingleRefType.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php index 61906b54f35a..c8acd2605844 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/SpecialModelName.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php index f016bc201443..d4a918f0b0fc 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/Tag.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Tag implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php index e2cd3f6295cc..1d15342fabb8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php index f78bfc93a3f8..d7fa21bd8ef6 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/Model/User.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -92,13 +92,13 @@ class User implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'username' => false, - 'first_name' => false, - 'last_name' => false, - 'email' => false, - 'password' => false, - 'phone' => false, - 'user_status' => false + 'username' => false, + 'first_name' => false, + 'last_name' => false, + 'email' => false, + 'password' => false, + 'phone' => false, + 'user_status' => false ]; /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php index 8398f415c99c..39ca3b962208 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/OpenAPIClient-php/lib/ObjectSerializer.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/OpenAPIClient-php/tests/AuthTest.php b/samples/client/petstore/php/OpenAPIClient-php/tests/AuthTest.php index daafb50ede7c..8da485b3f0a8 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/tests/AuthTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/tests/AuthTest.php @@ -2,10 +2,12 @@ namespace OpenAPI\Client; +use GuzzleHttp\Psr7\Response; use OpenAPI\Client\Api\FakeApi; use OpenAPI\Client\Api\PetApi; use OpenAPI\Client\Model\Pet; use PHPUnit\Framework\TestCase; +use Psr\Http\Message\ResponseInterface; require_once __DIR__ . '/FakeHttpClient.php'; @@ -17,6 +19,7 @@ public function testCustomApiKeyHeader() $authConfig->setApiKey('api_key', '123qwe'); $fakeHttpClient = new FakeHttpClient(); + $fakeHttpClient->setResponse(new Response(200, [], json_encode([]))); $api = new PetApi($fakeHttpClient, $authConfig); $api->getPetById(123); diff --git a/samples/client/petstore/php/OpenAPIClient-php/tests/HeadersTest.php b/samples/client/petstore/php/OpenAPIClient-php/tests/HeadersTest.php index 989516cc0c6e..8f5cc48564db 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/tests/HeadersTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/tests/HeadersTest.php @@ -2,6 +2,7 @@ namespace OpenAPI\Client; +use GuzzleHttp\Psr7\Response; use PHPUnit\Framework\TestCase; require_once __DIR__ . '/FakeHttpClient.php'; @@ -14,6 +15,7 @@ class HeadersTest extends TestCase public function setUp(): void { $this->fakeHttpClient = new FakeHttpClient(); + $this->fakeHttpClient->setResponse(new Response(200, [], json_encode([]))); } public function testUserAgent() diff --git a/samples/client/petstore/php/OpenAPIClient-php/tests/ResponseTypesTest.php b/samples/client/petstore/php/OpenAPIClient-php/tests/ResponseTypesTest.php index 8d65396ccbc4..1dd5a618b597 100644 --- a/samples/client/petstore/php/OpenAPIClient-php/tests/ResponseTypesTest.php +++ b/samples/client/petstore/php/OpenAPIClient-php/tests/ResponseTypesTest.php @@ -89,4 +89,29 @@ public function testDefaultErrorResponseObject() $this->assertNull($result); } + + public function invalidJSONResponseProvider() + { + return [ + 'status 200, content empty' => [200, ''], + 'status 200, content leading comma' => [200, '{"key": "value",}'], + 'status 200, content just text' => [200, 'invalid JSON'], + 'status 200, content null' => [200, null], + 'status 204, content empty' => [204, ''], + 'status 204, content leading comma' => [204, '{"key": "value",}'], + 'status 204, content just text' => [204, 'invalid JSON'], + 'status 204, content null' => [204, null], + ]; + } + /** + * @dataProvider invalidJSONResponseProvider + */ + public function testNotJSONResponse($statusCode, $responseBody) + { + $this->expectExceptionCode($statusCode); + $this->expectException(\OpenAPI\Client\ApiException::class); + + $this->fakeHttpClient->setResponse(new Response($statusCode, [], $responseBody)); + $this->api->getPetById(123); + } } diff --git a/samples/client/petstore/php/psr-18/.openapi-generator/VERSION b/samples/client/petstore/php/psr-18/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/php/psr-18/.openapi-generator/VERSION +++ b/samples/client/petstore/php/psr-18/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/php/psr-18/README.md b/samples/client/petstore/php/psr-18/README.md index f2d875286217..f386b2788bf8 100644 --- a/samples/client/petstore/php/psr-18/README.md +++ b/samples/client/petstore/php/psr-18/README.md @@ -94,6 +94,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterStringSerialize**](docs/Api/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](docs/Api/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | *FakeApi* | [**getParameterNameMapping**](docs/Api/FakeApi.md#getparameternamemapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*FakeApi* | [**testAdditionalPropertiesReference**](docs/Api/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](docs/Api/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](docs/Api/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/Api/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/php/psr-18/docs/Api/FakeApi.md b/samples/client/petstore/php/psr-18/docs/Api/FakeApi.md index e7b93904d5b6..db072f39718f 100644 --- a/samples/client/petstore/php/psr-18/docs/Api/FakeApi.md +++ b/samples/client/petstore/php/psr-18/docs/Api/FakeApi.md @@ -13,6 +13,7 @@ Method | HTTP request | Description [**fakeOuterStringSerialize()**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize()**](FakeApi.md#fakePropertyEnumIntegerSerialize) | **POST** /fake/property/enum-int | [**getParameterNameMapping()**](FakeApi.md#getParameterNameMapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +[**testAdditionalPropertiesReference()**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary()**](FakeApi.md#testBodyWithBinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema()**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams()**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | @@ -530,6 +531,61 @@ No authorization required [[Back to Model list]](../../README.md#models) [[Back to README]](../../README.md) +## `testAdditionalPropertiesReference()` + +```php +testAdditionalPropertiesReference($request_body) +``` + +test referenced additionalProperties + + + +### Example + +```php + | request body + +try { + $apiInstance->testAdditionalPropertiesReference($request_body); +} catch (Exception $e) { + echo 'Exception when calling FakeApi->testAdditionalPropertiesReference: ', $e->getMessage(), PHP_EOL; +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**array**](../Model/mixed.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: `application/json` +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../../README.md#endpoints) +[[Back to Model list]](../../README.md#models) +[[Back to README]](../../README.md) + ## `testBodyWithBinary()` ```php diff --git a/samples/client/petstore/php/psr-18/lib/Api/AnotherFakeApi.php b/samples/client/petstore/php/psr-18/lib/Api/AnotherFakeApi.php index 4fb4ac27b0f0..3a537e229e17 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/AnotherFakeApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/AnotherFakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Api/DefaultApi.php b/samples/client/petstore/php/psr-18/lib/Api/DefaultApi.php index baf6b5fd79cd..473bbff089bf 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/DefaultApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/DefaultApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Api/FakeApi.php b/samples/client/petstore/php/psr-18/lib/Api/FakeApi.php index 1dd75bd13c18..55c4bcd24629 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/FakeApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/FakeApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -2387,6 +2387,218 @@ public function getParameterNameMappingRequest($underscore_type, $type, $type_wi return $this->createRequest('GET', $uri, $headers, $httpBody); } + /** + * Operation testAdditionalPropertiesReference + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return void + */ + public function testAdditionalPropertiesReference($request_body) + { + $this->testAdditionalPropertiesReferenceWithHttpInfo($request_body); + } + + /** + * Operation testAdditionalPropertiesReferenceWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * + * @throws \OpenAPI\Client\ApiException on non-2xx response + * @throws \InvalidArgumentException + * @return array of null, HTTP status code, HTTP response headers (array of strings) + */ + public function testAdditionalPropertiesReferenceWithHttpInfo($request_body) + { + $request = $this->testAdditionalPropertiesReferenceRequest($request_body); + + try { + try { + $response = $this->httpClient->sendRequest($request); + } catch (HttpException $e) { + $response = $e->getResponse(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $response->getStatusCode(), + (string) $request->getUri() + ), + $request, + $response, + $e + ); + } catch (ClientExceptionInterface $e) { + throw new ApiException( + "[{$e->getCode()}] {$e->getMessage()}", + $request, + null, + $e + ); + } + + $statusCode = $response->getStatusCode(); + + return [null, $statusCode, $response->getHeaders()]; + + } catch (ApiException $e) { + switch ($e->getCode()) { + } + throw $e; + } + } + + /** + * Operation testAdditionalPropertiesReferenceAsync + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * + * @throws \InvalidArgumentException + * @return Promise + */ + public function testAdditionalPropertiesReferenceAsync($request_body) + { + return $this->testAdditionalPropertiesReferenceAsyncWithHttpInfo($request_body) + ->then( + function ($response) { + return $response[0]; + } + ); + } + + /** + * Operation testAdditionalPropertiesReferenceAsyncWithHttpInfo + * + * test referenced additionalProperties + * + * @param array $request_body request body (required) + * + * @throws \InvalidArgumentException + * @return Promise + */ + public function testAdditionalPropertiesReferenceAsyncWithHttpInfo($request_body) + { + $returnType = ''; + $request = $this->testAdditionalPropertiesReferenceRequest($request_body); + + return $this->httpAsyncClient->sendAsyncRequest($request) + ->then( + function ($response) use ($returnType) { + return [null, $response->getStatusCode(), $response->getHeaders()]; + }, + function (HttpException $exception) { + $response = $exception->getResponse(); + $statusCode = $response->getStatusCode(); + throw new ApiException( + sprintf( + '[%d] Error connecting to the API (%s)', + $statusCode, + $exception->getRequest()->getUri() + ), + $exception->getRequest(), + $exception->getResponse(), + $exception + ); + } + ); + } + + /** + * Create request for operation 'testAdditionalPropertiesReference' + * + * @param array $request_body request body (required) + * + * @throws \InvalidArgumentException + * @return RequestInterface + */ + public function testAdditionalPropertiesReferenceRequest($request_body) + { + // verify the required parameter 'request_body' is set + if ($request_body === null || (is_array($request_body) && count($request_body) === 0)) { + throw new \InvalidArgumentException( + 'Missing the required parameter $request_body when calling testAdditionalPropertiesReference' + ); + } + + $resourcePath = '/fake/additionalProperties-reference'; + $formParams = []; + $queryParams = []; + $headerParams = []; + $httpBody = null; + $multipart = false; + + + + + + if ($multipart) { + $headers = $this->headerSelector->selectHeadersForMultipart( + [] + ); + } else { + $headers = $this->headerSelector->selectHeaders( + [], + ['application/json'] + ); + } + + // for model (json/xml) + if (isset($request_body)) { + if ($headers['Content-Type'] === 'application/json') { + $httpBody = json_encode(ObjectSerializer::sanitizeForSerialization($request_body)); + } else { + $httpBody = $request_body; + } + } elseif (count($formParams) > 0) { + if ($multipart) { + $multipartContents = []; + foreach ($formParams as $formParamName => $formParamValue) { + $formParamValueItems = is_array($formParamValue) ? $formParamValue : [$formParamValue]; + foreach ($formParamValueItems as $formParamValueItem) { + $multipartContents[] = [ + 'name' => $formParamName, + 'contents' => $formParamValueItem + ]; + } + } + // for HTTP post (form) + $httpBody = new MultipartStream($multipartContents); + + } elseif ($headers['Content-Type'] === 'application/json') { + $httpBody = json_encode($formParams); + + } else { + // for HTTP post (form) + $httpBody = Query::build($formParams); + } + } + + + $defaultHeaders = []; + if ($this->config->getUserAgent()) { + $defaultHeaders['User-Agent'] = $this->config->getUserAgent(); + } + + $headers = array_merge( + $defaultHeaders, + $headerParams, + $headers + ); + + $operationHost = $this->config->getHost(); + + $uri = $this->createUri($operationHost, $resourcePath, $queryParams); + + return $this->createRequest('POST', $uri, $headers, $httpBody); + } + /** * Operation testBodyWithBinary * diff --git a/samples/client/petstore/php/psr-18/lib/Api/FakeClassnameTags123Api.php b/samples/client/petstore/php/psr-18/lib/Api/FakeClassnameTags123Api.php index d9529fa7826d..2a8ab8d0e346 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/FakeClassnameTags123Api.php +++ b/samples/client/petstore/php/psr-18/lib/Api/FakeClassnameTags123Api.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Api/PetApi.php b/samples/client/petstore/php/psr-18/lib/Api/PetApi.php index 932814cf2c75..a120c4e737c0 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/PetApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/PetApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Api/StoreApi.php b/samples/client/petstore/php/psr-18/lib/Api/StoreApi.php index 9880aa789c9e..b30af4075409 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/StoreApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/StoreApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Api/UserApi.php b/samples/client/petstore/php/psr-18/lib/Api/UserApi.php index f5ace7d71bd4..f8b1bd872701 100644 --- a/samples/client/petstore/php/psr-18/lib/Api/UserApi.php +++ b/samples/client/petstore/php/psr-18/lib/Api/UserApi.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/ApiException.php b/samples/client/petstore/php/psr-18/lib/ApiException.php index 1d27742e67ca..83e144cd69c9 100644 --- a/samples/client/petstore/php/psr-18/lib/ApiException.php +++ b/samples/client/petstore/php/psr-18/lib/ApiException.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Configuration.php b/samples/client/petstore/php/psr-18/lib/Configuration.php index c8a68ba11552..97d1c6410320 100644 --- a/samples/client/petstore/php/psr-18/lib/Configuration.php +++ b/samples/client/petstore/php/psr-18/lib/Configuration.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -209,7 +209,7 @@ public function getAccessToken() /** * Sets boolean format for query string. * - * @param string $booleanFormatForQueryString Boolean format for query string + * @param string $booleanFormat Boolean format for query string * * @return $this */ @@ -523,18 +523,18 @@ public function getHostSettings() * @param array|null $variables hash of variable and the corresponding value (optional) * @return string URL based on host settings */ - public static function getHostString(array $hostsSettings, $hostIndex, array $variables = null) + public static function getHostString(array $hostSettings, $hostIndex, array $variables = null) { if (null === $variables) { $variables = []; } // check array index out of bound - if ($hostIndex < 0 || $hostIndex >= count($hostsSettings)) { - throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostsSettings)); + if ($hostIndex < 0 || $hostIndex >= count($hostSettings)) { + throw new \InvalidArgumentException("Invalid index $hostIndex when selecting the host. Must be less than ".count($hostSettings)); } - $host = $hostsSettings[$hostIndex]; + $host = $hostSettings[$hostIndex]; $url = $host["url"]; // go through variable and assign a value diff --git a/samples/client/petstore/php/psr-18/lib/DebugPlugin.php b/samples/client/petstore/php/psr-18/lib/DebugPlugin.php index 8cdce5e92487..5da341d7c34a 100644 --- a/samples/client/petstore/php/psr-18/lib/DebugPlugin.php +++ b/samples/client/petstore/php/psr-18/lib/DebugPlugin.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/HeaderSelector.php b/samples/client/petstore/php/psr-18/lib/HeaderSelector.php index 98c657508c13..b72454566efa 100644 --- a/samples/client/petstore/php/psr-18/lib/HeaderSelector.php +++ b/samples/client/petstore/php/psr-18/lib/HeaderSelector.php @@ -16,7 +16,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/AdditionalPropertiesClass.php b/samples/client/petstore/php/psr-18/lib/Model/AdditionalPropertiesClass.php index 7ad01ecd87a5..7bb06678f294 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/AdditionalPropertiesClass.php +++ b/samples/client/petstore/php/psr-18/lib/Model/AdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class AdditionalPropertiesClass implements ModelInterface, ArrayAccess, \JsonSer */ protected static array $openAPINullables = [ 'map_property' => false, - 'map_of_map_property' => false + 'map_of_map_property' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/AllOfWithSingleRef.php b/samples/client/petstore/php/psr-18/lib/Model/AllOfWithSingleRef.php index b9d8b96c7ace..5dea8b080c79 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/AllOfWithSingleRef.php +++ b/samples/client/petstore/php/psr-18/lib/Model/AllOfWithSingleRef.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class AllOfWithSingleRef implements ModelInterface, ArrayAccess, \JsonSerializab */ protected static array $openAPINullables = [ 'username' => false, - 'single_ref_type' => false + 'single_ref_type' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Animal.php b/samples/client/petstore/php/psr-18/lib/Model/Animal.php index 2578fe0fdcde..b3b6a5751319 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Animal.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Animal.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Animal implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'class_name' => false, - 'color' => false + 'color' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ApiResponse.php b/samples/client/petstore/php/psr-18/lib/Model/ApiResponse.php index 2c48180de022..d4bd245cb3d9 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ApiResponse.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ApiResponse.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class ApiResponse implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'code' => false, - 'type' => false, - 'message' => false + 'type' => false, + 'message' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ArrayOfArrayOfNumberOnly.php b/samples/client/petstore/php/psr-18/lib/Model/ArrayOfArrayOfNumberOnly.php index 8a88346fef3c..404f500a1fbc 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ArrayOfArrayOfNumberOnly.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ArrayOfArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ArrayOfNumberOnly.php b/samples/client/petstore/php/psr-18/lib/Model/ArrayOfNumberOnly.php index 2bd26e01a049..ec45dfd24d69 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ArrayOfNumberOnly.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ArrayOfNumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ArrayTest.php b/samples/client/petstore/php/psr-18/lib/Model/ArrayTest.php index 4775338d3be3..5cfe29402892 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ArrayTest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ArrayTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class ArrayTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'array_of_string' => false, - 'array_array_of_integer' => false, - 'array_array_of_model' => false + 'array_array_of_integer' => false, + 'array_array_of_model' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Capitalization.php b/samples/client/petstore/php/psr-18/lib/Model/Capitalization.php index ac9039f763f1..d1e87653db0c 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Capitalization.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Capitalization.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Capitalization implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'small_camel' => false, - 'capital_camel' => false, - 'small_snake' => false, - 'capital_snake' => false, - 'sca_eth_flow_points' => false, - 'att_name' => false + 'capital_camel' => false, + 'small_snake' => false, + 'capital_snake' => false, + 'sca_eth_flow_points' => false, + 'att_name' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Cat.php b/samples/client/petstore/php/psr-18/lib/Model/Cat.php index 330cd4445738..0909b36c91f3 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Cat.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Cat.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Category.php b/samples/client/petstore/php/psr-18/lib/Model/Category.php index ca975413f2c7..dded1fa6709d 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Category.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Category.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Category implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ClassModel.php b/samples/client/petstore/php/psr-18/lib/Model/ClassModel.php index 3126e15e0dff..7cca16e90a7a 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ClassModel.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ClassModel.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Client.php b/samples/client/petstore/php/psr-18/lib/Model/Client.php index fab8874792bb..eaac47ce3f1d 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Client.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Client.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/DeprecatedObject.php b/samples/client/petstore/php/psr-18/lib/Model/DeprecatedObject.php index 0b7794b5602d..46441e24d565 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/DeprecatedObject.php +++ b/samples/client/petstore/php/psr-18/lib/Model/DeprecatedObject.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Dog.php b/samples/client/petstore/php/psr-18/lib/Model/Dog.php index 91ae32cd75c6..88d90035ee73 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Dog.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Dog.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/EnumArrays.php b/samples/client/petstore/php/psr-18/lib/Model/EnumArrays.php index 76548ed1e732..3fad01d16053 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/EnumArrays.php +++ b/samples/client/petstore/php/psr-18/lib/Model/EnumArrays.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class EnumArrays implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'just_symbol' => false, - 'array_enum' => false + 'array_enum' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/EnumClass.php b/samples/client/petstore/php/psr-18/lib/Model/EnumClass.php index 564dad7bf507..78f7f518cf24 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/EnumClass.php +++ b/samples/client/petstore/php/psr-18/lib/Model/EnumClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php b/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php index 8dbd8ad634d2..e4151df41e69 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/EnumTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -92,13 +92,13 @@ class EnumTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'enum_string' => false, - 'enum_string_required' => false, - 'enum_integer' => false, - 'enum_number' => false, - 'outer_enum' => true, - 'outer_enum_integer' => false, - 'outer_enum_default_value' => false, - 'outer_enum_integer_default_value' => false + 'enum_string_required' => false, + 'enum_integer' => false, + 'enum_number' => false, + 'outer_enum' => true, + 'outer_enum_integer' => false, + 'outer_enum_default_value' => false, + 'outer_enum_integer_default_value' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/FakeBigDecimalMap200Response.php b/samples/client/petstore/php/psr-18/lib/Model/FakeBigDecimalMap200Response.php index 204e9af87d7b..fe007f393e35 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/FakeBigDecimalMap200Response.php +++ b/samples/client/petstore/php/psr-18/lib/Model/FakeBigDecimalMap200Response.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class FakeBigDecimalMap200Response implements ModelInterface, ArrayAccess, \Json */ protected static array $openAPINullables = [ 'some_id' => false, - 'some_map' => false + 'some_map' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/File.php b/samples/client/petstore/php/psr-18/lib/Model/File.php index 6f8e747ee27f..cf3878d434e8 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/File.php +++ b/samples/client/petstore/php/psr-18/lib/Model/File.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/FileSchemaTestClass.php b/samples/client/petstore/php/psr-18/lib/Model/FileSchemaTestClass.php index 597666bf3e0a..9e2189892261 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/FileSchemaTestClass.php +++ b/samples/client/petstore/php/psr-18/lib/Model/FileSchemaTestClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class FileSchemaTestClass implements ModelInterface, ArrayAccess, \JsonSerializa */ protected static array $openAPINullables = [ 'file' => false, - 'files' => false + 'files' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Foo.php b/samples/client/petstore/php/psr-18/lib/Model/Foo.php index 1c062093489e..fef941fd6c0d 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Foo.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Foo.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/FooGetDefaultResponse.php b/samples/client/petstore/php/psr-18/lib/Model/FooGetDefaultResponse.php index 6eb0f77907da..9021eab4ce9a 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/FooGetDefaultResponse.php +++ b/samples/client/petstore/php/psr-18/lib/Model/FooGetDefaultResponse.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/FormatTest.php b/samples/client/petstore/php/psr-18/lib/Model/FormatTest.php index f61d401cbe69..76ec9093fdda 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/FormatTest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/FormatTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -108,21 +108,21 @@ class FormatTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'integer' => false, - 'int32' => false, - 'int64' => false, - 'number' => false, - 'float' => false, - 'double' => false, - 'decimal' => false, - 'string' => false, - 'byte' => false, - 'binary' => false, - 'date' => false, - 'date_time' => false, - 'uuid' => false, - 'password' => false, - 'pattern_with_digits' => false, - 'pattern_with_digits_and_delimiter' => false + 'int32' => false, + 'int64' => false, + 'number' => false, + 'float' => false, + 'double' => false, + 'decimal' => false, + 'string' => false, + 'byte' => false, + 'binary' => false, + 'date' => false, + 'date_time' => false, + 'uuid' => false, + 'password' => false, + 'pattern_with_digits' => false, + 'pattern_with_digits_and_delimiter' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/HasOnlyReadOnly.php b/samples/client/petstore/php/psr-18/lib/Model/HasOnlyReadOnly.php index 3904eeb5b931..453a3ae01eb0 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/HasOnlyReadOnly.php +++ b/samples/client/petstore/php/psr-18/lib/Model/HasOnlyReadOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class HasOnlyReadOnly implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'foo' => false + 'foo' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/HealthCheckResult.php b/samples/client/petstore/php/psr-18/lib/Model/HealthCheckResult.php index d5ead08d64b4..2d3e3b1aa32c 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/HealthCheckResult.php +++ b/samples/client/petstore/php/psr-18/lib/Model/HealthCheckResult.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/MapTest.php b/samples/client/petstore/php/psr-18/lib/Model/MapTest.php index 957c8d631014..c2037d565244 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/MapTest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/MapTest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class MapTest implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'map_map_of_string' => false, - 'map_of_enum_string' => false, - 'direct_map' => false, - 'indirect_map' => false + 'map_of_enum_string' => false, + 'direct_map' => false, + 'indirect_map' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php b/samples/client/petstore/php/psr-18/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php index 9ee00c9ef0f7..70d36e08b3ef 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php +++ b/samples/client/petstore/php/psr-18/lib/Model/MixedPropertiesAndAdditionalPropertiesClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class MixedPropertiesAndAdditionalPropertiesClass implements ModelInterface, Arr */ protected static array $openAPINullables = [ 'uuid' => false, - 'date_time' => false, - 'map' => false + 'date_time' => false, + 'map' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Model200Response.php b/samples/client/petstore/php/psr-18/lib/Model/Model200Response.php index ea45ce3dc86d..51f70024ac4c 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Model200Response.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Model200Response.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -81,7 +81,7 @@ class Model200Response implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'class' => false + 'class' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ModelInterface.php b/samples/client/petstore/php/psr-18/lib/Model/ModelInterface.php index a76ce2e767ba..d64722206235 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ModelInterface.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ModelInterface.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ModelList.php b/samples/client/petstore/php/psr-18/lib/Model/ModelList.php index 1b1cc8987a2c..28d4feb65ac0 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ModelList.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ModelList.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ModelReturn.php b/samples/client/petstore/php/psr-18/lib/Model/ModelReturn.php index 5337c680bb35..12efa46b600e 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ModelReturn.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ModelReturn.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Name.php b/samples/client/petstore/php/psr-18/lib/Model/Name.php index d87e2df9b50f..e8b2c991bf10 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Name.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Name.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -85,9 +85,9 @@ class Name implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'name' => false, - 'snake_case' => false, - 'property' => false, - '_123_number' => false + 'snake_case' => false, + 'property' => false, + '_123_number' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/NullableClass.php b/samples/client/petstore/php/psr-18/lib/Model/NullableClass.php index 30c50185b2c8..c7d86dada96e 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/NullableClass.php +++ b/samples/client/petstore/php/psr-18/lib/Model/NullableClass.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -100,17 +100,17 @@ class NullableClass implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'integer_prop' => true, - 'number_prop' => true, - 'boolean_prop' => true, - 'string_prop' => true, - 'date_prop' => true, - 'datetime_prop' => true, - 'array_nullable_prop' => true, - 'array_and_items_nullable_prop' => true, - 'array_items_nullable' => false, - 'object_nullable_prop' => true, - 'object_and_items_nullable_prop' => true, - 'object_items_nullable' => false + 'number_prop' => true, + 'boolean_prop' => true, + 'string_prop' => true, + 'date_prop' => true, + 'datetime_prop' => true, + 'array_nullable_prop' => true, + 'array_and_items_nullable_prop' => true, + 'array_items_nullable' => false, + 'object_nullable_prop' => true, + 'object_and_items_nullable_prop' => true, + 'object_items_nullable' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/NumberOnly.php b/samples/client/petstore/php/psr-18/lib/Model/NumberOnly.php index bb529455e718..24c28259ba95 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/NumberOnly.php +++ b/samples/client/petstore/php/psr-18/lib/Model/NumberOnly.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ObjectWithDeprecatedFields.php b/samples/client/petstore/php/psr-18/lib/Model/ObjectWithDeprecatedFields.php index 3f0c6a61c8bb..54cc48135f33 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ObjectWithDeprecatedFields.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ObjectWithDeprecatedFields.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class ObjectWithDeprecatedFields implements ModelInterface, ArrayAccess, \JsonSe */ protected static array $openAPINullables = [ 'uuid' => false, - 'id' => false, - 'deprecated_ref' => false, - 'bars' => false + 'id' => false, + 'deprecated_ref' => false, + 'bars' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Order.php b/samples/client/petstore/php/psr-18/lib/Model/Order.php index 502b8bbc944a..f56b6c308f75 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Order.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Order.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Order implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'pet_id' => false, - 'quantity' => false, - 'ship_date' => false, - 'status' => false, - 'complete' => false + 'pet_id' => false, + 'quantity' => false, + 'ship_date' => false, + 'status' => false, + 'complete' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterComposite.php b/samples/client/petstore/php/psr-18/lib/Model/OuterComposite.php index 4d8bc042776a..ddc9c396dfa9 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterComposite.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterComposite.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -82,8 +82,8 @@ class OuterComposite implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'my_number' => false, - 'my_string' => false, - 'my_boolean' => false + 'my_string' => false, + 'my_boolean' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterEnum.php b/samples/client/petstore/php/psr-18/lib/Model/OuterEnum.php index 1853560c9003..c7c2c614f678 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterEnum.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterEnum.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumDefaultValue.php b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumDefaultValue.php index 7fab44f133f9..664e5914401f 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumDefaultValue.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumInteger.php b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumInteger.php index cd1f81768b34..859de958fc5b 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumInteger.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumInteger.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumIntegerDefaultValue.php b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumIntegerDefaultValue.php index fdfd64c90050..c196c08dfd61 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterEnumIntegerDefaultValue.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterEnumIntegerDefaultValue.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/OuterObjectWithEnumProperty.php b/samples/client/petstore/php/psr-18/lib/Model/OuterObjectWithEnumProperty.php index dc1ae0ca9977..ba475165e28e 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/OuterObjectWithEnumProperty.php +++ b/samples/client/petstore/php/psr-18/lib/Model/OuterObjectWithEnumProperty.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Pet.php b/samples/client/petstore/php/psr-18/lib/Model/Pet.php index 8075da54d28c..c1f9f7304a7d 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Pet.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Pet.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -88,11 +88,11 @@ class Pet implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'category' => false, - 'name' => false, - 'photo_urls' => false, - 'tags' => false, - 'status' => false + 'category' => false, + 'name' => false, + 'photo_urls' => false, + 'tags' => false, + 'status' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/PropertyNameMapping.php b/samples/client/petstore/php/psr-18/lib/Model/PropertyNameMapping.php index e97fa27d01b4..93507a5fddeb 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/PropertyNameMapping.php +++ b/samples/client/petstore/php/psr-18/lib/Model/PropertyNameMapping.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -84,9 +84,9 @@ class PropertyNameMapping implements ModelInterface, ArrayAccess, \JsonSerializa */ protected static array $openAPINullables = [ 'http_debug_operation' => false, - 'underscore_type' => false, - 'type' => false, - 'type_with_underscore' => false + 'underscore_type' => false, + 'type' => false, + 'type_with_underscore' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/ReadOnlyFirst.php b/samples/client/petstore/php/psr-18/lib/Model/ReadOnlyFirst.php index 9d0e8cd97a8a..1fab9ca08b86 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/ReadOnlyFirst.php +++ b/samples/client/petstore/php/psr-18/lib/Model/ReadOnlyFirst.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class ReadOnlyFirst implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'bar' => false, - 'baz' => false + 'baz' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/SingleRefType.php b/samples/client/petstore/php/psr-18/lib/Model/SingleRefType.php index 5f579dcbc944..cc490edd942b 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/SingleRefType.php +++ b/samples/client/petstore/php/psr-18/lib/Model/SingleRefType.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/SpecialModelName.php b/samples/client/petstore/php/psr-18/lib/Model/SpecialModelName.php index 61906b54f35a..c8acd2605844 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/SpecialModelName.php +++ b/samples/client/petstore/php/psr-18/lib/Model/SpecialModelName.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/Tag.php b/samples/client/petstore/php/psr-18/lib/Model/Tag.php index f016bc201443..d4a918f0b0fc 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/Tag.php +++ b/samples/client/petstore/php/psr-18/lib/Model/Tag.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -80,7 +80,7 @@ class Tag implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'name' => false + 'name' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php b/samples/client/petstore/php/psr-18/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php index e2cd3f6295cc..1d15342fabb8 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php +++ b/samples/client/petstore/php/psr-18/lib/Model/TestInlineFreeformAdditionalPropertiesRequest.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/php/psr-18/lib/Model/User.php b/samples/client/petstore/php/psr-18/lib/Model/User.php index f78bfc93a3f8..d7fa21bd8ef6 100644 --- a/samples/client/petstore/php/psr-18/lib/Model/User.php +++ b/samples/client/petstore/php/psr-18/lib/Model/User.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** @@ -92,13 +92,13 @@ class User implements ModelInterface, ArrayAccess, \JsonSerializable */ protected static array $openAPINullables = [ 'id' => false, - 'username' => false, - 'first_name' => false, - 'last_name' => false, - 'email' => false, - 'password' => false, - 'phone' => false, - 'user_status' => false + 'username' => false, + 'first_name' => false, + 'last_name' => false, + 'email' => false, + 'password' => false, + 'phone' => false, + 'user_status' => false ]; /** diff --git a/samples/client/petstore/php/psr-18/lib/ObjectSerializer.php b/samples/client/petstore/php/psr-18/lib/ObjectSerializer.php index 8398f415c99c..39ca3b962208 100644 --- a/samples/client/petstore/php/psr-18/lib/ObjectSerializer.php +++ b/samples/client/petstore/php/psr-18/lib/ObjectSerializer.php @@ -17,7 +17,7 @@ * * The version of the OpenAPI document: 1.0.0 * Generated by: https://openapi-generator.tech - * OpenAPI Generator version: 7.1.0-SNAPSHOT + * OpenAPI Generator version: 7.3.0-SNAPSHOT */ /** diff --git a/samples/client/petstore/powershell/.openapi-generator/VERSION b/samples/client/petstore/powershell/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/powershell/.openapi-generator/VERSION +++ b/samples/client/petstore/powershell/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/powershell/Build.ps1 b/samples/client/petstore/powershell/Build.ps1 index e15418c3aadf..81c67431bdbf 100644 --- a/samples/client/petstore/powershell/Build.ps1 +++ b/samples/client/petstore/powershell/Build.ps1 @@ -45,7 +45,9 @@ function Get-FunctionsToExport { } $ScriptDir = Split-Path $script:MyInvocation.MyCommand.Path -$FunctionPath = 'Api', 'Model', 'Client' | ForEach-Object {Join-Path "$ScriptDir\src\PSPetstore\" $_} +$FunctionPath = 'Api', 'Model', 'Client' | Where-Object { + Join-Path "$ScriptDir\src\PSPetstore\" $_ | Test-Path +} | ForEach-Object { Join-Path "$ScriptDir\src\PSPetstore\" $_ } $Manifest = @{ Path = "$ScriptDir\src\PSPetstore\PSPetstore.psd1" diff --git a/samples/client/petstore/powershell/README.md b/samples/client/petstore/powershell/README.md index 57c663aae01d..d2cc11fce52b 100644 --- a/samples/client/petstore/powershell/README.md +++ b/samples/client/petstore/powershell/README.md @@ -63,6 +63,7 @@ Class | Method | HTTP request | Description *PSFakeApi* | [**Invoke-PSFakeOuterNumberSerialize**](docs/PSFakeApi.md#Invoke-PSFakeOuterNumberSerialize) | **POST** /fake/outer/number | *PSFakeApi* | [**Invoke-PSFakeOuterStringSerialize**](docs/PSFakeApi.md#Invoke-PSFakeOuterStringSerialize) | **POST** /fake/outer/string | *PSFakeApi* | [**Get-PSArrayOfEnums**](docs/PSFakeApi.md#Get-PSArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*PSFakeApi* | [**Test-PSAdditionalPropertiesReference**](docs/PSFakeApi.md#Test-PSAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *PSFakeApi* | [**Test-PSBodyWithFileSchema**](docs/PSFakeApi.md#Test-PSBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *PSFakeApi* | [**Test-PSBodyWithQueryParams**](docs/PSFakeApi.md#Test-PSBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *PSFakeApi* | [**Test-PSClientModel**](docs/PSFakeApi.md#Test-PSClientModel) | **PATCH** /fake | To test ""client"" model @@ -196,7 +197,7 @@ Authentication schemes defined for the API: - **Type**: API key -- **API key parameter name**: api_key +- **API key parameter name**: api_key_name - **Location**: HTTP header @@ -204,7 +205,7 @@ Authentication schemes defined for the API: - **Type**: API key -- **API key parameter name**: api_key_query +- **API key parameter name**: api_key_query_name - **Location**: URL query string diff --git a/samples/client/petstore/powershell/docs/PSFakeApi.md b/samples/client/petstore/powershell/docs/PSFakeApi.md index cfa337e34478..7b199fd9e021 100644 --- a/samples/client/petstore/powershell/docs/PSFakeApi.md +++ b/samples/client/petstore/powershell/docs/PSFakeApi.md @@ -10,6 +10,7 @@ Method | HTTP request | Description [**Invoke-PSFakeOuterNumberSerialize**](PSFakeApi.md#Invoke-PSFakeOuterNumberSerialize) | **POST** /fake/outer/number | [**Invoke-PSFakeOuterStringSerialize**](PSFakeApi.md#Invoke-PSFakeOuterStringSerialize) | **POST** /fake/outer/string | [**Get-PSArrayOfEnums**](PSFakeApi.md#Get-PSArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +[**Test-PSAdditionalPropertiesReference**](PSFakeApi.md#Test-PSAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**Test-PSBodyWithFileSchema**](PSFakeApi.md#Test-PSBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | [**Test-PSBodyWithQueryParams**](PSFakeApi.md#Test-PSBodyWithQueryParams) | **PUT** /fake/body-with-query-params | [**Test-PSClientModel**](PSFakeApi.md#Test-PSClientModel) | **PATCH** /fake | To test ""client"" model @@ -262,6 +263,49 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + +# **Test-PSAdditionalPropertiesReference** +> void Test-PSAdditionalPropertiesReference
              +>         [-RequestBody]
              + +test referenced additionalProperties + + + +### Example +```powershell +$RequestBody = @{ key_example = } # System.Collections.Hashtable | request body + +# test referenced additionalProperties +try { + $Result = Test-PSAdditionalPropertiesReference -RequestBody $RequestBody +} catch { + Write-Host ("Exception occurred when calling Test-PSAdditionalPropertiesReference: {0}" -f ($_.ErrorDetails | ConvertFrom-Json)) + Write-Host ("Response headers: {0}" -f ($_.Exception.Response.Headers | ConvertTo-Json)) +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **RequestBody** | [**System.Collections.Hashtable**](AnyType.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **Test-PSBodyWithFileSchema** > void Test-PSBodyWithFileSchema
              diff --git a/samples/client/petstore/powershell/docs/PSFakeClassnameTags123Api.md b/samples/client/petstore/powershell/docs/PSFakeClassnameTags123Api.md index 9da7ec300016..02bfd8628a25 100644 --- a/samples/client/petstore/powershell/docs/PSFakeClassnameTags123Api.md +++ b/samples/client/petstore/powershell/docs/PSFakeClassnameTags123Api.md @@ -21,9 +21,9 @@ To test class name in snake case # general setting of the PowerShell module, e.g. base URL, authentication, etc $Configuration = Get-Configuration # Configure API key authorization: api_key_query -$Configuration.ApiKey.api_key_query = "YOUR_API_KEY" +$Configuration.ApiKey.api_key_query_name = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$Configuration.ApiKeyPrefix.api_key_query = "Bearer" +#$Configuration.ApiKeyPrefix.api_key_query_name = "Bearer" $Client = Initialize-Client -Client "MyClient" # Client | client model diff --git a/samples/client/petstore/powershell/docs/PSPetApi.md b/samples/client/petstore/powershell/docs/PSPetApi.md index 6fc29288adfc..48d7f783ce4c 100644 --- a/samples/client/petstore/powershell/docs/PSPetApi.md +++ b/samples/client/petstore/powershell/docs/PSPetApi.md @@ -253,9 +253,9 @@ Returns a single pet # general setting of the PowerShell module, e.g. base URL, authentication, etc $Configuration = Get-Configuration # Configure API key authorization: api_key -$Configuration.ApiKey.api_key = "YOUR_API_KEY" +$Configuration.ApiKey.api_key_name = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$Configuration.ApiKeyPrefix.api_key = "Bearer" +#$Configuration.ApiKeyPrefix.api_key_name = "Bearer" $PetId = 789 # Int64 | ID of pet to return diff --git a/samples/client/petstore/powershell/docs/PSStoreApi.md b/samples/client/petstore/powershell/docs/PSStoreApi.md index 3d192a300182..2ff14209a049 100644 --- a/samples/client/petstore/powershell/docs/PSStoreApi.md +++ b/samples/client/petstore/powershell/docs/PSStoreApi.md @@ -66,9 +66,9 @@ Returns a map of status codes to quantities # general setting of the PowerShell module, e.g. base URL, authentication, etc $Configuration = Get-Configuration # Configure API key authorization: api_key -$Configuration.ApiKey.api_key = "YOUR_API_KEY" +$Configuration.ApiKey.api_key_name = "YOUR_API_KEY" # Uncomment below to setup prefix (e.g. Bearer) for API key, if needed -#$Configuration.ApiKeyPrefix.api_key = "Bearer" +#$Configuration.ApiKeyPrefix.api_key_name = "Bearer" # Returns pet inventories by status diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeApi.ps1 index 33edac7ec1bd..c68a87293dff 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeApi.ps1 @@ -430,6 +430,81 @@ function Get-PSArrayOfEnums { <# .SYNOPSIS +test referenced additionalProperties + +.DESCRIPTION + +No description available. + +.PARAMETER RequestBody +request body + +.PARAMETER WithHttpInfo + +A switch when turned on will return a hash table of Response, StatusCode and Headers instead of just the Response + +.OUTPUTS + +None +#> +function Test-PSAdditionalPropertiesReference { + [CmdletBinding()] + Param ( + [Parameter(Position = 0, ValueFromPipeline = $true, ValueFromPipelineByPropertyName = $true, Mandatory = $false)] + [System.Collections.Hashtable] + ${RequestBody}, + [Switch] + $WithHttpInfo + ) + + Process { + 'Calling method: Test-PSAdditionalPropertiesReference' | Write-Debug + $PSBoundParameters | Out-DebugParameter | Write-Debug + + $LocalVarAccepts = @() + $LocalVarContentTypes = @() + $LocalVarQueryParameters = @{} + $LocalVarHeaderParameters = @{} + $LocalVarFormParameters = @{} + $LocalVarPathParameters = @{} + $LocalVarCookieParameters = @{} + $LocalVarBodyParameter = $null + + $Configuration = Get-PSConfiguration + # HTTP header 'Content-Type' + $LocalVarContentTypes = @('application/json') + + $LocalVarUri = '/fake/additionalProperties-reference' + + if (!$RequestBody) { + throw "Error! The required parameter `RequestBody` missing when calling testAdditionalPropertiesReference." + } + + $LocalVarBodyParameter = $RequestBody | ConvertTo-Json -Depth 100 + + $LocalVarResult = Invoke-PSApiClient -Method 'POST' ` + -Uri $LocalVarUri ` + -Accepts $LocalVarAccepts ` + -ContentTypes $LocalVarContentTypes ` + -Body $LocalVarBodyParameter ` + -HeaderParameters $LocalVarHeaderParameters ` + -QueryParameters $LocalVarQueryParameters ` + -FormParameters $LocalVarFormParameters ` + -CookieParameters $LocalVarCookieParameters ` + -ReturnType "" ` + -IsBodyNullable $false + + if ($WithHttpInfo.IsPresent) { + return $LocalVarResult + } else { + return $LocalVarResult["Response"] + } + } +} + +<# +.SYNOPSIS + No summary available. .DESCRIPTION diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeClassnameTags123Api.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeClassnameTags123Api.ps1 index 35f1186fcce4..0ffb6cd7f3b3 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeClassnameTags123Api.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSFakeClassnameTags123Api.ps1 @@ -63,9 +63,9 @@ function Test-PSClassname { $LocalVarBodyParameter = $Client | ConvertTo-Json -Depth 100 - if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key_query"]) { - $LocalVarQueryParameters['api_key_query'] = $Configuration["ApiKey"]["api_key_query"] - Write-Verbose ("Using API key `api_key_query` in the URL query for authentication in {0}" -f $MyInvocation.MyCommand) + if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key_query_name"]) { + $LocalVarQueryParameters['api_key_query_name'] = $Configuration["ApiKey"]["api_key_query_name"] + Write-Verbose ("Using API key `api_key_query_name` in the URL query for authentication in {0}" -f $MyInvocation.MyCommand) } $LocalVarResult = Invoke-PSApiClient -Method 'PATCH' ` diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 index 3542112c914d..e28ffcabca08 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSPetApi.ps1 @@ -405,9 +405,9 @@ function Get-PSPetById { } $LocalVarUri = $LocalVarUri.replace('{petId}', [System.Web.HTTPUtility]::UrlEncode($PetId)) - if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key"]) { - $LocalVarHeaderParameters['api_key'] = $Configuration["ApiKey"]["api_key"] - Write-Verbose ("Using API key 'api_key' in the header for authentication in {0}" -f $MyInvocation.MyCommand) + if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key_name"]) { + $LocalVarHeaderParameters['api_key_name'] = $Configuration["ApiKey"]["api_key_name"] + Write-Verbose ("Using API key 'api_key_name' in the header for authentication in {0}" -f $MyInvocation.MyCommand) } $LocalVarResult = Invoke-PSApiClient -Method 'GET' ` diff --git a/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 index a0f88138a48d..40fd1e0c64f6 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Api/PSStoreApi.ps1 @@ -118,9 +118,9 @@ function Get-PSInventory { $LocalVarUri = '/store/inventory' - if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key"]) { - $LocalVarHeaderParameters['api_key'] = $Configuration["ApiKey"]["api_key"] - Write-Verbose ("Using API key 'api_key' in the header for authentication in {0}" -f $MyInvocation.MyCommand) + if ($Configuration["ApiKey"] -and $Configuration["ApiKey"]["api_key_name"]) { + $LocalVarHeaderParameters['api_key_name'] = $Configuration["ApiKey"]["api_key_name"] + Write-Verbose ("Using API key 'api_key_name' in the header for authentication in {0}" -f $MyInvocation.MyCommand) } $LocalVarResult = Invoke-PSApiClient -Method 'GET' ` diff --git a/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 b/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 index 8b0bd5f780e4..486b345ebc11 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 +++ b/samples/client/petstore/powershell/src/PSPetstore/PSPetstore.psm1 @@ -23,7 +23,9 @@ $Script:Configuration = [System.Collections.HashTable]@{} $Script:CmdletBindingParameters = @('Verbose','Debug','ErrorAction','WarningAction','InformationAction','ErrorVariable','WarningVariable','InformationVariable','OutVariable','OutBuffer','PipelineVariable') -'Api', 'Model', 'Client', 'Private' | Get-ChildItem -Path { +'Api', 'Model', 'Client', 'Private' | Where-Object { + Join-Path $PSScriptRoot $_ | Test-Path +} | Get-ChildItem -Path { Join-Path $PSScriptRoot $_ } -Filter '*.ps1' | ForEach-Object { Write-Debug "Importing file: $($_.BaseName)" diff --git a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 index ce637871f545..048cb4138a3b 100644 --- a/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 +++ b/samples/client/petstore/powershell/src/PSPetstore/Private/PSApiClient.ps1 @@ -192,7 +192,7 @@ function Invoke-PSApiClient { } return @{ - Response = DeserializeResponse -Response $Response -ReturnType $ReturnType -ContentTypes $Response.Headers["Content-Type"] + Response = DeserializeResponse -Response $Response.Content -ReturnType $ReturnType -ContentTypes $Response.Headers["Content-Type"] StatusCode = $Response.StatusCode Headers = $Response.Headers } diff --git a/samples/client/petstore/ruby-autoload/.openapi-generator/FILES b/samples/client/petstore/ruby-autoload/.openapi-generator/FILES index fc02f30778d3..7dbd2fdcd849 100644 --- a/samples/client/petstore/ruby-autoload/.openapi-generator/FILES +++ b/samples/client/petstore/ruby-autoload/.openapi-generator/FILES @@ -127,6 +127,4 @@ lib/petstore/models/test_inline_freeform_additional_properties_request.rb lib/petstore/models/user.rb lib/petstore/version.rb petstore.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION b/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby-autoload/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby-autoload/README.md b/samples/client/petstore/ruby-autoload/README.md index 2eec0459c1eb..8556b62fc360 100644 --- a/samples/client/petstore/ruby-autoload/README.md +++ b/samples/client/petstore/ruby-autoload/README.md @@ -85,6 +85,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*Petstore::FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/ruby-autoload/docs/FakeApi.md b/samples/client/petstore/ruby-autoload/docs/FakeApi.md index f43e4402cf1e..bb3486f585a4 100644 --- a/samples/client/petstore/ruby-autoload/docs/FakeApi.md +++ b/samples/client/petstore/ruby-autoload/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | +| [**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | @@ -544,6 +545,69 @@ No authorization required - **Accept**: */* +## test_additional_properties_reference + +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +request_body = { key: 3.56} # Hash | request body + +begin + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference: #{e}" +end +``` + +#### Using the test_additional_properties_reference_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_additional_properties_reference_with_http_info(request_body) + +```ruby +begin + # test referenced additionalProperties + data, status_code, headers = api_instance.test_additional_properties_reference_with_http_info(request_body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **request_body** | [**Hash<String, Object>**](Object.md) | request body | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## test_body_with_binary > test_body_with_binary(body) diff --git a/samples/client/petstore/ruby-autoload/lib/petstore.rb b/samples/client/petstore/ruby-autoload/lib/petstore.rb index cac10c9f0429..2bd86356525f 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb index a3bdc5af0bfc..bf065b030353 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb index f9fc19208aae..224ceda35bc1 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb index e3235d6990d6..68efaa01be7c 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -513,6 +513,72 @@ def fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_p return data, status_code, headers end + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_additional_properties_reference(request_body, opts = {}) + test_additional_properties_reference_with_http_info(request_body, opts) + nil + end + + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_additional_properties_reference_with_http_info(request_body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_additional_properties_reference ...' + end + # verify the required parameter 'request_body' is set + if @api_client.config.client_side_validation && request_body.nil? + fail ArgumentError, "Missing the required parameter 'request_body' when calling FakeApi.test_additional_properties_reference" + end + # resource path + local_var_path = '/fake/additionalProperties-reference' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(request_body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_additional_properties_reference", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_additional_properties_reference\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # For this test, the body has to be a binary file. # @param body [File] image to upload # @param [Hash] opts the optional parameters diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb index 3665b1137909..65bf53341469 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb index 9af0ed2672ec..e8d070b57577 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb index c23d44c56978..3948b8c08931 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb index 5b28f84953d8..13b69ff3714c 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb index f4a681dc6d28..2a8a22fe5a7c 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -46,9 +46,10 @@ def self.default # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -70,7 +71,9 @@ def call_api(http_method, path, opts = {}) end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -126,9 +129,7 @@ def build_request(http_method, path, opts = {}) end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -166,6 +167,8 @@ def build_request_body(header_params, form_params, body) # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -180,21 +183,24 @@ def download_file(request) prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end # Check if the given MIME is a JSON MIME. @@ -215,11 +221,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - return @tempfile if return_type == 'File' - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb b/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb index e220ece388a7..afd037d88fb9 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb b/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb index 674c9c447b6b..33e0fac3dfab 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb index c28fba75cbf2..0b59df2971fb 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -172,7 +172,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb index 99c49ee3e411..203c5fac9b3b 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/all_of_with_single_ref.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -190,7 +190,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb index 38c3e4ae50cc..a668fa9ea8a2 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -182,7 +182,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb index 3f05081ca8f5..5e0b22e68402 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb index e3fc21969343..58fa7bef8697 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb index c84931a3d2c8..2de31dbf84f6 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb index 3d4fe2a619b7..24e152f8b0de 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -211,7 +211,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb index 535ca7697ba4..2be58edd6d18 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -205,7 +205,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb index ddc6268f1752..efabf4cfeed7 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb index 029ecca4bf60..7b6d807111f9 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -175,7 +175,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/child_with_nullable.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/child_with_nullable.rb index a40a99e9b457..78bc9167e989 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/child_with_nullable.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/child_with_nullable.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -192,7 +192,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb index a69c0c3d8b18..6ef7b4730fcd 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb index d100b51d25eb..47bc5190c667 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb index c13b9812ce80..6170efcd6bba 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/deprecated_object.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb index baf8aed83aee..00ad6f159738 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb index b53d022ccbed..056ba338eea2 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -204,7 +204,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb index f842e0f451fa..5f8a25a8c7af 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb index f71d804b6d59..7e73f2f64027 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -304,7 +304,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/fake_big_decimal_map200_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/fake_big_decimal_map200_response.rb index 2e84764f47fd..d2000057c543 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/fake_big_decimal_map200_response.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/fake_big_decimal_map200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb index af161d8f6319..adf005d83895 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb index b4cc94be47b5..d286737cf28f 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb index 76988fd3cd5c..b9518f3f190e 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb index d50fec9cd9fd..7865e3b72ef4 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/foo_get_default_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb index f6da236ae5b7..3692050befbf 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -555,7 +555,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb index 9d82934d22e1..2edacc4318fb 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb index b850e8623c68..bbef6f643291 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb index ef3adc399fe4..85fbbc2e0196 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb index 0ced89f3c867..3e9e75a68740 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -216,7 +216,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index ad1a5b472351..f1e4d3dab002 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -179,7 +179,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb index 4d318df4c90f..a887433e91fa 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -169,7 +169,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb index ef0c65b55d8e..1bd93f188603 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb index a189793a3811..2175dcd1b90c 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -194,7 +194,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb index 5748150ee607..d45f6e70b6f4 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -280,7 +280,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb index 341193e3f17c..427eeee115b0 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb index 5df34bc5a128..21e9d84456cc 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/object_with_deprecated_fields.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb index 6d4ea1c77a7c..5b717adf1c16 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -241,7 +241,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb index bcb2334d38ad..983bd5b1ed24 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb index 09837aa4f28d..4b36df834005 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb index 4dde4e1d3e16..e40b9a7f7511 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb index 93b24aac3a51..f76dfb3786d6 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb index 9100aff19e13..99e45dc78a0c 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb index 1dd612ccaca5..471f9802d704 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/parent_with_nullable.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/parent_with_nullable.rb index 66ab22b8976c..6f85d343427e 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/parent_with_nullable.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/parent_with_nullable.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -208,7 +208,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb index e0bb197e8e69..dd7f9e4f8931 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -267,7 +267,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb index 46853a3feeee..44f10e959400 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb index ecccade2f191..2f9d950f5967 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/single_ref_type.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb index 07ede6cffe38..4e6b02341295 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb index 47cc6ac04379..71148ab081ed 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/test_inline_freeform_additional_properties_request.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/test_inline_freeform_additional_properties_request.rb index bf7c0b98a134..c13820d936b0 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/test_inline_freeform_additional_properties_request.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/test_inline_freeform_additional_properties_request.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb b/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb index 4045f639bcbf..b7e621ed365a 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -223,7 +223,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-autoload/lib/petstore/version.rb b/samples/client/petstore/ruby-autoload/lib/petstore/version.rb index 3d342d87a32f..8b40799d224a 100644 --- a/samples/client/petstore/ruby-autoload/lib/petstore/version.rb +++ b/samples/client/petstore/ruby-autoload/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/petstore.gemspec b/samples/client/petstore/ruby-autoload/petstore.gemspec index d5420ccb8bea..b5bd482b8feb 100644 --- a/samples/client/petstore/ruby-autoload/petstore.gemspec +++ b/samples/client/petstore/ruby-autoload/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb b/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb index ffa7f281caf8..27fce7602fb0 100644 --- a/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby-autoload/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb b/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb index c61e6f00029a..1075efa811bb 100644 --- a/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby-autoload/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-autoload/spec/spec_helper.rb b/samples/client/petstore/ruby-autoload/spec/spec_helper.rb index 5cd856c95041..db7155ecfb5d 100644 --- a/samples/client/petstore/ruby-autoload/spec/spec_helper.rb +++ b/samples/client/petstore/ruby-autoload/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/.openapi-generator/FILES b/samples/client/petstore/ruby-faraday/.openapi-generator/FILES index fc02f30778d3..7dbd2fdcd849 100644 --- a/samples/client/petstore/ruby-faraday/.openapi-generator/FILES +++ b/samples/client/petstore/ruby-faraday/.openapi-generator/FILES @@ -127,6 +127,4 @@ lib/petstore/models/test_inline_freeform_additional_properties_request.rb lib/petstore/models/user.rb lib/petstore/version.rb petstore.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby-faraday/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby-faraday/README.md b/samples/client/petstore/ruby-faraday/README.md index 2eec0459c1eb..8556b62fc360 100644 --- a/samples/client/petstore/ruby-faraday/README.md +++ b/samples/client/petstore/ruby-faraday/README.md @@ -85,6 +85,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*Petstore::FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | diff --git a/samples/client/petstore/ruby-faraday/docs/FakeApi.md b/samples/client/petstore/ruby-faraday/docs/FakeApi.md index f43e4402cf1e..bb3486f585a4 100644 --- a/samples/client/petstore/ruby-faraday/docs/FakeApi.md +++ b/samples/client/petstore/ruby-faraday/docs/FakeApi.md @@ -12,6 +12,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | | | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | +| [**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | @@ -544,6 +545,69 @@ No authorization required - **Accept**: */* +## test_additional_properties_reference + +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +request_body = { key: 3.56} # Hash | request body + +begin + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference: #{e}" +end +``` + +#### Using the test_additional_properties_reference_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_additional_properties_reference_with_http_info(request_body) + +```ruby +begin + # test referenced additionalProperties + data, status_code, headers = api_instance.test_additional_properties_reference_with_http_info(request_body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **request_body** | [**Hash<String, Object>**](Object.md) | request body | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## test_body_with_binary > test_body_with_binary(body) diff --git a/samples/client/petstore/ruby-faraday/lib/petstore.rb b/samples/client/petstore/ruby-faraday/lib/petstore.rb index 1eb267a633dc..774213f48bcb 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb index a3bdc5af0bfc..bf065b030353 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb index f9fc19208aae..224ceda35bc1 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb index e3235d6990d6..68efaa01be7c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -513,6 +513,72 @@ def fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_p return data, status_code, headers end + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_additional_properties_reference(request_body, opts = {}) + test_additional_properties_reference_with_http_info(request_body, opts) + nil + end + + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_additional_properties_reference_with_http_info(request_body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_additional_properties_reference ...' + end + # verify the required parameter 'request_body' is set + if @api_client.config.client_side_validation && request_body.nil? + fail ArgumentError, "Missing the required parameter 'request_body' when calling FakeApi.test_additional_properties_reference" + end + # resource path + local_var_path = '/fake/additionalProperties-reference' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(request_body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_additional_properties_reference", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_additional_properties_reference\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # For this test, the body has to be a binary file. # @param body [File] image to upload # @param [Hash] opts the optional parameters diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb index 3665b1137909..65bf53341469 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb index c3972cea110b..1ca4010974ec 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb index df4f0c3f7e81..68614eff5d8c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb index 9c4d48a96059..e93ec98c59e4 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb index cb459fa90561..02a87ca9ba52 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -49,9 +49,11 @@ def self.default # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: # the data deserialized from response body (could be nil), response status code and response headers. def call_api(http_method, path, opts = {}) + stream = nil begin response = connection(opts).public_send(http_method.to_sym.downcase) do |req| - build_request(http_method, path, req, opts) + request = build_request(http_method, path, req, opts) + stream = download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' end if config.debugging @@ -76,7 +78,9 @@ def call_api(http_method, path, opts = {}) fail ApiError.new('Connection failed') end - if opts[:return_type] + if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' + data = deserialize_file(response, stream) + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -118,7 +122,6 @@ def build_request(http_method, path, request, opts = {}) request.url url request.params = query_params - download_file(request) if opts[:return_type] == 'File' || opts[:return_type] == 'Binary' request end @@ -155,11 +158,40 @@ def build_request_body(header_params, form_params, body) end def download_file(request) - @stream = [] + stream = [] # handle streaming Responses request.options.on_data = Proc.new do |chunk, overall_received_bytes| - @stream << chunk + stream << chunk + end + stream + end + + def deserialize_file(response, stream) + body = response.body + if @config.return_binary_data == true + # return byte stream + encoding = body.encoding + stream.join.force_encoding(encoding) + else + # return file instead of binary data + content_disposition = response.headers['Content-Disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + tempfile.write(stream.join.force_encoding(encoding)) + tempfile.close + config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + tempfile end end @@ -226,36 +258,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - if return_type == 'File' - if @config.return_binary_data == true - # return byte stream - encoding = body.encoding - return @stream.join.force_encoding(encoding) - else - # return file instead of binary data - content_disposition = response.headers['Content-Disposition'] - if content_disposition && content_disposition =~ /filename=/i - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - prefix = sanitize_filename(filename) - else - prefix = 'download-' - end - prefix = prefix + '-' unless prefix.end_with?('-') - encoding = body.encoding - @tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile.write(@stream.join.force_encoding(encoding)) - @tempfile.close - @config.logger.info "Temp file written to #{@tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - return @tempfile - end - end - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb b/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb index e220ece388a7..afd037d88fb9 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb index f8ebe7e88bbe..45d94eb693d3 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb index c28fba75cbf2..0b59df2971fb 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -172,7 +172,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb index 99c49ee3e411..203c5fac9b3b 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/all_of_with_single_ref.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -190,7 +190,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb index 38c3e4ae50cc..a668fa9ea8a2 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -182,7 +182,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb index 3f05081ca8f5..5e0b22e68402 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb index e3fc21969343..58fa7bef8697 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb index c84931a3d2c8..2de31dbf84f6 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb index 3d4fe2a619b7..24e152f8b0de 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -211,7 +211,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb index 535ca7697ba4..2be58edd6d18 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -205,7 +205,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb index ddc6268f1752..efabf4cfeed7 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb index 029ecca4bf60..7b6d807111f9 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -175,7 +175,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/child_with_nullable.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/child_with_nullable.rb index a40a99e9b457..78bc9167e989 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/child_with_nullable.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/child_with_nullable.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -192,7 +192,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb index a69c0c3d8b18..6ef7b4730fcd 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb index d100b51d25eb..47bc5190c667 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/deprecated_object.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/deprecated_object.rb index c13b9812ce80..6170efcd6bba 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/deprecated_object.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/deprecated_object.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb index baf8aed83aee..00ad6f159738 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb index b53d022ccbed..056ba338eea2 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -204,7 +204,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb index f842e0f451fa..5f8a25a8c7af 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb index f71d804b6d59..7e73f2f64027 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -304,7 +304,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/fake_big_decimal_map200_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/fake_big_decimal_map200_response.rb index 2e84764f47fd..d2000057c543 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/fake_big_decimal_map200_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/fake_big_decimal_map200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb index af161d8f6319..adf005d83895 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb index b4cc94be47b5..d286737cf28f 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb index 76988fd3cd5c..b9518f3f190e 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo_get_default_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo_get_default_response.rb index d50fec9cd9fd..7865e3b72ef4 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/foo_get_default_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/foo_get_default_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb index f6da236ae5b7..3692050befbf 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -555,7 +555,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb index 9d82934d22e1..2edacc4318fb 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb index b850e8623c68..bbef6f643291 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb index ef3adc399fe4..85fbbc2e0196 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb index 0ced89f3c867..3e9e75a68740 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -216,7 +216,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index ad1a5b472351..f1e4d3dab002 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -179,7 +179,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb index 4d318df4c90f..a887433e91fa 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -169,7 +169,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb index ef0c65b55d8e..1bd93f188603 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb index a189793a3811..2175dcd1b90c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -194,7 +194,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb index 5748150ee607..d45f6e70b6f4 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -280,7 +280,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb index 341193e3f17c..427eeee115b0 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/object_with_deprecated_fields.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/object_with_deprecated_fields.rb index 5df34bc5a128..21e9d84456cc 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/object_with_deprecated_fields.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/object_with_deprecated_fields.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb index 6d4ea1c77a7c..5b717adf1c16 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -241,7 +241,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb index bcb2334d38ad..983bd5b1ed24 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb index 09837aa4f28d..4b36df834005 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb index 4dde4e1d3e16..e40b9a7f7511 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb index 93b24aac3a51..f76dfb3786d6 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb index 9100aff19e13..99e45dc78a0c 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb index 1dd612ccaca5..471f9802d704 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/parent_with_nullable.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/parent_with_nullable.rb index 66ab22b8976c..6f85d343427e 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/parent_with_nullable.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/parent_with_nullable.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -208,7 +208,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb index e0bb197e8e69..dd7f9e4f8931 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -267,7 +267,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb index 46853a3feeee..44f10e959400 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb index ecccade2f191..2f9d950f5967 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/single_ref_type.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb index 07ede6cffe38..4e6b02341295 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb index 47cc6ac04379..71148ab081ed 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/test_inline_freeform_additional_properties_request.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/test_inline_freeform_additional_properties_request.rb index bf7c0b98a134..c13820d936b0 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/test_inline_freeform_additional_properties_request.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/test_inline_freeform_additional_properties_request.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb b/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb index 4045f639bcbf..b7e621ed365a 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -223,7 +223,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb index 3d342d87a32f..8b40799d224a 100644 --- a/samples/client/petstore/ruby-faraday/lib/petstore/version.rb +++ b/samples/client/petstore/ruby-faraday/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/petstore.gemspec b/samples/client/petstore/ruby-faraday/petstore.gemspec index 7540e70134be..015465ddda11 100644 --- a/samples/client/petstore/ruby-faraday/petstore.gemspec +++ b/samples/client/petstore/ruby-faraday/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'faraday', '>= 1.0.1', '< 3.0' s.add_runtime_dependency 'faraday-multipart' diff --git a/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb b/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb index ecee30aaec1b..302f1ff0f178 100644 --- a/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby-faraday/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb index 153cd92d5457..4e7a996994c1 100644 --- a/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby-faraday/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb index 5cd856c95041..db7155ecfb5d 100644 --- a/samples/client/petstore/ruby-faraday/spec/spec_helper.rb +++ b/samples/client/petstore/ruby-faraday/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/.openapi-generator/FILES b/samples/client/petstore/ruby-httpx/.openapi-generator/FILES index aa241d0edb50..937697a733e7 100644 --- a/samples/client/petstore/ruby-httpx/.openapi-generator/FILES +++ b/samples/client/petstore/ruby-httpx/.openapi-generator/FILES @@ -19,6 +19,7 @@ docs/Cat.md docs/Category.md docs/ClassModel.md docs/Client.md +docs/Cow.md docs/DefaultApi.md docs/DeprecatedObject.md docs/Dog.md @@ -36,6 +37,7 @@ docs/FormatTest.md docs/HasOnlyReadOnly.md docs/HealthCheckResult.md docs/List.md +docs/MamalWithEnum.md docs/Mammal.md docs/MammalAnyof.md docs/MammalWithoutDiscriminator.md @@ -91,6 +93,7 @@ lib/petstore/models/cat.rb lib/petstore/models/category.rb lib/petstore/models/class_model.rb lib/petstore/models/client.rb +lib/petstore/models/cow.rb lib/petstore/models/deprecated_object.rb lib/petstore/models/dog.rb lib/petstore/models/enum_arrays.rb @@ -105,6 +108,7 @@ lib/petstore/models/format_test.rb lib/petstore/models/has_only_read_only.rb lib/petstore/models/health_check_result.rb lib/petstore/models/list.rb +lib/petstore/models/mamal_with_enum.rb lib/petstore/models/mammal.rb lib/petstore/models/mammal_anyof.rb lib/petstore/models/mammal_without_discriminator.rb @@ -135,6 +139,4 @@ lib/petstore/models/whale.rb lib/petstore/models/zebra.rb lib/petstore/version.rb petstore.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/client/petstore/ruby-httpx/.openapi-generator/VERSION b/samples/client/petstore/ruby-httpx/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/ruby-httpx/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby-httpx/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby-httpx/README.md b/samples/client/petstore/ruby-httpx/README.md index 219e3ef720f9..daa2a6d5b0fa 100644 --- a/samples/client/petstore/ruby-httpx/README.md +++ b/samples/client/petstore/ruby-httpx/README.md @@ -86,6 +86,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | *Petstore::FakeApi* | [**get_parameter_name_mapping**](docs/FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*Petstore::FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | @@ -135,6 +136,7 @@ Class | Method | HTTP request | Description - [Petstore::Category](docs/Category.md) - [Petstore::ClassModel](docs/ClassModel.md) - [Petstore::Client](docs/Client.md) + - [Petstore::Cow](docs/Cow.md) - [Petstore::DeprecatedObject](docs/DeprecatedObject.md) - [Petstore::Dog](docs/Dog.md) - [Petstore::EnumArrays](docs/EnumArrays.md) @@ -149,6 +151,7 @@ Class | Method | HTTP request | Description - [Petstore::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - [Petstore::HealthCheckResult](docs/HealthCheckResult.md) - [Petstore::List](docs/List.md) + - [Petstore::MamalWithEnum](docs/MamalWithEnum.md) - [Petstore::Mammal](docs/Mammal.md) - [Petstore::MammalAnyof](docs/MammalAnyof.md) - [Petstore::MammalWithoutDiscriminator](docs/MammalWithoutDiscriminator.md) diff --git a/samples/client/petstore/ruby-httpx/docs/Cow.md b/samples/client/petstore/ruby-httpx/docs/Cow.md new file mode 100644 index 000000000000..6fa7084b8a40 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/docs/Cow.md @@ -0,0 +1,15 @@ +# Petstore::Cow + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Cow.new() +``` + diff --git a/samples/client/petstore/ruby-httpx/docs/FakeApi.md b/samples/client/petstore/ruby-httpx/docs/FakeApi.md index 2519c0fdfeda..b61148721ca3 100644 --- a/samples/client/petstore/ruby-httpx/docs/FakeApi.md +++ b/samples/client/petstore/ruby-httpx/docs/FakeApi.md @@ -13,6 +13,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | | [**get_parameter_name_mapping**](FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | +| [**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | @@ -611,6 +612,69 @@ No authorization required - **Accept**: Not defined +## test_additional_properties_reference + +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +request_body = { key: 3.56} # Hash | request body + +begin + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference: #{e}" +end +``` + +#### Using the test_additional_properties_reference_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_additional_properties_reference_with_http_info(request_body) + +```ruby +begin + # test referenced additionalProperties + data, status_code, headers = api_instance.test_additional_properties_reference_with_http_info(request_body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **request_body** | [**Hash<String, Object>**](Object.md) | request body | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## test_body_with_binary > test_body_with_binary(body) diff --git a/samples/client/petstore/ruby-httpx/docs/MamalWithEnum.md b/samples/client/petstore/ruby-httpx/docs/MamalWithEnum.md new file mode 100644 index 000000000000..37b9252a2c82 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/docs/MamalWithEnum.md @@ -0,0 +1,47 @@ +# Petstore::MamalWithEnum + +## Class instance methods + +### `openapi_one_of` + +Returns the list of classes defined in oneOf. + +#### Example + +```ruby +require 'petstore' + +Petstore::MamalWithEnum.openapi_one_of +# => +# [ +# :'Cow' +# ] +``` + +### build + +Find the appropriate object from the `openapi_one_of` list and casts the data into it. + +#### Example + +```ruby +require 'petstore' + +Petstore::MamalWithEnum.build(data) +# => # + +Petstore::MamalWithEnum.build(data_that_doesnt_match) +# => nil +``` + +#### Parameters + +| Name | Type | Description | +| ---- | ---- | ----------- | +| **data** | **Mixed** | data to be matched against the list of oneOf items | + +#### Return type + +- `Cow` +- `nil` (if no type matches) + diff --git a/samples/client/petstore/ruby-httpx/lib/petstore.rb b/samples/client/petstore/ruby-httpx/lib/petstore.rb index 058c4a4fffac..b6662f07ea56 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -28,6 +28,7 @@ require 'petstore/models/category' require 'petstore/models/class_model' require 'petstore/models/client' +require 'petstore/models/cow' require 'petstore/models/deprecated_object' require 'petstore/models/enum_arrays' require 'petstore/models/enum_class' @@ -41,6 +42,7 @@ require 'petstore/models/has_only_read_only' require 'petstore/models/health_check_result' require 'petstore/models/list' +require 'petstore/models/mamal_with_enum' require 'petstore/models/mammal' require 'petstore/models/mammal_anyof' require 'petstore/models/mammal_without_discriminator' diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/another_fake_api.rb index a3bdc5af0bfc..bf065b030353 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/default_api.rb index f9fc19208aae..224ceda35bc1 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_api.rb index a759e20736fe..064496fe435c 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -594,6 +594,72 @@ def get_parameter_name_mapping_with_http_info(_type, type, type_, http_debug_opt return data, status_code, headers end + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_additional_properties_reference(request_body, opts = {}) + test_additional_properties_reference_with_http_info(request_body, opts) + nil + end + + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_additional_properties_reference_with_http_info(request_body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_additional_properties_reference ...' + end + # verify the required parameter 'request_body' is set + if @api_client.config.client_side_validation && request_body.nil? + fail ArgumentError, "Missing the required parameter 'request_body' when calling FakeApi.test_additional_properties_reference" + end + # resource path + local_var_path = '/fake/additionalProperties-reference' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(request_body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_additional_properties_reference", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_additional_properties_reference\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # For this test, the body has to be a binary file. # @param body [File] image to upload # @param [Hash] opts the optional parameters diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_classname_tags123_api.rb index 3665b1137909..65bf53341469 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/pet_api.rb index c3972cea110b..1ca4010974ec 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/store_api.rb index df4f0c3f7e81..68614eff5d8c 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api/user_api.rb index 9c4d48a96059..e93ec98c59e4 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api_client.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api_client.rb index fe5e25ab3870..9efdf06b55b2 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -69,7 +69,9 @@ def call_api(http_method, path, opts = {}) fail ApiError.new('Connection failed') end - if opts[:return_type] + if opts[:return_type] == 'File' + data = deserialize_file(response) + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -126,6 +128,33 @@ def build_request_body(header_params, form_params, body) end end + def deserialize_file(response) + body = response.body + if @config.return_binary_data == true + # TODO: force response encoding + body.to_s + else + content_disposition = response.headers['content-disposition'] + if content_disposition && content_disposition =~ /filename=/i + filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] + prefix = sanitize_filename(filename) + else + prefix = 'download-' + end + prefix = prefix + '-' unless prefix.end_with?('-') + encoding = response.body.encoding + tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) + response.copy_to(tempfile) + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + + tempfile + end + end + def session return @session if defined?(@session) @@ -168,35 +197,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - if return_type == 'File' - if @config.return_binary_data == true - # TODO: force response encoding - return body.to_s - else - content_disposition = response.headers['content-disposition'] - if content_disposition && content_disposition =~ /filename=/i - filename = content_disposition[/filename=['"]?([^'"\s]+)['"]?/, 1] - prefix = sanitize_filename(filename) - else - prefix = 'download-' - end - prefix = prefix + '-' unless prefix.end_with?('-') - encoding = response.body.encoding - tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - response.copy_to(tempfile) - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - - return tempfile - end - end - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/api_error.rb b/samples/client/petstore/ruby-httpx/lib/petstore/api_error.rb index e220ece388a7..afd037d88fb9 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/configuration.rb b/samples/client/petstore/ruby-httpx/lib/petstore/configuration.rb index 12985b968922..9a478b5f05c8 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/additional_properties_class.rb index c28fba75cbf2..0b59df2971fb 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -172,7 +172,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/all_of_with_single_ref.rb index 99c49ee3e411..203c5fac9b3b 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/all_of_with_single_ref.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -190,7 +190,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/animal.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/animal.rb index 38c3e4ae50cc..a668fa9ea8a2 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -182,7 +182,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/api_response.rb index 3f05081ca8f5..5e0b22e68402 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_array_of_number_only.rb index e3fc21969343..58fa7bef8697 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_number_only.rb index c84931a3d2c8..2de31dbf84f6 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_test.rb index 3d4fe2a619b7..24e152f8b0de 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -211,7 +211,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/capitalization.rb index 535ca7697ba4..2be58edd6d18 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -205,7 +205,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/cat.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/cat.rb index ddc6268f1752..efabf4cfeed7 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/category.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/category.rb index 029ecca4bf60..7b6d807111f9 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -175,7 +175,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/class_model.rb index a69c0c3d8b18..6ef7b4730fcd 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/client.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/client.rb index d100b51d25eb..47bc5190c667 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/cow.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/cow.rb new file mode 100644 index 000000000000..c209f752ce82 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/cow.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Cow + BLACK_AND_WHITE_COW = "BlackAndWhiteCow".freeze + BROWN_COW = "BrownCow".freeze + + def self.all_vars + @all_vars ||= [BLACK_AND_WHITE_COW, BROWN_COW].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if Cow.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #Cow" + end + end +end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/deprecated_object.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/deprecated_object.rb index c13b9812ce80..6170efcd6bba 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/deprecated_object.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/deprecated_object.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/dog.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/dog.rb index baf8aed83aee..00ad6f159738 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_arrays.rb index b53d022ccbed..056ba338eea2 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -204,7 +204,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_class.rb index f842e0f451fa..5f8a25a8c7af 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_test.rb index f71d804b6d59..7e73f2f64027 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -304,7 +304,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/fake_big_decimal_map200_response.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/fake_big_decimal_map200_response.rb index 2e84764f47fd..d2000057c543 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/fake_big_decimal_map200_response.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/fake_big_decimal_map200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/file.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/file.rb index af161d8f6319..adf005d83895 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/file_schema_test_class.rb index b4cc94be47b5..d286737cf28f 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/foo.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/foo.rb index 76988fd3cd5c..b9518f3f190e 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/foo_get_default_response.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/foo_get_default_response.rb index d50fec9cd9fd..7865e3b72ef4 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/foo_get_default_response.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/foo_get_default_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/format_test.rb index f6da236ae5b7..3692050befbf 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -555,7 +555,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/has_only_read_only.rb index 9d82934d22e1..2edacc4318fb 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/health_check_result.rb index b850e8623c68..bbef6f643291 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/list.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/list.rb index ef3adc399fe4..85fbbc2e0196 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/mamal_with_enum.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/mamal_with_enum.rb new file mode 100644 index 000000000000..4cf499b269d5 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/mamal_with_enum.rb @@ -0,0 +1,104 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + module MamalWithEnum + class << self + # List of class defined in oneOf (OpenAPI v3) + def openapi_one_of + [ + :'Cow' + ] + end + + # Builds the object + # @param [Mixed] Data to be matched against the list of oneOf items + # @return [Object] Returns the model or the data itself + def build(data) + # Go through the list of oneOf items and attempt to identify the appropriate one. + # Note: + # - We do not attempt to check whether exactly one item matches. + # - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 }) + # due to the way the deserialization is made in the base_object template (it just casts without verifying). + # - TODO: scalar values are de facto behaving as if they were nullable. + # - TODO: logging when debugging is set. + openapi_one_of.each do |klass| + begin + next if klass == :AnyType # "nullable: true" + typed_data = find_and_cast_into_type(klass, data) + return typed_data if typed_data + rescue # rescue all errors so we keep iterating even if the current item lookup raises + end + end + + openapi_one_of.include?(:AnyType) ? data : nil + end + + private + + SchemaMismatchError = Class.new(StandardError) + + # Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse. + def find_and_cast_into_type(klass, data) + return if data.nil? + + case klass.to_s + when 'Boolean' + return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass) + when 'Float' + return data if data.instance_of?(Float) + when 'Integer' + return data if data.instance_of?(Integer) + when 'Time' + return Time.parse(data) + when 'Date' + return Date.parse(data) + when 'String' + return data if data.instance_of?(String) + when 'Object' # "type: object" + return data if data.instance_of?(Hash) + when /\AArray<(?.+)>\z/ # "type: array" + if data.instance_of?(Array) + sub_type = Regexp.last_match[:sub_type] + return data.map { |item| find_and_cast_into_type(sub_type, item) } + end + when /\AHash.+)>\z/ # "type: object" with "additionalProperties: { ... }" + if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) } + sub_type = Regexp.last_match[:sub_type] + return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) } + end + else # model + const = Petstore.const_get(klass) + if const + if const.respond_to?(:openapi_one_of) # nested oneOf model + model = const.build(data) + return model if model + else + # raise if data contains keys that are not known to the model + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? + model = const.build_from_hash(data) + return model if model + end + end + end + + raise # if no match by now, raise + rescue + raise SchemaMismatchError, "#{data} doesn't match the #{klass} type" + end + end + end + +end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal.rb index 204dd4685e7a..65b6bbedac2e 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_anyof.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_anyof.rb index f1432ade8b0d..7d5aed31496f 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_anyof.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_anyof.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -87,7 +87,7 @@ def find_and_cast_into_type(klass, data) return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_without_discriminator.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_without_discriminator.rb index 331fc4ac7c35..6eaac608cf7b 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_without_discriminator.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/mammal_without_discriminator.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -88,7 +88,7 @@ def find_and_cast_into_type(klass, data) return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/map_test.rb index 0ced89f3c867..3e9e75a68740 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -216,7 +216,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index ad1a5b472351..f1e4d3dab002 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -179,7 +179,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/model200_response.rb index 4d318df4c90f..a887433e91fa 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -169,7 +169,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/model_return.rb index ef0c65b55d8e..1bd93f188603 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/name.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/name.rb index a189793a3811..2175dcd1b90c 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -194,7 +194,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/nullable_class.rb index 5748150ee607..d45f6e70b6f4 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -280,7 +280,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/number_only.rb index 341193e3f17c..427eeee115b0 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/object_with_deprecated_fields.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/object_with_deprecated_fields.rb index 5df34bc5a128..21e9d84456cc 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/object_with_deprecated_fields.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/object_with_deprecated_fields.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/order.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/order.rb index 6d4ea1c77a7c..5b717adf1c16 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -241,7 +241,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_composite.rb index bcb2334d38ad..983bd5b1ed24 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum.rb index 09837aa4f28d..4b36df834005 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_default_value.rb index 4dde4e1d3e16..e40b9a7f7511 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer.rb index 93b24aac3a51..f76dfb3786d6 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer_default_value.rb index 9100aff19e13..99e45dc78a0c 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_object_with_enum_property.rb index 1dd612ccaca5..471f9802d704 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/pet.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/pet.rb index e0bb197e8e69..dd7f9e4f8931 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -267,7 +267,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/property_name_mapping.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/property_name_mapping.rb index a9e15d67141e..26e29854d73b 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/property_name_mapping.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/property_name_mapping.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -186,7 +186,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/read_only_first.rb index 46853a3feeee..44f10e959400 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/single_ref_type.rb index ecccade2f191..2f9d950f5967 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/single_ref_type.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/special_model_name.rb index 07ede6cffe38..4e6b02341295 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/tag.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/tag.rb index 47cc6ac04379..71148ab081ed 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/test_inline_freeform_additional_properties_request.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/test_inline_freeform_additional_properties_request.rb index bf7c0b98a134..c13820d936b0 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/test_inline_freeform_additional_properties_request.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/test_inline_freeform_additional_properties_request.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/user.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/user.rb index 4045f639bcbf..b7e621ed365a 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -223,7 +223,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/whale.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/whale.rb index 7127a617e73f..6c560925e057 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/whale.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/whale.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -184,7 +184,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/models/zebra.rb b/samples/client/petstore/ruby-httpx/lib/petstore/models/zebra.rb index 6767c534c330..490ca6c963e0 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/models/zebra.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/models/zebra.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -209,7 +209,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby-httpx/lib/petstore/version.rb b/samples/client/petstore/ruby-httpx/lib/petstore/version.rb index 3d342d87a32f..8b40799d224a 100644 --- a/samples/client/petstore/ruby-httpx/lib/petstore/version.rb +++ b/samples/client/petstore/ruby-httpx/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/petstore.gemspec b/samples/client/petstore/ruby-httpx/petstore.gemspec index 403ec03e1bd4..05cfe930a282 100644 --- a/samples/client/petstore/ruby-httpx/petstore.gemspec +++ b/samples/client/petstore/ruby-httpx/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'httpx', '~> 1.0', '>= 1.0.0' diff --git a/samples/client/petstore/ruby-httpx/spec/api_client_spec.rb b/samples/client/petstore/ruby-httpx/spec/api_client_spec.rb index deb8f6d70aa5..11e797b4d54a 100644 --- a/samples/client/petstore/ruby-httpx/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby-httpx/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/spec/configuration_spec.rb b/samples/client/petstore/ruby-httpx/spec/configuration_spec.rb index 2df70df93ac5..09e3f14a75b4 100644 --- a/samples/client/petstore/ruby-httpx/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby-httpx/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby-httpx/spec/models/cow_spec.rb b/samples/client/petstore/ruby-httpx/spec/models/cow_spec.rb new file mode 100644 index 000000000000..e1cf66c03ac0 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/spec/models/cow_spec.rb @@ -0,0 +1,30 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Cow +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Cow do + let(:instance) { Petstore::Cow.new } + + describe 'test an instance of Cow' do + it 'should create an instance of Cow' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(Petstore::Cow) + end + end + +end diff --git a/samples/client/petstore/ruby-httpx/spec/models/mamal_with_enum_spec.rb b/samples/client/petstore/ruby-httpx/spec/models/mamal_with_enum_spec.rb new file mode 100644 index 000000000000..95002b49ea45 --- /dev/null +++ b/samples/client/petstore/ruby-httpx/spec/models/mamal_with_enum_spec.rb @@ -0,0 +1,32 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::MamalWithEnum +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::MamalWithEnum do + describe '.openapi_one_of' do + it 'lists the items referenced in the oneOf array' do + expect(described_class.openapi_one_of).to_not be_empty + end + end + + describe '.build' do + it 'returns the correct model' do + # assertion here. ref: https://rspec.info/features/3-12/rspec-expectations/built-in-matchers/ + end + end +end diff --git a/samples/client/petstore/ruby-httpx/spec/spec_helper.rb b/samples/client/petstore/ruby-httpx/spec/spec_helper.rb index 5cd856c95041..db7155ecfb5d 100644 --- a/samples/client/petstore/ruby-httpx/spec/spec_helper.rb +++ b/samples/client/petstore/ruby-httpx/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/.openapi-generator/FILES b/samples/client/petstore/ruby/.openapi-generator/FILES index aa241d0edb50..937697a733e7 100644 --- a/samples/client/petstore/ruby/.openapi-generator/FILES +++ b/samples/client/petstore/ruby/.openapi-generator/FILES @@ -19,6 +19,7 @@ docs/Cat.md docs/Category.md docs/ClassModel.md docs/Client.md +docs/Cow.md docs/DefaultApi.md docs/DeprecatedObject.md docs/Dog.md @@ -36,6 +37,7 @@ docs/FormatTest.md docs/HasOnlyReadOnly.md docs/HealthCheckResult.md docs/List.md +docs/MamalWithEnum.md docs/Mammal.md docs/MammalAnyof.md docs/MammalWithoutDiscriminator.md @@ -91,6 +93,7 @@ lib/petstore/models/cat.rb lib/petstore/models/category.rb lib/petstore/models/class_model.rb lib/petstore/models/client.rb +lib/petstore/models/cow.rb lib/petstore/models/deprecated_object.rb lib/petstore/models/dog.rb lib/petstore/models/enum_arrays.rb @@ -105,6 +108,7 @@ lib/petstore/models/format_test.rb lib/petstore/models/has_only_read_only.rb lib/petstore/models/health_check_result.rb lib/petstore/models/list.rb +lib/petstore/models/mamal_with_enum.rb lib/petstore/models/mammal.rb lib/petstore/models/mammal_anyof.rb lib/petstore/models/mammal_without_discriminator.rb @@ -135,6 +139,4 @@ lib/petstore/models/whale.rb lib/petstore/models/zebra.rb lib/petstore/version.rb petstore.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/client/petstore/ruby/.openapi-generator/VERSION b/samples/client/petstore/ruby/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/ruby/.openapi-generator/VERSION +++ b/samples/client/petstore/ruby/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/ruby/README.md b/samples/client/petstore/ruby/README.md index 219e3ef720f9..daa2a6d5b0fa 100644 --- a/samples/client/petstore/ruby/README.md +++ b/samples/client/petstore/ruby/README.md @@ -86,6 +86,7 @@ Class | Method | HTTP request | Description *Petstore::FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *Petstore::FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | *Petstore::FakeApi* | [**get_parameter_name_mapping**](docs/FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test +*Petstore::FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *Petstore::FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *Petstore::FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *Petstore::FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | @@ -135,6 +136,7 @@ Class | Method | HTTP request | Description - [Petstore::Category](docs/Category.md) - [Petstore::ClassModel](docs/ClassModel.md) - [Petstore::Client](docs/Client.md) + - [Petstore::Cow](docs/Cow.md) - [Petstore::DeprecatedObject](docs/DeprecatedObject.md) - [Petstore::Dog](docs/Dog.md) - [Petstore::EnumArrays](docs/EnumArrays.md) @@ -149,6 +151,7 @@ Class | Method | HTTP request | Description - [Petstore::HasOnlyReadOnly](docs/HasOnlyReadOnly.md) - [Petstore::HealthCheckResult](docs/HealthCheckResult.md) - [Petstore::List](docs/List.md) + - [Petstore::MamalWithEnum](docs/MamalWithEnum.md) - [Petstore::Mammal](docs/Mammal.md) - [Petstore::MammalAnyof](docs/MammalAnyof.md) - [Petstore::MammalWithoutDiscriminator](docs/MammalWithoutDiscriminator.md) diff --git a/samples/client/petstore/ruby/docs/Cow.md b/samples/client/petstore/ruby/docs/Cow.md new file mode 100644 index 000000000000..6fa7084b8a40 --- /dev/null +++ b/samples/client/petstore/ruby/docs/Cow.md @@ -0,0 +1,15 @@ +# Petstore::Cow + +## Properties + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | + +## Example + +```ruby +require 'petstore' + +instance = Petstore::Cow.new() +``` + diff --git a/samples/client/petstore/ruby/docs/FakeApi.md b/samples/client/petstore/ruby/docs/FakeApi.md index 5785290cf7bd..f3594ca3fb9b 100644 --- a/samples/client/petstore/ruby/docs/FakeApi.md +++ b/samples/client/petstore/ruby/docs/FakeApi.md @@ -13,6 +13,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | | | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | | | [**get_parameter_name_mapping**](FakeApi.md#get_parameter_name_mapping) | **GET** /fake/parameter-name-mapping | parameter name mapping test | +| [**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | | | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | | | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | | @@ -611,6 +612,69 @@ No authorization required - **Accept**: Not defined +## test_additional_properties_reference + +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Examples + +```ruby +require 'time' +require 'petstore' + +api_instance = Petstore::FakeApi.new +request_body = { key: 3.56} # Hash | request body + +begin + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference: #{e}" +end +``` + +#### Using the test_additional_properties_reference_with_http_info variant + +This returns an Array which contains the response data (`nil` in this case), status code and headers. + +> test_additional_properties_reference_with_http_info(request_body) + +```ruby +begin + # test referenced additionalProperties + data, status_code, headers = api_instance.test_additional_properties_reference_with_http_info(request_body) + p status_code # => 2xx + p headers # => { ... } + p data # => nil +rescue Petstore::ApiError => e + puts "Error when calling FakeApi->test_additional_properties_reference_with_http_info: #{e}" +end +``` + +### Parameters + +| Name | Type | Description | Notes | +| ---- | ---- | ----------- | ----- | +| **request_body** | [**Hash<String, Object>**](Object.md) | request body | | + +### Return type + +nil (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + + ## test_body_with_binary > test_body_with_binary(body) diff --git a/samples/client/petstore/ruby/docs/MamalWithEnum.md b/samples/client/petstore/ruby/docs/MamalWithEnum.md new file mode 100644 index 000000000000..37b9252a2c82 --- /dev/null +++ b/samples/client/petstore/ruby/docs/MamalWithEnum.md @@ -0,0 +1,47 @@ +# Petstore::MamalWithEnum + +## Class instance methods + +### `openapi_one_of` + +Returns the list of classes defined in oneOf. + +#### Example + +```ruby +require 'petstore' + +Petstore::MamalWithEnum.openapi_one_of +# => +# [ +# :'Cow' +# ] +``` + +### build + +Find the appropriate object from the `openapi_one_of` list and casts the data into it. + +#### Example + +```ruby +require 'petstore' + +Petstore::MamalWithEnum.build(data) +# => # + +Petstore::MamalWithEnum.build(data_that_doesnt_match) +# => nil +``` + +#### Parameters + +| Name | Type | Description | +| ---- | ---- | ----------- | +| **data** | **Mixed** | data to be matched against the list of oneOf items | + +#### Return type + +- `Cow` +- `nil` (if no type matches) + diff --git a/samples/client/petstore/ruby/lib/petstore.rb b/samples/client/petstore/ruby/lib/petstore.rb index 058c4a4fffac..b6662f07ea56 100644 --- a/samples/client/petstore/ruby/lib/petstore.rb +++ b/samples/client/petstore/ruby/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -28,6 +28,7 @@ require 'petstore/models/category' require 'petstore/models/class_model' require 'petstore/models/client' +require 'petstore/models/cow' require 'petstore/models/deprecated_object' require 'petstore/models/enum_arrays' require 'petstore/models/enum_class' @@ -41,6 +42,7 @@ require 'petstore/models/has_only_read_only' require 'petstore/models/health_check_result' require 'petstore/models/list' +require 'petstore/models/mamal_with_enum' require 'petstore/models/mammal' require 'petstore/models/mammal_anyof' require 'petstore/models/mammal_without_discriminator' diff --git a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb index a3bdc5af0bfc..bf065b030353 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/another_fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/default_api.rb b/samples/client/petstore/ruby/lib/petstore/api/default_api.rb index f9fc19208aae..224ceda35bc1 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/default_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/default_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb index 85fe5da990bc..b26b4b239433 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -594,6 +594,72 @@ def get_parameter_name_mapping_with_http_info(underscore_type, type, type_with_u return data, status_code, headers end + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [nil] + def test_additional_properties_reference(request_body, opts = {}) + test_additional_properties_reference_with_http_info(request_body, opts) + nil + end + + # test referenced additionalProperties + # + # @param request_body [Hash] request body + # @param [Hash] opts the optional parameters + # @return [Array<(nil, Integer, Hash)>] nil, response status code and response headers + def test_additional_properties_reference_with_http_info(request_body, opts = {}) + if @api_client.config.debugging + @api_client.config.logger.debug 'Calling API: FakeApi.test_additional_properties_reference ...' + end + # verify the required parameter 'request_body' is set + if @api_client.config.client_side_validation && request_body.nil? + fail ArgumentError, "Missing the required parameter 'request_body' when calling FakeApi.test_additional_properties_reference" + end + # resource path + local_var_path = '/fake/additionalProperties-reference' + + # query parameters + query_params = opts[:query_params] || {} + + # header parameters + header_params = opts[:header_params] || {} + # HTTP header 'Content-Type' + content_type = @api_client.select_header_content_type(['application/json']) + if !content_type.nil? + header_params['Content-Type'] = content_type + end + + # form parameters + form_params = opts[:form_params] || {} + + # http body (model) + post_body = opts[:debug_body] || @api_client.object_to_http_body(request_body) + + # return_type + return_type = opts[:debug_return_type] + + # auth_names + auth_names = opts[:debug_auth_names] || [] + + new_options = opts.merge( + :operation => :"FakeApi.test_additional_properties_reference", + :header_params => header_params, + :query_params => query_params, + :form_params => form_params, + :body => post_body, + :auth_names => auth_names, + :return_type => return_type + ) + + data, status_code, headers = @api_client.call_api(:POST, local_var_path, new_options) + if @api_client.config.debugging + @api_client.config.logger.debug "API called: FakeApi#test_additional_properties_reference\nData: #{data.inspect}\nStatus code: #{status_code}\nHeaders: #{headers}" + end + return data, status_code, headers + end + # For this test, the body has to be a binary file. # @param body [File] image to upload # @param [Hash] opts the optional parameters diff --git a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb index 3665b1137909..65bf53341469 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/fake_classname_tags123_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb index 9af0ed2672ec..e8d070b57577 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/pet_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb index c23d44c56978..3948b8c08931 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/store_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/store_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb index 5b28f84953d8..13b69ff3714c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api/user_api.rb +++ b/samples/client/petstore/ruby/lib/petstore/api/user_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/api_client.rb b/samples/client/petstore/ruby/lib/petstore/api_client.rb index f4a681dc6d28..2a8a22fe5a7c 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_client.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -46,9 +46,10 @@ def self.default # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -70,7 +71,9 @@ def call_api(http_method, path, opts = {}) end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -126,9 +129,7 @@ def build_request(http_method, path, opts = {}) end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -166,6 +167,8 @@ def build_request_body(header_params, form_params, body) # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -180,21 +183,24 @@ def download_file(request) prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end # Check if the given MIME is a JSON MIME. @@ -215,11 +221,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - return @tempfile if return_type == 'File' - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/client/petstore/ruby/lib/petstore/api_error.rb b/samples/client/petstore/ruby/lib/petstore/api_error.rb index e220ece388a7..afd037d88fb9 100644 --- a/samples/client/petstore/ruby/lib/petstore/api_error.rb +++ b/samples/client/petstore/ruby/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/configuration.rb b/samples/client/petstore/ruby/lib/petstore/configuration.rb index 3491a46ae1bf..9955149da9bf 100644 --- a/samples/client/petstore/ruby/lib/petstore/configuration.rb +++ b/samples/client/petstore/ruby/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb index c28fba75cbf2..0b59df2971fb 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -172,7 +172,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb b/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb index 99c49ee3e411..203c5fac9b3b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/all_of_with_single_ref.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -190,7 +190,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/animal.rb b/samples/client/petstore/ruby/lib/petstore/models/animal.rb index 38c3e4ae50cc..a668fa9ea8a2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/animal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/animal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -182,7 +182,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb index 3f05081ca8f5..5e0b22e68402 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/api_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/api_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb index e3fc21969343..58fa7bef8697 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb index c84931a3d2c8..2de31dbf84f6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_of_number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb index 3d4fe2a619b7..24e152f8b0de 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/array_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/array_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -211,7 +211,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb index 535ca7697ba4..2be58edd6d18 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/capitalization.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -205,7 +205,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cat.rb b/samples/client/petstore/ruby/lib/petstore/models/cat.rb index ddc6268f1752..efabf4cfeed7 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/cat.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/cat.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/category.rb b/samples/client/petstore/ruby/lib/petstore/models/category.rb index 029ecca4bf60..7b6d807111f9 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/category.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/category.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -175,7 +175,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/class_model.rb b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb index a69c0c3d8b18..6ef7b4730fcd 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/class_model.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/class_model.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/client.rb b/samples/client/petstore/ruby/lib/petstore/models/client.rb index d100b51d25eb..47bc5190c667 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/client.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/cow.rb b/samples/client/petstore/ruby/lib/petstore/models/cow.rb new file mode 100644 index 000000000000..c209f752ce82 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/cow.rb @@ -0,0 +1,40 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + class Cow + BLACK_AND_WHITE_COW = "BlackAndWhiteCow".freeze + BROWN_COW = "BrownCow".freeze + + def self.all_vars + @all_vars ||= [BLACK_AND_WHITE_COW, BROWN_COW].freeze + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def self.build_from_hash(value) + new.build_from_hash(value) + end + + # Builds the enum from string + # @param [String] The enum value in the form of the string + # @return [String] The enum value + def build_from_hash(value) + return value if Cow.all_vars.include?(value) + raise "Invalid ENUM value #{value} for class #Cow" + end + end +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/deprecated_object.rb b/samples/client/petstore/ruby/lib/petstore/models/deprecated_object.rb index c13b9812ce80..6170efcd6bba 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/deprecated_object.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/deprecated_object.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/dog.rb b/samples/client/petstore/ruby/lib/petstore/models/dog.rb index baf8aed83aee..00ad6f159738 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/dog.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/dog.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb index b53d022ccbed..056ba338eea2 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_arrays.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -204,7 +204,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb index f842e0f451fa..5f8a25a8c7af 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb index f71d804b6d59..7e73f2f64027 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/enum_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -304,7 +304,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/fake_big_decimal_map200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/fake_big_decimal_map200_response.rb index 2e84764f47fd..d2000057c543 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/fake_big_decimal_map200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/fake_big_decimal_map200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/file.rb b/samples/client/petstore/ruby/lib/petstore/models/file.rb index af161d8f6319..adf005d83895 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/file.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/file.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb b/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb index b4cc94be47b5..d286737cf28f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/file_schema_test_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -170,7 +170,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/foo.rb b/samples/client/petstore/ruby/lib/petstore/models/foo.rb index 76988fd3cd5c..b9518f3f190e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/foo.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/foo.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/foo_get_default_response.rb b/samples/client/petstore/ruby/lib/petstore/models/foo_get_default_response.rb index d50fec9cd9fd..7865e3b72ef4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/foo_get_default_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/foo_get_default_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb index f6da236ae5b7..3692050befbf 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/format_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/format_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -555,7 +555,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb index 9d82934d22e1..2edacc4318fb 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/has_only_read_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb b/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb index b850e8623c68..bbef6f643291 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/health_check_result.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -161,7 +161,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/list.rb b/samples/client/petstore/ruby/lib/petstore/models/list.rb index ef3adc399fe4..85fbbc2e0196 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/list.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/list.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mamal_with_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/mamal_with_enum.rb new file mode 100644 index 000000000000..4cf499b269d5 --- /dev/null +++ b/samples/client/petstore/ruby/lib/petstore/models/mamal_with_enum.rb @@ -0,0 +1,104 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'date' +require 'time' + +module Petstore + module MamalWithEnum + class << self + # List of class defined in oneOf (OpenAPI v3) + def openapi_one_of + [ + :'Cow' + ] + end + + # Builds the object + # @param [Mixed] Data to be matched against the list of oneOf items + # @return [Object] Returns the model or the data itself + def build(data) + # Go through the list of oneOf items and attempt to identify the appropriate one. + # Note: + # - We do not attempt to check whether exactly one item matches. + # - No advanced validation of types in some cases (e.g. "x: { type: string }" will happily match { x: 123 }) + # due to the way the deserialization is made in the base_object template (it just casts without verifying). + # - TODO: scalar values are de facto behaving as if they were nullable. + # - TODO: logging when debugging is set. + openapi_one_of.each do |klass| + begin + next if klass == :AnyType # "nullable: true" + typed_data = find_and_cast_into_type(klass, data) + return typed_data if typed_data + rescue # rescue all errors so we keep iterating even if the current item lookup raises + end + end + + openapi_one_of.include?(:AnyType) ? data : nil + end + + private + + SchemaMismatchError = Class.new(StandardError) + + # Note: 'File' is missing here because in the regular case we get the data _after_ a call to JSON.parse. + def find_and_cast_into_type(klass, data) + return if data.nil? + + case klass.to_s + when 'Boolean' + return data if data.instance_of?(TrueClass) || data.instance_of?(FalseClass) + when 'Float' + return data if data.instance_of?(Float) + when 'Integer' + return data if data.instance_of?(Integer) + when 'Time' + return Time.parse(data) + when 'Date' + return Date.parse(data) + when 'String' + return data if data.instance_of?(String) + when 'Object' # "type: object" + return data if data.instance_of?(Hash) + when /\AArray<(?.+)>\z/ # "type: array" + if data.instance_of?(Array) + sub_type = Regexp.last_match[:sub_type] + return data.map { |item| find_and_cast_into_type(sub_type, item) } + end + when /\AHash.+)>\z/ # "type: object" with "additionalProperties: { ... }" + if data.instance_of?(Hash) && data.keys.all? { |k| k.instance_of?(Symbol) || k.instance_of?(String) } + sub_type = Regexp.last_match[:sub_type] + return data.each_with_object({}) { |(k, v), hsh| hsh[k] = find_and_cast_into_type(sub_type, v) } + end + else # model + const = Petstore.const_get(klass) + if const + if const.respond_to?(:openapi_one_of) # nested oneOf model + model = const.build(data) + return model if model + else + # raise if data contains keys that are not known to the model + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? + model = const.build_from_hash(data) + return model if model + end + end + end + + raise # if no match by now, raise + rescue + raise SchemaMismatchError, "#{data} doesn't match the #{klass} type" + end + end + end + +end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mammal.rb b/samples/client/petstore/ruby/lib/petstore/models/mammal.rb index 204dd4685e7a..65b6bbedac2e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mammal.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mammal.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mammal_anyof.rb b/samples/client/petstore/ruby/lib/petstore/models/mammal_anyof.rb index f1432ade8b0d..7d5aed31496f 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mammal_anyof.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mammal_anyof.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -87,7 +87,7 @@ def find_and_cast_into_type(klass, data) return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mammal_without_discriminator.rb b/samples/client/petstore/ruby/lib/petstore/models/mammal_without_discriminator.rb index 331fc4ac7c35..6eaac608cf7b 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mammal_without_discriminator.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mammal_without_discriminator.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -88,7 +88,7 @@ def find_and_cast_into_type(klass, data) return model if model else # raise if data contains keys that are not known to the model - raise unless (data.keys - const.acceptable_attributes).empty? + raise if const.respond_to?(:acceptable_attributes) && !(data.keys - const.acceptable_attributes).empty? model = const.build_from_hash(data) return model if model end diff --git a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb index 0ced89f3c867..3e9e75a68740 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/map_test.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/map_test.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -216,7 +216,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb index ad1a5b472351..f1e4d3dab002 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/mixed_properties_and_additional_properties_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -179,7 +179,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb b/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb index 4d318df4c90f..a887433e91fa 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model200_response.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -169,7 +169,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb index ef0c65b55d8e..1bd93f188603 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/model_return.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/model_return.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -160,7 +160,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/name.rb b/samples/client/petstore/ruby/lib/petstore/models/name.rb index a189793a3811..2175dcd1b90c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -194,7 +194,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb b/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb index 5748150ee607..d45f6e70b6f4 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/nullable_class.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -280,7 +280,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb index 341193e3f17c..427eeee115b0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/number_only.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/number_only.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/object_with_deprecated_fields.rb b/samples/client/petstore/ruby/lib/petstore/models/object_with_deprecated_fields.rb index 5df34bc5a128..21e9d84456cc 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/object_with_deprecated_fields.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/object_with_deprecated_fields.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/order.rb b/samples/client/petstore/ruby/lib/petstore/models/order.rb index 6d4ea1c77a7c..5b717adf1c16 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/order.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/order.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -241,7 +241,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb index bcb2334d38ad..983bd5b1ed24 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_composite.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -177,7 +177,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb index 09837aa4f28d..491f6604837d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -17,10 +17,10 @@ module Petstore class OuterEnum PLACED = "placed".freeze APPROVED = "approved".freeze - DELIVERED = "delivered".freeze + SHIPPED = "delivered".freeze def self.all_vars - @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + @all_vars ||= [PLACED, APPROVED, SHIPPED].freeze end # Builds the enum from string diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb index 4dde4e1d3e16..8f371926ef0d 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -17,10 +17,10 @@ module Petstore class OuterEnumDefaultValue PLACED = "placed".freeze APPROVED = "approved".freeze - DELIVERED = "delivered".freeze + SHIPPED = "delivered".freeze def self.all_vars - @all_vars ||= [PLACED, APPROVED, DELIVERED].freeze + @all_vars ||= [PLACED, APPROVED, SHIPPED].freeze end # Builds the enum from string diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb index 93b24aac3a51..f76dfb3786d6 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb index 9100aff19e13..99e45dc78a0c 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_enum_integer_default_value.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb b/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb index 1dd612ccaca5..471f9802d704 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/outer_object_with_enum_property.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -188,7 +188,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/pet.rb b/samples/client/petstore/ruby/lib/petstore/models/pet.rb index e0bb197e8e69..dd7f9e4f8931 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/pet.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/pet.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -267,7 +267,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/property_name_mapping.rb b/samples/client/petstore/ruby/lib/petstore/models/property_name_mapping.rb index d565c9619833..839fa974225e 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/property_name_mapping.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/property_name_mapping.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -186,7 +186,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb index 46853a3feeee..44f10e959400 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/read_only_first.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb b/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb index ecccade2f191..2f9d950f5967 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/single_ref_type.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb index 07ede6cffe38..4e6b02341295 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/special_model_name.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/tag.rb b/samples/client/petstore/ruby/lib/petstore/models/tag.rb index 47cc6ac04379..71148ab081ed 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/tag.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/tag.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -168,7 +168,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/test_inline_freeform_additional_properties_request.rb b/samples/client/petstore/ruby/lib/petstore/models/test_inline_freeform_additional_properties_request.rb index bf7c0b98a134..c13820d936b0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/test_inline_freeform_additional_properties_request.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/test_inline_freeform_additional_properties_request.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -159,7 +159,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/user.rb b/samples/client/petstore/ruby/lib/petstore/models/user.rb index 4045f639bcbf..b7e621ed365a 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/user.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/user.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -223,7 +223,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/whale.rb b/samples/client/petstore/ruby/lib/petstore/models/whale.rb index 7127a617e73f..6c560925e057 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/whale.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/whale.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -184,7 +184,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/models/zebra.rb b/samples/client/petstore/ruby/lib/petstore/models/zebra.rb index 6767c534c330..490ca6c963e0 100644 --- a/samples/client/petstore/ruby/lib/petstore/models/zebra.rb +++ b/samples/client/petstore/ruby/lib/petstore/models/zebra.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -209,7 +209,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/client/petstore/ruby/lib/petstore/version.rb b/samples/client/petstore/ruby/lib/petstore/version.rb index 3d342d87a32f..8b40799d224a 100644 --- a/samples/client/petstore/ruby/lib/petstore/version.rb +++ b/samples/client/petstore/ruby/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/petstore.gemspec b/samples/client/petstore/ruby/petstore.gemspec index d5420ccb8bea..b5bd482b8feb 100644 --- a/samples/client/petstore/ruby/petstore.gemspec +++ b/samples/client/petstore/ruby/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/client/petstore/ruby/spec/api_client_spec.rb b/samples/client/petstore/ruby/spec/api_client_spec.rb index ffa7f281caf8..27fce7602fb0 100644 --- a/samples/client/petstore/ruby/spec/api_client_spec.rb +++ b/samples/client/petstore/ruby/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/spec/configuration_spec.rb b/samples/client/petstore/ruby/spec/configuration_spec.rb index c61e6f00029a..1075efa811bb 100644 --- a/samples/client/petstore/ruby/spec/configuration_spec.rb +++ b/samples/client/petstore/ruby/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/client/petstore/ruby/spec/models/cow_spec.rb b/samples/client/petstore/ruby/spec/models/cow_spec.rb new file mode 100644 index 000000000000..e1cf66c03ac0 --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/cow_spec.rb @@ -0,0 +1,30 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::Cow +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::Cow do + let(:instance) { Petstore::Cow.new } + + describe 'test an instance of Cow' do + it 'should create an instance of Cow' do + # uncomment below to test the instance creation + #expect(instance).to be_instance_of(Petstore::Cow) + end + end + +end diff --git a/samples/client/petstore/ruby/spec/models/mamal_with_enum_spec.rb b/samples/client/petstore/ruby/spec/models/mamal_with_enum_spec.rb new file mode 100644 index 000000000000..e3c1f1255c1a --- /dev/null +++ b/samples/client/petstore/ruby/spec/models/mamal_with_enum_spec.rb @@ -0,0 +1,36 @@ +=begin +#OpenAPI Petstore + +#This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +The version of the OpenAPI document: 1.0.0 + +Generated by: https://openapi-generator.tech +OpenAPI Generator version: 7.3.0-SNAPSHOT + +=end + +require 'spec_helper' +require 'json' +require 'date' + +# Unit tests for Petstore::MamalWithEnum +# Automatically generated by openapi-generator (https://openapi-generator.tech) +# Please update as you see appropriate +describe Petstore::MamalWithEnum do + describe '.openapi_one_of' do + it 'lists the items referenced in the oneOf array' do + expect(described_class.openapi_one_of).to_not be_empty + end + end + + describe '.build' do + it 'returns the correct model' do + expect(described_class.build("BlackAndWhiteCow")).to eq(Petstore::Cow::BLACK_AND_WHITE_COW) + end + + it 'returns nil for unknown model' do + expect(described_class.build({ classname: 'monkey', type: 'gorilla' })).to be_nil + end + end +end diff --git a/samples/client/petstore/ruby/spec/spec_helper.rb b/samples/client/petstore/ruby/spec/spec_helper.rb index 5cd856c95041..db7155ecfb5d 100644 --- a/samples/client/petstore/ruby/spec/spec_helper.rb +++ b/samples/client/petstore/ruby/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES index 2acd491c5ee4..b813c7f60efa 100644 --- a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES +++ b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/FILES @@ -20,6 +20,7 @@ docs/StoreApi.md docs/Tag.md docs/TestingApi.md docs/TypeTesting.md +docs/UniqueItemArrayTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -48,4 +49,5 @@ src/models/pet.rs src/models/property_test.rs src/models/tag.rs src/models/type_testing.rs +src/models/unique_item_array_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/hyper/petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/hyper/petstore/README.md b/samples/client/petstore/rust/hyper/petstore/README.md index 376185f5aa82..9c8f30b5fa41 100644 --- a/samples/client/petstore/rust/hyper/petstore/README.md +++ b/samples/client/petstore/rust/hyper/petstore/README.md @@ -66,6 +66,7 @@ Class | Method | HTTP request | Description - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [TypeTesting](docs/TypeTesting.md) + - [UniqueItemArrayTesting](docs/UniqueItemArrayTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/hyper/petstore/docs/UniqueItemArrayTesting.md b/samples/client/petstore/rust/hyper/petstore/docs/UniqueItemArrayTesting.md new file mode 100644 index 000000000000..6e103e2bb28d --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/docs/UniqueItemArrayTesting.md @@ -0,0 +1,11 @@ +# UniqueItemArrayTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**unique_item_array** | **Vec** | Helper object for the unique item array test | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs b/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs index db76077d2b97..fa16eac3cac9 100644 --- a/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs +++ b/samples/client/petstore/rust/hyper/petstore/src/models/mod.rs @@ -26,5 +26,7 @@ pub mod tag; pub use self::tag::Tag; pub mod type_testing; pub use self::type_testing::TypeTesting; +pub mod unique_item_array_testing; +pub use self::unique_item_array_testing::UniqueItemArrayTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/hyper/petstore/src/models/unique_item_array_testing.rs b/samples/client/petstore/rust/hyper/petstore/src/models/unique_item_array_testing.rs new file mode 100644 index 000000000000..a82e3e5773bd --- /dev/null +++ b/samples/client/petstore/rust/hyper/petstore/src/models/unique_item_array_testing.rs @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// UniqueItemArrayTesting : Test handling of enum array with unique items + + + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct UniqueItemArrayTesting { + /// Helper object for the unique item array test + #[serde(rename = "unique_item_array")] + pub unique_item_array: std::collections::HashSet, +} + +impl UniqueItemArrayTesting { + /// Test handling of enum array with unique items + pub fn new(unique_item_array: std::collections::HashSet) -> UniqueItemArrayTesting { + UniqueItemArrayTesting { + unique_item_array, + } + } +} + +/// Helper object for the unique item array test +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum UniqueItemArray { + #[serde(rename = "unique_item_1")] + Variant1, + #[serde(rename = "unique_item_2")] + Variant2, + #[serde(rename = "unique_item_3")] + Variant3, +} + +impl Default for UniqueItemArray { + fn default() -> UniqueItemArray { + Self::Variant1 + } +} + diff --git a/samples/client/petstore/rust/reqwest/name-mapping/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/name-mapping/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/reqwest/name-mapping/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/name-mapping/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/name-mapping/Cargo.toml b/samples/client/petstore/rust/reqwest/name-mapping/Cargo.toml index 5e7f18223f5e..d7c5df28fbf6 100644 --- a/samples/client/petstore/rust/reqwest/name-mapping/Cargo.toml +++ b/samples/client/petstore/rust/reqwest/name-mapping/Cargo.toml @@ -12,4 +12,6 @@ serde_derive = "^1.0" serde_json = "^1.0" url = "^2.2" uuid = { version = "^1.0", features = ["serde", "v4"] } -reqwest = "~0.9" +[dependencies.reqwest] +version = "^0.11" +features = ["json", "blocking", "multipart"] diff --git a/samples/client/petstore/rust/reqwest/name-mapping/src/apis/configuration.rs b/samples/client/petstore/rust/reqwest/name-mapping/src/apis/configuration.rs index 76cc4bf042b8..c2176e57ad09 100644 --- a/samples/client/petstore/rust/reqwest/name-mapping/src/apis/configuration.rs +++ b/samples/client/petstore/rust/reqwest/name-mapping/src/apis/configuration.rs @@ -14,7 +14,7 @@ pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest::blocking::Client, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, @@ -42,7 +42,7 @@ impl Default for Configuration { Configuration { base_path: "http://petstore.swagger.io/v2".to_owned(), user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: reqwest::Client::new(), + client: reqwest::blocking::Client::new(), basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/FILES index 5fb0f5022d67..17419c0ea7cd 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/FILES @@ -20,6 +20,7 @@ docs/StoreApi.md docs/Tag.md docs/TestingApi.md docs/TypeTesting.md +docs/UniqueItemArrayTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -46,4 +47,5 @@ src/models/pet.rs src/models/property_test.rs src/models/tag.rs src/models/type_testing.rs +src/models/unique_item_array_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/README.md b/samples/client/petstore/rust/reqwest/petstore-async-middleware/README.md index 2c0f34ad0dca..b2710a872d8b 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async-middleware/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/README.md @@ -66,6 +66,7 @@ Class | Method | HTTP request | Description - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [TypeTesting](docs/TypeTesting.md) + - [UniqueItemArrayTesting](docs/UniqueItemArrayTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/docs/UniqueItemArrayTesting.md b/samples/client/petstore/rust/reqwest/petstore-async-middleware/docs/UniqueItemArrayTesting.md new file mode 100644 index 000000000000..6e103e2bb28d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/docs/UniqueItemArrayTesting.md @@ -0,0 +1,11 @@ +# UniqueItemArrayTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**unique_item_array** | **Vec** | Helper object for the unique item array test | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/mod.rs index db76077d2b97..fa16eac3cac9 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/mod.rs @@ -26,5 +26,7 @@ pub mod tag; pub use self::tag::Tag; pub mod type_testing; pub use self::type_testing::TypeTesting; +pub mod unique_item_array_testing; +pub use self::unique_item_array_testing::UniqueItemArrayTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/unique_item_array_testing.rs b/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/unique_item_array_testing.rs new file mode 100644 index 000000000000..a82e3e5773bd --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async-middleware/src/models/unique_item_array_testing.rs @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// UniqueItemArrayTesting : Test handling of enum array with unique items + + + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct UniqueItemArrayTesting { + /// Helper object for the unique item array test + #[serde(rename = "unique_item_array")] + pub unique_item_array: std::collections::HashSet, +} + +impl UniqueItemArrayTesting { + /// Test handling of enum array with unique items + pub fn new(unique_item_array: std::collections::HashSet) -> UniqueItemArrayTesting { + UniqueItemArrayTesting { + unique_item_array, + } + } +} + +/// Helper object for the unique item array test +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum UniqueItemArray { + #[serde(rename = "unique_item_1")] + Variant1, + #[serde(rename = "unique_item_2")] + Variant2, + #[serde(rename = "unique_item_3")] + Variant3, +} + +impl Default for UniqueItemArray { + fn default() -> UniqueItemArray { + Self::Variant1 + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES index 5fb0f5022d67..17419c0ea7cd 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/FILES @@ -20,6 +20,7 @@ docs/StoreApi.md docs/Tag.md docs/TestingApi.md docs/TypeTesting.md +docs/UniqueItemArrayTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -46,4 +47,5 @@ src/models/pet.rs src/models/property_test.rs src/models/tag.rs src/models/type_testing.rs +src/models/unique_item_array_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore-async/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore-async/README.md b/samples/client/petstore/rust/reqwest/petstore-async/README.md index 7e3b9e0c2923..349da0fc5917 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-async/README.md @@ -66,6 +66,7 @@ Class | Method | HTTP request | Description - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [TypeTesting](docs/TypeTesting.md) + - [UniqueItemArrayTesting](docs/UniqueItemArrayTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-async/docs/UniqueItemArrayTesting.md b/samples/client/petstore/rust/reqwest/petstore-async/docs/UniqueItemArrayTesting.md new file mode 100644 index 000000000000..6e103e2bb28d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/docs/UniqueItemArrayTesting.md @@ -0,0 +1,11 @@ +# UniqueItemArrayTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**unique_item_array** | **Vec** | Helper object for the unique item array test | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs index db76077d2b97..fa16eac3cac9 100644 --- a/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/mod.rs @@ -26,5 +26,7 @@ pub mod tag; pub use self::tag::Tag; pub mod type_testing; pub use self::type_testing::TypeTesting; +pub mod unique_item_array_testing; +pub use self::unique_item_array_testing::UniqueItemArrayTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore-async/src/models/unique_item_array_testing.rs b/samples/client/petstore/rust/reqwest/petstore-async/src/models/unique_item_array_testing.rs new file mode 100644 index 000000000000..a82e3e5773bd --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-async/src/models/unique_item_array_testing.rs @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// UniqueItemArrayTesting : Test handling of enum array with unique items + + + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct UniqueItemArrayTesting { + /// Helper object for the unique item array test + #[serde(rename = "unique_item_array")] + pub unique_item_array: std::collections::HashSet, +} + +impl UniqueItemArrayTesting { + /// Test handling of enum array with unique items + pub fn new(unique_item_array: std::collections::HashSet) -> UniqueItemArrayTesting { + UniqueItemArrayTesting { + unique_item_array, + } + } +} + +/// Helper object for the unique item array test +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum UniqueItemArray { + #[serde(rename = "unique_item_1")] + Variant1, + #[serde(rename = "unique_item_2")] + Variant2, + #[serde(rename = "unique_item_3")] + Variant3, +} + +impl Default for UniqueItemArray { + fn default() -> UniqueItemArray { + Self::Variant1 + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES index 5fb0f5022d67..17419c0ea7cd 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/FILES @@ -20,6 +20,7 @@ docs/StoreApi.md docs/Tag.md docs/TestingApi.md docs/TypeTesting.md +docs/UniqueItemArrayTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -46,4 +47,5 @@ src/models/pet.rs src/models/property_test.rs src/models/tag.rs src/models/type_testing.rs +src/models/unique_item_array_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml index 031c64aab0fe..a390b57fa5bf 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/Cargo.toml @@ -16,4 +16,6 @@ uuid = { version = "^1.0", features = ["serde", "v4"] } aws-sigv4 = "0.3.0" http = "0.2.5" secrecy = "0.8.0" -reqwest = "~0.9" +[dependencies.reqwest] +version = "^0.11" +features = ["json", "blocking", "multipart"] diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md index 30afa984f48d..84bf3ebd6736 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/README.md @@ -66,6 +66,7 @@ Class | Method | HTTP request | Description - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [TypeTesting](docs/TypeTesting.md) + - [UniqueItemArrayTesting](docs/UniqueItemArrayTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/UniqueItemArrayTesting.md b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/UniqueItemArrayTesting.md new file mode 100644 index 000000000000..6e103e2bb28d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/docs/UniqueItemArrayTesting.md @@ -0,0 +1,11 @@ +# UniqueItemArrayTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**unique_item_array** | **Vec** | Helper object for the unique item array test | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/configuration.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/configuration.rs index 3e10cc7c3582..e8b030ae01b9 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/configuration.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/configuration.rs @@ -18,7 +18,7 @@ use secrecy::{SecretString, ExposeSecret}; pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest::blocking::Client, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, @@ -83,7 +83,7 @@ impl Default for Configuration { Configuration { base_path: "http://petstore.swagger.io/v2".to_owned(), user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: reqwest::Client::new(), + client: reqwest::blocking::Client::new(), basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs index 5f23a08cdf91..9b4554aa07fe 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/mod.rs @@ -38,7 +38,7 @@ impl error::Error for Error { Error::Serde(e) => e, Error::Io(e) => e, Error::ResponseError(_) => return None, - Error::AWSV4SignatureError(_) => return None, + Error::AWSV4SignatureError(_) => return None, }) } } diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/pet_api.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/pet_api.rs index bbfd13f12656..81edae5f241e 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/apis/pet_api.rs @@ -444,7 +444,7 @@ pub fn upload_file(configuration: &configuration::Configuration, pet_id: i64, ad if let Some(ref local_var_token) = local_var_configuration.oauth_access_token { local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut local_var_form = reqwest::multipart::Form::new(); + let mut local_var_form = reqwest::blocking::multipart::Form::new(); if let Some(local_var_param_value) = additional_metadata { local_var_form = local_var_form.text("additionalMetadata", local_var_param_value.to_string()); } diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs index db76077d2b97..fa16eac3cac9 100644 --- a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/mod.rs @@ -26,5 +26,7 @@ pub mod tag; pub use self::tag::Tag; pub mod type_testing; pub use self::type_testing::TypeTesting; +pub mod unique_item_array_testing; +pub use self::unique_item_array_testing::UniqueItemArrayTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/unique_item_array_testing.rs b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/unique_item_array_testing.rs new file mode 100644 index 000000000000..a82e3e5773bd --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore-awsv4signature/src/models/unique_item_array_testing.rs @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// UniqueItemArrayTesting : Test handling of enum array with unique items + + + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct UniqueItemArrayTesting { + /// Helper object for the unique item array test + #[serde(rename = "unique_item_array")] + pub unique_item_array: std::collections::HashSet, +} + +impl UniqueItemArrayTesting { + /// Test handling of enum array with unique items + pub fn new(unique_item_array: std::collections::HashSet) -> UniqueItemArrayTesting { + UniqueItemArrayTesting { + unique_item_array, + } + } +} + +/// Helper object for the unique item array test +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum UniqueItemArray { + #[serde(rename = "unique_item_1")] + Variant1, + #[serde(rename = "unique_item_2")] + Variant2, + #[serde(rename = "unique_item_3")] + Variant3, +} + +impl Default for UniqueItemArray { + fn default() -> UniqueItemArray { + Self::Variant1 + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES index 5fb0f5022d67..17419c0ea7cd 100644 --- a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES +++ b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/FILES @@ -20,6 +20,7 @@ docs/StoreApi.md docs/Tag.md docs/TestingApi.md docs/TypeTesting.md +docs/UniqueItemArrayTesting.md docs/User.md docs/UserApi.md git_push.sh @@ -46,4 +47,5 @@ src/models/pet.rs src/models/property_test.rs src/models/tag.rs src/models/type_testing.rs +src/models/unique_item_array_testing.rs src/models/user.rs diff --git a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/rust/reqwest/petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/rust/reqwest/petstore/Cargo.toml b/samples/client/petstore/rust/reqwest/petstore/Cargo.toml index ae0098206eb1..ac96d24a7db3 100644 --- a/samples/client/petstore/rust/reqwest/petstore/Cargo.toml +++ b/samples/client/petstore/rust/reqwest/petstore/Cargo.toml @@ -13,4 +13,6 @@ serde_with = "^2.0" serde_json = "^1.0" url = "^2.2" uuid = { version = "^1.0", features = ["serde", "v4"] } -reqwest = "~0.9" +[dependencies.reqwest] +version = "^0.11" +features = ["json", "blocking", "multipart"] diff --git a/samples/client/petstore/rust/reqwest/petstore/README.md b/samples/client/petstore/rust/reqwest/petstore/README.md index 132869e14ca7..47b805c54b2d 100644 --- a/samples/client/petstore/rust/reqwest/petstore/README.md +++ b/samples/client/petstore/rust/reqwest/petstore/README.md @@ -66,6 +66,7 @@ Class | Method | HTTP request | Description - [Return](docs/Return.md) - [Tag](docs/Tag.md) - [TypeTesting](docs/TypeTesting.md) + - [UniqueItemArrayTesting](docs/UniqueItemArrayTesting.md) - [User](docs/User.md) diff --git a/samples/client/petstore/rust/reqwest/petstore/docs/UniqueItemArrayTesting.md b/samples/client/petstore/rust/reqwest/petstore/docs/UniqueItemArrayTesting.md new file mode 100644 index 000000000000..6e103e2bb28d --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/docs/UniqueItemArrayTesting.md @@ -0,0 +1,11 @@ +# UniqueItemArrayTesting + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**unique_item_array** | **Vec** | Helper object for the unique item array test | + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/configuration.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/configuration.rs index ba335d974cc6..8a43283dd436 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/configuration.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/configuration.rs @@ -14,7 +14,7 @@ pub struct Configuration { pub base_path: String, pub user_agent: Option, - pub client: reqwest::Client, + pub client: reqwest::blocking::Client, pub basic_auth: Option, pub oauth_access_token: Option, pub bearer_access_token: Option, @@ -42,7 +42,7 @@ impl Default for Configuration { Configuration { base_path: "http://petstore.swagger.io/v2".to_owned(), user_agent: Some("OpenAPI-Generator/1.0.0/rust".to_owned()), - client: reqwest::Client::new(), + client: reqwest::blocking::Client::new(), basic_auth: None, oauth_access_token: None, bearer_access_token: None, diff --git a/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs b/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs index 0e0a2bc19a15..4fb8e4c8af62 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/apis/pet_api.rs @@ -340,7 +340,7 @@ pub fn upload_file(configuration: &configuration::Configuration, pet_id: i64, ad if let Some(ref local_var_token) = local_var_configuration.oauth_access_token { local_var_req_builder = local_var_req_builder.bearer_auth(local_var_token.to_owned()); }; - let mut local_var_form = reqwest::multipart::Form::new(); + let mut local_var_form = reqwest::blocking::multipart::Form::new(); if let Some(local_var_param_value) = additional_metadata { local_var_form = local_var_form.text("additionalMetadata", local_var_param_value.to_string()); } diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs index db76077d2b97..fa16eac3cac9 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/mod.rs @@ -26,5 +26,7 @@ pub mod tag; pub use self::tag::Tag; pub mod type_testing; pub use self::type_testing::TypeTesting; +pub mod unique_item_array_testing; +pub use self::unique_item_array_testing::UniqueItemArrayTesting; pub mod user; pub use self::user::User; diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/order.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/order.rs index 3c7d00591001..d3fe7e2a955f 100644 --- a/samples/client/petstore/rust/reqwest/petstore/src/models/order.rs +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/order.rs @@ -51,7 +51,7 @@ pub enum Status { #[serde(rename = "approved")] Approved, #[serde(rename = "delivered")] - Delivered, + shipped, } impl Default for Status { diff --git a/samples/client/petstore/rust/reqwest/petstore/src/models/unique_item_array_testing.rs b/samples/client/petstore/rust/reqwest/petstore/src/models/unique_item_array_testing.rs new file mode 100644 index 000000000000..a82e3e5773bd --- /dev/null +++ b/samples/client/petstore/rust/reqwest/petstore/src/models/unique_item_array_testing.rs @@ -0,0 +1,47 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * Generated by: https://openapi-generator.tech + */ + +/// UniqueItemArrayTesting : Test handling of enum array with unique items + + + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct UniqueItemArrayTesting { + /// Helper object for the unique item array test + #[serde(rename = "unique_item_array")] + pub unique_item_array: std::collections::HashSet, +} + +impl UniqueItemArrayTesting { + /// Test handling of enum array with unique items + pub fn new(unique_item_array: std::collections::HashSet) -> UniqueItemArrayTesting { + UniqueItemArrayTesting { + unique_item_array, + } + } +} + +/// Helper object for the unique item array test +#[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Serialize, Deserialize)] +pub enum UniqueItemArray { + #[serde(rename = "unique_item_1")] + Variant1, + #[serde(rename = "unique_item_2")] + Variant2, + #[serde(rename = "unique_item_3")] + Variant3, +} + +impl Default for UniqueItemArray { + fn default() -> UniqueItemArray { + Self::Variant1 + } +} + diff --git a/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs b/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs index e89187b170cc..186ae1acade0 100644 --- a/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs +++ b/samples/client/petstore/rust/reqwest/petstore/tests/type_testing.rs @@ -1,10 +1,19 @@ extern crate petstore_reqwest; use petstore_reqwest::models::TypeTesting; +use uuid::Uuid; #[test] fn test_types() { - let tt = TypeTesting::default(); + let tt = TypeTesting { + int32: 123, + int64: 456, + float: 12.34, + double: 45.56, + string: String::from("something"), + boolean: true, + uuid: Uuid::new_v4() + }; assert_eq!(type_of(tt.int32), "i32"); assert_eq!(type_of(tt.int64), "i64"); assert_eq!(type_of(tt.float), "f32"); diff --git a/samples/client/petstore/scala-akka/.openapi-generator/VERSION b/samples/client/petstore/scala-akka/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/scala-akka/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-akka/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala index 3dfa61094de0..d6f5ae6182e3 100644 --- a/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala +++ b/samples/client/petstore/scala-akka/src/main/scala/org/openapitools/client/core/ApiRequest.scala @@ -59,6 +59,8 @@ case class ApiRequest[U]( def withPathParam(name: String, value: Any): ApiRequest[U] = copy[U](pathParams = pathParams + (name -> value)) + def withQueryParam(values: Map[String, Any]): ApiRequest[U] = copy[U](queryParams = queryParams ++ values) + def withQueryParam(name: String, value: Any): ApiRequest[U] = copy[U](queryParams = queryParams + (name -> value)) def withHeaderParam(name: String, value: Any): ApiRequest[U] = copy[U](headerParams = headerParams + (name -> value)) diff --git a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala index 48c8d4c644fd..15bec1fea3ba 100644 --- a/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala +++ b/samples/client/petstore/scala-akka/src/test/scala/PetApiTest.scala @@ -87,7 +87,6 @@ class PetApiTest extends AsyncFlatSpec with Matchers { it should "find pets by status" in { val request = api.findPetsByStatus(List("available")) - invoker .execute(request) .map { apiResponse => diff --git a/samples/client/petstore/scala-pekko/.openapi-generator-ignore b/samples/client/petstore/scala-pekko/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/client/petstore/scala-pekko/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/client/petstore/scala-pekko/.openapi-generator/FILES b/samples/client/petstore/scala-pekko/.openapi-generator/FILES new file mode 100644 index 000000000000..d5d327c27595 --- /dev/null +++ b/samples/client/petstore/scala-pekko/.openapi-generator/FILES @@ -0,0 +1,29 @@ +README.md +build.sbt +docs/ApiResponse.md +docs/Category.md +docs/Order.md +docs/Pet.md +docs/PetApi.md +docs/StoreApi.md +docs/Tag.md +docs/User.md +docs/UserApi.md +pom.xml +project/build.properties +src/main/resources/reference.conf +src/main/scala/org/openapitools/client/api/EnumsSerializers.scala +src/main/scala/org/openapitools/client/api/PetApi.scala +src/main/scala/org/openapitools/client/api/StoreApi.scala +src/main/scala/org/openapitools/client/api/UserApi.scala +src/main/scala/org/openapitools/client/core/ApiInvoker.scala +src/main/scala/org/openapitools/client/core/ApiRequest.scala +src/main/scala/org/openapitools/client/core/ApiSettings.scala +src/main/scala/org/openapitools/client/core/Serializers.scala +src/main/scala/org/openapitools/client/core/requests.scala +src/main/scala/org/openapitools/client/model/ApiResponse.scala +src/main/scala/org/openapitools/client/model/Category.scala +src/main/scala/org/openapitools/client/model/Order.scala +src/main/scala/org/openapitools/client/model/Pet.scala +src/main/scala/org/openapitools/client/model/Tag.scala +src/main/scala/org/openapitools/client/model/User.scala diff --git a/samples/client/petstore/scala-pekko/.openapi-generator/VERSION b/samples/client/petstore/scala-pekko/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/client/petstore/scala-pekko/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-pekko/README.md b/samples/client/petstore/scala-pekko/README.md new file mode 100644 index 000000000000..65a0f09699cb --- /dev/null +++ b/samples/client/petstore/scala-pekko/README.md @@ -0,0 +1,170 @@ +# scala-pekko-petstore-client + +OpenAPI Petstore +- API version: 1.0.0 + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + + +*Automatically generated by the [OpenAPI Generator](https://openapi-generator.tech)* + +## Requirements + +Building the API client library requires: +1. Java 1.7+ +2. Maven/Gradle/SBT + +## Installation + +To install the API client library to your local Maven repository, simply execute: + +```shell +mvn clean install +``` + +To deploy it to a remote Maven repository instead, configure the settings of the repository and execute: + +```shell +mvn clean deploy +``` + +Refer to the [OSSRH Guide](http://central.sonatype.org/pages/ossrh-guide.html) for more information. + +### Maven users + +Add this dependency to your project's POM: + +```xml + + org.openapitools + scala-pekko-petstore-client + 1.0.0 + compile + +``` + +### Gradle users + +Add this dependency to your project's build file: + +```groovy +compile "org.openapitools:scala-pekko-petstore-client:1.0.0" +``` + +### SBT users + +```scala +libraryDependencies += "org.openapitools" % "scala-pekko-petstore-client" % "1.0.0" +``` + +## Getting Started + +Please follow the [installation](#installation) instruction and execute the following Java code: + +```scala + +import org.openapitools.client.core._ +import org.openapitools.client.model._ +import org.openapitools.client.api.PetApi + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object PetApiExample extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Create invoker to execute requests + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val pet: Pet = // Pet | Pet object that needs to be added to the store + + val request = apiInstance.addPet(pet) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(org.openapitools.client.core.ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#addPet") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#addPet") + exception.printStackTrace(); + } + +} + +``` + +## Documentation for API Endpoints + +All URIs are relative to *https://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetApi* | [**addPet**](docs/PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +*PetApi* | [**deletePet**](docs/PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +*PetApi* | [**findPetsByStatus**](docs/PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +*PetApi* | [**findPetsByTags**](docs/PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +*PetApi* | [**getPetById**](docs/PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +*PetApi* | [**updatePet**](docs/PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +*PetApi* | [**updatePetWithForm**](docs/PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +*PetApi* | [**uploadFile**](docs/PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +*StoreApi* | [**deleteOrder**](docs/StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +*StoreApi* | [**getInventory**](docs/StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +*StoreApi* | [**getOrderById**](docs/StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +*StoreApi* | [**placeOrder**](docs/StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +*UserApi* | [**createUser**](docs/UserApi.md#createUser) | **POST** /user | Create user +*UserApi* | [**createUsersWithArrayInput**](docs/UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +*UserApi* | [**createUsersWithListInput**](docs/UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +*UserApi* | [**deleteUser**](docs/UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +*UserApi* | [**getUserByName**](docs/UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +*UserApi* | [**loginUser**](docs/UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +*UserApi* | [**logoutUser**](docs/UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +*UserApi* | [**updateUser**](docs/UserApi.md#updateUser) | **PUT** /user/{username} | Updated user + + +## Documentation for Models + + - [ApiResponse](docs/ApiResponse.md) + - [Category](docs/Category.md) + - [Order](docs/Order.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + - [User](docs/User.md) + + + +## Documentation for Authorization + + +Authentication schemes defined for the API: + +### api_key + +- **Type**: API key +- **API key parameter name**: api_key +- **Location**: HTTP header + + +### auth_cookie + +- **Type**: API key +- **API key parameter name**: AUTH_KEY +- **Location**: + + +## Author + + + diff --git a/samples/client/petstore/scala-pekko/build.sbt b/samples/client/petstore/scala-pekko/build.sbt new file mode 100644 index 000000000000..9a66e5880699 --- /dev/null +++ b/samples/client/petstore/scala-pekko/build.sbt @@ -0,0 +1,29 @@ +version := "1.0.0" +name := "scala-pekko-petstore-client" +organization := "org.openapitools" + +scalaVersion := "2.13.12" +val PekkoVersion = "1.0.2" + +libraryDependencies ++= Seq( + "com.typesafe" % "config" % "1.4.3", + "org.apache.pekko" %% "pekko-actor" % PekkoVersion, + "org.apache.pekko" %% "pekko-stream" % PekkoVersion, + "org.apache.pekko" %% "pekko-stream" % PekkoVersion, + "com.github.pjfanning" %% "pekko-http-json4s" % "2.3.2", + "org.json4s" %% "json4s-jackson" % "4.0.7", + "org.json4s" %% "json4s-ext" % "4.0.7", + // test dependencies + "org.scalatest" %% "scalatest" % "3.2.17" % "test", + "org.scalatestplus" %% "junit-4-13" % "3.2.17.0" % "test" +) + +resolvers ++= Seq(Resolver.mavenLocal) + +scalacOptions := Seq( + "-unchecked", + "-deprecation", + "-feature" +) + +publishArtifact in (Compile, packageDoc) := false diff --git a/samples/client/petstore/scala-pekko/docs/ApiResponse.md b/samples/client/petstore/scala-pekko/docs/ApiResponse.md new file mode 100644 index 000000000000..bd174989f6f0 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/ApiResponse.md @@ -0,0 +1,16 @@ + + +# ApiResponse + +Describes the result of uploading an image resource + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**code** | **Int** | | [optional] +**`type`** | **String** | | [optional] +**message** | **String** | | [optional] + + + diff --git a/samples/client/petstore/scala-pekko/docs/Category.md b/samples/client/petstore/scala-pekko/docs/Category.md new file mode 100644 index 000000000000..6f5421307d51 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/Category.md @@ -0,0 +1,15 @@ + + +# Category + +A category for a pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/scala-pekko/docs/Order.md b/samples/client/petstore/scala-pekko/docs/Order.md new file mode 100644 index 000000000000..2b9b49297531 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/Order.md @@ -0,0 +1,24 @@ + + +# Order + +An order for a pets from the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**petId** | **Long** | | [optional] +**quantity** | **Int** | | [optional] +**shipDate** | **OffsetDateTime** | | [optional] +**status** | [**Status**](#Status) | Order Status | [optional] +**complete** | **Boolean** | | [optional] + + +## Enum: Status +Allowed values: [placed, approved, delivered] + + + + diff --git a/samples/client/petstore/scala-pekko/docs/Pet.md b/samples/client/petstore/scala-pekko/docs/Pet.md new file mode 100644 index 000000000000..2c65c5440df0 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/Pet.md @@ -0,0 +1,24 @@ + + +# Pet + +A pet for sale in the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**category** | [**Category**](Category.md) | | [optional] +**name** | **String** | | +**photoUrls** | **Seq<String>** | | +**tags** | [**Seq<Tag>**](Tag.md) | | [optional] +**status** | [**Status**](#Status) | pet status in the store | [optional] + + +## Enum: Status +Allowed values: [available, pending, sold] + + + + diff --git a/samples/client/petstore/scala-pekko/docs/PetApi.md b/samples/client/petstore/scala-pekko/docs/PetApi.md new file mode 100644 index 000000000000..1b24b9a61988 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/PetApi.md @@ -0,0 +1,688 @@ +# PetApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**addPet**](PetApi.md#addPet) | **POST** /pet | Add a new pet to the store +[**addPetWithHttpInfo**](PetApi.md#addPetWithHttpInfo) | **POST** /pet | Add a new pet to the store +[**deletePet**](PetApi.md#deletePet) | **DELETE** /pet/{petId} | Deletes a pet +[**deletePetWithHttpInfo**](PetApi.md#deletePetWithHttpInfo) | **DELETE** /pet/{petId} | Deletes a pet +[**findPetsByStatus**](PetApi.md#findPetsByStatus) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByStatusWithHttpInfo**](PetApi.md#findPetsByStatusWithHttpInfo) | **GET** /pet/findByStatus | Finds Pets by status +[**findPetsByTags**](PetApi.md#findPetsByTags) | **GET** /pet/findByTags | Finds Pets by tags +[**findPetsByTagsWithHttpInfo**](PetApi.md#findPetsByTagsWithHttpInfo) | **GET** /pet/findByTags | Finds Pets by tags +[**getPetById**](PetApi.md#getPetById) | **GET** /pet/{petId} | Find pet by ID +[**getPetByIdWithHttpInfo**](PetApi.md#getPetByIdWithHttpInfo) | **GET** /pet/{petId} | Find pet by ID +[**updatePet**](PetApi.md#updatePet) | **PUT** /pet | Update an existing pet +[**updatePetWithHttpInfo**](PetApi.md#updatePetWithHttpInfo) | **PUT** /pet | Update an existing pet +[**updatePetWithForm**](PetApi.md#updatePetWithForm) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**updatePetWithFormWithHttpInfo**](PetApi.md#updatePetWithFormWithHttpInfo) | **POST** /pet/{petId} | Updates a pet in the store with form data +[**uploadFile**](PetApi.md#uploadFile) | **POST** /pet/{petId}/uploadImage | uploads an image +[**uploadFileWithHttpInfo**](PetApi.md#uploadFileWithHttpInfo) | **POST** /pet/{petId}/uploadImage | uploads an image + + + +## addPet + +> addPet(addPetRequest): ApiRequest[Pet] + +Add a new pet to the store + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val pet: Pet = // Pet | Pet object that needs to be added to the store + + val request = apiInstance.addPet(pet) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#addPet") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#addPet") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +ApiRequest[[**Pet**](Pet.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + + +## deletePet + +> deletePet(deletePetRequest): ApiRequest[Unit] + +Deletes a pet + + + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val petId: Long = 789 // Long | Pet id to delete + + val apiKey: String = apiKey_example // String | + + val request = apiInstance.deletePet(petId, apiKey) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#deletePet") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#deletePet") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| Pet id to delete | + **apiKey** | **String**| | [optional] + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid pet value | - | + + +## findPetsByStatus + +> findPetsByStatus(findPetsByStatusRequest): ApiRequest[Seq[Pet]] + +Finds Pets by status + +Multiple status values can be provided with comma separated strings + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val status: Seq[String] = // Seq[String] | Status values that need to be considered for filter + + val request = apiInstance.findPetsByStatus(status) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#findPetsByStatus") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#findPetsByStatus") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **status** | [**Seq[String]**](String.md)| Status values that need to be considered for filter | [enum: available, pending, sold] + +### Return type + +ApiRequest[[**Seq[Pet]**](Pet.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid status value | - | + + +## findPetsByTags + +> findPetsByTags(findPetsByTagsRequest): ApiRequest[Seq[Pet]] + +Finds Pets by tags + +Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val tags: Seq[String] = // Seq[String] | Tags to filter by + + val request = apiInstance.findPetsByTags(tags) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#findPetsByTags") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#findPetsByTags") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **tags** | [**Seq[String]**](String.md)| Tags to filter by | + +### Return type + +ApiRequest[[**Seq[Pet]**](Pet.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid tag value | - | + + +## getPetById + +> getPetById(getPetByIdRequest): ApiRequest[Pet] + +Find pet by ID + +Returns a single pet + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: api_key + implicit val api_key: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val petId: Long = 789 // Long | ID of pet to return + + val request = apiInstance.getPetById(petId) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#getPetById") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#getPetById") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to return | + +### Return type + +ApiRequest[[**Pet**](Pet.md)] + + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | + + +## updatePet + +> updatePet(updatePetRequest): ApiRequest[Pet] + +Update an existing pet + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val pet: Pet = // Pet | Pet object that needs to be added to the store + + val request = apiInstance.updatePet(pet) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#updatePet") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#updatePet") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | + +### Return type + +ApiRequest[[**Pet**](Pet.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Pet not found | - | +| **405** | Validation exception | - | + + +## updatePetWithForm + +> updatePetWithForm(updatePetWithFormRequest): ApiRequest[Unit] + +Updates a pet in the store with form data + + + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val petId: Long = 789 // Long | ID of pet that needs to be updated + + val name: String = name_example // String | Updated name of the pet + + val status: String = status_example // String | Updated status of the pet + + val request = apiInstance.updatePetWithForm(petId, name, status) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#updatePetWithForm") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#updatePetWithForm") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet that needs to be updated | + **name** | **String**| Updated name of the pet | [optional] + **status** | **String**| Updated status of the pet | [optional] + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/x-www-form-urlencoded +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **405** | Invalid input | - | + + +## uploadFile + +> uploadFile(uploadFileRequest): ApiRequest[ApiResponse] + +uploads an image + + + +### Example + +```scala +// Import classes: +import +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = PetApi("https://petstore.swagger.io/v2") + val petId: Long = 789 // Long | ID of pet to update + + val additionalMetadata: String = additionalMetadata_example // String | Additional data to pass to server + + val file: File = BINARY_DATA_HERE // File | file to upload + + val request = apiInstance.uploadFile(petId, additionalMetadata, file) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling PetApi#uploadFile") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling PetApi#uploadFile") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **petId** | **Long**| ID of pet to update | + **additionalMetadata** | **String**| Additional data to pass to server | [optional] + **file** | **File**| file to upload | [optional] + +### Return type + +ApiRequest[[**ApiResponse**](ApiResponse.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: multipart/form-data +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + diff --git a/samples/client/petstore/scala-pekko/docs/StoreApi.md b/samples/client/petstore/scala-pekko/docs/StoreApi.md new file mode 100644 index 000000000000..d9a7378bf4ec --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/StoreApi.md @@ -0,0 +1,335 @@ +# StoreApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**deleteOrder**](StoreApi.md#deleteOrder) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**deleteOrderWithHttpInfo**](StoreApi.md#deleteOrderWithHttpInfo) | **DELETE** /store/order/{orderId} | Delete purchase order by ID +[**getInventory**](StoreApi.md#getInventory) | **GET** /store/inventory | Returns pet inventories by status +[**getInventoryWithHttpInfo**](StoreApi.md#getInventoryWithHttpInfo) | **GET** /store/inventory | Returns pet inventories by status +[**getOrderById**](StoreApi.md#getOrderById) | **GET** /store/order/{orderId} | Find purchase order by ID +[**getOrderByIdWithHttpInfo**](StoreApi.md#getOrderByIdWithHttpInfo) | **GET** /store/order/{orderId} | Find purchase order by ID +[**placeOrder**](StoreApi.md#placeOrder) | **POST** /store/order | Place an order for a pet +[**placeOrderWithHttpInfo**](StoreApi.md#placeOrderWithHttpInfo) | **POST** /store/order | Place an order for a pet + + + +## deleteOrder + +> deleteOrder(deleteOrderRequest): ApiRequest[Unit] + +Delete purchase order by ID + +For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = StoreApi("https://petstore.swagger.io/v2") + val orderId: String = orderId_example // String | ID of the order that needs to be deleted + + val request = apiInstance.deleteOrder(orderId) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling StoreApi#deleteOrder") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling StoreApi#deleteOrder") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **String**| ID of the order that needs to be deleted | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## getInventory + +> getInventory(): ApiRequest[Map[String, Int]] + +Returns pet inventories by status + +Returns a map of status codes to quantities + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: api_key + implicit val api_key: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = StoreApi("https://petstore.swagger.io/v2") + val request = apiInstance.getInventory() + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling StoreApi#getInventory") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling StoreApi#getInventory") + exception.printStackTrace(); + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +ApiRequest[**Map[String, Int]**] + + +### Authorization + +[api_key](../README.md#api_key) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + +## getOrderById + +> getOrderById(getOrderByIdRequest): ApiRequest[Order] + +Find purchase order by ID + +For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = StoreApi("https://petstore.swagger.io/v2") + val orderId: Long = 789 // Long | ID of pet that needs to be fetched + + val request = apiInstance.getOrderById(orderId) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling StoreApi#getOrderById") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling StoreApi#getOrderById") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **orderId** | **Long**| ID of pet that needs to be fetched | + +### Return type + +ApiRequest[[**Order**](Order.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid ID supplied | - | +| **404** | Order not found | - | + + +## placeOrder + +> placeOrder(placeOrderRequest): ApiRequest[Order] + +Place an order for a pet + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = StoreApi("https://petstore.swagger.io/v2") + val order: Order = // Order | order placed for purchasing the pet + + val request = apiInstance.placeOrder(order) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling StoreApi#placeOrder") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling StoreApi#placeOrder") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **order** | [**Order**](Order.md)| order placed for purchasing the pet | + +### Return type + +ApiRequest[[**Order**](Order.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid Order | - | + diff --git a/samples/client/petstore/scala-pekko/docs/Tag.md b/samples/client/petstore/scala-pekko/docs/Tag.md new file mode 100644 index 000000000000..ae6756ef3935 --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/Tag.md @@ -0,0 +1,15 @@ + + +# Tag + +A tag for a pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**name** | **String** | | [optional] + + + diff --git a/samples/client/petstore/scala-pekko/docs/User.md b/samples/client/petstore/scala-pekko/docs/User.md new file mode 100644 index 000000000000..44bea4103d0d --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/User.md @@ -0,0 +1,21 @@ + + +# User + +A User who is purchasing from the pet store + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**id** | **Long** | | [optional] +**username** | **String** | | [optional] +**firstName** | **String** | | [optional] +**lastName** | **String** | | [optional] +**email** | **String** | | [optional] +**password** | **String** | | [optional] +**phone** | **String** | | [optional] +**userStatus** | **Int** | User Status | [optional] + + + diff --git a/samples/client/petstore/scala-pekko/docs/UserApi.md b/samples/client/petstore/scala-pekko/docs/UserApi.md new file mode 100644 index 000000000000..097714ce9a7b --- /dev/null +++ b/samples/client/petstore/scala-pekko/docs/UserApi.md @@ -0,0 +1,680 @@ +# UserApi + +All URIs are relative to *https://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**createUser**](UserApi.md#createUser) | **POST** /user | Create user +[**createUserWithHttpInfo**](UserApi.md#createUserWithHttpInfo) | **POST** /user | Create user +[**createUsersWithArrayInput**](UserApi.md#createUsersWithArrayInput) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithArrayInputWithHttpInfo**](UserApi.md#createUsersWithArrayInputWithHttpInfo) | **POST** /user/createWithArray | Creates list of users with given input array +[**createUsersWithListInput**](UserApi.md#createUsersWithListInput) | **POST** /user/createWithList | Creates list of users with given input array +[**createUsersWithListInputWithHttpInfo**](UserApi.md#createUsersWithListInputWithHttpInfo) | **POST** /user/createWithList | Creates list of users with given input array +[**deleteUser**](UserApi.md#deleteUser) | **DELETE** /user/{username} | Delete user +[**deleteUserWithHttpInfo**](UserApi.md#deleteUserWithHttpInfo) | **DELETE** /user/{username} | Delete user +[**getUserByName**](UserApi.md#getUserByName) | **GET** /user/{username} | Get user by user name +[**getUserByNameWithHttpInfo**](UserApi.md#getUserByNameWithHttpInfo) | **GET** /user/{username} | Get user by user name +[**loginUser**](UserApi.md#loginUser) | **GET** /user/login | Logs user into the system +[**loginUserWithHttpInfo**](UserApi.md#loginUserWithHttpInfo) | **GET** /user/login | Logs user into the system +[**logoutUser**](UserApi.md#logoutUser) | **GET** /user/logout | Logs out current logged in user session +[**logoutUserWithHttpInfo**](UserApi.md#logoutUserWithHttpInfo) | **GET** /user/logout | Logs out current logged in user session +[**updateUser**](UserApi.md#updateUser) | **PUT** /user/{username} | Updated user +[**updateUserWithHttpInfo**](UserApi.md#updateUserWithHttpInfo) | **PUT** /user/{username} | Updated user + + + +## createUser + +> createUser(createUserRequest): ApiRequest[Unit] + +Create user + +This can only be done by the logged in user. + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val user: User = // User | Created user object + + val request = apiInstance.createUser(user) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#createUser") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#createUser") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**User**](User.md)| Created user object | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithArrayInput + +> createUsersWithArrayInput(createUsersWithArrayInputRequest): ApiRequest[Unit] + +Creates list of users with given input array + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val user: Seq[User] = // Seq[User] | List of user object + + val request = apiInstance.createUsersWithArrayInput(user) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#createUsersWithArrayInput") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#createUsersWithArrayInput") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**Seq[User]**](User.md)| List of user object | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## createUsersWithListInput + +> createUsersWithListInput(createUsersWithListInputRequest): ApiRequest[Unit] + +Creates list of users with given input array + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val user: Seq[User] = // Seq[User] | List of user object + + val request = apiInstance.createUsersWithListInput(user) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#createUsersWithListInput") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#createUsersWithListInput") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **user** | [**Seq[User]**](User.md)| List of user object | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## deleteUser + +> deleteUser(deleteUserRequest): ApiRequest[Unit] + +Delete user + +This can only be done by the logged in user. + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val username: String = username_example // String | The name that needs to be deleted + + val request = apiInstance.deleteUser(username) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#deleteUser") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#deleteUser") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be deleted | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## getUserByName + +> getUserByName(getUserByNameRequest): ApiRequest[User] + +Get user by user name + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val username: String = username_example // String | The name that needs to be fetched. Use user1 for testing. + + val request = apiInstance.getUserByName(username) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#getUserByName") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#getUserByName") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The name that needs to be fetched. Use user1 for testing. | + +### Return type + +ApiRequest[[**User**](User.md)] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | +| **400** | Invalid username supplied | - | +| **404** | User not found | - | + + +## loginUser + +> loginUser(loginUserRequest): ApiRequest[String] + +Logs user into the system + + + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val username: String = username_example // String | The user name for login + + val password: String = password_example // String | The password for login in clear text + + val request = apiInstance.loginUser(username, password) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + System.out.println(s"Response body: $content") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#loginUser") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#loginUser") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| The user name for login | + **password** | **String**| The password for login in clear text | + +### Return type + +ApiRequest[**String**] + + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: application/xml, application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | * Set-Cookie - Cookie authentication key for use with the `auth_cookie` apiKey authentication.
              * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | +| **400** | Invalid username/password supplied | - | + + +## logoutUser + +> logoutUser(): ApiRequest[Unit] + +Logs out current logged in user session + + + +### Example + +```scala +// Import classes: +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val request = apiInstance.logoutUser() + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#logoutUser") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#logoutUser") + exception.printStackTrace(); + } +} +``` + +### Parameters + +This endpoint does not need any parameter. + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: Not defined +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **0** | successful operation | - | + + +## updateUser + +> updateUser(updateUserRequest): ApiRequest[Unit] + +Updated user + +This can only be done by the logged in user. + +### Example + +```scala +// Import classes: +import +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +import org.apache.pekko.actor.ActorSystem +import scala.concurrent.Future +import scala.util.{Failure, Success} + +object Example extends App { + + implicit val system: ActorSystem = ActorSystem() + import system.dispatcher + + // Configure API key authorization: auth_cookie + implicit val auth_cookie: ApiKeyValue = ApiKeyValue("YOUR API KEY") + + val apiInvoker = ApiInvoker() + val apiInstance = UserApi("https://petstore.swagger.io/v2") + val username: String = username_example // String | name that need to be deleted + + val user: User = // User | Updated user object + + val request = apiInstance.updateUser(username, user) + val response = apiInvoker.execute(request) + + response.onComplete { + case Success(ApiResponse(code, content, headers)) => + System.out.println(s"Status code: $code}") + System.out.println(s"Response headers: ${headers.mkString(", ")}") + + case Failure(error @ ApiError(code, message, responseContent, cause, headers)) => + System.err.println("Exception when calling UserApi#updateUser") + System.err.println(s"Status code: $code}") + System.err.println(s"Reason: $responseContent") + System.err.println(s"Response headers: ${headers.mkString(", ")}") + error.printStackTrace(); + + case Failure(exception) => + System.err.println("Exception when calling UserApi#updateUser") + exception.printStackTrace(); + } +} +``` + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **username** | **String**| name that need to be deleted | + **user** | [**User**](User.md)| Updated user object | + +### Return type + + +ApiRequest[Unit] (empty response body) + +### Authorization + +[auth_cookie](../README.md#auth_cookie) + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **400** | Invalid user supplied | - | +| **404** | User not found | - | + diff --git a/samples/client/petstore/scala-pekko/pom.xml b/samples/client/petstore/scala-pekko/pom.xml new file mode 100644 index 000000000000..a37f416a058b --- /dev/null +++ b/samples/client/petstore/scala-pekko/pom.xml @@ -0,0 +1,254 @@ + + 4.0.0 + + scala-pekko-petstore-client + + org.openapitools + scala-pekko-petstore-client + 1.0.0 + + jar + + + UTF-8 + UTF-8 + + 1.8 + 2.13.12 + 4.0.7 + 4.0.7 + 1.0.2 + 1.0.0 + 1.4.3 + 2.3.2 + 3.2.17 + 3.2.17.0 + + 3.3.1 + + + + + org.scala-lang + scala-library + ${scala.version} + provided + + + com.typesafe + config + ${typesafeconfig.version} + + + org.apache.pekko + pekko-actor_2.13 + ${pekko.version} + + + org.apache.pekko + pekko-stream_2.13 + ${pekko.version} + + + org.apache.pekko + pekko-http_2.13 + ${pekko.http.version} + + + org.json4s + json4s-jackson_2.13 + ${json4s.jackson.version} + + + org.json4s + json4s-ext_2.13 + ${json4s.jackson.version} + + + com.github.pjfanning + pekko-http-json4s_2.13 + ${pekko.http.json4s.version} + + + + + org.scalatest + scalatest_2.13 + ${scala.test.version} + test + + + org.scalatestplus + junit-4-13_2.13 + ${scala.test.plus.version} + test + + + + + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.2 + + + org.apache.maven.plugins + maven-source-plugin + 3.0.1 + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M1 + + + enforce-maven + + enforce + + + + + 2.2.0 + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M4 + + + + loggerPath + conf/log4j.properties + + + -Xms512m -Xmx1500m + methods + 4 + pertest + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.0.2 + + + package + + copy-dependencies + + + ${project.build.directory}/lib + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 2.6 + + + + jar + test-jar + + + + + + + + + org.codehaus.mojo + build-helper-maven-plugin + 3.0.0 + + + add_sources + generate-sources + + add-source + + + + + src/main/java + + + + + + add_test_sources + generate-test-sources + + add-test-source + + + + + src/test/java + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.7.0 + + ${java.version} + ${java.version} + + + + net.alchim31.maven + scala-maven-plugin + ${scala.maven.plugin.version} + + + scala-compile-first + process-resources + + add-source + compile + + + + scala-test-compile + process-test-resources + + testCompile + + + + + + -feature + + + -Xms128m + -Xmx1500m + + + + + + diff --git a/samples/client/petstore/scala-pekko/project/build.properties b/samples/client/petstore/scala-pekko/project/build.properties new file mode 100644 index 000000000000..8cf07b7c2540 --- /dev/null +++ b/samples/client/petstore/scala-pekko/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.9.8 \ No newline at end of file diff --git a/samples/client/petstore/scala-pekko/src/main/resources/reference.conf b/samples/client/petstore/scala-pekko/src/main/resources/reference.conf new file mode 100644 index 000000000000..76e9842a8f8c --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/resources/reference.conf @@ -0,0 +1,24 @@ +org.openapitools.client { + + apiRequest { + + compression { + enabled: false + size-threshold: 0 + } + + trust-certificates: true + + connection-timeout: 5000ms + + default-headers { + "userAgent": "scala-pekko-petstore-client_1.0.0" + } + + // let you define custom http status code, as in : + // { code: 601, reason: "some custom http status code", success: false } + custom-codes : [] + } +} + +spray.can.host-connector.max-redirects = 10 \ No newline at end of file diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala new file mode 100644 index 000000000000..71ad618e31fb --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/EnumsSerializers.scala @@ -0,0 +1,51 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model._ +import org.json4s._ +import scala.reflect.ClassTag + +object EnumsSerializers { + + def all: Seq[Serializer[_]] = Seq[Serializer[_]]() :+ + new EnumNameSerializer(OrderEnums.Status) :+ + new EnumNameSerializer(PetEnums.Status) + + private class EnumNameSerializer[E <: Enumeration: ClassTag](enum: E) + extends Serializer[E#Value] { + import JsonDSL._ + + val EnumerationClass: Class[E#Value] = classOf[E#Value] + + def deserialize(implicit format: Formats): + PartialFunction[(TypeInfo, JValue), E#Value] = { + case (t @ TypeInfo(EnumerationClass, _), json) if isValid(json) => + json match { + case JString(value) => + enum.withName(value) + case value => + throw new MappingException(s"Can't convert $value to $EnumerationClass") + } + } + + private[this] def isValid(json: JValue) = json match { + case JString(value) if enum.values.exists(_.toString == value) => true + case _ => false + } + + def serialize(implicit format: Formats): PartialFunction[Any, JValue] = { + case i: E#Value => i.toString + } + } + +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/PetApi.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/PetApi.scala new file mode 100644 index 000000000000..f112d9ba1ff0 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/PetApi.scala @@ -0,0 +1,175 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model.ApiResponse +import java.io.File +import org.openapitools.client.model.Pet +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +object PetApi { + + def apply(baseUrl: String = "https://petstore.swagger.io/v2") = new PetApi(baseUrl) +} + +class PetApi(baseUrl: String) { + + /** + * + * + * Expected answers: + * code 200 : Pet (successful operation) + * code 405 : (Invalid input) + * + * @param pet Pet object that needs to be added to the store + */ + def addPet(pet: Pet): ApiRequest[Pet] = + ApiRequest[Pet](ApiMethods.POST, baseUrl, "/pet", "application/json") + .withBody(pet) + .withSuccessResponse[Pet](200) + .withErrorResponse[Unit](405) + + + /** + * + * + * Expected answers: + * code 400 : (Invalid pet value) + * + * @param petId Pet id to delete + * @param apiKey + */ + def deletePet(petId: Long, apiKey: Option[String] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, baseUrl, "/pet/{petId}", "application/json") + .withPathParam("petId", petId) + .withHeaderParam("api_key", apiKey) + .withErrorResponse[Unit](400) + + + /** + * Multiple status values can be provided with comma separated strings + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid status value) + * + * @param status Status values that need to be considered for filter + */ + def findPetsByStatus(status: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, baseUrl, "/pet/findByStatus", "application/json") + .withQueryParam("status", ArrayValues(status, CSV)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + + /** + * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + * + * Expected answers: + * code 200 : Seq[Pet] (successful operation) + * code 400 : (Invalid tag value) + * + * @param tags Tags to filter by + */ + def findPetsByTags(tags: Seq[String]): ApiRequest[Seq[Pet]] = + ApiRequest[Seq[Pet]](ApiMethods.GET, baseUrl, "/pet/findByTags", "application/json") + .withQueryParam("tags", ArrayValues(tags, CSV)) + .withSuccessResponse[Seq[Pet]](200) + .withErrorResponse[Unit](400) + + + /** + * Returns a single pet + * + * Expected answers: + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) + * + * Available security schemes: + * api_key (apiKey) + * + * @param petId ID of pet to return + */ + def getPetById(petId: Long)(implicit apiKey: ApiKeyValue): ApiRequest[Pet] = + ApiRequest[Pet](ApiMethods.GET, baseUrl, "/pet/{petId}", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withPathParam("petId", petId) + .withSuccessResponse[Pet](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + /** + * + * + * Expected answers: + * code 200 : Pet (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Pet not found) + * code 405 : (Validation exception) + * + * @param pet Pet object that needs to be added to the store + */ + def updatePet(pet: Pet): ApiRequest[Pet] = + ApiRequest[Pet](ApiMethods.PUT, baseUrl, "/pet", "application/json") + .withBody(pet) + .withSuccessResponse[Pet](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + .withErrorResponse[Unit](405) + + + /** + * + * + * Expected answers: + * code 200 : (successful operation) + * code 405 : (Invalid input) + * + * @param petId ID of pet that needs to be updated + * @param name Updated name of the pet + * @param status Updated status of the pet + */ + def updatePetWithForm(petId: Long, name: Option[String] = None, status: Option[String] = None): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, baseUrl, "/pet/{petId}", "application/x-www-form-urlencoded") + .withFormParam("name", name) + .withFormParam("status", status) + .withPathParam("petId", petId) + .withSuccessResponse[Unit](200) + .withErrorResponse[Unit](405) + + + /** + * + * + * Expected answers: + * code 200 : ApiResponse (successful operation) + * + * @param petId ID of pet to update + * @param additionalMetadata Additional data to pass to server + * @param file file to upload + */ + def uploadFile(petId: Long, additionalMetadata: Option[String] = None, file: Option[File] = None): ApiRequest[ApiResponse] = + ApiRequest[ApiResponse](ApiMethods.POST, baseUrl, "/pet/{petId}/uploadImage", "multipart/form-data") + .withFormParam("additionalMetadata", additionalMetadata) + .withFormParam("file", file) + .withPathParam("petId", petId) + .withSuccessResponse[ApiResponse](200) + + + + +} + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/StoreApi.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/StoreApi.scala new file mode 100644 index 000000000000..bffe37c55f45 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/StoreApi.scala @@ -0,0 +1,94 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import org.openapitools.client.model.Order +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +object StoreApi { + + def apply(baseUrl: String = "https://petstore.swagger.io/v2") = new StoreApi(baseUrl) +} + +class StoreApi(baseUrl: String) { + + /** + * For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + * + * Expected answers: + * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) + * + * @param orderId ID of the order that needs to be deleted + */ + def deleteOrder(orderId: String): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, baseUrl, "/store/order/{orderId}", "application/json") + .withPathParam("orderId", orderId) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + /** + * Returns a map of status codes to quantities + * + * Expected answers: + * code 200 : Map[String, Int] (successful operation) + * + * Available security schemes: + * api_key (apiKey) + */ + def getInventory()(implicit apiKey: ApiKeyValue): ApiRequest[Map[String, Int]] = + ApiRequest[Map[String, Int]](ApiMethods.GET, baseUrl, "/store/inventory", "application/json") + .withApiKey(apiKey, "api_key", HEADER) + .withSuccessResponse[Map[String, Int]](200) + + + /** + * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions + * + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid ID supplied) + * code 404 : (Order not found) + * + * @param orderId ID of pet that needs to be fetched + */ + def getOrderById(orderId: Long): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.GET, baseUrl, "/store/order/{orderId}", "application/json") + .withPathParam("orderId", orderId) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + /** + * + * + * Expected answers: + * code 200 : Order (successful operation) + * code 400 : (Invalid Order) + * + * @param order order placed for purchasing the pet + */ + def placeOrder(order: Order): ApiRequest[Order] = + ApiRequest[Order](ApiMethods.POST, baseUrl, "/store/order", "application/json") + .withBody(order) + .withSuccessResponse[Order](200) + .withErrorResponse[Unit](400) + + + + +} + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/UserApi.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/UserApi.scala new file mode 100644 index 000000000000..0e49335179be --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/api/UserApi.scala @@ -0,0 +1,186 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.api + +import java.time.OffsetDateTime +import org.openapitools.client.model.User +import org.openapitools.client.core._ +import org.openapitools.client.core.CollectionFormats._ +import org.openapitools.client.core.ApiKeyLocations._ + +object UserApi { + + def apply(baseUrl: String = "https://petstore.swagger.io/v2") = new UserApi(baseUrl) +} + +class UserApi(baseUrl: String) { + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user Created user object + */ + def createUser(user: User)(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, baseUrl, "/user", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withBody(user) + .withDefaultErrorResponse[Unit] + + + /** + * + * + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user List of user object + */ + def createUsersWithArrayInput(user: Seq[User])(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, baseUrl, "/user/createWithArray", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withBody(user) + .withDefaultErrorResponse[Unit] + + + /** + * + * + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param user List of user object + */ + def createUsersWithListInput(user: Seq[User])(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.POST, baseUrl, "/user/createWithList", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withBody(user) + .withDefaultErrorResponse[Unit] + + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 400 : (Invalid username supplied) + * code 404 : (User not found) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param username The name that needs to be deleted + */ + def deleteUser(username: String)(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.DELETE, baseUrl, "/user/{username}", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withPathParam("username", username) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + /** + * + * + * Expected answers: + * code 200 : User (successful operation) + * code 400 : (Invalid username supplied) + * code 404 : (User not found) + * + * @param username The name that needs to be fetched. Use user1 for testing. + */ + def getUserByName(username: String): ApiRequest[User] = + ApiRequest[User](ApiMethods.GET, baseUrl, "/user/{username}", "application/json") + .withPathParam("username", username) + .withSuccessResponse[User](200) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + /** + * + * + * Expected answers: + * code 200 : String (successful operation) + * Headers : + * Set-Cookie - Cookie authentication key for use with the `auth_cookie` apiKey authentication. + * X-Rate-Limit - calls per hour allowed by the user + * X-Expires-After - date in UTC when token expires + * code 400 : (Invalid username/password supplied) + * + * @param username The user name for login + * @param password The password for login in clear text + */ + def loginUser(username: String, password: String): ApiRequest[String] = + ApiRequest[String](ApiMethods.GET, baseUrl, "/user/login", "application/json") + .withQueryParam("username", username) + .withQueryParam("password", password) + .withSuccessResponse[String](200) + .withErrorResponse[Unit](400) + + object LoginUserHeaders { + def setCookie(r: ApiReturnWithHeaders) = r.getStringHeader("Set-Cookie") + def xRateLimit(r: ApiReturnWithHeaders) = r.getIntHeader("X-Rate-Limit") + def xExpiresAfter(r: ApiReturnWithHeaders) = r.getOffsetDateTimeHeader("X-Expires-After") + } + + /** + * + * + * Expected answers: + * code 0 : (successful operation) + * + * Available security schemes: + * auth_cookie (apiKey) + */ + def logoutUser()(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.GET, baseUrl, "/user/logout", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withDefaultErrorResponse[Unit] + + + /** + * This can only be done by the logged in user. + * + * Expected answers: + * code 400 : (Invalid user supplied) + * code 404 : (User not found) + * + * Available security schemes: + * auth_cookie (apiKey) + * + * @param username name that need to be deleted + * @param user Updated user object + */ + def updateUser(username: String, user: User)(implicit apiKey: ApiKeyValue): ApiRequest[Unit] = + ApiRequest[Unit](ApiMethods.PUT, baseUrl, "/user/{username}", "application/json") + .withApiKey(apiKey, "AUTH_KEY", COOKIE) + .withBody(user) + .withPathParam("username", username) + .withErrorResponse[Unit](400) + .withErrorResponse[Unit](404) + + + + +} + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiInvoker.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiInvoker.scala new file mode 100644 index 000000000000..2eee84d882f9 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiInvoker.scala @@ -0,0 +1,295 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +import java.io.File + +import org.apache.pekko.actor.ActorSystem +import org.apache.pekko.http.scaladsl.Http +import org.apache.pekko.http.scaladsl.coding._ +import org.apache.pekko.http.scaladsl.model.Multipart.FormData.BodyPart +import org.apache.pekko.http.scaladsl.model.Uri.Query +import org.apache.pekko.http.scaladsl.model._ +import org.apache.pekko.http.scaladsl.model.headers._ +import org.apache.pekko.http.scaladsl.unmarshalling.{ Unmarshal, Unmarshaller } +import org.apache.pekko.stream.Materializer +import org.apache.pekko.stream.scaladsl.Source +import org.apache.pekko.util.{ ByteString, Timeout } +import com.github.pjfanning.pekkohttpjson4s.Json4sSupport +import org.json4s._ +import org.json4s.jackson.JsonMethods._ +import org.json4s.jackson.Serialization + +import scala.collection.immutable +import scala.concurrent.{ ExecutionContext, ExecutionContextExecutor, Future } +import scala.reflect.ClassTag + +object ApiInvoker { + + def apply()(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats ++ Serializers.all) + + def apply(serializers: Iterable[Serializer[_]])(implicit system: ActorSystem): ApiInvoker = + apply(DefaultFormats ++ Serializers.all ++ serializers) + + def apply(formats: Formats)(implicit system: ActorSystem): ApiInvoker = new ApiInvoker(formats) + + + /** + * Allows request execution without calling apiInvoker.execute(request) + * request.response can be used to get a future of the ApiResponse generated. + * request.result can be used to get a future of the expected ApiResponse content. If content doesn't match, a + * Future will fail with a ClassCastException + * + * @param request the apiRequest to be executed + */ + implicit class ApiRequestImprovements[T: Manifest](request: ApiRequest[T]) { + + def response(invoker: ApiInvoker)(implicit ec: ExecutionContext, system: ActorSystem): Future[ApiResponse[T]] = + response(ec, system, invoker) + + def response(implicit ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[ApiResponse[T]] = + invoker.execute(request) + + def result[U <: T](implicit c: ClassTag[U], ec: ExecutionContext, system: ActorSystem, invoker: ApiInvoker): Future[U] = + invoker.execute(request).map(_.content).mapTo[U] + + } + + /** + * Allows transformation from ApiMethod to spray HttpMethods + * + * @param method the ApiMethod to be converted + */ + implicit class ApiMethodExtensions(val method: ApiMethod) { + def toAkkaHttpMethod: HttpMethod = HttpMethods.getForKey(method.value).getOrElse(HttpMethods.GET) + } + +} + +trait UnitJSONSupport { + +} + +class ApiInvoker(formats: Formats)(implicit system: ActorSystem) extends CustomContentTypes with Json4sSupport { + + import org.openapitools.client.core.ApiInvoker._ + import org.openapitools.client.core.ParametersMap._ + + implicit val ec: ExecutionContextExecutor = system.dispatcher + implicit val jsonFormats: Formats = formats + + protected val settings: ApiSettings = ApiSettings(system) + + private implicit val materializer: Materializer = Materializer(system) + private implicit val serialization: Serialization = jackson.Serialization + + + private val http = Http() + + val CompressionFilter: HttpMessage => Boolean = (msg: HttpMessage) => + Seq( + { _: HttpMessage => settings.compressionEnabled }, + Encoder.DefaultFilter, + (message: HttpMessage) => { + val long = message.entity().getContentLengthOption() + if (long.isPresent) long.getAsLong > settings.compressionSizeThreshold else true + } + ) + .map(f => f(msg)) + .forall(identity) + + + private def addAuthentication(credentialsSeq: Seq[Credentials]) = { + request: HttpRequest => + credentialsSeq.foldLeft(request) { + case (req, BasicCredentials(login, password)) => + req.addHeader(Authorization(BasicHttpCredentials(login, password))) + case (req, ApiKeyCredentials(keyValue, keyName, ApiKeyLocations.HEADER)) => + req.addHeader(RawHeader(keyName, keyValue.value)) + case (req, BearerToken(token)) => + req.addHeader(RawHeader("Authorization", s"Bearer $token")) + case (req, _) => req + } + } + + private def headers(headers: Map[String, Any]): immutable.Seq[HttpHeader] = + headers.asFormattedParams + .map { case (name, value) => RawHeader(name, value.toString) } + .to(immutable.Seq) + + + private def bodyPart(name: String, value: Any): BodyPart = { + value match { + case f: File => + BodyPart.fromFile( + name, + ContentType(MediaTypes.`application/octet-stream`), + f, + f.length().toInt + ) + case v: String => + BodyPart.Strict(name, v.toString) + case NumericValue(v) => + BodyPart.Strict(name, v.toString) + case m: ApiModel => + BodyPart.Strict(name, Serialization.write(m)) + } + } + + + private def formDataContent(request: ApiRequest[_]) = { + val params = request.formParams.asFormattedParams + if (params.isEmpty) + None + else + Some( + normalizedContentType(request.contentType).mediaType match { + case MediaTypes.`multipart/form-data` => + Multipart.FormData(Source(params.toList.map { case (name, value) => bodyPart(name, value) })) + case MediaTypes.`application/x-www-form-urlencoded` => + FormData(params.view.mapValues(_.toString).toMap) + case _: MediaType => // Default : application/x-www-form-urlencoded. + FormData(params.view.mapValues(_.toString).toMap) + } + ) + } + + private def bodyContent(request: ApiRequest[_]): Option[Any] = request + .bodyParam + .map(Extraction.decompose) + .map(compact) + + private def createRequest(uri: Uri, request: ApiRequest[_]): HttpRequest = { + val httpRequest = request.method.toAkkaHttpMethod match { + case m@(HttpMethods.GET | HttpMethods.DELETE) => HttpRequest(m, uri) + case m@(HttpMethods.POST | HttpMethods.PUT | HttpMethods.PATCH) => + formDataContent(request) orElse bodyContent(request) match { + case Some(c: FormData) => + HttpRequest(m, uri, entity = c.toEntity) + case Some(c: Multipart.FormData) => + HttpRequest(m, uri, entity = c.toEntity) + case Some(c: String) => + HttpRequest(m, uri, entity = HttpEntity(normalizedContentType(request.contentType), ByteString(c))) + case _ => + HttpRequest(m, uri, entity = HttpEntity(normalizedContentType(request.contentType), ByteString(""))) + } + case m: HttpMethod => HttpRequest(m, uri) + } + + addAuthentication(request.credentials)( + httpRequest.withHeaders(headers(request.headerParams)) + ) + } + + def makeQuery(r: ApiRequest[_]): Query = { + r.credentials.foldLeft(r.queryParams) { + case (params, ApiKeyCredentials(key, keyName, ApiKeyLocations.QUERY)) => + params + (keyName -> key.value) + case (params, _) => params + }.asFormattedParams + .view + .mapValues(_.toString) + .toMap + .foldRight[Query](Uri.Query.Empty) { + case ((name, value), acc) => acc.+:(name, value) + } + } + + def makeUri(r: ApiRequest[_]): Uri = { + val opPath = r.operationPath.replaceAll("\\{format\\}", "json") + val opPathWithParams = r.pathParams.asFormattedParams + .view + .mapValues(_.toString) + .toMap + .foldLeft(opPath) { + case (path, (name, value)) => path.replaceAll(s"\\{$name\\}", value) + } + val query = makeQuery(r) + + Uri(r.basePath + opPathWithParams).withQuery(query) + } + + def execute[T: Manifest](r: ApiRequest[T]): Future[ApiResponse[T]] = { + implicit val timeout: Timeout = settings.connectionTimeout + + val request = createRequest(makeUri(r), r) + + http + .singleRequest(request) + .map { response => + val decoder: Decoder with Decoder = response.encoding match { + case HttpEncodings.gzip => + Coders.Gzip + case HttpEncodings.deflate => + Coders.Deflate + case HttpEncodings.identity => + Coders.NoCoding + case HttpEncoding(encoding) => + throw new IllegalArgumentException(s"Unsupported encoding: $encoding") + } + + decoder.decodeMessage(response) + } + .flatMap(unmarshallApiResponse(r)) + } + + def unmarshallApiResponse[T: Manifest](request: ApiRequest[T])(response: HttpResponse): Future[ApiResponse[T]] = { + def responseForState[V](state: ResponseState, value: V): ApiResponse[V] = { + state match { + case ResponseState.Success => + ApiResponse(response.status.intValue, value, response.headers.map(header => (header.name, header.value)).toMap) + case ResponseState.Error => + throw ApiError( + response.status.intValue, + "Error response received", + Some(value), + headers = response.headers.map(header => (header.name, header.value)).toMap + ) + } + } + val mf = implicitly(manifest[T]) + request + .responseForCode(response.status.intValue) match { + case Some((Manifest.Unit, state: ResponseState)) => + Future(responseForState(state, ()).asInstanceOf[ApiResponse[T]]) + case Some((manifest, state: ResponseState)) if manifest == mf => + implicit val m: Unmarshaller[HttpEntity, T] = unmarshaller[T](mf, serialization, formats) + Unmarshal(response.entity) + .to[T] + .recoverWith { + case e => throw ApiError(response.status.intValue, s"Unable to unmarshall content to [$manifest]", Some(response.entity.toString), e) + } + .map(value => responseForState(state, value)) + case None | Some(_) => + Future.failed(ApiError(response.status.intValue, "Unexpected response code", Some(response.entity.toString))) + } + } +} + +sealed trait CustomContentTypes { + + protected def normalizedContentType(original: String): ContentType = + ContentType(parseContentType(original).mediaType, () => HttpCharsets.`UTF-8`) + + protected def parseContentType(contentType: String): ContentType = { + + ContentType.parse(contentType) match { + case Right(ct: ContentType) => + ct + case Left(error: List[ErrorInfo]) => + throw new IllegalArgumentException( + s"Error converting '$contentType' to a ContentType header: '${error.map(_.summary).mkString(", ")}'" + ) + } + } +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiRequest.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiRequest.scala new file mode 100644 index 000000000000..d6f5ae6182e3 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiRequest.scala @@ -0,0 +1,67 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +sealed trait ResponseState + +object ResponseState { + + case object Success extends ResponseState + + case object Error extends ResponseState + +} + +case class ApiRequest[U]( + // required fields + method: ApiMethod, + basePath: String, + operationPath: String, + contentType: String, + + // optional fields + responses: Map[Int, (Manifest[_], ResponseState)] = Map.empty, + bodyParam: Option[Any] = None, + formParams: Map[String, Any] = Map.empty, + pathParams: Map[String, Any] = Map.empty, + queryParams: Map[String, Any] = Map.empty, + headerParams: Map[String, Any] = Map.empty, + credentials: Seq[Credentials] = List.empty) { + + def withCredentials(cred: Credentials): ApiRequest[U] = copy[U](credentials = credentials :+ cred) + + def withApiKey(key: ApiKeyValue, keyName: String, location: ApiKeyLocation): ApiRequest[U] = withCredentials(ApiKeyCredentials(key, keyName, location)) + + def withSuccessResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Success))) + + def withErrorResponse[T](code: Int)(implicit m: Manifest[T]): ApiRequest[U] = copy[U](responses = responses + (code -> (m, ResponseState.Error))) + + def withDefaultSuccessResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withSuccessResponse[T](0) + + def withDefaultErrorResponse[T](implicit m: Manifest[T]): ApiRequest[U] = withErrorResponse[T](0) + + def responseForCode(statusCode: Int): Option[(Manifest[_], ResponseState)] = responses.get(statusCode) orElse responses.get(0) + + def withoutBody(): ApiRequest[U] = copy[U](bodyParam = None) + + def withBody(body: Any): ApiRequest[U] = copy[U](bodyParam = Some(body)) + + def withFormParam(name: String, value: Any): ApiRequest[U] = copy[U](formParams = formParams + (name -> value)) + + def withPathParam(name: String, value: Any): ApiRequest[U] = copy[U](pathParams = pathParams + (name -> value)) + + def withQueryParam(values: Map[String, Any]): ApiRequest[U] = copy[U](queryParams = queryParams ++ values) + + def withQueryParam(name: String, value: Any): ApiRequest[U] = copy[U](queryParams = queryParams + (name -> value)) + + def withHeaderParam(name: String, value: Any): ApiRequest[U] = copy[U](headerParams = headerParams + (name -> value)) +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiSettings.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiSettings.scala new file mode 100644 index 000000000000..31fe118a423f --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/ApiSettings.scala @@ -0,0 +1,54 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +import java.util.concurrent.TimeUnit + +import org.apache.pekko.actor.{ActorSystem, ExtendedActorSystem, Extension, ExtensionId, ExtensionIdProvider} +import org.apache.pekko.http.scaladsl.model.{StatusCode, StatusCodes} +import org.apache.pekko.http.scaladsl.model.headers.RawHeader +import com.typesafe.config.Config + +import scala.jdk.CollectionConverters._ +import scala.concurrent.duration.FiniteDuration + +class ApiSettings(config: Config) extends Extension { + def this(system: ExtendedActorSystem) = this(system.settings.config) + + private def cfg = config.getConfig("org.openapitools.client.apiRequest") + + val alwaysTrustCertificates: Boolean = cfg.getBoolean("trust-certificates") + val defaultHeaders: List[RawHeader] = cfg.getConfig("default-headers").entrySet.asScala.toList.map(c => RawHeader(c.getKey, c.getValue.render)) + val connectionTimeout = FiniteDuration(cfg.getDuration("connection-timeout", TimeUnit.MILLISECONDS), TimeUnit.MILLISECONDS) + val compressionEnabled: Boolean = cfg.getBoolean("compression.enabled") + val compressionSizeThreshold: Int = cfg.getBytes("compression.size-threshold").toInt + val customCodes: List[StatusCode]= cfg.getConfigList("custom-codes").asScala.toList.map { c => + StatusCodes.custom( + c.getInt("code"), + c.getString("reason"), + if (c.hasPath("defaultMessage")) c.getString("defaultMessage") else c.getString("reason"), + c.getBoolean("success"), + if (c.hasPath("allowsEntity")) c.getBoolean("allowsEntity") else true + ) + } +} + +object ApiSettings extends ExtensionId[ApiSettings] with ExtensionIdProvider { + + override def lookup = ApiSettings + + override def createExtension(system: ExtendedActorSystem): ApiSettings = + new ApiSettings(system) + + // needed to get the type right when used from Java + override def get(system: ActorSystem): ApiSettings = super.get(system) +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/Serializers.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/Serializers.scala new file mode 100644 index 000000000000..a569d56b4985 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/Serializers.scala @@ -0,0 +1,31 @@ +package org.openapitools.client.core + +import java.time.{LocalDate, LocalDateTime, OffsetDateTime, ZoneId} +import java.time.format.DateTimeFormatter +import org.json4s.{Serializer, CustomSerializer, JNull} +import org.json4s.ext.JavaTypesSerializers +import org.json4s.JsonAST.JString + +import scala.util.Try + +object Serializers { + + case object DateTimeSerializer extends CustomSerializer[OffsetDateTime]( _ => ( { + case JString(s) => + Try(OffsetDateTime.parse(s, DateTimeFormatter.ISO_OFFSET_DATE_TIME)) orElse + Try(LocalDateTime.parse(s).atZone(ZoneId.systemDefault()).toOffsetDateTime) getOrElse null + }, { + case d: OffsetDateTime => + JString(d.format(DateTimeFormatter.ISO_OFFSET_DATE_TIME)) + })) + + case object LocalDateSerializer extends CustomSerializer[LocalDate]( _ => ( { + case JString(s) => LocalDate.parse(s) + }, { + case d: LocalDate => + JString(d.format(DateTimeFormatter.ISO_LOCAL_DATE)) + })) + + def all: Seq[Serializer[_]] = JavaTypesSerializers.all :+ DateTimeSerializer :+ LocalDateSerializer + +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/requests.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/requests.scala new file mode 100644 index 000000000000..4d962d761817 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/core/requests.scala @@ -0,0 +1,202 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.core + +import java.io.File +import java.net.URLEncoder +import java.util.UUID +import java.time.OffsetDateTime + +import scala.util.Try + +sealed trait ApiReturnWithHeaders { + def headers: Map[String, String] + + def header(name: String): Option[String] = headers.get(name) + + def getStringHeader(name: String): Option[String] = header(name) + + // workaround: return date time header in string instead of datetime object + def getDateTimeHeader(name: String): Option[String] = header(name) + + def getIntHeader(name: String): Option[Int] = castedHeader(name, java.lang.Integer.parseInt) + + def getLongHeader(name: String): Option[Long] = castedHeader(name, java.lang.Long.parseLong) + + def getFloatHeader(name: String): Option[Float] = castedHeader(name, java.lang.Float.parseFloat) + + def getDoubleHeader(name: String): Option[Double] = castedHeader(name, java.lang.Double.parseDouble) + + def getBooleanHeader(name: String): Option[Boolean] = castedHeader(name, java.lang.Boolean.parseBoolean) + + def getOffsetDateTimeHeader(name: String): Option[OffsetDateTime] = castedHeader(name, java.time.OffsetDateTime.parse) + + private def castedHeader[U](name: String, conversion: String => U): Option[U] = { + Try { + header(name).map(conversion) + }.get + } +} + +sealed case class ApiResponse[T](code: Int, content: T, headers: Map[String, String] = Map.empty) + extends ApiReturnWithHeaders + +sealed case class ApiError[T](code: Int, message: String, responseContent: Option[T], cause: Throwable = null, headers: Map[String, String] = Map.empty) + extends Throwable(s"($code) $message.${responseContent.map(s => s" Content : $s").getOrElse("")}", cause) + with ApiReturnWithHeaders + +sealed case class ApiMethod(value: String) + +object ApiMethods { + val CONNECT = ApiMethod("CONNECT") + val DELETE = ApiMethod("DELETE") + val GET = ApiMethod("GET") + val HEAD = ApiMethod("HEAD") + val OPTIONS = ApiMethod("OPTIONS") + val PATCH = ApiMethod("PATCH") + val POST = ApiMethod("POST") + val PUT = ApiMethod("PUT") + val TRACE = ApiMethod("TRACE") +} + +/** + * This trait needs to be added to any model defined by the api. + */ +trait ApiModel + +/** + * Single trait defining a credential that can be transformed to a paramName / paramValue tuple + */ +sealed trait Credentials { + def asQueryParam: Option[(String, String)] = None +} + +sealed case class BasicCredentials(user: String, password: String) extends Credentials + +sealed case class BearerToken(token: String) extends Credentials + +sealed case class ApiKeyCredentials(key: ApiKeyValue, keyName: String, location: ApiKeyLocation) extends Credentials { + override def asQueryParam: Option[(String, String)] = location match { + case ApiKeyLocations.QUERY => Some((keyName, key.value)) + case _ => None + } +} + +sealed case class ApiKeyValue(value: String) + +sealed trait ApiKeyLocation + +object ApiKeyLocations { + + case object QUERY extends ApiKeyLocation + + case object HEADER extends ApiKeyLocation + + case object COOKIE extends ApiKeyLocation + +} + + +/** + * Case class used to unapply numeric values only in pattern matching + * + * @param value the string representation of the numeric value + */ +sealed case class NumericValue(value: String) { + override def toString: String = value +} + +object NumericValue { + def unapply(n: Any): Option[NumericValue] = n match { + case (_: Int | _: Long | _: Float | _: Double | _: Boolean | _: Byte) => Some(NumericValue(String.valueOf(n))) + case _ => None + } +} + +/** + * Used for params being arrays + */ +sealed case class ArrayValues(values: Seq[Any], format: CollectionFormat = CollectionFormats.CSV) + +object ArrayValues { + def apply(values: Option[Seq[Any]], format: CollectionFormat): ArrayValues = + ArrayValues(values.getOrElse(Seq.empty), format) + + def apply(values: Option[Seq[Any]]): ArrayValues = ArrayValues(values, CollectionFormats.CSV) +} + + +/** + * Defines how arrays should be rendered in query strings. + */ +sealed trait CollectionFormat + +trait MergedArrayFormat extends CollectionFormat { + def separator: String +} + +object CollectionFormats { + + case object CSV extends MergedArrayFormat { + override val separator = "," + } + + case object TSV extends MergedArrayFormat { + override val separator = "\t" + } + + case object SSV extends MergedArrayFormat { + override val separator = " " + } + + case object PIPES extends MergedArrayFormat { + override val separator = "|" + } + + case object MULTI extends CollectionFormat + +} + +object ParametersMap { + + /** + * Pimp parameters maps (Map[String, Any]) in order to transform them in a sequence of String -> Any tuples, + * with valid url-encoding, arrays handling, files preservation, ... + */ + implicit class ParametersMapImprovements(val m: Map[String, Any]) { + + def asFormattedParamsList: List[(String, Any)] = m.toList.flatMap(formattedParams) + + def asFormattedParams: Map[String, Any] = m.flatMap(formattedParams) + + private def urlEncode(v: Any) = URLEncoder.encode(String.valueOf(v), "utf-8").replaceAll("\\+", "%20") + + private def formattedParams(tuple: (String, Any)): Seq[(String, Any)] = formattedParams(tuple._1, tuple._2) + + private def formattedParams(name: String, value: Any): Seq[(String, Any)] = value match { + case arr: ArrayValues => + arr.format match { + case CollectionFormats.MULTI => arr.values.flatMap(formattedParams(name, _)) + case format: MergedArrayFormat => Seq((name, arr.values.mkString(format.separator))) + } + case None => Seq.empty + case Some(opt) => formattedParams(name, opt) + case s: Seq[Any] => formattedParams(name, ArrayValues(s)) + case v: String => Seq((name, urlEncode(v))) + case v: UUID => formattedParams(name, v.toString) + case NumericValue(v) => Seq((name, urlEncode(v))) + case f: File => Seq((name, f)) + case m: ApiModel => Seq((name, m)) + } + } + +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/ApiResponse.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/ApiResponse.scala new file mode 100644 index 000000000000..fd96f81da8e1 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/ApiResponse.scala @@ -0,0 +1,21 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class ApiResponse ( + code: Option[Int] = None, + `type`: Option[String] = None, + message: Option[String] = None +) extends ApiModel + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Category.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Category.scala new file mode 100644 index 000000000000..8f5791b43c72 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Category.scala @@ -0,0 +1,20 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class Category ( + id: Option[Long] = None, + name: Option[String] = None +) extends ApiModel + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Order.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Order.scala new file mode 100644 index 000000000000..370abcfb04ad --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Order.scala @@ -0,0 +1,36 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import java.time.OffsetDateTime +import org.openapitools.client.core.ApiModel + +case class Order ( + id: Option[Long] = None, + petId: Option[Long] = None, + quantity: Option[Int] = None, + shipDate: Option[OffsetDateTime] = None, + /* Order Status */ + status: Option[OrderEnums.Status] = None, + complete: Option[Boolean] = None +) extends ApiModel + +object OrderEnums { + + type Status = Status.Value + object Status extends Enumeration { + val Placed = Value("placed") + val Approved = Value("approved") + val Delivered = Value("delivered") + } + +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Pet.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Pet.scala new file mode 100644 index 000000000000..9422e64d58bc --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Pet.scala @@ -0,0 +1,35 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class Pet ( + id: Option[Long] = None, + category: Option[Category] = None, + name: String, + photoUrls: Seq[String], + tags: Option[Seq[Tag]] = None, + /* pet status in the store */ + status: Option[PetEnums.Status] = None +) extends ApiModel + +object PetEnums { + + type Status = Status.Value + object Status extends Enumeration { + val Available = Value("available") + val Pending = Value("pending") + val Sold = Value("sold") + } + +} diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Tag.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Tag.scala new file mode 100644 index 000000000000..10e6455e072c --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/Tag.scala @@ -0,0 +1,20 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class Tag ( + id: Option[Long] = None, + name: Option[String] = None +) extends ApiModel + diff --git a/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/User.scala b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/User.scala new file mode 100644 index 000000000000..d8dafdc59c47 --- /dev/null +++ b/samples/client/petstore/scala-pekko/src/main/scala/org/openapitools/client/model/User.scala @@ -0,0 +1,27 @@ +/** + * OpenAPI Petstore + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * The version of the OpenAPI document: 1.0.0 + * + * + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.client.model + +import org.openapitools.client.core.ApiModel + +case class User ( + id: Option[Long] = None, + username: Option[String] = None, + firstName: Option[String] = None, + lastName: Option[String] = None, + email: Option[String] = None, + password: Option[String] = None, + phone: Option[String] = None, + /* User Status */ + userStatus: Option[Int] = None +) extends ApiModel + diff --git a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/scala-sttp/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-sttp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/scala-sttp4/.openapi-generator/VERSION b/samples/client/petstore/scala-sttp4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/scala-sttp4/.openapi-generator/VERSION +++ b/samples/client/petstore/scala-sttp4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java b/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java index f4cfbc41db59..b5cc3b873c67 100644 --- a/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java +++ b/samples/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-deprecated/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-deprecated/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-cloud-deprecated/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-deprecated/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/PetApi.java index 431b8861bfb6..e622be71aafc 100644 --- a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/StoreApi.java index cd1427025e5c..6b4cf8fc5360 100644 --- a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/UserApi.java index 6af526a12e98..dde4c4fcb379 100644 --- a/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-deprecated/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -94,7 +94,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -124,7 +124,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/client/petstore/spring-cloud-feign-without-url/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-feign-without-url/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-feign-without-url/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApi.java index a203af27250a..ae696a1a005d 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApi.java index d6d0287be553..542a3fcf6319 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApi.java index d153abd27417..3907f07b5114 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -84,7 +84,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -114,7 +114,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/client/petstore/spring-cloud-feign-without-url/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/client/petstore/spring-cloud-tags/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud-tags/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-cloud-tags/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud-tags/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/PetController.java b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/PetController.java index 5c735d80c837..f3f2de470bbc 100644 --- a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/PetController.java +++ b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/PetController.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/StoreController.java b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/StoreController.java index 36eba0006dd7..0f1588b67a63 100644 --- a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/StoreController.java +++ b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/StoreController.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/UserController.java b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/UserController.java index e11d84cb3727..c46fe189f133 100644 --- a/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/UserController.java +++ b/samples/client/petstore/spring-cloud-tags/src/main/java/org/openapitools/api/UserController.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -75,7 +75,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ); @@ -100,7 +100,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ); diff --git a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-cloud/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-cloud/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java index a203af27250a..ae696a1a005d 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java index d6d0287be553..542a3fcf6319 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java index d153abd27417..3907f07b5114 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -84,7 +84,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -114,7 +114,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/client/petstore/spring-cloud/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/client/petstore/spring-http-interface-reactive/.openapi-generator/VERSION b/samples/client/petstore/spring-http-interface-reactive/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-http-interface-reactive/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-http-interface-reactive/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java index 02f764b41d06..3d37ac27ab58 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeApi.java index 18977cb99a9c..a93eddc48ff0 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java index 9df3b11062b9..4e5698af7b7c 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/PetApi.java index 465ab60f87d8..22d76619d77d 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/StoreApi.java index 84c4caa1d967..57b79054f6e9 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/UserApi.java index 86382ef890d4..0af6509b0015 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java index cb5fd3664485..c2d77cc677ae 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/model/FormatTest.java b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/model/FormatTest.java index 47b445bbf5cf..2330a52e6710 100644 --- a/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/client/petstore/spring-http-interface-reactive/src/main/java/org/openapitools/model/FormatTest.java @@ -393,7 +393,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/spring-http-interface/.openapi-generator/VERSION b/samples/client/petstore/spring-http-interface/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/spring-http-interface/.openapi-generator/VERSION +++ b/samples/client/petstore/spring-http-interface/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/AnotherFakeApi.java index 55f9d50a95e6..959ee03fec2d 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeApi.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeApi.java index 3fd6f8e3861b..5fa4b3f788f7 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java index 49f37cb7304b..fefd4bb10928 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/PetApi.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/PetApi.java index 8ac471e16fd2..335ca99dcb98 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/StoreApi.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/StoreApi.java index d18ddc2ff043..57c21f1d0597 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/UserApi.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/UserApi.java index 6f9a290e64b6..82e6c45dae81 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java index cb5fd3664485..c2d77cc677ae 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/configuration/HttpInterfacesAbstractConfigurator.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/model/FormatTestDto.java b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/model/FormatTestDto.java index 68f17b1f1f21..bad61ca86826 100644 --- a/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/model/FormatTestDto.java +++ b/samples/client/petstore/spring-http-interface/src/main/java/org/openapitools/model/FormatTestDto.java @@ -379,7 +379,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/client/petstore/swift-combine/client/.openapi-generator/VERSION b/samples/client/petstore/swift-combine/client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift-combine/client/.openapi-generator/VERSION +++ b/samples/client/petstore/swift-combine/client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift-combine/client/PetstoreOpenAPI/Sources/Models/Order.swift b/samples/client/petstore/swift-combine/client/PetstoreOpenAPI/Sources/Models/Order.swift index 9a9b4e2bf3b1..5bdf9cc1212b 100644 --- a/samples/client/petstore/swift-combine/client/PetstoreOpenAPI/Sources/Models/Order.swift +++ b/samples/client/petstore/swift-combine/client/PetstoreOpenAPI/Sources/Models/Order.swift @@ -12,7 +12,7 @@ public struct Order: Codable { public enum Status: String, Codable, CaseIterable { case placed = "placed" case approved = "approved" - case delivered = "delivered" + case shipped = "delivered" } public var id: Int64? public var petId: Int64? diff --git a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/alamofireLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 44e76f4550ff..7c06bb2f6d1b 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 1dff5ad6a256..9e246a77ebea 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index e4290335f9db..d70cffdbdde7 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0f5727b8b181..747cb1406a87 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift index 93d52871dd78..3cbc5a189121 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/PetstoreClient/Classes/OpenAPIs/OpenAPIDateWithoutTime.swift @@ -23,11 +23,21 @@ public struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable { case wrappedDate case timezone } + + public enum DecodingError: Error { + case notADateString + } /// On decoding ISO8601 timezone is assumed public init(from decoder: Decoder) throws { let container = try decoder.singleValueContainer() - self.wrappedDate = try container.decode(Date.self) + + let dateString = try container.decode(String.self) + guard let date = OpenISO8601DateFormatter.withoutTime.date(from: dateString) else { + throw DecodingError.notADateString + } + self.wrappedDate = date + self.timezone = OpenISO8601DateFormatter.withoutTime.timeZone } @@ -60,10 +70,14 @@ public struct OpenAPIDateWithoutTime: Codable, Hashable, Equatable { return wrappedDate.addingTimeInterval( Double(timezone.secondsFromGMT(for: wrappedDate))) } + + public static func == (lhs: Self, rhs: Self) -> Bool { + Calendar.current.compare(lhs.wrappedDate, to: rhs.wrappedDate, toGranularity: .day) == .orderedSame + } } extension OpenAPIDateWithoutTime: JSONEncodable { func encodeToJSON() -> Any { return OpenISO8601DateFormatter.withoutTime.string(from: self.normalizedWrappedDate()) } -} \ No newline at end of file +} diff --git a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/DateFormatTests.swift b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/DateFormatTests.swift index e18a104f3aa2..64bb60adcf13 100644 --- a/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/DateFormatTests.swift +++ b/samples/client/petstore/swift5/alamofireLibrary/SwaggerClientTests/SwaggerClientTests/DateFormatTests.swift @@ -111,4 +111,11 @@ class DateFormatTests: XCTestCase { XCTAssert(jsonString == exampleJSONString, "Encoded JSON String: \(jsonString) should match: \(exampleJSONString)") } + func testCodableOpenAPIDateWithoutTime() throws { + let sut = OpenAPIDateWithoutTime(wrappedDate: Date(timeIntervalSince1970: 0)) + let encodedDate = try JSONEncoder().encode(sut) + let decodedDate = try JSONDecoder().decode(OpenAPIDateWithoutTime.self, from: encodedDate) + + XCTAssert(sut == decodedDate, "Decoded date: \(decodedDate) should match initially given date: \(String(describing: sut))") + } } diff --git a/samples/client/petstore/swift5/anycodableLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/anycodableLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/anycodableLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/anycodableLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/anycodableLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/anycodableLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/anycodableLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/anycodableLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 68afa8abbddd..51cfb6d716ee 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -38,7 +38,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 1440ed063265..a5e7145d297c 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -172,7 +172,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -210,7 +210,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -246,7 +246,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -548,7 +548,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 8e8866fe940b..c799d91e6b5d 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -41,7 +41,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index c4051ddb97b0..dfefa61d1d58 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -43,7 +43,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -261,7 +261,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/asyncAwaitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/combineLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index fc51facf2e5f..db7aba6b321e 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -58,7 +58,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 341a9d534c4e..e65abe35fcd4 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -260,7 +260,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -315,7 +315,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -368,7 +368,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -738,7 +738,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 96e20a3766a9..7958821e05cf 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -61,7 +61,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 8976a588129e..b206cde011e3 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -63,7 +63,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -366,7 +366,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/combineLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/default/.openapi-generator/VERSION b/samples/client/petstore/swift5/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/default/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 3055a9c2a84a..d7d6146e3566 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -48,6 +48,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ + "Content-Type": "application/json", "uuid_test": uuidTest.encodeToJSON(), ] diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index f28ddd9d1286..1a5d74a29efc 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -46,7 +46,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/xml", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -256,7 +256,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -346,7 +346,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -680,7 +680,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index e4290335f9db..d70cffdbdde7 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 7a6dd52e8054..9d32596ac814 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -48,7 +48,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -306,7 +306,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift index bf7da6a3f862..818233c5fcee 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/Order.swift @@ -15,7 +15,7 @@ public struct Order: Codable, JSONEncodable, Hashable { public enum Status: String, Codable, CaseIterable { case placed = "placed" case approved = "approved" - case delivered = "delivered" + case shipped = "delivered" } public var id: Int64? public var petId: Int64? diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift index 76c34b3c2ce6..a1981c09f18f 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/Models/OuterEnum.swift @@ -13,5 +13,5 @@ import AnyCodable public enum OuterEnum: String, Codable, CaseIterable { case placed = "placed" case approved = "approved" - case delivered = "delivered" + case shipped = "delivered" } diff --git a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/default/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/deprecated/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 2bf98b094706..acdb94ed0f38 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -49,7 +49,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift index af2006a55669..f260704a5880 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/StoreAPI.swift @@ -185,7 +185,7 @@ open class StoreAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift index 644fe10642eb..58a192156e55 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/APIs/UserAPI.swift @@ -49,7 +49,7 @@ open class UserAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -96,7 +96,7 @@ open class UserAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -143,7 +143,7 @@ open class UserAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -388,7 +388,7 @@ open class UserAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/deprecated/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/frozenEnums/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 44e76f4550ff..7c06bb2f6d1b 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 102ea93f6df5..50acd84cc9f9 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index e4290335f9db..d70cffdbdde7 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 35aacb16b9ac..03880773800a 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/frozenEnums/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/nonPublicApi/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index df848839c975..42e6de272667 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ internal class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 62aec8ada0c9..b4d2b389e062 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ internal class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ internal class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ internal class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ internal class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index cab978d6bed1..53612a899782 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ internal class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index e828ad278910..6aac5a80c345 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ internal class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ internal class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index bb1f168079ea..f5313020c6f4 100644 --- a/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/nonPublicApi/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/objcCompatible/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 29b71ac12ec9..a4710970b265 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 7b9ae5cebe68..3f6e3111d931 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ import AnyCodable ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 260b5036a469..a7356ec8efb3 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 1ee356b8a2fd..5510610fcd5b 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ import AnyCodable let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/objcCompatible/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/oneOf/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/oneOf/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/promisekitLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 89126346df46..e8ad6419443e 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -47,7 +47,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 02bfa1c5f947..9358f7ce983f 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -213,7 +213,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -259,7 +259,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -303,7 +303,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -637,7 +637,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 1c03b338da6b..a4645e9f8aa2 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -50,7 +50,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index bcff9b37b22b..c2813aa9f6ed 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -52,7 +52,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -310,7 +310,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/promisekitLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/readonlyProperties/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 44e76f4550ff..7c06bb2f6d1b 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 6113837af712..e2056a929dc3 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index e4290335f9db..d70cffdbdde7 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0f5727b8b181..747cb1406a87 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/readonlyProperties/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/resultLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 9bed93b838e5..17af54d30bab 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 4b15d4cfd83d..e18c6a34c8f0 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index 43d5e652324a..bd70a5f065e9 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 00136658209a..73235282d443 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/resultLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/rxswiftLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index d68645423dd7..fc3c578ad600 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -53,7 +53,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index e23c89811b94..03433120c1ab 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -243,7 +243,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -295,7 +295,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -345,7 +345,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -703,7 +703,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index d9f0549dbd2e..c8366f282b25 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -56,7 +56,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 6d24bf65fee0..161cac524b57 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -58,7 +58,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -346,7 +346,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/rxswiftLibrary/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/urlsessionLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift index 4632a8c2dc6c..a464702c03b8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/AnotherFakeAPI.swift @@ -49,7 +49,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift index d03476d2f400..6f88769930d8 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeAPI.swift @@ -215,7 +215,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -261,7 +261,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -305,7 +305,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -639,7 +639,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift index 249596866eff..28bd354a8ecd 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/FakeClassnameTags123API.swift @@ -52,7 +52,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift index 60431b445344..3741d7f42773 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/APIs/PetAPI.swift @@ -54,7 +54,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -312,7 +312,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/urlsessionLibrary/Sources/PetstoreClient/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/validation/.openapi-generator/VERSION b/samples/client/petstore/swift5/validation/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/validation/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/validation/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/validation/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/validation/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/validation/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/validation/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/vaporLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION +++ b/samples/client/petstore/swift5/x-swift-hashable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift index 44e76f4550ff..7c06bb2f6d1b 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/AnotherFakeAPI.swift @@ -46,7 +46,7 @@ open class AnotherFakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift index 6113837af712..e2056a929dc3 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeAPI.swift @@ -212,7 +212,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -258,7 +258,7 @@ open class FakeAPI { ]) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -302,7 +302,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -636,7 +636,7 @@ open class FakeAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift index e4290335f9db..d70cffdbdde7 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/FakeClassnameTags123API.swift @@ -49,7 +49,7 @@ open class FakeClassnameTags123API { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift index 0f5727b8b181..747cb1406a87 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/APIs/PetAPI.swift @@ -51,7 +51,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) @@ -309,7 +309,7 @@ open class PetAPI { let localVariableUrlComponents = URLComponents(string: localVariableURLString) let localVariableNillableHeaders: [String: Any?] = [ - : + "Content-Type": "application/json", ] let localVariableHeaderParameters = APIHelper.rejectNilHeaders(localVariableNillableHeaders) diff --git a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift index 5d75bbfecb7d..e91fef04ceaa 100644 --- a/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift +++ b/samples/client/petstore/swift5/x-swift-hashable/PetstoreClient/Classes/OpenAPIs/URLSessionImplementations.swift @@ -592,14 +592,20 @@ private class OctetStreamEncoding: ParameterEncoding { var urlRequest = urlRequest - var requestBodyComponents = URLComponents() - requestBodyComponents.queryItems = APIHelper.mapValuesToQueryItems(parameters ?? [:]) + guard let body = parameters?["body"] else { return urlRequest } if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/octet-stream", forHTTPHeaderField: "Content-Type") } - urlRequest.httpBody = requestBodyComponents.query?.data(using: .utf8) + switch body { + case let fileURL as URL: + urlRequest.httpBody = try Data(contentsOf: fileURL) + case let data as Data: + urlRequest.httpBody = data + default: + fatalError("Unprocessable body \(body)") + } return urlRequest } diff --git a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v12-oneOf/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v12-provided-in-any/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v12-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v13-oneOf/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v13-provided-in-any/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v13-provided-in-root/builds/with-npm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v14-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v14-query-param-object-format/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v15-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v15-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v15-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v15-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-angular-v16-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-angular-v16-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-angular-v16-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-angular-v16-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-aurelia/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/api.ts b/samples/client/petstore/typescript-axios/builds/composed-schemas/api.ts index f6e6dcfe2595..c1752e116e98 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/api.ts +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * @@ -188,7 +188,7 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati * @param {*} [options] Override http request option. * @throws {RequiredError} */ - filePost: async (filePostRequest?: FilePostRequest, options: AxiosRequestConfig = {}): Promise => { + filePost: async (filePostRequest?: FilePostRequest, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/file`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -221,7 +221,7 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati * @param {*} [options] Override http request option. * @throws {RequiredError} */ - petsFilteredPatch: async (petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options: AxiosRequestConfig = {}): Promise => { + petsFilteredPatch: async (petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/pets-filtered`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -254,7 +254,7 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati * @param {*} [options] Override http request option. * @throws {RequiredError} */ - petsPatch: async (petsPatchRequest?: PetsPatchRequest | null, options: AxiosRequestConfig = {}): Promise => { + petsPatch: async (petsPatchRequest?: PetsPatchRequest | null, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/pets`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -297,9 +297,11 @@ export const DefaultApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async filePost(filePostRequest?: FilePostRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async filePost(filePostRequest?: FilePostRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.filePost(filePostRequest, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['DefaultApi.filePost']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -307,9 +309,11 @@ export const DefaultApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async petsFilteredPatch(petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async petsFilteredPatch(petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.petsFilteredPatch(petsFilteredPatchRequest, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['DefaultApi.petsFilteredPatch']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -317,9 +321,11 @@ export const DefaultApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async petsPatch(petsPatchRequest?: PetsPatchRequest | null, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async petsPatch(petsPatchRequest?: PetsPatchRequest | null, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.petsPatch(petsPatchRequest, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['DefaultApi.petsPatch']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -375,7 +381,7 @@ export class DefaultApi extends BaseAPI { * @throws {RequiredError} * @memberof DefaultApi */ - public filePost(filePostRequest?: FilePostRequest, options?: AxiosRequestConfig) { + public filePost(filePostRequest?: FilePostRequest, options?: RawAxiosRequestConfig) { return DefaultApiFp(this.configuration).filePost(filePostRequest, options).then((request) => request(this.axios, this.basePath)); } @@ -386,7 +392,7 @@ export class DefaultApi extends BaseAPI { * @throws {RequiredError} * @memberof DefaultApi */ - public petsFilteredPatch(petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options?: AxiosRequestConfig) { + public petsFilteredPatch(petsFilteredPatchRequest?: PetsFilteredPatchRequest | null, options?: RawAxiosRequestConfig) { return DefaultApiFp(this.configuration).petsFilteredPatch(petsFilteredPatchRequest, options).then((request) => request(this.axios, this.basePath)); } @@ -397,7 +403,7 @@ export class DefaultApi extends BaseAPI { * @throws {RequiredError} * @memberof DefaultApi */ - public petsPatch(petsPatchRequest?: PetsPatchRequest | null, options?: AxiosRequestConfig) { + public petsPatch(petsPatchRequest?: PetsPatchRequest | null, options?: RawAxiosRequestConfig) { return DefaultApiFp(this.configuration).petsPatch(petsPatchRequest, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/base.ts b/samples/client/petstore/typescript-axios/builds/composed-schemas/base.ts index d24c18a6aed5..e215695bd26e 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/base.ts +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://api.example.xyz/v1".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts b/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts index 7bd190906d3a..d629dec4427f 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/composed-schemas/configuration.ts b/samples/client/petstore/typescript-axios/builds/composed-schemas/configuration.ts index 50cbfea996b1..46522502419f 100644 --- a/samples/client/petstore/typescript-axios/builds/composed-schemas/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/composed-schemas/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/default/api.ts b/samples/client/petstore/typescript-axios/builds/default/api.ts index 1af5de4a800a..f74593fe5bb7 100644 --- a/samples/client/petstore/typescript-axios/builds/default/api.ts +++ b/samples/client/petstore/typescript-axios/builds/default/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -259,7 +259,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -300,7 +300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -342,7 +342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -384,7 +384,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -425,7 +425,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -462,7 +462,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -504,7 +504,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -556,7 +556,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -616,9 +616,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -628,9 +630,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -639,9 +643,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -651,9 +657,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -662,9 +670,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -673,9 +683,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -686,9 +698,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -699,9 +713,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -817,7 +833,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -830,7 +846,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -842,7 +858,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -855,7 +871,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -867,7 +883,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -879,7 +895,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -893,7 +909,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -907,7 +923,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -936,7 +952,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -969,7 +985,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1003,7 +1019,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1037,7 +1053,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -1083,9 +1099,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1093,9 +1111,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1104,9 +1124,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1115,9 +1137,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1186,7 +1210,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1197,7 +1221,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1209,7 +1233,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1221,7 +1245,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1241,7 +1265,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1277,7 +1301,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1313,7 +1337,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1349,7 +1373,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1383,7 +1407,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1418,7 +1442,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1460,7 +1484,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1492,7 +1516,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1541,9 +1565,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1552,9 +1578,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1563,9 +1591,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1574,9 +1604,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1585,9 +1617,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1597,9 +1631,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1607,9 +1643,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1619,9 +1657,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1732,7 +1772,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1744,7 +1784,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1756,7 +1796,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1768,7 +1808,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1780,7 +1820,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1793,7 +1833,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1804,7 +1844,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1817,7 +1857,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/default/base.ts b/samples/client/petstore/typescript-axios/builds/default/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/default/base.ts +++ b/samples/client/petstore/typescript-axios/builds/default/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/default/common.ts b/samples/client/petstore/typescript-axios/builds/default/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/default/common.ts +++ b/samples/client/petstore/typescript-axios/builds/default/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/default/configuration.ts b/samples/client/petstore/typescript-axios/builds/default/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/default/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/default/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts index 1af5de4a800a..f74593fe5bb7 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/api.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -259,7 +259,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -300,7 +300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -342,7 +342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -384,7 +384,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -425,7 +425,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -462,7 +462,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -504,7 +504,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -556,7 +556,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -616,9 +616,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -628,9 +630,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -639,9 +643,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -651,9 +657,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -662,9 +670,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -673,9 +683,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -686,9 +698,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -699,9 +713,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -817,7 +833,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -830,7 +846,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -842,7 +858,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -855,7 +871,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -867,7 +883,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -879,7 +895,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -893,7 +909,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -907,7 +923,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -936,7 +952,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -969,7 +985,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1003,7 +1019,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1037,7 +1053,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -1083,9 +1099,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1093,9 +1111,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1104,9 +1124,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1115,9 +1137,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1186,7 +1210,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1197,7 +1221,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1209,7 +1233,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1221,7 +1245,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1241,7 +1265,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1277,7 +1301,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1313,7 +1337,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1349,7 +1373,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1383,7 +1407,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1418,7 +1442,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1460,7 +1484,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1492,7 +1516,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1541,9 +1565,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1552,9 +1578,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1563,9 +1591,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1574,9 +1604,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1585,9 +1617,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1597,9 +1631,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1607,9 +1643,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1619,9 +1657,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1732,7 +1772,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1744,7 +1784,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1756,7 +1796,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1768,7 +1808,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1780,7 +1820,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1793,7 +1833,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1804,7 +1844,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1817,7 +1857,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/base.ts b/samples/client/petstore/typescript-axios/builds/es6-target/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/base.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/common.ts b/samples/client/petstore/typescript-axios/builds/es6-target/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/common.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/configuration.ts b/samples/client/petstore/typescript-axios/builds/es6-target/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/es6-target/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/es6-target/package.json b/samples/client/petstore/typescript-axios/builds/es6-target/package.json index dc2da01a43e4..07a92ace734a 100644 --- a/samples/client/petstore/typescript-axios/builds/es6-target/package.json +++ b/samples/client/petstore/typescript-axios/builds/es6-target/package.json @@ -24,7 +24,7 @@ "prepare": "npm run build" }, "dependencies": { - "axios": "^0.27.2" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/test-petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts index 1b920b9b5396..227d14988511 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * @@ -1107,16 +1107,16 @@ export interface NullableClass { 'object_nullable_prop'?: { [key: string]: object; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - 'object_and_items_nullable_prop'?: { [key: string]: object; } | null; + 'object_and_items_nullable_prop'?: { [key: string]: object | null; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - 'object_items_nullable'?: { [key: string]: object; }; + 'object_items_nullable'?: { [key: string]: object | null; }; } /** * @type NullableShape @@ -1709,7 +1709,7 @@ export const AnotherFakeApiAxiosParamCreator = function (configuration?: Configu * @param {*} [options] Override http request option. * @throws {RequiredError} */ - _123testSpecialTags: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + _123testSpecialTags: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('_123testSpecialTags', 'client', client) const localVarPath = `/another-fake/dummy`; @@ -1755,9 +1755,11 @@ export const AnotherFakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async _123testSpecialTags(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async _123testSpecialTags(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator._123testSpecialTags(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['AnotherFakeApi._123testSpecialTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1797,7 +1799,7 @@ export class AnotherFakeApi extends BaseAPI { * @throws {RequiredError} * @memberof AnotherFakeApi */ - public _123testSpecialTags(client: Client, options?: AxiosRequestConfig) { + public _123testSpecialTags(client: Client, options?: RawAxiosRequestConfig) { return AnotherFakeApiFp(this.configuration)._123testSpecialTags(client, options).then((request) => request(this.axios, this.basePath)); } } @@ -1815,7 +1817,7 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fooGet: async (options: AxiosRequestConfig = {}): Promise => { + fooGet: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/foo`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1854,9 +1856,11 @@ export const DefaultApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fooGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fooGet(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fooGet(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['DefaultApi.fooGet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1892,7 +1896,7 @@ export class DefaultApi extends BaseAPI { * @throws {RequiredError} * @memberof DefaultApi */ - public fooGet(options?: AxiosRequestConfig) { + public fooGet(options?: RawAxiosRequestConfig) { return DefaultApiFp(this.configuration).fooGet(options).then((request) => request(this.axios, this.basePath)); } } @@ -1911,7 +1915,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeHealthGet: async (options: AxiosRequestConfig = {}): Promise => { + fakeHealthGet: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/health`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1941,7 +1945,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterBooleanSerialize: async (body?: boolean, options: AxiosRequestConfig = {}): Promise => { + fakeOuterBooleanSerialize: async (body?: boolean, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/boolean`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1974,7 +1978,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterCompositeSerialize: async (outerComposite?: OuterComposite, options: AxiosRequestConfig = {}): Promise => { + fakeOuterCompositeSerialize: async (outerComposite?: OuterComposite, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/composite`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2007,7 +2011,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterNumberSerialize: async (body?: number, options: AxiosRequestConfig = {}): Promise => { + fakeOuterNumberSerialize: async (body?: number, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/number`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2040,7 +2044,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterStringSerialize: async (body?: string, options: AxiosRequestConfig = {}): Promise => { + fakeOuterStringSerialize: async (body?: string, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/string`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2073,7 +2077,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getArrayOfEnums: async (options: AxiosRequestConfig = {}): Promise => { + getArrayOfEnums: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/array-of-enums`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2097,13 +2101,49 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) options: localVarRequestOptions, }; }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAdditionalPropertiesReference: async (requestBody: { [key: string]: any; }, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'requestBody' is not null or undefined + assertParamExists('testAdditionalPropertiesReference', 'requestBody', requestBody) + const localVarPath = `/fake/additionalProperties-reference`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(requestBody, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testBodyWithFileSchema: async (fileSchemaTestClass: FileSchemaTestClass, options: AxiosRequestConfig = {}): Promise => { + testBodyWithFileSchema: async (fileSchemaTestClass: FileSchemaTestClass, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'fileSchemaTestClass' is not null or undefined assertParamExists('testBodyWithFileSchema', 'fileSchemaTestClass', fileSchemaTestClass) const localVarPath = `/fake/body-with-file-schema`; @@ -2139,7 +2179,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testBodyWithQueryParams: async (query: string, user: User, options: AxiosRequestConfig = {}): Promise => { + testBodyWithQueryParams: async (query: string, user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'query' is not null or undefined assertParamExists('testBodyWithQueryParams', 'query', query) // verify required parameter 'user' is not null or undefined @@ -2181,7 +2221,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testClientModel: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + testClientModel: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('testClientModel', 'client', client) const localVarPath = `/fake`; @@ -2230,7 +2270,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { + testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'number' is not null or undefined assertParamExists('testEndpointParameters', 'number', number) // verify required parameter '_double' is not null or undefined @@ -2340,7 +2380,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEnumParameters: async (enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options: AxiosRequestConfig = {}): Promise => { + testEnumParameters: async (enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2413,7 +2453,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testGroupParameters: async (requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options: AxiosRequestConfig = {}): Promise => { + testGroupParameters: async (requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'requiredStringGroup' is not null or undefined assertParamExists('testGroupParameters', 'requiredStringGroup', requiredStringGroup) // verify required parameter 'requiredBooleanGroup' is not null or undefined @@ -2482,7 +2522,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testInlineAdditionalProperties: async (requestBody: { [key: string]: string; }, options: AxiosRequestConfig = {}): Promise => { + testInlineAdditionalProperties: async (requestBody: { [key: string]: string; }, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'requestBody' is not null or undefined assertParamExists('testInlineAdditionalProperties', 'requestBody', requestBody) const localVarPath = `/fake/inline-additionalProperties`; @@ -2518,7 +2558,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testInlineFreeformAdditionalProperties: async (testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options: AxiosRequestConfig = {}): Promise => { + testInlineFreeformAdditionalProperties: async (testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'testInlineFreeformAdditionalPropertiesRequest' is not null or undefined assertParamExists('testInlineFreeformAdditionalProperties', 'testInlineFreeformAdditionalPropertiesRequest', testInlineFreeformAdditionalPropertiesRequest) const localVarPath = `/fake/inline-freeform-additionalProperties`; @@ -2555,7 +2595,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testJsonFormData: async (param: string, param2: string, options: AxiosRequestConfig = {}): Promise => { + testJsonFormData: async (param: string, param2: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'param' is not null or undefined assertParamExists('testJsonFormData', 'param', param) // verify required parameter 'param2' is not null or undefined @@ -2605,7 +2645,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testQueryParameterCollectionFormat: async (pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options: AxiosRequestConfig = {}): Promise => { + testQueryParameterCollectionFormat: async (pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pipe' is not null or undefined assertParamExists('testQueryParameterCollectionFormat', 'pipe', pipe) // verify required parameter 'ioutil' is not null or undefined @@ -2675,9 +2715,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeHealthGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeHealthGet(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeHealthGet(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeHealthGet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer boolean types @@ -2685,9 +2727,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterBooleanSerialize(body?: boolean, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterBooleanSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterBooleanSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of object with outer number type @@ -2695,9 +2739,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterCompositeSerialize(outerComposite, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterCompositeSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer number types @@ -2705,9 +2751,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterNumberSerialize(body?: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterNumberSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterNumberSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer string types @@ -2715,9 +2763,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterStringSerialize(body?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterStringSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterStringSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2725,9 +2775,24 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getArrayOfEnums(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async getArrayOfEnums(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getArrayOfEnums(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.getArrayOfEnums']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testAdditionalPropertiesReference(requestBody, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testAdditionalPropertiesReference']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For this test, the body for this request much reference a schema named `File`. @@ -2735,9 +2800,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithFileSchema(fileSchemaTestClass, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testBodyWithFileSchema']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2746,9 +2813,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testBodyWithQueryParams(query: string, user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithQueryParams(query, user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testBodyWithQueryParams']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test \"client\" model @@ -2757,9 +2826,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testClientModel(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testClientModel(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testClientModel(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testClientModel']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -2781,9 +2852,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testEndpointParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test enum parameters @@ -2799,9 +2872,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testEnumParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Fake endpoint to test group parameters (optional) @@ -2815,9 +2890,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testGroupParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2826,9 +2903,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testInlineAdditionalProperties(requestBody, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testInlineAdditionalProperties']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2837,9 +2916,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testInlineFreeformAdditionalProperties']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2849,9 +2930,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testJsonFormData(param: string, param2: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testJsonFormData(param, param2, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testJsonFormData']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test the collection format in query parameters @@ -2863,9 +2946,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testQueryParameterCollectionFormat']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -2931,6 +3016,16 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? getArrayOfEnums(options?: any): AxiosPromise> { return localVarFp.getArrayOfEnums(options).then((request) => request(axios, basePath)); }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: any): AxiosPromise { + return localVarFp.testAdditionalPropertiesReference(requestBody, options).then((request) => request(axios, basePath)); + }, /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass @@ -3076,7 +3171,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeHealthGet(options?: AxiosRequestConfig) { + public fakeHealthGet(options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeHealthGet(options).then((request) => request(this.axios, this.basePath)); } @@ -3087,7 +3182,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig) { + public fakeOuterBooleanSerialize(body?: boolean, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterBooleanSerialize(body, options).then((request) => request(this.axios, this.basePath)); } @@ -3098,7 +3193,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig) { + public fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterCompositeSerialize(outerComposite, options).then((request) => request(this.axios, this.basePath)); } @@ -3109,7 +3204,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig) { + public fakeOuterNumberSerialize(body?: number, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterNumberSerialize(body, options).then((request) => request(this.axios, this.basePath)); } @@ -3120,7 +3215,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig) { + public fakeOuterStringSerialize(body?: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterStringSerialize(body, options).then((request) => request(this.axios, this.basePath)); } @@ -3131,10 +3226,22 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public getArrayOfEnums(options?: AxiosRequestConfig) { + public getArrayOfEnums(options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).getArrayOfEnums(options).then((request) => request(this.axios, this.basePath)); } + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof FakeApi + */ + public testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: RawAxiosRequestConfig) { + return FakeApiFp(this.configuration).testAdditionalPropertiesReference(requestBody, options).then((request) => request(this.axios, this.basePath)); + } + /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass @@ -3142,7 +3249,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig) { + public testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testBodyWithFileSchema(fileSchemaTestClass, options).then((request) => request(this.axios, this.basePath)); } @@ -3154,7 +3261,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig) { + public testBodyWithQueryParams(query: string, user: User, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testBodyWithQueryParams(query, user, options).then((request) => request(this.axios, this.basePath)); } @@ -3166,7 +3273,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testClientModel(client: Client, options?: AxiosRequestConfig) { + public testClientModel(client: Client, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testClientModel(client, options).then((request) => request(this.axios, this.basePath)); } @@ -3191,7 +3298,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { + public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(this.axios, this.basePath)); } @@ -3210,7 +3317,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: AxiosRequestConfig) { + public testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options).then((request) => request(this.axios, this.basePath)); } @@ -3227,7 +3334,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig) { + public testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options).then((request) => request(this.axios, this.basePath)); } @@ -3239,7 +3346,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig) { + public testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testInlineAdditionalProperties(requestBody, options).then((request) => request(this.axios, this.basePath)); } @@ -3251,7 +3358,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: AxiosRequestConfig) { + public testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest, options).then((request) => request(this.axios, this.basePath)); } @@ -3264,7 +3371,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig) { + public testJsonFormData(param: string, param2: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testJsonFormData(param, param2, options).then((request) => request(this.axios, this.basePath)); } @@ -3279,7 +3386,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: AxiosRequestConfig) { + public testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options).then((request) => request(this.axios, this.basePath)); } } @@ -3366,7 +3473,7 @@ export const FakeClassnameTags123ApiAxiosParamCreator = function (configuration? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testClassname: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + testClassname: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('testClassname', 'client', client) const localVarPath = `/fake_classname_test`; @@ -3415,9 +3522,11 @@ export const FakeClassnameTags123ApiFp = function(configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testClassname(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testClassname(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testClassname(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeClassnameTags123Api.testClassname']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -3457,7 +3566,7 @@ export class FakeClassnameTags123Api extends BaseAPI { * @throws {RequiredError} * @memberof FakeClassnameTags123Api */ - public testClassname(client: Client, options?: AxiosRequestConfig) { + public testClassname(client: Client, options?: RawAxiosRequestConfig) { return FakeClassnameTags123ApiFp(this.configuration).testClassname(client, options).then((request) => request(this.axios, this.basePath)); } } @@ -3477,7 +3586,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (pet: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('addPet', 'pet', pet) const localVarPath = `/pet`; @@ -3520,7 +3629,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3562,7 +3671,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -3606,7 +3715,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -3649,7 +3758,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3686,7 +3795,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (pet: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('updatePet', 'pet', pet) const localVarPath = `/pet`; @@ -3730,7 +3839,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3782,7 +3891,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -3834,7 +3943,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { + uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFileWithRequiredFile', 'petId', petId) // verify required parameter 'requiredFile' is not null or undefined @@ -3896,9 +4005,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(pet: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3908,9 +4019,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -3919,9 +4032,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -3931,9 +4046,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -3942,9 +4059,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3953,9 +4072,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(pet: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(pet, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3966,9 +4087,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3979,9 +4102,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3992,9 +4117,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFileWithRequiredFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -4122,7 +4249,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(pet: Pet, options?: AxiosRequestConfig) { + public addPet(pet: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(pet, options).then((request) => request(this.axios, this.basePath)); } @@ -4135,7 +4262,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -4147,7 +4274,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -4160,7 +4287,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -4172,7 +4299,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -4184,7 +4311,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(pet: Pet, options?: AxiosRequestConfig) { + public updatePet(pet: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(pet, options).then((request) => request(this.axios, this.basePath)); } @@ -4198,7 +4325,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -4212,7 +4339,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } @@ -4226,7 +4353,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig) { + public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(this.axios, this.basePath)); } } @@ -4255,7 +4382,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{order_id}` @@ -4288,7 +4415,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -4322,7 +4449,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{order_id}` @@ -4356,7 +4483,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (order: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (order: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'order' is not null or undefined assertParamExists('placeOrder', 'order', order) const localVarPath = `/store/order`; @@ -4402,9 +4529,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -4412,9 +4541,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -4423,9 +4554,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4434,9 +4567,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(order: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(order: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(order, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -4505,7 +4640,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -4516,7 +4651,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -4528,7 +4663,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -4540,7 +4675,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(order: Order, options?: AxiosRequestConfig) { + public placeOrder(order: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(order, options).then((request) => request(this.axios, this.basePath)); } } @@ -4560,7 +4695,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (user: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUser', 'user', user) const localVarPath = `/user`; @@ -4596,7 +4731,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithArrayInput', 'user', user) const localVarPath = `/user/createWithArray`; @@ -4632,7 +4767,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithListInput', 'user', user) const localVarPath = `/user/createWithList`; @@ -4668,7 +4803,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -4702,7 +4837,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -4737,7 +4872,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -4779,7 +4914,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -4811,7 +4946,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, user: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'user' is not null or undefined @@ -4860,9 +4995,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4871,9 +5008,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4882,9 +5021,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -4893,9 +5034,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4904,9 +5047,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4916,9 +5061,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4926,9 +5073,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -4938,9 +5087,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -5051,7 +5202,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(user: User, options?: AxiosRequestConfig) { + public createUser(user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(user, options).then((request) => request(this.axios, this.basePath)); } @@ -5063,7 +5214,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -5075,7 +5226,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -5087,7 +5238,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -5099,7 +5250,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -5112,7 +5263,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -5123,7 +5274,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -5136,7 +5287,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, user: User, options?: AxiosRequestConfig) { + public updateUser(username: string, user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, user, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/base.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/base.ts index de8321eac184..ba1854123f7c 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/base.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io:80/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,37 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { + "PetApi.addPet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + } + ], + "PetApi.updatePet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + } + ], +} diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts index d202a5478f37..c0f62a7b6df1 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/test-petstore/configuration.ts b/samples/client/petstore/typescript-axios/builds/test-petstore/configuration.ts index 9d6922b1165a..c8051a678dcf 100644 --- a/samples/client/petstore/typescript-axios/builds/test-petstore/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/test-petstore/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts index 4cae18aed315..53ff891d4199 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -276,7 +276,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options: AxiosRequestConfig = {}): Promise => { + addPet: async (pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('addPet', 'pet', pet) const localVarPath = `/pet`; @@ -334,7 +334,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -376,7 +376,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -418,7 +418,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -459,7 +459,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -496,7 +496,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (pet: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('updatePet', 'pet', pet) const localVarPath = `/pet`; @@ -538,7 +538,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -590,7 +590,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -653,9 +653,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, header1, header2, accept, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -665,9 +667,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -676,9 +680,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -688,9 +694,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -699,9 +707,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -710,9 +720,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(pet: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(pet, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -723,9 +735,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -736,9 +750,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -860,7 +876,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: AxiosRequestConfig) { + public addPet(pet: Pet, header1?: Pet, header2?: Array, accept?: MediaType, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(pet, header1, header2, accept, options).then((request) => request(this.axios, this.basePath)); } @@ -873,7 +889,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -885,7 +901,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -898,7 +914,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -910,7 +926,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -922,7 +938,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(pet: Pet, options?: AxiosRequestConfig) { + public updatePet(pet: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(pet, options).then((request) => request(this.axios, this.basePath)); } @@ -936,7 +952,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -950,7 +966,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -979,7 +995,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1012,7 +1028,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1046,7 +1062,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1080,7 +1096,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (order: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (order: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'order' is not null or undefined assertParamExists('placeOrder', 'order', order) const localVarPath = `/store/order`; @@ -1126,9 +1142,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1136,9 +1154,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1147,9 +1167,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1158,9 +1180,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(order: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(order: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(order, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1229,7 +1253,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1240,7 +1264,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1252,7 +1276,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1264,7 +1288,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(order: Order, options?: AxiosRequestConfig) { + public placeOrder(order: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(order, options).then((request) => request(this.axios, this.basePath)); } } @@ -1284,7 +1308,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (user: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUser', 'user', user) const localVarPath = `/user`; @@ -1320,7 +1344,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithArrayInput', 'user', user) const localVarPath = `/user/createWithArray`; @@ -1356,7 +1380,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithListInput', 'user', user) const localVarPath = `/user/createWithList`; @@ -1392,7 +1416,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1426,7 +1450,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1461,7 +1485,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1503,7 +1527,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1535,7 +1559,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, user: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'user' is not null or undefined @@ -1584,9 +1608,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1595,9 +1621,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1606,9 +1634,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1617,9 +1647,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1628,9 +1660,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1640,9 +1674,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1650,9 +1686,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1662,9 +1700,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1775,7 +1815,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(user: User, options?: AxiosRequestConfig) { + public createUser(user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(user, options).then((request) => request(this.axios, this.basePath)); } @@ -1787,7 +1827,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -1799,7 +1839,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -1811,7 +1851,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1823,7 +1863,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1836,7 +1876,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1847,7 +1887,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1860,7 +1900,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, user: User, options?: AxiosRequestConfig) { + public updateUser(username: string, user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, user, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/base.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-complex-headers/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-complex-headers/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-complex-headers/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-complex-headers/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts index 640656edab23..42f7689e6109 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * @@ -875,16 +875,16 @@ export interface NullableClass { 'object_nullable_prop'?: { [key: string]: object; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - 'object_and_items_nullable_prop'?: { [key: string]: object; } | null; + 'object_and_items_nullable_prop'?: { [key: string]: object | null; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - 'object_items_nullable'?: { [key: string]: object; }; + 'object_items_nullable'?: { [key: string]: object | null; }; } /** * @@ -1363,7 +1363,7 @@ export const AnotherFakeApiAxiosParamCreator = function (configuration?: Configu * @param {*} [options] Override http request option. * @throws {RequiredError} */ - _123testSpecialTags: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + _123testSpecialTags: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('_123testSpecialTags', 'client', client) const localVarPath = `/another-fake/dummy`; @@ -1409,9 +1409,11 @@ export const AnotherFakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async _123testSpecialTags(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async _123testSpecialTags(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator._123testSpecialTags(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['AnotherFakeApi._123testSpecialTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1451,7 +1453,7 @@ export class AnotherFakeApi extends BaseAPI { * @throws {RequiredError} * @memberof AnotherFakeApi */ - public _123testSpecialTags(client: Client, options?: AxiosRequestConfig) { + public _123testSpecialTags(client: Client, options?: RawAxiosRequestConfig) { return AnotherFakeApiFp(this.configuration)._123testSpecialTags(client, options).then((request) => request(this.axios, this.basePath)); } } @@ -1469,7 +1471,7 @@ export const DefaultApiAxiosParamCreator = function (configuration?: Configurati * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fooGet: async (options: AxiosRequestConfig = {}): Promise => { + fooGet: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/foo`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1508,9 +1510,11 @@ export const DefaultApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fooGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fooGet(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fooGet(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['DefaultApi.fooGet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1546,7 +1550,7 @@ export class DefaultApi extends BaseAPI { * @throws {RequiredError} * @memberof DefaultApi */ - public fooGet(options?: AxiosRequestConfig) { + public fooGet(options?: RawAxiosRequestConfig) { return DefaultApiFp(this.configuration).fooGet(options).then((request) => request(this.axios, this.basePath)); } } @@ -1565,7 +1569,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeHealthGet: async (options: AxiosRequestConfig = {}): Promise => { + fakeHealthGet: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/health`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1595,7 +1599,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterBooleanSerialize: async (body?: boolean, options: AxiosRequestConfig = {}): Promise => { + fakeOuterBooleanSerialize: async (body?: boolean, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/boolean`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1628,7 +1632,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterCompositeSerialize: async (outerComposite?: OuterComposite, options: AxiosRequestConfig = {}): Promise => { + fakeOuterCompositeSerialize: async (outerComposite?: OuterComposite, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/composite`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1661,7 +1665,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterNumberSerialize: async (body?: number, options: AxiosRequestConfig = {}): Promise => { + fakeOuterNumberSerialize: async (body?: number, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/number`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1694,7 +1698,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - fakeOuterStringSerialize: async (body?: string, options: AxiosRequestConfig = {}): Promise => { + fakeOuterStringSerialize: async (body?: string, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake/outer/string`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1721,13 +1725,49 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) options: localVarRequestOptions, }; }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAdditionalPropertiesReference: async (requestBody: { [key: string]: any; }, options: RawAxiosRequestConfig = {}): Promise => { + // verify required parameter 'requestBody' is not null or undefined + assertParamExists('testAdditionalPropertiesReference', 'requestBody', requestBody) + const localVarPath = `/fake/additionalProperties-reference`; + // use dummy base URL string because the URL constructor only accepts absolute URLs. + const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); + let baseOptions; + if (configuration) { + baseOptions = configuration.baseOptions; + } + + const localVarRequestOptions = { method: 'POST', ...baseOptions, ...options}; + const localVarHeaderParameter = {} as any; + const localVarQueryParameter = {} as any; + + + + localVarHeaderParameter['Content-Type'] = 'application/json'; + + setSearchParams(localVarUrlObj, localVarQueryParameter); + let headersFromBaseOptions = baseOptions && baseOptions.headers ? baseOptions.headers : {}; + localVarRequestOptions.headers = {...localVarHeaderParameter, ...headersFromBaseOptions, ...options.headers}; + localVarRequestOptions.data = serializeDataIfNeeded(requestBody, localVarRequestOptions, configuration) + + return { + url: toPathString(localVarUrlObj), + options: localVarRequestOptions, + }; + }, /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testBodyWithFileSchema: async (fileSchemaTestClass: FileSchemaTestClass, options: AxiosRequestConfig = {}): Promise => { + testBodyWithFileSchema: async (fileSchemaTestClass: FileSchemaTestClass, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'fileSchemaTestClass' is not null or undefined assertParamExists('testBodyWithFileSchema', 'fileSchemaTestClass', fileSchemaTestClass) const localVarPath = `/fake/body-with-file-schema`; @@ -1763,7 +1803,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testBodyWithQueryParams: async (query: string, user: User, options: AxiosRequestConfig = {}): Promise => { + testBodyWithQueryParams: async (query: string, user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'query' is not null or undefined assertParamExists('testBodyWithQueryParams', 'query', query) // verify required parameter 'user' is not null or undefined @@ -1805,7 +1845,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testClientModel: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + testClientModel: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('testClientModel', 'client', client) const localVarPath = `/fake`; @@ -1854,7 +1894,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: AxiosRequestConfig = {}): Promise => { + testEndpointParameters: async (number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'number' is not null or undefined assertParamExists('testEndpointParameters', 'number', number) // verify required parameter '_double' is not null or undefined @@ -1964,7 +2004,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testEnumParameters: async (enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options: AxiosRequestConfig = {}): Promise => { + testEnumParameters: async (enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/fake`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -2037,7 +2077,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testGroupParameters: async (requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options: AxiosRequestConfig = {}): Promise => { + testGroupParameters: async (requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'requiredStringGroup' is not null or undefined assertParamExists('testGroupParameters', 'requiredStringGroup', requiredStringGroup) // verify required parameter 'requiredBooleanGroup' is not null or undefined @@ -2106,7 +2146,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testInlineAdditionalProperties: async (requestBody: { [key: string]: string; }, options: AxiosRequestConfig = {}): Promise => { + testInlineAdditionalProperties: async (requestBody: { [key: string]: string; }, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'requestBody' is not null or undefined assertParamExists('testInlineAdditionalProperties', 'requestBody', requestBody) const localVarPath = `/fake/inline-additionalProperties`; @@ -2142,7 +2182,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testInlineFreeformAdditionalProperties: async (testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options: AxiosRequestConfig = {}): Promise => { + testInlineFreeformAdditionalProperties: async (testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'testInlineFreeformAdditionalPropertiesRequest' is not null or undefined assertParamExists('testInlineFreeformAdditionalProperties', 'testInlineFreeformAdditionalPropertiesRequest', testInlineFreeformAdditionalPropertiesRequest) const localVarPath = `/fake/inline-freeform-additionalProperties`; @@ -2179,7 +2219,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testJsonFormData: async (param: string, param2: string, options: AxiosRequestConfig = {}): Promise => { + testJsonFormData: async (param: string, param2: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'param' is not null or undefined assertParamExists('testJsonFormData', 'param', param) // verify required parameter 'param2' is not null or undefined @@ -2229,7 +2269,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testQueryParameterCollectionFormat: async (pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options: AxiosRequestConfig = {}): Promise => { + testQueryParameterCollectionFormat: async (pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pipe' is not null or undefined assertParamExists('testQueryParameterCollectionFormat', 'pipe', pipe) // verify required parameter 'ioutil' is not null or undefined @@ -2290,7 +2330,7 @@ export const FakeApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testUniqueItemsHeaderAndQueryParameterCollectionFormat: async (queryUnique: Set, headerUnique: Set, options: AxiosRequestConfig = {}): Promise => { + testUniqueItemsHeaderAndQueryParameterCollectionFormat: async (queryUnique: Set, headerUnique: Set, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'queryUnique' is not null or undefined assertParamExists('testUniqueItemsHeaderAndQueryParameterCollectionFormat', 'queryUnique', queryUnique) // verify required parameter 'headerUnique' is not null or undefined @@ -2343,9 +2383,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeHealthGet(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeHealthGet(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeHealthGet(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeHealthGet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer boolean types @@ -2353,9 +2395,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterBooleanSerialize(body?: boolean, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterBooleanSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterBooleanSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of object with outer number type @@ -2363,9 +2407,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterCompositeSerialize(outerComposite, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterCompositeSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer number types @@ -2373,9 +2419,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterNumberSerialize(body?: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterNumberSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterNumberSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Test serialization of outer string types @@ -2383,9 +2431,24 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async fakeOuterStringSerialize(body?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.fakeOuterStringSerialize(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.fakeOuterStringSerialize']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); + }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + async testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + const localVarAxiosArgs = await localVarAxiosParamCreator.testAdditionalPropertiesReference(requestBody, options); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testAdditionalPropertiesReference']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For this test, the body for this request much reference a schema named `File`. @@ -2393,9 +2456,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithFileSchema(fileSchemaTestClass, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testBodyWithFileSchema']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2404,9 +2469,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testBodyWithQueryParams(query: string, user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testBodyWithQueryParams(query, user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testBodyWithQueryParams']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test \"client\" model @@ -2415,9 +2482,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testClientModel(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testClientModel(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testClientModel(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testClientModel']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 @@ -2439,9 +2508,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testEndpointParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test enum parameters @@ -2457,9 +2528,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testEnumParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Fake endpoint to test group parameters (optional) @@ -2473,9 +2546,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testGroupParameters']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2484,9 +2559,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testInlineAdditionalProperties(requestBody, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testInlineAdditionalProperties']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2495,9 +2572,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testInlineFreeformAdditionalProperties']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -2507,9 +2586,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testJsonFormData(param: string, param2: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testJsonFormData(param, param2, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testJsonFormData']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test the collection format in query parameters @@ -2521,9 +2602,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testQueryParameterCollectionFormat']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * To test unique items in header and query parameters @@ -2532,9 +2615,11 @@ export const FakeApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set, headerUnique: Set, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set, headerUnique: Set, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique, headerUnique, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeApi.testUniqueItemsHeaderAndQueryParameterCollectionFormat']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -2591,6 +2676,16 @@ export const FakeApiFactory = function (configuration?: Configuration, basePath? fakeOuterStringSerialize(body?: string, options?: any): AxiosPromise { return localVarFp.fakeOuterStringSerialize(body, options).then((request) => request(axios, basePath)); }, + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + */ + testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: any): AxiosPromise { + return localVarFp.testAdditionalPropertiesReference(requestBody, options).then((request) => request(axios, basePath)); + }, /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass @@ -2746,7 +2841,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeHealthGet(options?: AxiosRequestConfig) { + public fakeHealthGet(options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeHealthGet(options).then((request) => request(this.axios, this.basePath)); } @@ -2757,7 +2852,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterBooleanSerialize(body?: boolean, options?: AxiosRequestConfig) { + public fakeOuterBooleanSerialize(body?: boolean, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterBooleanSerialize(body, options).then((request) => request(this.axios, this.basePath)); } @@ -2768,7 +2863,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: AxiosRequestConfig) { + public fakeOuterCompositeSerialize(outerComposite?: OuterComposite, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterCompositeSerialize(outerComposite, options).then((request) => request(this.axios, this.basePath)); } @@ -2779,7 +2874,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterNumberSerialize(body?: number, options?: AxiosRequestConfig) { + public fakeOuterNumberSerialize(body?: number, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterNumberSerialize(body, options).then((request) => request(this.axios, this.basePath)); } @@ -2790,10 +2885,22 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public fakeOuterStringSerialize(body?: string, options?: AxiosRequestConfig) { + public fakeOuterStringSerialize(body?: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).fakeOuterStringSerialize(body, options).then((request) => request(this.axios, this.basePath)); } + /** + * + * @summary test referenced additionalProperties + * @param {{ [key: string]: any; }} requestBody request body + * @param {*} [options] Override http request option. + * @throws {RequiredError} + * @memberof FakeApi + */ + public testAdditionalPropertiesReference(requestBody: { [key: string]: any; }, options?: RawAxiosRequestConfig) { + return FakeApiFp(this.configuration).testAdditionalPropertiesReference(requestBody, options).then((request) => request(this.axios, this.basePath)); + } + /** * For this test, the body for this request much reference a schema named `File`. * @param {FileSchemaTestClass} fileSchemaTestClass @@ -2801,7 +2908,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: AxiosRequestConfig) { + public testBodyWithFileSchema(fileSchemaTestClass: FileSchemaTestClass, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testBodyWithFileSchema(fileSchemaTestClass, options).then((request) => request(this.axios, this.basePath)); } @@ -2813,7 +2920,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testBodyWithQueryParams(query: string, user: User, options?: AxiosRequestConfig) { + public testBodyWithQueryParams(query: string, user: User, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testBodyWithQueryParams(query, user, options).then((request) => request(this.axios, this.basePath)); } @@ -2825,7 +2932,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testClientModel(client: Client, options?: AxiosRequestConfig) { + public testClientModel(client: Client, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testClientModel(client, options).then((request) => request(this.axios, this.basePath)); } @@ -2850,7 +2957,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: AxiosRequestConfig) { + public testEndpointParameters(number: number, _double: number, patternWithoutDelimiter: string, _byte: string, integer?: number, int32?: number, int64?: number, _float?: number, string?: string, binary?: File, date?: string, dateTime?: string, password?: string, callback?: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testEndpointParameters(number, _double, patternWithoutDelimiter, _byte, integer, int32, int64, _float, string, binary, date, dateTime, password, callback, options).then((request) => request(this.axios, this.basePath)); } @@ -2869,7 +2976,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: AxiosRequestConfig) { + public testEnumParameters(enumHeaderStringArray?: Array, enumHeaderString?: TestEnumParametersEnumHeaderStringEnum, enumQueryStringArray?: Array, enumQueryString?: TestEnumParametersEnumQueryStringEnum, enumQueryInteger?: TestEnumParametersEnumQueryIntegerEnum, enumQueryDouble?: TestEnumParametersEnumQueryDoubleEnum, enumFormStringArray?: Array, enumFormString?: TestEnumParametersEnumFormStringEnum, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumFormStringArray, enumFormString, options).then((request) => request(this.axios, this.basePath)); } @@ -2886,7 +2993,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: AxiosRequestConfig) { + public testGroupParameters(requiredStringGroup: number, requiredBooleanGroup: boolean, requiredInt64Group: number, stringGroup?: number, booleanGroup?: boolean, int64Group?: number, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testGroupParameters(requiredStringGroup, requiredBooleanGroup, requiredInt64Group, stringGroup, booleanGroup, int64Group, options).then((request) => request(this.axios, this.basePath)); } @@ -2898,7 +3005,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: AxiosRequestConfig) { + public testInlineAdditionalProperties(requestBody: { [key: string]: string; }, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testInlineAdditionalProperties(requestBody, options).then((request) => request(this.axios, this.basePath)); } @@ -2910,7 +3017,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: AxiosRequestConfig) { + public testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest: TestInlineFreeformAdditionalPropertiesRequest, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testInlineFreeformAdditionalProperties(testInlineFreeformAdditionalPropertiesRequest, options).then((request) => request(this.axios, this.basePath)); } @@ -2923,7 +3030,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testJsonFormData(param: string, param2: string, options?: AxiosRequestConfig) { + public testJsonFormData(param: string, param2: string, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testJsonFormData(param, param2, options).then((request) => request(this.axios, this.basePath)); } @@ -2938,7 +3045,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: AxiosRequestConfig) { + public testQueryParameterCollectionFormat(pipe: Array, ioutil: Array, http: Array, url: Array, context: Array, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testQueryParameterCollectionFormat(pipe, ioutil, http, url, context, options).then((request) => request(this.axios, this.basePath)); } @@ -2950,7 +3057,7 @@ export class FakeApi extends BaseAPI { * @throws {RequiredError} * @memberof FakeApi */ - public testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set, headerUnique: Set, options?: AxiosRequestConfig) { + public testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique: Set, headerUnique: Set, options?: RawAxiosRequestConfig) { return FakeApiFp(this.configuration).testUniqueItemsHeaderAndQueryParameterCollectionFormat(queryUnique, headerUnique, options).then((request) => request(this.axios, this.basePath)); } } @@ -3037,7 +3144,7 @@ export const FakeClassnameTags123ApiAxiosParamCreator = function (configuration? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - testClassname: async (client: Client, options: AxiosRequestConfig = {}): Promise => { + testClassname: async (client: Client, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'client' is not null or undefined assertParamExists('testClassname', 'client', client) const localVarPath = `/fake_classname_test`; @@ -3086,9 +3193,11 @@ export const FakeClassnameTags123ApiFp = function(configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async testClassname(client: Client, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async testClassname(client: Client, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.testClassname(client, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['FakeClassnameTags123Api.testClassname']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -3128,7 +3237,7 @@ export class FakeClassnameTags123Api extends BaseAPI { * @throws {RequiredError} * @memberof FakeClassnameTags123Api */ - public testClassname(client: Client, options?: AxiosRequestConfig) { + public testClassname(client: Client, options?: RawAxiosRequestConfig) { return FakeClassnameTags123ApiFp(this.configuration).testClassname(client, options).then((request) => request(this.axios, this.basePath)); } } @@ -3148,7 +3257,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (pet: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('addPet', 'pet', pet) const localVarPath = `/pet`; @@ -3191,7 +3300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3233,7 +3342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -3277,7 +3386,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -3320,7 +3429,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3357,7 +3466,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (pet: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (pet: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'pet' is not null or undefined assertParamExists('updatePet', 'pet', pet) const localVarPath = `/pet`; @@ -3401,7 +3510,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -3453,7 +3562,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -3505,7 +3614,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: AxiosRequestConfig = {}): Promise => { + uploadFileWithRequiredFile: async (petId: number, requiredFile: File, additionalMetadata?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFileWithRequiredFile', 'petId', petId) // verify required parameter 'requiredFile' is not null or undefined @@ -3567,9 +3676,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(pet: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(pet, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3579,9 +3690,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -3590,9 +3703,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -3602,9 +3717,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -3613,9 +3730,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3624,9 +3743,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(pet: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(pet: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(pet, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3637,9 +3758,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3650,9 +3773,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -3663,9 +3788,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFileWithRequiredFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -3793,7 +3920,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(pet: Pet, options?: AxiosRequestConfig) { + public addPet(pet: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(pet, options).then((request) => request(this.axios, this.basePath)); } @@ -3806,7 +3933,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -3818,7 +3945,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -3831,7 +3958,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -3843,7 +3970,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -3855,7 +3982,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(pet: Pet, options?: AxiosRequestConfig) { + public updatePet(pet: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(pet, options).then((request) => request(this.axios, this.basePath)); } @@ -3869,7 +3996,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -3883,7 +4010,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } @@ -3897,7 +4024,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: AxiosRequestConfig) { + public uploadFileWithRequiredFile(petId: number, requiredFile: File, additionalMetadata?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFileWithRequiredFile(petId, requiredFile, additionalMetadata, options).then((request) => request(this.axios, this.basePath)); } } @@ -3926,7 +4053,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{order_id}` @@ -3959,7 +4086,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -3993,7 +4120,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{order_id}` @@ -4027,7 +4154,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (order: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (order: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'order' is not null or undefined assertParamExists('placeOrder', 'order', order) const localVarPath = `/store/order`; @@ -4073,9 +4200,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -4083,9 +4212,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -4094,9 +4225,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4105,9 +4238,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(order: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(order: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(order, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -4176,7 +4311,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -4187,7 +4322,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -4199,7 +4334,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -4211,7 +4346,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(order: Order, options?: AxiosRequestConfig) { + public placeOrder(order: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(order, options).then((request) => request(this.axios, this.basePath)); } } @@ -4231,7 +4366,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (user: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUser', 'user', user) const localVarPath = `/user`; @@ -4267,7 +4402,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithArrayInput', 'user', user) const localVarPath = `/user/createWithArray`; @@ -4303,7 +4438,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (user: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (user: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'user' is not null or undefined assertParamExists('createUsersWithListInput', 'user', user) const localVarPath = `/user/createWithList`; @@ -4339,7 +4474,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -4373,7 +4508,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -4408,7 +4543,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -4450,7 +4585,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -4482,7 +4617,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, user: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, user: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'user' is not null or undefined @@ -4531,9 +4666,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4542,9 +4679,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4553,9 +4692,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(user: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -4564,9 +4705,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4575,9 +4718,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4587,9 +4732,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -4597,9 +4744,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -4609,9 +4758,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, user: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, user: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, user, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -4722,7 +4873,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(user: User, options?: AxiosRequestConfig) { + public createUser(user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(user, options).then((request) => request(this.axios, this.basePath)); } @@ -4734,7 +4885,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -4746,7 +4897,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(user: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(user: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(user, options).then((request) => request(this.axios, this.basePath)); } @@ -4758,7 +4909,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -4770,7 +4921,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -4783,7 +4934,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -4794,7 +4945,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -4807,7 +4958,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, user: User, options?: AxiosRequestConfig) { + public updateUser(username: string, user: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, user, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/base.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/base.ts index de8321eac184..ba1854123f7c 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io:80/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,37 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { + "PetApi.addPet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + } + ], + "PetApi.updatePet": [ + { + url: "http://petstore.swagger.io/v2", + description: "No description provided", + }, + { + url: "http://path-server-test.petstore.local/v2", + description: "No description provided", + } + ], +} diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts index d202a5478f37..c0f62a7b6df1 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/configuration.ts index 9d6922b1165a..c8051a678dcf 100644 --- a/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-fake-endpoints-models-for-testing-with-http-signature/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts index 6d41ec62c45e..aa2518ef893f 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -259,7 +259,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -300,7 +300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -342,7 +342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -384,7 +384,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -425,7 +425,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -462,7 +462,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -504,7 +504,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -556,7 +556,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -616,9 +616,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -628,9 +630,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -639,9 +643,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -651,9 +657,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -662,9 +670,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -673,9 +683,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -686,9 +698,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -699,9 +713,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -816,7 +832,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - addPet(body: Pet, options?: AxiosRequestConfig): AxiosPromise; + addPet(body: Pet, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -827,7 +843,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): AxiosPromise; + deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * Multiple status values can be provided with comma separated strings @@ -837,7 +853,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - findPetsByStatus(status: Array, options?: AxiosRequestConfig): AxiosPromise>; + findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): AxiosPromise>; /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -848,7 +864,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - findPetsByTags(tags: Array, options?: AxiosRequestConfig): AxiosPromise>; + findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): AxiosPromise>; /** * Returns a single pet @@ -858,7 +874,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - getPetById(petId: number, options?: AxiosRequestConfig): AxiosPromise; + getPetById(petId: number, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -868,7 +884,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - updatePet(body: Pet, options?: AxiosRequestConfig): AxiosPromise; + updatePet(body: Pet, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -880,7 +896,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): AxiosPromise; + updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -892,7 +908,7 @@ export interface PetApiInterface { * @throws {RequiredError} * @memberof PetApiInterface */ - uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): AxiosPromise; + uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): AxiosPromise; } @@ -911,7 +927,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -924,7 +940,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -936,7 +952,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -949,7 +965,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -961,7 +977,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -973,7 +989,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -987,7 +1003,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -1001,7 +1017,7 @@ export class PetApi extends BaseAPI implements PetApiInterface { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -1030,7 +1046,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1063,7 +1079,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1097,7 +1113,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1131,7 +1147,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -1177,9 +1193,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1187,9 +1205,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1198,9 +1218,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1209,9 +1231,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1279,7 +1303,7 @@ export interface StoreApiInterface { * @throws {RequiredError} * @memberof StoreApiInterface */ - deleteOrder(orderId: string, options?: AxiosRequestConfig): AxiosPromise; + deleteOrder(orderId: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * Returns a map of status codes to quantities @@ -1288,7 +1312,7 @@ export interface StoreApiInterface { * @throws {RequiredError} * @memberof StoreApiInterface */ - getInventory(options?: AxiosRequestConfig): AxiosPromise<{ [key: string]: number; }>; + getInventory(options?: RawAxiosRequestConfig): AxiosPromise<{ [key: string]: number; }>; /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1298,7 +1322,7 @@ export interface StoreApiInterface { * @throws {RequiredError} * @memberof StoreApiInterface */ - getOrderById(orderId: number, options?: AxiosRequestConfig): AxiosPromise; + getOrderById(orderId: number, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1308,7 +1332,7 @@ export interface StoreApiInterface { * @throws {RequiredError} * @memberof StoreApiInterface */ - placeOrder(body: Order, options?: AxiosRequestConfig): AxiosPromise; + placeOrder(body: Order, options?: RawAxiosRequestConfig): AxiosPromise; } @@ -1327,7 +1351,7 @@ export class StoreApi extends BaseAPI implements StoreApiInterface { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1338,7 +1362,7 @@ export class StoreApi extends BaseAPI implements StoreApiInterface { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1350,7 +1374,7 @@ export class StoreApi extends BaseAPI implements StoreApiInterface { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1362,7 +1386,7 @@ export class StoreApi extends BaseAPI implements StoreApiInterface { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1382,7 +1406,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1418,7 +1442,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1454,7 +1478,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1490,7 +1514,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1524,7 +1548,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1559,7 +1583,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1601,7 +1625,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1633,7 +1657,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1682,9 +1706,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1693,9 +1719,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1704,9 +1732,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1715,9 +1745,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1726,9 +1758,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1738,9 +1772,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1748,9 +1784,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1760,9 +1798,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1872,7 +1912,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - createUser(body: User, options?: AxiosRequestConfig): AxiosPromise; + createUser(body: User, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1882,7 +1922,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): AxiosPromise; + createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1892,7 +1932,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - createUsersWithListInput(body: Array, options?: AxiosRequestConfig): AxiosPromise; + createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): AxiosPromise; /** * This can only be done by the logged in user. @@ -1902,7 +1942,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - deleteUser(username: string, options?: AxiosRequestConfig): AxiosPromise; + deleteUser(username: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1912,7 +1952,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - getUserByName(username: string, options?: AxiosRequestConfig): AxiosPromise; + getUserByName(username: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1923,7 +1963,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - loginUser(username: string, password: string, options?: AxiosRequestConfig): AxiosPromise; + loginUser(username: string, password: string, options?: RawAxiosRequestConfig): AxiosPromise; /** * @@ -1932,7 +1972,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - logoutUser(options?: AxiosRequestConfig): AxiosPromise; + logoutUser(options?: RawAxiosRequestConfig): AxiosPromise; /** * This can only be done by the logged in user. @@ -1943,7 +1983,7 @@ export interface UserApiInterface { * @throws {RequiredError} * @memberof UserApiInterface */ - updateUser(username: string, body: User, options?: AxiosRequestConfig): AxiosPromise; + updateUser(username: string, body: User, options?: RawAxiosRequestConfig): AxiosPromise; } @@ -1962,7 +2002,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1974,7 +2014,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1986,7 +2026,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1998,7 +2038,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -2010,7 +2050,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -2023,7 +2063,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -2034,7 +2074,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -2047,7 +2087,7 @@ export class UserApi extends BaseAPI implements UserApiInterface { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/base.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-interfaces/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-interfaces/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-interfaces/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-interfaces/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-node-imports/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts index 4e4a826dd932..bc170c05d884 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/api.ts @@ -14,7 +14,7 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // URLSearchParams not necessarily used // @ts-ignore @@ -25,7 +25,7 @@ import FormData from 'form-data' import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -263,7 +263,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -304,7 +304,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -346,7 +346,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -388,7 +388,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -429,7 +429,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -466,7 +466,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -508,7 +508,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -560,7 +560,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -620,9 +620,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -632,9 +634,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -643,9 +647,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -655,9 +661,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -666,9 +674,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -677,9 +687,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -690,9 +702,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -703,9 +717,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -821,7 +837,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -834,7 +850,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -846,7 +862,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -859,7 +875,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -871,7 +887,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -883,7 +899,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -897,7 +913,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -911,7 +927,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -940,7 +956,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -973,7 +989,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1007,7 +1023,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1041,7 +1057,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body?: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body?: Order, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/order`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1085,9 +1101,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1095,9 +1113,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1106,9 +1126,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1117,9 +1139,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body?: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body?: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1188,7 +1212,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1199,7 +1223,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1211,7 +1235,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1223,7 +1247,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body?: Order, options?: AxiosRequestConfig) { + public placeOrder(body?: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1243,7 +1267,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1279,7 +1303,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1315,7 +1339,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1351,7 +1375,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1385,7 +1409,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1420,7 +1444,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1462,7 +1486,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1494,7 +1518,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1543,9 +1567,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1554,9 +1580,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1565,9 +1593,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1576,9 +1606,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1587,9 +1619,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1599,9 +1633,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1609,9 +1645,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1621,9 +1659,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1734,7 +1774,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1746,7 +1786,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1758,7 +1798,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1770,7 +1810,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1782,7 +1822,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1795,7 +1835,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1806,7 +1846,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1819,7 +1859,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/base.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts index a3088139a9a3..a88b97565783 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/common.ts @@ -145,7 +145,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-node-imports/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-node-imports/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-node-imports/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-node-imports/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts index 3ab10e2270ff..ffdd77ed2e6e 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/pet-api.ts @@ -14,13 +14,13 @@ import type { Configuration } from '../../../configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../../../common'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../../../base'; +import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../../../base'; // @ts-ignore import { ApiResponse } from '../../../model/some/levels/deep'; // @ts-ignore @@ -38,7 +38,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -79,7 +79,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -121,7 +121,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -163,7 +163,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -204,7 +204,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -241,7 +241,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -283,7 +283,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -335,7 +335,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -395,9 +395,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -407,9 +409,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -418,9 +422,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -430,9 +436,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -441,9 +449,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -452,9 +462,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -465,9 +477,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -478,9 +492,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -596,7 +612,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -609,7 +625,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -621,7 +637,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -634,7 +650,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -646,7 +662,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -658,7 +674,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -672,7 +688,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -686,7 +702,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts index 6b243be82f52..e65822ad40eb 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/store-api.ts @@ -14,13 +14,13 @@ import type { Configuration } from '../../../configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../../../common'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../../../base'; +import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../../../base'; // @ts-ignore import { Order } from '../../../model/some/levels/deep'; /** @@ -36,7 +36,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -69,7 +69,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -103,7 +103,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -137,7 +137,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -183,9 +183,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -193,9 +195,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -204,9 +208,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -215,9 +221,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -286,7 +294,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -297,7 +305,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -309,7 +317,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -321,7 +329,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts index 017a25d8074b..2840fefac7d4 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/api/another/level/user-api.ts @@ -14,13 +14,13 @@ import type { Configuration } from '../../../configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from '../../../common'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError } from '../../../base'; +import { BASE_PATH, COLLECTION_FORMATS, RequestArgs, BaseAPI, RequiredError, operationServerMap } from '../../../base'; // @ts-ignore import { User } from '../../../model/some/levels/deep'; /** @@ -36,7 +36,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -72,7 +72,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -108,7 +108,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -144,7 +144,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -178,7 +178,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -213,7 +213,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -255,7 +255,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -287,7 +287,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -336,9 +336,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -347,9 +349,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -358,9 +362,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -369,9 +375,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -380,9 +388,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -392,9 +402,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -402,9 +414,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -414,9 +428,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -527,7 +543,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -539,7 +555,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -551,7 +567,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -563,7 +579,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -575,7 +591,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -588,7 +604,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -599,7 +615,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -612,7 +628,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/base.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json index 8569103e4e4f..81cacb217244 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version-and-separate-models-and-api/package.json @@ -18,11 +18,11 @@ "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc ", + "build": "tsc", "prepare": "npm run build" }, "dependencies": { - "axios": "^0.27.2" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts index 1af5de4a800a..f74593fe5bb7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -259,7 +259,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -300,7 +300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -342,7 +342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -384,7 +384,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -425,7 +425,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -462,7 +462,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -504,7 +504,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -556,7 +556,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -616,9 +616,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -628,9 +630,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -639,9 +643,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -651,9 +657,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -662,9 +670,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -673,9 +683,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -686,9 +698,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -699,9 +713,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -817,7 +833,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -830,7 +846,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -842,7 +858,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -855,7 +871,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -867,7 +883,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -879,7 +895,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -893,7 +909,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -907,7 +923,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -936,7 +952,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -969,7 +985,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1003,7 +1019,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1037,7 +1053,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -1083,9 +1099,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1093,9 +1111,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1104,9 +1124,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1115,9 +1137,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1186,7 +1210,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1197,7 +1221,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1209,7 +1233,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1221,7 +1245,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1241,7 +1265,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1277,7 +1301,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1313,7 +1337,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1349,7 +1373,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1383,7 +1407,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1418,7 +1442,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1460,7 +1484,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1492,7 +1516,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1541,9 +1565,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1552,9 +1578,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1563,9 +1591,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1574,9 +1604,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1585,9 +1617,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1597,9 +1631,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1607,9 +1643,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1619,9 +1657,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1732,7 +1772,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1744,7 +1784,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1756,7 +1796,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1768,7 +1808,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1780,7 +1820,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1793,7 +1833,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1804,7 +1844,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1817,7 +1857,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/base.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-npm-version/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/package-lock.json b/samples/client/petstore/typescript-axios/builds/with-npm-version/package-lock.json index 014e497001ad..1afa264fc3ca 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/package-lock.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/package-lock.json @@ -9,7 +9,7 @@ "version": "1.0.0", "license": "Unlicense", "dependencies": { - "axios": "^0.26.1" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", @@ -22,18 +22,44 @@ "integrity": "sha512-FW0q7NI8UnjbKrJK8NGr6QXY69ATw9IFe6ItIo5yozPwA9DU/xkhiPddctUVyrmFXvyFYerYgQak/qu200UBDw==", "dev": true }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "node_modules/axios": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", - "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", "dependencies": { - "follow-redirects": "^1.14.8" + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "engines": { + "node": ">=0.4.0" } }, "node_modules/follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==", + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", "funding": [ { "type": "individual", @@ -49,6 +75,43 @@ } } }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" + }, "node_modules/typescript": { "version": "4.6.3", "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.6.3.tgz", @@ -70,18 +133,66 @@ "integrity": "sha512-FW0q7NI8UnjbKrJK8NGr6QXY69ATw9IFe6ItIo5yozPwA9DU/xkhiPddctUVyrmFXvyFYerYgQak/qu200UBDw==", "dev": true }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==" + }, "axios": { - "version": "0.26.1", - "resolved": "https://registry.npmjs.org/axios/-/axios-0.26.1.tgz", - "integrity": "sha512-fPwcX4EvnSHuInCMItEhAGnaSEXRBjtzh9fOtsE6E1G6p7vl7edEeZe11QHf18+6+9gR5PbKV/sGKNaD8YaMeA==", + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", "requires": { - "follow-redirects": "^1.14.8" + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" } }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "requires": { + "delayed-stream": "~1.0.0" + } + }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==" + }, "follow-redirects": { - "version": "1.14.9", - "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.14.9.tgz", - "integrity": "sha512-MQDfihBQYMcyy5dhRDJUHcw7lb2Pv/TuE6xP1vyraLukNDHKbDxDNaOE3NbCAdKQApno+GPRyo1YAp89yCjK4w==" + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==" + }, + "form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==" + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "requires": { + "mime-db": "1.52.0" + } + }, + "proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==" }, "typescript": { "version": "4.6.3", diff --git a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json index 8569103e4e4f..81cacb217244 100644 --- a/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json +++ b/samples/client/petstore/typescript-axios/builds/with-npm-version/package.json @@ -18,11 +18,11 @@ "main": "./dist/index.js", "typings": "./dist/index.d.ts", "scripts": { - "build": "tsc ", + "build": "tsc", "prepare": "npm run build" }, "dependencies": { - "axios": "^0.27.2" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts index 19622092d291..df80d94e0f6f 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -259,7 +259,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -300,7 +300,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -342,7 +342,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -384,7 +384,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -425,7 +425,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -462,7 +462,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -504,7 +504,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -556,7 +556,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -616,9 +616,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -628,9 +630,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -639,9 +643,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -651,9 +657,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -662,9 +670,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -673,9 +683,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -686,9 +698,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -699,9 +713,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -720,7 +736,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet(requestParameters: PetApiAddPetRequest, options?: AxiosRequestConfig): AxiosPromise { + addPet(requestParameters: PetApiAddPetRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.addPet(requestParameters.body, options).then((request) => request(axios, basePath)); }, /** @@ -730,7 +746,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet(requestParameters: PetApiDeletePetRequest, options?: AxiosRequestConfig): AxiosPromise { + deletePet(requestParameters: PetApiDeletePetRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.deletePet(requestParameters.petId, requestParameters.apiKey, options).then((request) => request(axios, basePath)); }, /** @@ -740,7 +756,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus(requestParameters: PetApiFindPetsByStatusRequest, options?: AxiosRequestConfig): AxiosPromise> { + findPetsByStatus(requestParameters: PetApiFindPetsByStatusRequest, options?: RawAxiosRequestConfig): AxiosPromise> { return localVarFp.findPetsByStatus(requestParameters.status, options).then((request) => request(axios, basePath)); }, /** @@ -751,7 +767,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @deprecated * @throws {RequiredError} */ - findPetsByTags(requestParameters: PetApiFindPetsByTagsRequest, options?: AxiosRequestConfig): AxiosPromise> { + findPetsByTags(requestParameters: PetApiFindPetsByTagsRequest, options?: RawAxiosRequestConfig): AxiosPromise> { return localVarFp.findPetsByTags(requestParameters.tags, options).then((request) => request(axios, basePath)); }, /** @@ -761,7 +777,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById(requestParameters: PetApiGetPetByIdRequest, options?: AxiosRequestConfig): AxiosPromise { + getPetById(requestParameters: PetApiGetPetByIdRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.getPetById(requestParameters.petId, options).then((request) => request(axios, basePath)); }, /** @@ -771,7 +787,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet(requestParameters: PetApiUpdatePetRequest, options?: AxiosRequestConfig): AxiosPromise { + updatePet(requestParameters: PetApiUpdatePetRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.updatePet(requestParameters.body, options).then((request) => request(axios, basePath)); }, /** @@ -781,7 +797,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm(requestParameters: PetApiUpdatePetWithFormRequest, options?: AxiosRequestConfig): AxiosPromise { + updatePetWithForm(requestParameters: PetApiUpdatePetWithFormRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.updatePetWithForm(requestParameters.petId, requestParameters.name, requestParameters.status, options).then((request) => request(axios, basePath)); }, /** @@ -791,7 +807,7 @@ export const PetApiFactory = function (configuration?: Configuration, basePath?: * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile(requestParameters: PetApiUploadFileRequest, options?: AxiosRequestConfig): AxiosPromise { + uploadFile(requestParameters: PetApiUploadFileRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.uploadFile(requestParameters.petId, requestParameters.additionalMetadata, requestParameters.file, options).then((request) => request(axios, basePath)); }, }; @@ -959,7 +975,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(requestParameters: PetApiAddPetRequest, options?: AxiosRequestConfig) { + public addPet(requestParameters: PetApiAddPetRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } @@ -971,7 +987,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(requestParameters: PetApiDeletePetRequest, options?: AxiosRequestConfig) { + public deletePet(requestParameters: PetApiDeletePetRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(requestParameters.petId, requestParameters.apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -983,7 +999,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(requestParameters: PetApiFindPetsByStatusRequest, options?: AxiosRequestConfig) { + public findPetsByStatus(requestParameters: PetApiFindPetsByStatusRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(requestParameters.status, options).then((request) => request(this.axios, this.basePath)); } @@ -996,7 +1012,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(requestParameters: PetApiFindPetsByTagsRequest, options?: AxiosRequestConfig) { + public findPetsByTags(requestParameters: PetApiFindPetsByTagsRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(requestParameters.tags, options).then((request) => request(this.axios, this.basePath)); } @@ -1008,7 +1024,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(requestParameters: PetApiGetPetByIdRequest, options?: AxiosRequestConfig) { + public getPetById(requestParameters: PetApiGetPetByIdRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(requestParameters.petId, options).then((request) => request(this.axios, this.basePath)); } @@ -1020,7 +1036,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(requestParameters: PetApiUpdatePetRequest, options?: AxiosRequestConfig) { + public updatePet(requestParameters: PetApiUpdatePetRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } @@ -1032,7 +1048,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(requestParameters: PetApiUpdatePetWithFormRequest, options?: AxiosRequestConfig) { + public updatePetWithForm(requestParameters: PetApiUpdatePetWithFormRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(requestParameters.petId, requestParameters.name, requestParameters.status, options).then((request) => request(this.axios, this.basePath)); } @@ -1044,7 +1060,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(requestParameters: PetApiUploadFileRequest, options?: AxiosRequestConfig) { + public uploadFile(requestParameters: PetApiUploadFileRequest, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(requestParameters.petId, requestParameters.additionalMetadata, requestParameters.file, options).then((request) => request(this.axios, this.basePath)); } } @@ -1073,7 +1089,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1106,7 +1122,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1140,7 +1156,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1174,7 +1190,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body?: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body?: Order, options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/order`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1218,9 +1234,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1228,9 +1246,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1239,9 +1259,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1250,9 +1272,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body?: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body?: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1271,7 +1295,7 @@ export const StoreApiFactory = function (configuration?: Configuration, basePath * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder(requestParameters: StoreApiDeleteOrderRequest, options?: AxiosRequestConfig): AxiosPromise { + deleteOrder(requestParameters: StoreApiDeleteOrderRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.deleteOrder(requestParameters.orderId, options).then((request) => request(axios, basePath)); }, /** @@ -1280,7 +1304,7 @@ export const StoreApiFactory = function (configuration?: Configuration, basePath * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory(options?: AxiosRequestConfig): AxiosPromise<{ [key: string]: number; }> { + getInventory(options?: RawAxiosRequestConfig): AxiosPromise<{ [key: string]: number; }> { return localVarFp.getInventory(options).then((request) => request(axios, basePath)); }, /** @@ -1290,7 +1314,7 @@ export const StoreApiFactory = function (configuration?: Configuration, basePath * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById(requestParameters: StoreApiGetOrderByIdRequest, options?: AxiosRequestConfig): AxiosPromise { + getOrderById(requestParameters: StoreApiGetOrderByIdRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.getOrderById(requestParameters.orderId, options).then((request) => request(axios, basePath)); }, /** @@ -1300,7 +1324,7 @@ export const StoreApiFactory = function (configuration?: Configuration, basePath * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder(requestParameters: StoreApiPlaceOrderRequest = {}, options?: AxiosRequestConfig): AxiosPromise { + placeOrder(requestParameters: StoreApiPlaceOrderRequest = {}, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.placeOrder(requestParameters.body, options).then((request) => request(axios, basePath)); }, }; @@ -1363,7 +1387,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(requestParameters: StoreApiDeleteOrderRequest, options?: AxiosRequestConfig) { + public deleteOrder(requestParameters: StoreApiDeleteOrderRequest, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(requestParameters.orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1374,7 +1398,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1386,7 +1410,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(requestParameters: StoreApiGetOrderByIdRequest, options?: AxiosRequestConfig) { + public getOrderById(requestParameters: StoreApiGetOrderByIdRequest, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(requestParameters.orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1398,7 +1422,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(requestParameters: StoreApiPlaceOrderRequest = {}, options?: AxiosRequestConfig) { + public placeOrder(requestParameters: StoreApiPlaceOrderRequest = {}, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1418,7 +1442,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1454,7 +1478,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1490,7 +1514,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1526,7 +1550,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1560,7 +1584,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1595,7 +1619,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1637,7 +1661,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1669,7 +1693,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1718,9 +1742,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1729,9 +1755,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1740,9 +1768,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1751,9 +1781,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1762,9 +1794,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1774,9 +1808,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1784,9 +1820,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1796,9 +1834,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1817,7 +1857,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser(requestParameters: UserApiCreateUserRequest, options?: AxiosRequestConfig): AxiosPromise { + createUser(requestParameters: UserApiCreateUserRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.createUser(requestParameters.body, options).then((request) => request(axios, basePath)); }, /** @@ -1827,7 +1867,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput(requestParameters: UserApiCreateUsersWithArrayInputRequest, options?: AxiosRequestConfig): AxiosPromise { + createUsersWithArrayInput(requestParameters: UserApiCreateUsersWithArrayInputRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.createUsersWithArrayInput(requestParameters.body, options).then((request) => request(axios, basePath)); }, /** @@ -1837,7 +1877,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput(requestParameters: UserApiCreateUsersWithListInputRequest, options?: AxiosRequestConfig): AxiosPromise { + createUsersWithListInput(requestParameters: UserApiCreateUsersWithListInputRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.createUsersWithListInput(requestParameters.body, options).then((request) => request(axios, basePath)); }, /** @@ -1847,7 +1887,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser(requestParameters: UserApiDeleteUserRequest, options?: AxiosRequestConfig): AxiosPromise { + deleteUser(requestParameters: UserApiDeleteUserRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.deleteUser(requestParameters.username, options).then((request) => request(axios, basePath)); }, /** @@ -1857,7 +1897,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName(requestParameters: UserApiGetUserByNameRequest, options?: AxiosRequestConfig): AxiosPromise { + getUserByName(requestParameters: UserApiGetUserByNameRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.getUserByName(requestParameters.username, options).then((request) => request(axios, basePath)); }, /** @@ -1867,7 +1907,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser(requestParameters: UserApiLoginUserRequest, options?: AxiosRequestConfig): AxiosPromise { + loginUser(requestParameters: UserApiLoginUserRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.loginUser(requestParameters.username, requestParameters.password, options).then((request) => request(axios, basePath)); }, /** @@ -1876,7 +1916,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser(options?: AxiosRequestConfig): AxiosPromise { + logoutUser(options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.logoutUser(options).then((request) => request(axios, basePath)); }, /** @@ -1886,7 +1926,7 @@ export const UserApiFactory = function (configuration?: Configuration, basePath? * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser(requestParameters: UserApiUpdateUserRequest, options?: AxiosRequestConfig): AxiosPromise { + updateUser(requestParameters: UserApiUpdateUserRequest, options?: RawAxiosRequestConfig): AxiosPromise { return localVarFp.updateUser(requestParameters.username, requestParameters.body, options).then((request) => request(axios, basePath)); }, }; @@ -2019,7 +2059,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(requestParameters: UserApiCreateUserRequest, options?: AxiosRequestConfig) { + public createUser(requestParameters: UserApiCreateUserRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } @@ -2031,7 +2071,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(requestParameters: UserApiCreateUsersWithArrayInputRequest, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(requestParameters: UserApiCreateUsersWithArrayInputRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } @@ -2043,7 +2083,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(requestParameters: UserApiCreateUsersWithListInputRequest, options?: AxiosRequestConfig) { + public createUsersWithListInput(requestParameters: UserApiCreateUsersWithListInputRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } @@ -2055,7 +2095,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(requestParameters: UserApiDeleteUserRequest, options?: AxiosRequestConfig) { + public deleteUser(requestParameters: UserApiDeleteUserRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(requestParameters.username, options).then((request) => request(this.axios, this.basePath)); } @@ -2067,7 +2107,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(requestParameters: UserApiGetUserByNameRequest, options?: AxiosRequestConfig) { + public getUserByName(requestParameters: UserApiGetUserByNameRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(requestParameters.username, options).then((request) => request(this.axios, this.basePath)); } @@ -2079,7 +2119,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(requestParameters: UserApiLoginUserRequest, options?: AxiosRequestConfig) { + public loginUser(requestParameters: UserApiLoginUserRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(requestParameters.username, requestParameters.password, options).then((request) => request(this.axios, this.basePath)); } @@ -2090,7 +2130,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -2102,7 +2142,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(requestParameters: UserApiUpdateUserRequest, options?: AxiosRequestConfig) { + public updateUser(requestParameters: UserApiUpdateUserRequest, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(requestParameters.username, requestParameters.body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/base.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-single-request-parameters/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/.openapi-generator/VERSION b/samples/client/petstore/typescript-axios/builds/with-string-enums/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts index f260f2004097..2742f3d7e273 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/api.ts @@ -14,14 +14,14 @@ import type { Configuration } from './configuration'; -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; // Some imports not used depending on template conditions // @ts-ignore import { DUMMY_BASE_URL, assertParamExists, setApiKeyToObject, setBasicAuthToObject, setBearerAuthToObject, setOAuthToObject, setSearchParams, serializeDataIfNeeded, toPathString, createRequestFunction } from './common'; import type { RequestArgs } from './base'; // @ts-ignore -import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError } from './base'; +import { BASE_PATH, COLLECTION_FORMATS, BaseAPI, RequiredError, operationServerMap } from './base'; /** * Describes the result of uploading an image resource @@ -263,7 +263,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - addPet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + addPet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('addPet', 'body', body) const localVarPath = `/pet`; @@ -304,7 +304,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deletePet: async (petId: number, apiKey?: string, options: AxiosRequestConfig = {}): Promise => { + deletePet: async (petId: number, apiKey?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('deletePet', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -346,7 +346,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - findPetsByStatus: async (status: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByStatus: async (status: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'status' is not null or undefined assertParamExists('findPetsByStatus', 'status', status) const localVarPath = `/pet/findByStatus`; @@ -388,7 +388,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @deprecated * @throws {RequiredError} */ - findPetsByTags: async (tags: Array, options: AxiosRequestConfig = {}): Promise => { + findPetsByTags: async (tags: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'tags' is not null or undefined assertParamExists('findPetsByTags', 'tags', tags) const localVarPath = `/pet/findByTags`; @@ -429,7 +429,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getPetById: async (petId: number, options: AxiosRequestConfig = {}): Promise => { + getPetById: async (petId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('getPetById', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -466,7 +466,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePet: async (body: Pet, options: AxiosRequestConfig = {}): Promise => { + updatePet: async (body: Pet, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('updatePet', 'body', body) const localVarPath = `/pet`; @@ -508,7 +508,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updatePetWithForm: async (petId: number, name?: string, status?: string, options: AxiosRequestConfig = {}): Promise => { + updatePetWithForm: async (petId: number, name?: string, status?: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('updatePetWithForm', 'petId', petId) const localVarPath = `/pet/{petId}` @@ -560,7 +560,7 @@ export const PetApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: AxiosRequestConfig = {}): Promise => { + uploadFile: async (petId: number, additionalMetadata?: string, file?: File, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'petId' is not null or undefined assertParamExists('uploadFile', 'petId', petId) const localVarPath = `/pet/{petId}/uploadImage` @@ -620,9 +620,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async addPet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async addPet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.addPet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.addPet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -632,9 +634,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deletePet(petId, apiKey, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.deletePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple status values can be provided with comma separated strings @@ -643,9 +647,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async findPetsByStatus(status: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByStatus(status: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByStatus(status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByStatus']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. @@ -655,9 +661,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @deprecated * @throws {RequiredError} */ - async findPetsByTags(tags: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { + async findPetsByTags(tags: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise>> { const localVarAxiosArgs = await localVarAxiosParamCreator.findPetsByTags(tags, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.findPetsByTags']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a single pet @@ -666,9 +674,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getPetById(petId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getPetById(petId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getPetById(petId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.getPetById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -677,9 +687,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePet(body: Pet, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePet(body: Pet, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePet(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePet']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -690,9 +702,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updatePetWithForm(petId, name, status, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.updatePetWithForm']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -703,9 +717,11 @@ export const PetApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.uploadFile(petId, additionalMetadata, file, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['PetApi.uploadFile']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -821,7 +837,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public addPet(body: Pet, options?: AxiosRequestConfig) { + public addPet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).addPet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -834,7 +850,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public deletePet(petId: number, apiKey?: string, options?: AxiosRequestConfig) { + public deletePet(petId: number, apiKey?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).deletePet(petId, apiKey, options).then((request) => request(this.axios, this.basePath)); } @@ -846,7 +862,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByStatus(status: Array, options?: AxiosRequestConfig) { + public findPetsByStatus(status: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByStatus(status, options).then((request) => request(this.axios, this.basePath)); } @@ -859,7 +875,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public findPetsByTags(tags: Array, options?: AxiosRequestConfig) { + public findPetsByTags(tags: Array, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).findPetsByTags(tags, options).then((request) => request(this.axios, this.basePath)); } @@ -871,7 +887,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public getPetById(petId: number, options?: AxiosRequestConfig) { + public getPetById(petId: number, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).getPetById(petId, options).then((request) => request(this.axios, this.basePath)); } @@ -883,7 +899,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePet(body: Pet, options?: AxiosRequestConfig) { + public updatePet(body: Pet, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePet(body, options).then((request) => request(this.axios, this.basePath)); } @@ -897,7 +913,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public updatePetWithForm(petId: number, name?: string, status?: string, options?: AxiosRequestConfig) { + public updatePetWithForm(petId: number, name?: string, status?: string, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).updatePetWithForm(petId, name, status, options).then((request) => request(this.axios, this.basePath)); } @@ -911,7 +927,7 @@ export class PetApi extends BaseAPI { * @throws {RequiredError} * @memberof PetApi */ - public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: AxiosRequestConfig) { + public uploadFile(petId: number, additionalMetadata?: string, file?: File, options?: RawAxiosRequestConfig) { return PetApiFp(this.configuration).uploadFile(petId, additionalMetadata, file, options).then((request) => request(this.axios, this.basePath)); } } @@ -940,7 +956,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteOrder: async (orderId: string, options: AxiosRequestConfig = {}): Promise => { + deleteOrder: async (orderId: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('deleteOrder', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -973,7 +989,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getInventory: async (options: AxiosRequestConfig = {}): Promise => { + getInventory: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/store/inventory`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1007,7 +1023,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getOrderById: async (orderId: number, options: AxiosRequestConfig = {}): Promise => { + getOrderById: async (orderId: number, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'orderId' is not null or undefined assertParamExists('getOrderById', 'orderId', orderId) const localVarPath = `/store/order/{orderId}` @@ -1041,7 +1057,7 @@ export const StoreApiAxiosParamCreator = function (configuration?: Configuration * @param {*} [options] Override http request option. * @throws {RequiredError} */ - placeOrder: async (body: Order, options: AxiosRequestConfig = {}): Promise => { + placeOrder: async (body: Order, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('placeOrder', 'body', body) const localVarPath = `/store/order`; @@ -1087,9 +1103,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteOrder(orderId: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteOrder(orderId: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteOrder(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.deleteOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * Returns a map of status codes to quantities @@ -1097,9 +1115,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getInventory(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { + async getInventory(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise<{ [key: string]: number; }>> { const localVarAxiosArgs = await localVarAxiosParamCreator.getInventory(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getInventory']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions @@ -1108,9 +1128,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getOrderById(orderId: number, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getOrderById(orderId: number, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getOrderById(orderId, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.getOrderById']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1119,9 +1141,11 @@ export const StoreApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async placeOrder(body: Order, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async placeOrder(body: Order, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.placeOrder(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['StoreApi.placeOrder']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1190,7 +1214,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public deleteOrder(orderId: string, options?: AxiosRequestConfig) { + public deleteOrder(orderId: string, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).deleteOrder(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1201,7 +1225,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getInventory(options?: AxiosRequestConfig) { + public getInventory(options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getInventory(options).then((request) => request(this.axios, this.basePath)); } @@ -1213,7 +1237,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public getOrderById(orderId: number, options?: AxiosRequestConfig) { + public getOrderById(orderId: number, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).getOrderById(orderId, options).then((request) => request(this.axios, this.basePath)); } @@ -1225,7 +1249,7 @@ export class StoreApi extends BaseAPI { * @throws {RequiredError} * @memberof StoreApi */ - public placeOrder(body: Order, options?: AxiosRequestConfig) { + public placeOrder(body: Order, options?: RawAxiosRequestConfig) { return StoreApiFp(this.configuration).placeOrder(body, options).then((request) => request(this.axios, this.basePath)); } } @@ -1245,7 +1269,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUser: async (body: User, options: AxiosRequestConfig = {}): Promise => { + createUser: async (body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUser', 'body', body) const localVarPath = `/user`; @@ -1281,7 +1305,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithArrayInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithArrayInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithArrayInput', 'body', body) const localVarPath = `/user/createWithArray`; @@ -1317,7 +1341,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - createUsersWithListInput: async (body: Array, options: AxiosRequestConfig = {}): Promise => { + createUsersWithListInput: async (body: Array, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'body' is not null or undefined assertParamExists('createUsersWithListInput', 'body', body) const localVarPath = `/user/createWithList`; @@ -1353,7 +1377,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - deleteUser: async (username: string, options: AxiosRequestConfig = {}): Promise => { + deleteUser: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('deleteUser', 'username', username) const localVarPath = `/user/{username}` @@ -1387,7 +1411,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - getUserByName: async (username: string, options: AxiosRequestConfig = {}): Promise => { + getUserByName: async (username: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('getUserByName', 'username', username) const localVarPath = `/user/{username}` @@ -1422,7 +1446,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - loginUser: async (username: string, password: string, options: AxiosRequestConfig = {}): Promise => { + loginUser: async (username: string, password: string, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('loginUser', 'username', username) // verify required parameter 'password' is not null or undefined @@ -1464,7 +1488,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - logoutUser: async (options: AxiosRequestConfig = {}): Promise => { + logoutUser: async (options: RawAxiosRequestConfig = {}): Promise => { const localVarPath = `/user/logout`; // use dummy base URL string because the URL constructor only accepts absolute URLs. const localVarUrlObj = new URL(localVarPath, DUMMY_BASE_URL); @@ -1496,7 +1520,7 @@ export const UserApiAxiosParamCreator = function (configuration?: Configuration) * @param {*} [options] Override http request option. * @throws {RequiredError} */ - updateUser: async (username: string, body: User, options: AxiosRequestConfig = {}): Promise => { + updateUser: async (username: string, body: User, options: RawAxiosRequestConfig = {}): Promise => { // verify required parameter 'username' is not null or undefined assertParamExists('updateUser', 'username', username) // verify required parameter 'body' is not null or undefined @@ -1545,9 +1569,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUser(body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUser(body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUser(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1556,9 +1582,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithArrayInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithArrayInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1567,9 +1595,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async createUsersWithListInput(body: Array, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.createUsersWithListInput(body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.createUsersWithListInput']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1578,9 +1608,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async deleteUser(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async deleteUser(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.deleteUser(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.deleteUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1589,9 +1621,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async getUserByName(username: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async getUserByName(username: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.getUserByName(username, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.getUserByName']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1601,9 +1635,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async loginUser(username: string, password: string, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async loginUser(username: string, password: string, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.loginUser(username, password, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.loginUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * @@ -1611,9 +1647,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async logoutUser(options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async logoutUser(options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.logoutUser(options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.logoutUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, /** * This can only be done by the logged in user. @@ -1623,9 +1661,11 @@ export const UserApiFp = function(configuration?: Configuration) { * @param {*} [options] Override http request option. * @throws {RequiredError} */ - async updateUser(username: string, body: User, options?: AxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { + async updateUser(username: string, body: User, options?: RawAxiosRequestConfig): Promise<(axios?: AxiosInstance, basePath?: string) => AxiosPromise> { const localVarAxiosArgs = await localVarAxiosParamCreator.updateUser(username, body, options); - return createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration); + const index = configuration?.serverIndex ?? 0; + const operationBasePath = operationServerMap['UserApi.updateUser']?.[index]?.url; + return (axios, basePath) => createRequestFunction(localVarAxiosArgs, globalAxios, BASE_PATH, configuration)(axios, operationBasePath || basePath); }, } }; @@ -1736,7 +1776,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUser(body: User, options?: AxiosRequestConfig) { + public createUser(body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUser(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1748,7 +1788,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithArrayInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithArrayInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithArrayInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1760,7 +1800,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public createUsersWithListInput(body: Array, options?: AxiosRequestConfig) { + public createUsersWithListInput(body: Array, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).createUsersWithListInput(body, options).then((request) => request(this.axios, this.basePath)); } @@ -1772,7 +1812,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public deleteUser(username: string, options?: AxiosRequestConfig) { + public deleteUser(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).deleteUser(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1784,7 +1824,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public getUserByName(username: string, options?: AxiosRequestConfig) { + public getUserByName(username: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).getUserByName(username, options).then((request) => request(this.axios, this.basePath)); } @@ -1797,7 +1837,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public loginUser(username: string, password: string, options?: AxiosRequestConfig) { + public loginUser(username: string, password: string, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).loginUser(username, password, options).then((request) => request(this.axios, this.basePath)); } @@ -1808,7 +1848,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public logoutUser(options?: AxiosRequestConfig) { + public logoutUser(options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).logoutUser(options).then((request) => request(this.axios, this.basePath)); } @@ -1821,7 +1861,7 @@ export class UserApi extends BaseAPI { * @throws {RequiredError} * @memberof UserApi */ - public updateUser(username: string, body: User, options?: AxiosRequestConfig) { + public updateUser(username: string, body: User, options?: RawAxiosRequestConfig) { return UserApiFp(this.configuration).updateUser(username, body, options).then((request) => request(this.axios, this.basePath)); } } diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/base.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/base.ts index 6a80fbd4e509..b92a383a84c7 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/base.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/base.ts @@ -16,7 +16,7 @@ import type { Configuration } from './configuration'; // Some imports not used depending on template conditions // @ts-ignore -import type { AxiosPromise, AxiosInstance, AxiosRequestConfig } from 'axios'; +import type { AxiosPromise, AxiosInstance, RawAxiosRequestConfig } from 'axios'; import globalAxios from 'axios'; export const BASE_PATH = "http://petstore.swagger.io/v2".replace(/\/+$/, ""); @@ -39,7 +39,7 @@ export const COLLECTION_FORMATS = { */ export interface RequestArgs { url: string; - options: AxiosRequestConfig; + options: RawAxiosRequestConfig; } /** @@ -53,7 +53,7 @@ export class BaseAPI { constructor(configuration?: Configuration, protected basePath: string = BASE_PATH, protected axios: AxiosInstance = globalAxios) { if (configuration) { this.configuration = configuration; - this.basePath = configuration.basePath || this.basePath; + this.basePath = configuration.basePath ?? basePath; } } }; @@ -70,3 +70,17 @@ export class RequiredError extends Error { this.name = "RequiredError" } } + +interface ServerMap { + [key: string]: { + url: string, + description: string, + }[]; +} + +/** + * + * @export + */ +export const operationServerMap: ServerMap = { +} diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts index ecbcb323f7a3..d5b9e4718aea 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/common.ts @@ -144,7 +144,7 @@ export const toPathString = function (url: URL) { */ export const createRequestFunction = function (axiosArgs: RequestArgs, globalAxios: AxiosInstance, BASE_PATH: string, configuration?: Configuration) { return >(axios: AxiosInstance = globalAxios, basePath: string = BASE_PATH) => { - const axiosRequestArgs = {...axiosArgs.options, url: (configuration?.basePath || axios.defaults.baseURL || basePath) + axiosArgs.url}; + const axiosRequestArgs = {...axiosArgs.options, url: (axios.defaults.baseURL ? '' : configuration?.basePath ?? basePath) + axiosArgs.url}; return axios.request(axiosRequestArgs); }; } diff --git a/samples/client/petstore/typescript-axios/builds/with-string-enums/configuration.ts b/samples/client/petstore/typescript-axios/builds/with-string-enums/configuration.ts index b8780457121d..d05f5a0d0835 100644 --- a/samples/client/petstore/typescript-axios/builds/with-string-enums/configuration.ts +++ b/samples/client/petstore/typescript-axios/builds/with-string-enums/configuration.ts @@ -19,6 +19,7 @@ export interface ConfigurationParameters { password?: string; accessToken?: string | Promise | ((name?: string, scopes?: string[]) => string) | ((name?: string, scopes?: string[]) => Promise); basePath?: string; + serverIndex?: number; baseOptions?: any; formDataCtor?: new () => any; } @@ -58,6 +59,13 @@ export class Configuration { * @memberof Configuration */ basePath?: string; + /** + * override server index + * + * @type {number} + * @memberof Configuration + */ + serverIndex?: number; /** * base options for axios calls * @@ -80,6 +88,7 @@ export class Configuration { this.password = param.password; this.accessToken = param.accessToken; this.basePath = param.basePath; + this.serverIndex = param.serverIndex; this.baseOptions = param.baseOptions; this.formDataCtor = param.formDataCtor; } diff --git a/samples/client/petstore/typescript-axios/tests/default/package-lock.json b/samples/client/petstore/typescript-axios/tests/default/package-lock.json index 24b2819d42bb..eb463a6465d4 100644 --- a/samples/client/petstore/typescript-axios/tests/default/package-lock.json +++ b/samples/client/petstore/typescript-axios/tests/default/package-lock.json @@ -10,16 +10,17 @@ "hasInstallScript": true, "license": "ISC", "dependencies": { - "@openapitools/typescript-axios-petstore": "file:../../builds/with-npm-version", - "chai": "^4.2.0", - "ts-node": "^9.1.1" + "@openapitools/typescript-axios-petstore": "file:../../builds/with-npm-version" }, "devDependencies": { "@types/chai": "^4.2.14", "@types/mocha": "^8.2.0", "@types/node": "^14.14.14", + "axios": "*", "browserify": "^17.0.0", + "chai": "^4.2.0", "mocha": "^8.2.1", + "ts-node": "^9.1.1", "typescript": "^4.1.2" } }, @@ -28,7 +29,7 @@ "version": "1.0.0", "license": "Unlicense", "dependencies": { - "axios": "^0.26.1" + "axios": "^1.6.1" }, "devDependencies": { "@types/node": "^12.11.5", @@ -154,6 +155,7 @@ }, "node_modules/arg": { "version": "4.1.3", + "dev": true, "license": "MIT" }, "node_modules/argparse": { @@ -209,11 +211,18 @@ }, "node_modules/assertion-error": { "version": "1.1.0", + "dev": true, "license": "MIT", "engines": { "node": "*" } }, + "node_modules/asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true + }, "node_modules/available-typed-arrays": { "version": "1.0.2", "dev": true, @@ -228,6 +237,17 @@ "url": "https://github.com/sponsors/ljharb" } }, + "node_modules/axios": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", + "dev": true, + "dependencies": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "node_modules/balanced-match": { "version": "1.0.0", "dev": true, @@ -452,6 +472,7 @@ }, "node_modules/buffer-from": { "version": "1.1.1", + "dev": true, "license": "MIT" }, "node_modules/buffer-xor": { @@ -483,6 +504,7 @@ }, "node_modules/chai": { "version": "4.2.0", + "dev": true, "license": "MIT", "dependencies": { "assertion-error": "^1.1.0", @@ -513,6 +535,7 @@ }, "node_modules/check-error": { "version": "1.0.2", + "dev": true, "license": "MIT", "engines": { "node": "*" @@ -562,6 +585,18 @@ "node": ">=0.10.0" } }, + "node_modules/combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "dependencies": { + "delayed-stream": "~1.0.0" + }, + "engines": { + "node": ">= 0.8" + } + }, "node_modules/concat-map": { "version": "0.0.1", "dev": true, @@ -641,6 +676,7 @@ }, "node_modules/create-require": { "version": "1.1.1", + "dev": true, "license": "MIT" }, "node_modules/crypto-browserify": { @@ -695,6 +731,7 @@ }, "node_modules/deep-eql": { "version": "3.0.1", + "dev": true, "license": "MIT", "dependencies": { "type-detect": "^4.0.0" @@ -719,6 +756,15 @@ "dev": true, "license": "MIT" }, + "node_modules/delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/deps-sort": { "version": "2.0.1", "dev": true, @@ -760,6 +806,7 @@ }, "node_modules/diff": { "version": "4.0.2", + "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.3.1" @@ -930,11 +977,45 @@ "flat": "cli.js" } }, + "node_modules/follow-redirects": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", + "dev": true, + "funding": [ + { + "type": "individual", + "url": "https://github.com/sponsors/RubenVerborgh" + } + ], + "engines": { + "node": ">=4.0" + }, + "peerDependenciesMeta": { + "debug": { + "optional": true + } + } + }, "node_modules/foreach": { "version": "2.0.5", "dev": true, "license": "MIT" }, + "node_modules/form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dev": true, + "dependencies": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + }, + "engines": { + "node": ">= 6" + } + }, "node_modules/fs.realpath": { "version": "1.0.0", "dev": true, @@ -960,6 +1041,7 @@ }, "node_modules/get-func-name": { "version": "2.0.0", + "dev": true, "license": "MIT", "engines": { "node": "*" @@ -1384,6 +1466,7 @@ }, "node_modules/make-error": { "version": "1.3.6", + "dev": true, "license": "ISC" }, "node_modules/md5.js": { @@ -1413,6 +1496,27 @@ "dev": true, "license": "MIT" }, + "node_modules/mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true, + "engines": { + "node": ">= 0.6" + } + }, + "node_modules/mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "dependencies": { + "mime-db": "1.52.0" + }, + "engines": { + "node": ">= 0.6" + } + }, "node_modules/minimalistic-assert": { "version": "1.0.1", "dev": true, @@ -1964,6 +2068,7 @@ }, "node_modules/pathval": { "version": "1.1.0", + "dev": true, "license": "MIT", "engines": { "node": "*" @@ -2008,6 +2113,12 @@ "dev": true, "license": "MIT" }, + "node_modules/proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "dev": true + }, "node_modules/public-encrypt": { "version": "4.0.3", "dev": true, @@ -2214,6 +2325,7 @@ }, "node_modules/source-map": { "version": "0.6.1", + "dev": true, "license": "BSD-3-Clause", "engines": { "node": ">=0.10.0" @@ -2221,6 +2333,7 @@ }, "node_modules/source-map-support": { "version": "0.5.19", + "dev": true, "license": "MIT", "dependencies": { "buffer-from": "^1.0.0", @@ -2423,6 +2536,7 @@ }, "node_modules/ts-node": { "version": "9.1.1", + "dev": true, "license": "MIT", "dependencies": { "arg": "^4.1.0", @@ -2452,6 +2566,7 @@ }, "node_modules/type-detect": { "version": "4.0.8", + "dev": true, "license": "MIT", "engines": { "node": ">=4" @@ -2464,6 +2579,7 @@ }, "node_modules/typescript": { "version": "4.1.3", + "dev": true, "license": "Apache-2.0", "bin": { "tsc": "bin/tsc", @@ -2721,6 +2837,7 @@ }, "node_modules/yn": { "version": "3.1.1", + "dev": true, "license": "MIT", "engines": { "node": ">=6" @@ -2743,7 +2860,7 @@ "version": "file:../../builds/with-npm-version", "requires": { "@types/node": "^12.11.5", - "axios": "^0.26.1", + "axios": "^1.6.1", "typescript": "^4.0" }, "dependencies": { @@ -2811,7 +2928,8 @@ } }, "arg": { - "version": "4.1.3" + "version": "4.1.3", + "dev": true }, "argparse": { "version": "1.0.10", @@ -2862,7 +2980,14 @@ } }, "assertion-error": { - "version": "1.1.0" + "version": "1.1.0", + "dev": true + }, + "asynckit": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/asynckit/-/asynckit-0.4.0.tgz", + "integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==", + "dev": true }, "available-typed-arrays": { "version": "1.0.2", @@ -2871,6 +2996,17 @@ "array-filter": "^1.0.0" } }, + "axios": { + "version": "1.6.1", + "resolved": "https://registry.npmjs.org/axios/-/axios-1.6.1.tgz", + "integrity": "sha512-vfBmhDpKafglh0EldBEbVuoe7DyAavGSLWhuSm5ZSEKQnHhBf0xAAwybbNH1IkrJNGnS/VG4I5yxig1pCEXE4g==", + "dev": true, + "requires": { + "follow-redirects": "^1.15.0", + "form-data": "^4.0.0", + "proxy-from-env": "^1.1.0" + } + }, "balanced-match": { "version": "1.0.0", "dev": true @@ -3053,7 +3189,8 @@ } }, "buffer-from": { - "version": "1.1.1" + "version": "1.1.1", + "dev": true }, "buffer-xor": { "version": "1.0.3", @@ -3077,6 +3214,7 @@ }, "chai": { "version": "4.2.0", + "dev": true, "requires": { "assertion-error": "^1.1.0", "check-error": "^1.0.2", @@ -3095,7 +3233,8 @@ } }, "check-error": { - "version": "1.0.2" + "version": "1.0.2", + "dev": true }, "cipher-base": { "version": "1.0.4", @@ -3132,6 +3271,15 @@ } } }, + "combined-stream": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/combined-stream/-/combined-stream-1.0.8.tgz", + "integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==", + "dev": true, + "requires": { + "delayed-stream": "~1.0.0" + } + }, "concat-map": { "version": "0.0.1", "dev": true @@ -3200,7 +3348,8 @@ } }, "create-require": { - "version": "1.1.1" + "version": "1.1.1", + "dev": true }, "crypto-browserify": { "version": "3.12.0", @@ -3236,6 +3385,7 @@ }, "deep-eql": { "version": "3.0.1", + "dev": true, "requires": { "type-detect": "^4.0.0" } @@ -3251,6 +3401,12 @@ "version": "1.0.0", "dev": true }, + "delayed-stream": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/delayed-stream/-/delayed-stream-1.0.0.tgz", + "integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==", + "dev": true + }, "deps-sort": { "version": "2.0.1", "dev": true, @@ -3279,7 +3435,8 @@ } }, "diff": { - "version": "4.0.2" + "version": "4.0.2", + "dev": true }, "diffie-hellman": { "version": "5.0.3", @@ -3393,10 +3550,27 @@ "version": "5.0.2", "dev": true }, + "follow-redirects": { + "version": "1.15.3", + "resolved": "https://registry.npmjs.org/follow-redirects/-/follow-redirects-1.15.3.tgz", + "integrity": "sha512-1VzOtuEM8pC9SFU1E+8KfTjZyMztRsgEfwQl44z8A25uy13jSzTj6dyK2Df52iV0vgHCfBwLhDWevLn95w5v6Q==", + "dev": true + }, "foreach": { "version": "2.0.5", "dev": true }, + "form-data": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/form-data/-/form-data-4.0.0.tgz", + "integrity": "sha512-ETEklSGi5t0QMZuiXoA/Q6vcnxcLQP5vdugSpuAyi6SVGi2clPPp+xgEhuMaHC+zGgn31Kd235W35f7Hykkaww==", + "dev": true, + "requires": { + "asynckit": "^0.4.0", + "combined-stream": "^1.0.8", + "mime-types": "^2.1.12" + } + }, "fs.realpath": { "version": "1.0.0", "dev": true @@ -3414,7 +3588,8 @@ "dev": true }, "get-func-name": { - "version": "2.0.0" + "version": "2.0.0", + "dev": true }, "get-intrinsic": { "version": "1.0.1", @@ -3668,7 +3843,8 @@ } }, "make-error": { - "version": "1.3.6" + "version": "1.3.6", + "dev": true }, "md5.js": { "version": "1.3.5", @@ -3693,6 +3869,21 @@ } } }, + "mime-db": { + "version": "1.52.0", + "resolved": "https://registry.npmjs.org/mime-db/-/mime-db-1.52.0.tgz", + "integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==", + "dev": true + }, + "mime-types": { + "version": "2.1.35", + "resolved": "https://registry.npmjs.org/mime-types/-/mime-types-2.1.35.tgz", + "integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==", + "dev": true, + "requires": { + "mime-db": "1.52.0" + } + }, "minimalistic-assert": { "version": "1.0.1", "dev": true @@ -4051,7 +4242,8 @@ "dev": true }, "pathval": { - "version": "1.1.0" + "version": "1.1.0", + "dev": true }, "pbkdf2": { "version": "3.1.1", @@ -4076,6 +4268,12 @@ "version": "2.0.1", "dev": true }, + "proxy-from-env": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/proxy-from-env/-/proxy-from-env-1.1.0.tgz", + "integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==", + "dev": true + }, "public-encrypt": { "version": "4.0.3", "dev": true, @@ -4221,10 +4419,12 @@ "dev": true }, "source-map": { - "version": "0.6.1" + "version": "0.6.1", + "dev": true }, "source-map-support": { "version": "0.5.19", + "dev": true, "requires": { "buffer-from": "^1.0.0", "source-map": "^0.6.0" @@ -4380,6 +4580,7 @@ }, "ts-node": { "version": "9.1.1", + "dev": true, "requires": { "arg": "^4.1.0", "create-require": "^1.1.0", @@ -4394,14 +4595,16 @@ "dev": true }, "type-detect": { - "version": "4.0.8" + "version": "4.0.8", + "dev": true }, "typedarray": { "version": "0.0.6", "dev": true }, "typescript": { - "version": "4.1.3" + "version": "4.1.3", + "dev": true }, "umd": { "version": "3.0.3", @@ -4580,7 +4783,8 @@ } }, "yn": { - "version": "3.1.1" + "version": "3.1.1", + "dev": true }, "yocto-queue": { "version": "0.1.0", diff --git a/samples/client/petstore/typescript-axios/tests/default/package.json b/samples/client/petstore/typescript-axios/tests/default/package.json index c723eabd6f38..88bc110e0270 100644 --- a/samples/client/petstore/typescript-axios/tests/default/package.json +++ b/samples/client/petstore/typescript-axios/tests/default/package.json @@ -1,12 +1,10 @@ { "private": true, "dependencies": { - "@openapitools/typescript-axios-petstore": "file:../../builds/with-npm-version", - "chai": "^4.2.0", - "ts-node": "^9.1.1" + "@openapitools/typescript-axios-petstore": "file:../../builds/with-npm-version" }, "scripts": { - "preinstall": "npm install ../../builds/with-npm-version && npm run build", + "preinstall": "npm --prefix ../../builds/with-npm-version install && npm run build", "test": "mocha test/*.ts --require ts-node/register --timeout 10000", "build": "tsc", "browserify": "browserify test -p [ tsify ] > ./dist/test.browserify-bundle.js" @@ -15,8 +13,11 @@ "@types/chai": "^4.2.14", "@types/mocha": "^8.2.0", "@types/node": "^14.14.14", + "axios": "*", "browserify": "^17.0.0", + "chai": "^4.2.0", "mocha": "^8.2.1", + "ts-node": "^9.1.1", "typescript": "^4.1.2" }, "name": "typescript-axios-test", diff --git a/samples/client/petstore/typescript-axios/tests/default/test/PetApi.ts b/samples/client/petstore/typescript-axios/tests/default/test/PetApi.ts index f052c4c47fb7..dabb4d9a4f4f 100644 --- a/samples/client/petstore/typescript-axios/tests/default/test/PetApi.ts +++ b/samples/client/petstore/typescript-axios/tests/default/test/PetApi.ts @@ -1,6 +1,6 @@ import { expect } from "chai"; import { PetApi, Pet, PetStatusEnum, Category } from "@openapitools/typescript-axios-petstore"; -import axios, {AxiosInstance, AxiosResponse} from "@openapitools/typescript-axios-petstore/node_modules/axios"; +import axios, {AxiosInstance, AxiosResponse} from "axios"; describe("PetApi", () => { function runSuite(description: string, requestOptions?: any, customAxiosInstance?: AxiosInstance): void { diff --git a/samples/client/petstore/typescript-axios/tests/default/test/PetApiFactory.ts b/samples/client/petstore/typescript-axios/tests/default/test/PetApiFactory.ts index e51c3270e4c4..b4d602e28ce4 100644 --- a/samples/client/petstore/typescript-axios/tests/default/test/PetApiFactory.ts +++ b/samples/client/petstore/typescript-axios/tests/default/test/PetApiFactory.ts @@ -6,7 +6,7 @@ import { Category } from "@openapitools/typescript-axios-petstore"; import { Configuration } from "@openapitools/typescript-axios-petstore"; -import axios, {AxiosInstance, AxiosResponse} from "@openapitools/typescript-axios-petstore/node_modules/axios"; +import axios, {AxiosInstance, AxiosResponse} from "axios"; let config: Configuration; diff --git a/samples/client/petstore/typescript-axios/tests/default/test/StoreApi.ts b/samples/client/petstore/typescript-axios/tests/default/test/StoreApi.ts index 1aa120ca6e85..35137340fcab 100644 --- a/samples/client/petstore/typescript-axios/tests/default/test/StoreApi.ts +++ b/samples/client/petstore/typescript-axios/tests/default/test/StoreApi.ts @@ -1,6 +1,6 @@ import { expect } from "chai"; import { StoreApi } from "@openapitools/typescript-axios-petstore"; -import axios, {AxiosInstance, AxiosResponse} from "@openapitools/typescript-axios-petstore/node_modules/axios"; +import axios, {AxiosInstance, AxiosResponse} from "axios"; describe("StoreApi", function() { function runSuite(description: string, requestOptions?: any, customAxiosInstance?: AxiosInstance): void { diff --git a/samples/client/petstore/typescript-axios/tests/default/test/StoreApiFactory.ts b/samples/client/petstore/typescript-axios/tests/default/test/StoreApiFactory.ts index da87526f4e29..17e8f6766c9c 100644 --- a/samples/client/petstore/typescript-axios/tests/default/test/StoreApiFactory.ts +++ b/samples/client/petstore/typescript-axios/tests/default/test/StoreApiFactory.ts @@ -1,7 +1,7 @@ import { expect } from "chai"; import { StoreApiFactory } from "@openapitools/typescript-axios-petstore"; import { Configuration } from "@openapitools/typescript-axios-petstore"; -import axios, {AxiosInstance, AxiosResponse} from "@openapitools/typescript-axios-petstore/node_modules/axios"; +import axios, {AxiosInstance, AxiosResponse} from "axios"; let config: Configuration; diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-nullable/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/allOf-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/allOf-nullable/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/allOf-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-nullable/runtime.ts b/samples/client/petstore/typescript-fetch/builds/allOf-nullable/runtime.ts index b92abe556179..5bbe125fb671 100644 --- a/samples/client/petstore/typescript-fetch/builds/allOf-nullable/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/allOf-nullable/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts index b92abe556179..5bbe125fb671 100644 --- a/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/allOf-readonly/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts index 68ae3752e33b..974f7a5ded79 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/FakeApi.ts @@ -78,6 +78,10 @@ export interface FakePropertyEnumIntegerSerializeRequest { outerObjectWithEnumProperty: OuterObjectWithEnumProperty; } +export interface TestAdditionalPropertiesReferenceRequest { + requestBody: { [key: string]: any; }; +} + export interface TestBodyWithBinaryRequest { body: Blob | null; } @@ -418,6 +422,40 @@ export class FakeApi extends runtime.BaseAPI { return await response.value(); } + /** + * + * test referenced additionalProperties + */ + async testAdditionalPropertiesReferenceRaw(requestParameters: TestAdditionalPropertiesReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { + if (requestParameters.requestBody === null || requestParameters.requestBody === undefined) { + throw new runtime.RequiredError('requestBody','Required parameter requestParameters.requestBody was null or undefined when calling testAdditionalPropertiesReference.'); + } + + const queryParameters: any = {}; + + const headerParameters: runtime.HTTPHeaders = {}; + + headerParameters['Content-Type'] = 'application/json'; + + const response = await this.request({ + path: `/fake/additionalProperties-reference`, + method: 'POST', + headers: headerParameters, + query: queryParameters, + body: requestParameters.requestBody, + }, initOverrides); + + return new runtime.VoidApiResponse(response); + } + + /** + * + * test referenced additionalProperties + */ + async testAdditionalPropertiesReference(requestParameters: TestAdditionalPropertiesReferenceRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { + await this.testAdditionalPropertiesReferenceRaw(requestParameters, initOverrides); + } + /** * For this test, the body has to be a binary file. */ diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/PetApi.ts index 59470c6e5385..50584b111b1f 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/apis/PetApi.ts @@ -196,6 +196,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -228,6 +229,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Capitalization.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Capitalization.ts index 6143a3f37074..53fec91847d2 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Capitalization.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/Capitalization.ts @@ -51,6 +51,7 @@ export interface Capitalization { sCAETHFlowPoints?: string; /** * Name of the pet + * * @type {string} * @memberof Capitalization */ diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/NullableClass.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/NullableClass.ts index 94b8e43e6f51..52e1a2171642 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/NullableClass.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/models/NullableClass.ts @@ -82,16 +82,16 @@ export interface NullableClass { objectNullableProp?: { [key: string]: object; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - objectAndItemsNullableProp?: { [key: string]: object; } | null; + objectAndItemsNullableProp?: { [key: string]: object | null; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - objectItemsNullable?: { [key: string]: object; }; + objectItemsNullable?: { [key: string]: object | null; }; } /** diff --git a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts index c95b2ac453e5..f4720695347a 100644 --- a/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default-v3.0/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts index 3a82dd1e7fb1..1576f9cbba6e 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/apis/PetApi.ts @@ -186,6 +186,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -218,6 +219,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/default/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/default/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/enum/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts index d4d2025e1e3c..7bfa4c052756 100644 --- a/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/enum/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts index 3a82dd1e7fb1..1576f9cbba6e 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/apis/PetApi.ts @@ -186,6 +186,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -218,6 +219,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/es6-target/src/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/apis/PetApi.ts index 353bc45bd7c5..ffb7b3858af9 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/apis/PetApi.ts @@ -186,6 +186,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -218,6 +219,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(tags: Array, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw({ tags: tags }, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/multiple-parameters/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/apis/PetApi.ts index 9373a1f215a0..ecca2de78bed 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/apis/PetApi.ts @@ -186,6 +186,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: PetApiFindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -218,6 +219,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: PetApiFindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/prefix-parameter-interfaces/src/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts index 9d6e88587dfe..90fe9aecaf52 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/apis/PetApi.ts @@ -174,6 +174,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple ids can be provided with comma separated strings. * Finds Pets by ids + * @deprecated */ async findPetsByIdsRaw(requestParameters: FindPetsByIdsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.ids === null || requestParameters.ids === undefined) { @@ -206,6 +207,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple ids can be provided with comma separated strings. * Finds Pets by ids + * @deprecated */ async findPetsByIds(ids: Array, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByIdsRaw({ ids: ids }, initOverrides); @@ -256,6 +258,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -288,6 +291,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(tags: Array, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw({ tags: tags }, initOverrides); @@ -297,6 +301,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple ids can be provided with comma separated strings. * Finds Pets by user ids + * @deprecated */ async findPetsByUserIdsRaw(requestParameters: FindPetsByUserIdsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { if (requestParameters.ids === null || requestParameters.ids === undefined) { @@ -329,6 +334,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple ids can be provided with comma separated strings. * Finds Pets by user ids + * @deprecated */ async findPetsByUserIds(ids: Array, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise { const response = await this.findPetsByUserIdsRaw({ ids: ids }, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts index 6327071c4ee2..905a06373264 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/CategoryRecord.ts @@ -67,8 +67,8 @@ class CategoryRecordUtils extends ApiRecordUtils { const { recType, - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts index 9422abd83ec7..0d4f6e0b4429 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/OrderRecord.ts @@ -72,8 +72,8 @@ class OrderRecordUtils extends ApiRecordUtils { const { recType, - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts index 5cb401603d84..5f5348e24546 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/PetRecord.ts @@ -130,8 +130,8 @@ class PetRecordUtils extends ApiRecordUtils { _entries: _entries_original, tags: tags_original, optionalTags: optionalTags_original, - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { // @ts-ignore diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts index b14cd7e71957..40e790f3c578 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/TagRecord.ts @@ -67,8 +67,8 @@ class TagRecordUtils extends ApiRecordUtils { const { recType, - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts index 0d892e64a75a..59d9cba4b3ec 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/models/UserRecord.ts @@ -75,8 +75,8 @@ class UserRecordUtils extends ApiRecordUtils { const { recType, - ...unchangedProperties - } = entity; + ...unchangedProperties + } = entity; const entityProperties = { } diff --git a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/sagas-and-records/src/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/apis/PetApi.ts index 59470c6e5385..50584b111b1f 100644 --- a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/apis/PetApi.ts @@ -196,6 +196,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -228,6 +229,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/Capitalization.ts b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/Capitalization.ts index 6143a3f37074..53fec91847d2 100644 --- a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/Capitalization.ts +++ b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/Capitalization.ts @@ -51,6 +51,7 @@ export interface Capitalization { sCAETHFlowPoints?: string; /** * Name of the pet + * * @type {string} * @memberof Capitalization */ diff --git a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/NullableClass.ts b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/NullableClass.ts index 94b8e43e6f51..52e1a2171642 100644 --- a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/NullableClass.ts +++ b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/models/NullableClass.ts @@ -82,16 +82,16 @@ export interface NullableClass { objectNullableProp?: { [key: string]: object; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - objectAndItemsNullableProp?: { [key: string]: object; } | null; + objectAndItemsNullableProp?: { [key: string]: object | null; } | null; /** * - * @type {{ [key: string]: object; }} + * @type {{ [key: string]: object | null; }} * @memberof NullableClass */ - objectItemsNullable?: { [key: string]: object; }; + objectItemsNullable?: { [key: string]: object | null; }; } /** diff --git a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/runtime.ts b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/runtime.ts index c95b2ac453e5..f4720695347a 100644 --- a/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/snakecase-discriminator/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/apis/PetApi.ts index eb7a25c6d01c..d11e216b3710 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/apis/PetApi.ts @@ -130,6 +130,7 @@ export interface PetApiInterface { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>; @@ -324,6 +325,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -356,6 +358,7 @@ export class PetApi extends runtime.BaseAPI implements PetApiInterface { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-interfaces/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/apis/PetApi.ts index 3a82dd1e7fb1..1576f9cbba6e 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/apis/PetApi.ts @@ -186,6 +186,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -218,6 +219,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts index 2a90ca5b632c..9238a60cfe37 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-npm-version/src/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/with-string-enums/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/with-string-enums/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-string-enums/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/with-string-enums/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts b/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts index d4d2025e1e3c..7bfa4c052756 100644 --- a/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/with-string-enums/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts index effff57e9a99..77f3d5c074b3 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/apis/PetApi.ts @@ -180,6 +180,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTagsRaw(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise>> { if (requestParameters.tags === null || requestParameters.tags === undefined) { @@ -212,6 +213,7 @@ export class PetApi extends runtime.BaseAPI { /** * Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. * Finds Pets by tags + * @deprecated */ async findPetsByTags(requestParameters: FindPetsByTagsRequest, initOverrides?: RequestInit | runtime.InitOverrideFunction): Promise> { const response = await this.findPetsByTagsRaw(requestParameters, initOverrides); diff --git a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts index 8b52e158ff08..722fd25f0107 100644 --- a/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts +++ b/samples/client/petstore/typescript-fetch/builds/without-runtime-checks/src/runtime.ts @@ -91,7 +91,7 @@ export const DefaultConfig = new Configuration(); */ export class BaseAPI { - private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); + private static readonly jsonRegex = new RegExp('^(:?application\/json|[^;/ \t]+\/[^;/ \t]+[+]json)[ \t]*(:?;.*)?$', 'i'); private middleware: Middleware[]; constructor(protected configuration = DefaultConfig) { diff --git a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-inversify/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-jquery/npm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/package.json b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/package.json index 1008d9771822..d8efa421c356 100644 --- a/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/package.json +++ b/samples/client/petstore/typescript-nestjs-v6-provided-in-root/builds/default/package.json @@ -34,13 +34,13 @@ "@nestjs/platform-express": "^6.0.0", "reflect-metadata": "^0.1.13", "rimraf": "^2.6.3", - "rxjs": "^6.5.2" + "rxjs": "^7.1.0" }, "devDependencies": { "@nestjs/testing": "~6.0.0", "@types/express": "^4.16.0", "@types/jest": "^24.0.15", - "@types/node": "^12.6.1", + "@types/node": "^14.8.2", "@types/supertest": "^2.0.8", "concurrently": "^4.1.1", "nodemon": "^1.19.1", diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts index db4bae9b9f86..e70c901e9d09 100644 --- a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/api.module.ts @@ -1,4 +1,4 @@ -import { DynamicModule, Module, Global } from '@nestjs/common'; +import { DynamicModule, Module, Global, Provider } from '@nestjs/common'; import { HttpModule, HttpService } from '@nestjs/axios'; import { AsyncConfiguration, Configuration, ConfigurationFactory } from './configuration'; diff --git a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json index c49a0a25b9c8..bd74fe891d00 100644 --- a/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json +++ b/samples/client/petstore/typescript-nestjs-v8-provided-in-root/builds/default/package.json @@ -32,15 +32,16 @@ "@nestjs/common": "^8.0.0", "@nestjs/core": "^8.0.0", "@nestjs/platform-express": "^8.0.0", + "@nestjs/axios": "^2.0.0", "reflect-metadata": "^0.1.13", "rimraf": "^2.6.3", - "rxjs": "^6.5.2" + "rxjs": "^7.1.0" }, "devDependencies": { "@nestjs/testing": "~8.0.0", "@types/express": "^4.16.0", "@types/jest": "^24.0.15", - "@types/node": "^12.6.1", + "@types/node": "^14.8.2", "@types/supertest": "^2.0.8", "concurrently": "^4.1.1", "nodemon": "^1.19.1", diff --git a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-node/npm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-redux-query/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/es6-target/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/with-npm-version/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION +++ b/samples/client/petstore/typescript-rxjs/builds/with-progress-subscriber/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/xojo/client-synchronous/.openapi-generator/VERSION b/samples/client/petstore/xojo/client-synchronous/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/xojo/client-synchronous/.openapi-generator/VERSION +++ b/samples/client/petstore/xojo/client-synchronous/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Order.xojo_code b/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Order.xojo_code index a26fb8a9aef3..506238c849b5 100644 --- a/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Order.xojo_code +++ b/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Order.xojo_code @@ -34,13 +34,13 @@ Protected Class Order #tag EndProperty - #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 - + #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 + Placed Approved Delivered - - #tag EndEnum + + #tag EndEnum #tag Method, Flags = &h0 diff --git a/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Pet.xojo_code b/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Pet.xojo_code index cdc79f9ec094..178e6009f412 100644 --- a/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Pet.xojo_code +++ b/samples/client/petstore/xojo/client-synchronous/XojoOpenAPIClientSynchronous/Models/Pet.xojo_code @@ -34,13 +34,13 @@ Protected Class Pet #tag EndProperty - #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 - + #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 + Available Pending Sold - - #tag EndEnum + + #tag EndEnum #tag Method, Flags = &h0 diff --git a/samples/client/petstore/xojo/client/.openapi-generator/VERSION b/samples/client/petstore/xojo/client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/xojo/client/.openapi-generator/VERSION +++ b/samples/client/petstore/xojo/client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/xojo/client/OpenAPIClient/Models/Order.xojo_code b/samples/client/petstore/xojo/client/OpenAPIClient/Models/Order.xojo_code index a26fb8a9aef3..506238c849b5 100644 --- a/samples/client/petstore/xojo/client/OpenAPIClient/Models/Order.xojo_code +++ b/samples/client/petstore/xojo/client/OpenAPIClient/Models/Order.xojo_code @@ -34,13 +34,13 @@ Protected Class Order #tag EndProperty - #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 - + #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 + Placed Approved Delivered - - #tag EndEnum + + #tag EndEnum #tag Method, Flags = &h0 diff --git a/samples/client/petstore/xojo/client/OpenAPIClient/Models/Pet.xojo_code b/samples/client/petstore/xojo/client/OpenAPIClient/Models/Pet.xojo_code index 5fa04e3b94cb..a7c6aba143ad 100644 --- a/samples/client/petstore/xojo/client/OpenAPIClient/Models/Pet.xojo_code +++ b/samples/client/petstore/xojo/client/OpenAPIClient/Models/Pet.xojo_code @@ -34,13 +34,13 @@ Protected Class Pet #tag EndProperty - #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 - + #tag Enum, Name = StatusEnum, Type = Integer, Flags = &h0 + Available Pending Sold - - #tag EndEnum + + #tag EndEnum #tag Method, Flags = &h0 diff --git a/samples/client/petstore/zapier/.openapi-generator/VERSION b/samples/client/petstore/zapier/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/client/petstore/zapier/.openapi-generator/VERSION +++ b/samples/client/petstore/zapier/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/client/petstore/zapier/models/Pet.js b/samples/client/petstore/zapier/models/Pet.js index 48467248dd4b..c66305545cb2 100644 --- a/samples/client/petstore/zapier/models/Pet.js +++ b/samples/client/petstore/zapier/models/Pet.js @@ -15,11 +15,13 @@ module.exports = { { key: `${keyPrefix}name`, label: `[${labelPrefix}name]`, + required: true, type: 'string', }, { key: `${keyPrefix}photoUrls`, label: `[${labelPrefix}photoUrls]`, + required: true, list: true, type: 'string', }, diff --git a/samples/client/petstore/zapier/package.json b/samples/client/petstore/zapier/package.json index 415649542cc2..9514b41256a9 100644 --- a/samples/client/petstore/zapier/package.json +++ b/samples/client/petstore/zapier/package.json @@ -13,8 +13,8 @@ }, "dependencies": { "lodash": "^4.17.21", - "zapier-platform-core": "15.0.1", - "form-data": "2.1.4" + "zapier-platform-core": "15.5.1", + "form-data": "^4.0.0" }, "devDependencies": { "mocha": "^10.2.0", @@ -22,6 +22,6 @@ }, "private": true, "zapier": { - "convertedByCLIVersion": "14.1.1" + "convertedByCLIVersion": "15.5.1" } } \ No newline at end of file diff --git a/samples/client/petstore/zapier/utils/utils.js b/samples/client/petstore/zapier/utils/utils.js index a73f00e4778b..201a15fb582b 100644 --- a/samples/client/petstore/zapier/utils/utils.js +++ b/samples/client/petstore/zapier/utils/utils.js @@ -1,14 +1,14 @@ const _ = require('lodash') const replacePathParameters = (url) => url.replace(/{([^{}]+)}/g, (keyExpr, key) => `{{bundle.inputData.${key}}}`) -const childMapping = (objectsArray, prefix, model) => objectsArray.map(object => model.mapping({inputData: object}, prefix)) +const childMapping = (objectsArray, prefix, model) => objectsArray ? objectsArray.map(object => model.mapping({inputData: object}, prefix)) : undefined const removeIfEmpty = (obj) => _.isEmpty(JSON.parse(JSON.stringify(obj))) ? undefined : obj const buildKeyAndLabel = (prefix, isInput = true, isArrayChild = false) => { const keyPrefix = !_.isEmpty(prefix) && (!isArrayChild || isInput) ? `${prefix}${isInput ? '.' : '__'}` : prefix const labelPrefix = !_.isEmpty(keyPrefix) ? keyPrefix.replaceAll('__', '.') : '' return { keyPrefix: keyPrefix, - labelPrefix:labelPrefix, + labelPrefix: labelPrefix, } } const isSearchAction = (key) => { diff --git a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION +++ b/samples/config/petstore/protobuf-schema/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/meta-codegen/lib/pom.xml b/samples/meta-codegen/lib/pom.xml index 4dc293c36263..e151fae92738 100644 --- a/samples/meta-codegen/lib/pom.xml +++ b/samples/meta-codegen/lib/pom.xml @@ -121,7 +121,7 @@ UTF-8 - 7.1.0-SNAPSHOT + 7.3.0-SNAPSHOT 1.0.0 4.13.2 diff --git a/samples/meta-codegen/usage/.openapi-generator/VERSION b/samples/meta-codegen/usage/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/meta-codegen/usage/.openapi-generator/VERSION +++ b/samples/meta-codegen/usage/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/elm/.openapi-generator/VERSION b/samples/openapi3/client/elm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/elm/.openapi-generator/VERSION +++ b/samples/openapi3/client/elm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md index e92494904b51..6d9b0b811670 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/README.md @@ -13,20 +13,20 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat Install the following dependencies: -```shell +```sh go get github.com/stretchr/testify/assert go get golang.org/x/net/context ``` Put the package under your project folder and add the following in import: -```golang +```go import x_auth_id_alias "github.com/GIT_USER_ID/GIT_REPO_ID" ``` To use a proxy, set the environment variable `HTTP_PROXY`: -```golang +```go os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") ``` @@ -36,17 +36,17 @@ Default configuration comes with `Servers` field that contains server objects as ### Select Server Configuration -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. +For using other server than the one defined on index 0 set context value `x_auth_id_alias.ContextServerIndex` of type `int`. -```golang +```go ctx := context.WithValue(context.Background(), x_auth_id_alias.ContextServerIndex, 1) ``` ### Templated Server URL -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. +Templated server URL is formatted using default variables from configuration or from context value `x_auth_id_alias.ContextServerVariables` of type `map[string]string`. -```golang +```go ctx := context.WithValue(context.Background(), x_auth_id_alias.ContextServerVariables, map[string]string{ "basePath": "v2", }) @@ -58,9 +58,9 @@ Note, enum values are always validated and all unused variables are silently ign Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. +Similar rules for overriding default operation server index and variables applies by using `x_auth_id_alias.ContextOperationServerIndices` and `x_auth_id_alias.ContextOperationServerVariables` context maps. -```golang +```go ctx := context.WithValue(context.Background(), x_auth_id_alias.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -101,11 +101,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + x_auth_id_alias.ContextAPIKeys, + map[string]x_auth_id_alias.APIKey{ "X-Api-Key": {Key: "API_KEY_STRING"}, }, ) @@ -122,11 +122,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + x_auth_id_alias.ContextAPIKeys, + map[string]x_auth_id_alias.APIKey{ "api_key": {Key: "API_KEY_STRING"}, }, ) diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go index d23863248f95..431577cfccd2 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/client.go @@ -35,8 +35,8 @@ import ( ) var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) ) @@ -436,7 +436,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = f.Seek(0, io.SeekStart) - err = os.Remove(f.Name()) return } if f, ok := v.(**os.File); ok { @@ -449,16 +448,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = (*f).Seek(0, io.SeekStart) - err = os.Remove((*f).Name()) return } - if xmlCheck.MatchString(contentType) { + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } - if jsonCheck.MatchString(contentType) { + if JsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { @@ -523,9 +521,9 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { + } else if XmlCheck.MatchString(contentType) { var bs []byte bs, err = xml.Marshal(body) if err == nil { diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageAPI.md b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageAPI.md index 3d924a659c6c..c5046e375740 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageAPI.md +++ b/samples/openapi3/client/extensions/x-auth-id-alias/go-experimental/docs/UsageAPI.md @@ -25,23 +25,23 @@ Use any API key package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UsageAPI.AnyKey(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.AnyKey``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `AnyKey`: map[string]interface{} - fmt.Fprintf(os.Stdout, "Response from `UsageAPI.AnyKey`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UsageAPI.AnyKey(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.AnyKey``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `AnyKey`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageAPI.AnyKey`: %v\n", resp) } ``` @@ -86,23 +86,23 @@ Use both API keys package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UsageAPI.BothKeys(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.BothKeys``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `BothKeys`: map[string]interface{} - fmt.Fprintf(os.Stdout, "Response from `UsageAPI.BothKeys`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UsageAPI.BothKeys(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.BothKeys``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `BothKeys`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageAPI.BothKeys`: %v\n", resp) } ``` @@ -147,23 +147,23 @@ Use API key in header package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UsageAPI.KeyInHeader(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.KeyInHeader``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `KeyInHeader`: map[string]interface{} - fmt.Fprintf(os.Stdout, "Response from `UsageAPI.KeyInHeader`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UsageAPI.KeyInHeader(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.KeyInHeader``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInHeader`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageAPI.KeyInHeader`: %v\n", resp) } ``` @@ -208,23 +208,23 @@ Use API key in query package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UsageAPI.KeyInQuery(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.KeyInQuery``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `KeyInQuery`: map[string]interface{} - fmt.Fprintf(os.Stdout, "Response from `UsageAPI.KeyInQuery`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UsageAPI.KeyInQuery(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UsageAPI.KeyInQuery``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `KeyInQuery`: map[string]interface{} + fmt.Fprintf(os.Stdout, "Response from `UsageAPI.KeyInQuery`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION deleted file mode 100644 index 757e67400401..000000000000 --- a/samples/openapi3/client/extensions/x-auth-id-alias/python/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES index dfc08bbc7fa1..fa901794fe31 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/FILES @@ -14,7 +14,5 @@ lib/x_auth_id_alias/api_client.rb lib/x_auth_id_alias/api_error.rb lib/x_auth_id_alias/configuration.rb lib/x_auth_id_alias/version.rb -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb x_auth_id_alias.gemspec diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb index ac7eae6a8999..16c9f9b41252 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb index ff6ee6a537c4..b0ae1e7f7bf0 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb index b91656255879..a2e16ff6b434 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -46,9 +46,10 @@ def self.default # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -70,7 +71,9 @@ def call_api(http_method, path, opts = {}) end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -126,9 +129,7 @@ def build_request(http_method, path, opts = {}) end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -166,6 +167,8 @@ def build_request_body(header_params, form_params, body) # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -180,21 +183,24 @@ def download_file(request) prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end # Check if the given MIME is a JSON MIME. @@ -215,11 +221,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - return @tempfile if return_type == 'File' - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb index 472b844cf3b2..bc95ed562867 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb index 884e914bbfcc..2ad6a9a5074c 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb index 0585c3a11622..cd327742d522 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/lib/x_auth_id_alias/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb index e567d24b718d..666409256975 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb index e838f2bb56ca..b251b0118db0 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb index 17d76c2378f0..8cfb9c2aabb7 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec index c4a502db6857..3ba6a8a7ed09 100644 --- a/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec +++ b/samples/openapi3/client/extensions/x-auth-id-alias/ruby-client/x_auth_id_alias.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This specification shows how to use x-auth-id-alias extension for API keys." s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/FILES b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/FILES index 33ffe73a2d58..5a684a799062 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/FILES +++ b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/FILES @@ -15,6 +15,4 @@ lib/dynamic_servers/api_client.rb lib/dynamic_servers/api_error.rb lib/dynamic_servers/configuration.rb lib/dynamic_servers/version.rb -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/dynamic-servers/ruby/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec b/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec index 4c0134d4e5e9..ce8cb1fcf7ac 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec +++ b/samples/openapi3/client/features/dynamic-servers/ruby/dynamic_servers.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This specification shows how to use dynamic servers." s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb index 268050dda012..1dc2343848ee 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb index cd339e40d84e..aefd51a6a70c 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb index 378180347db3..0838b4d2c1dc 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -46,9 +46,10 @@ def self.default # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -70,7 +71,9 @@ def call_api(http_method, path, opts = {}) end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -125,9 +128,7 @@ def build_request(http_method, path, opts = {}) end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -165,6 +166,8 @@ def build_request_body(header_params, form_params, body) # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -179,21 +182,24 @@ def download_file(request) prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end # Check if the given MIME is a JSON MIME. @@ -214,11 +220,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - return @tempfile if return_type == 'File' - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb index 891d37f5f8a8..45812599ae54 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb index 1a30bccc9d90..1cbaa8af3d4a 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb index 43dc577f4a8e..e7a44376ddba 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/lib/dynamic_servers/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb index d8966996fc00..ebbb268d33c7 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb index e2985bd7c554..2a99cf04524a 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb b/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb index 00ad7e95ed8e..86782b7730f7 100644 --- a/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb +++ b/samples/openapi3/client/features/dynamic-servers/ruby/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/FILES b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/FILES index 3d3b3e99e4bd..34265527f49e 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/FILES +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/FILES @@ -19,6 +19,4 @@ lib/petstore/models/array_alias.rb lib/petstore/models/map_alias.rb lib/petstore/version.rb petstore.gemspec -spec/api_client_spec.rb -spec/configuration_spec.rb spec/spec_helper.rb diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb index b7a977230fb3..cac3415f50e2 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb index 0648e6fab256..6e88d502e14f 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api/usage_api.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb index cf94fdc965a0..90a8fa29e064 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_client.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -46,9 +46,10 @@ def self.default # Call an API with given options. # # @return [Array<(Object, Integer, Hash)>] an array of 3 elements: - # the data deserialized from response body (could be nil), response status code and response headers. + # the data deserialized from response body (may be a Tempfile or nil), response status code and response headers. def call_api(http_method, path, opts = {}) request = build_request(http_method, path, opts) + tempfile = download_file(request) if opts[:return_type] == 'File' response = request.run if @config.debugging @@ -70,7 +71,9 @@ def call_api(http_method, path, opts = {}) end end - if opts[:return_type] + if opts[:return_type] == 'File' + data = tempfile + elsif opts[:return_type] data = deserialize(response, opts[:return_type]) else data = nil @@ -125,9 +128,7 @@ def build_request(http_method, path, opts = {}) end end - request = Typhoeus::Request.new(url, req_opts) - download_file(request) if opts[:return_type] == 'File' - request + Typhoeus::Request.new(url, req_opts) end # Builds the HTTP request body @@ -165,6 +166,8 @@ def build_request_body(header_params, form_params, body) # process can use. # # @see Configuration#temp_folder_path + # + # @return [Tempfile] the tempfile generated def download_file(request) tempfile = nil encoding = nil @@ -179,21 +182,24 @@ def download_file(request) prefix = prefix + '-' unless prefix.end_with?('-') encoding = response.body.encoding tempfile = Tempfile.open(prefix, @config.temp_folder_path, encoding: encoding) - @tempfile = tempfile end request.on_body do |chunk| chunk.force_encoding(encoding) tempfile.write(chunk) end - request.on_complete do |response| - if tempfile - tempfile.close - @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ - "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ - "will be deleted automatically with GC. It's also recommended to delete the temp file "\ - "explicitly with `tempfile.delete`" - end + # run the request to ensure the tempfile is created successfully before returning it + request.run + if tempfile + tempfile.close + @config.logger.info "Temp file written to #{tempfile.path}, please copy the file to a proper folder "\ + "with e.g. `FileUtils.cp(tempfile.path, '/new/file/path')` otherwise the temp file "\ + "will be deleted automatically with GC. It's also recommended to delete the temp file "\ + "explicitly with `tempfile.delete`" + else + fail ApiError.new("Failed to create the tempfile based on the HTTP response from the server: #{request.inspect}") end + + tempfile end # Check if the given MIME is a JSON MIME. @@ -214,11 +220,6 @@ def json_mime?(mime) # @param [String] return_type some examples: "User", "Array", "Hash" def deserialize(response, return_type) body = response.body - - # handle file downloading - return the File instance processed in request callbacks - # note that response body is empty when the file is written in chunks in request on_body callback - return @tempfile if return_type == 'File' - return nil if body.nil? || body.empty? # return response body directly for String return type diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb index 2802659d740b..81db8ef22b03 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/api_error.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb index 9a3e35892c9f..6f5bfea2bb50 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/configuration.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb index 569146fac473..22bb8ced9fad 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/array_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -154,7 +154,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb index e12a9e974d3d..9c48878aef31 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/models/map_alias.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -150,7 +150,7 @@ def self._deserialize(type, value) else # model # models (e.g. Pet) or oneOf klass = Petstore.const_get(type) - klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) + klass.respond_to?(:openapi_any_of) || klass.respond_to?(:openapi_one_of) ? klass.build(value) : klass.build_from_hash(value) end end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb index eaacb3865979..bea2f6b4f11a 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/lib/petstore/version.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec index 3b537846b36f..41f34dd1768c 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/petstore.gemspec @@ -8,7 +8,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end @@ -26,6 +26,7 @@ Gem::Specification.new do |s| s.description = "This specification shows how to generate aliases to maps and arrays as models." s.license = "Unlicense" s.required_ruby_version = ">= 2.7" + s.metadata = {} s.add_runtime_dependency 'typhoeus', '~> 1.0', '>= 1.0.1' diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb index ab3122e1588f..33a07403e3fc 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/api_client_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb index 0bcafd44f120..5fa6b13b3ecf 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/configuration_spec.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.2.0-SNAPSHOT =end diff --git a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb index 21a71465cf06..05b01de5a0ea 100644 --- a/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb +++ b/samples/openapi3/client/features/generate-alias-as-model/ruby-client/spec/spec_helper.rb @@ -6,7 +6,7 @@ The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech -OpenAPI Generator version: 7.1.0-SNAPSHOT +OpenAPI Generator version: 7.3.0-SNAPSHOT =end diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/oneof/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml index 139ad7abf559..16a95850087a 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/oneof/analysis_options.yaml @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart errors: diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml index 139ad7abf559..16a95850087a 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/analysis_options.yaml @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart errors: diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md index 949695f4d36f..cab0e7e57386 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRef.md @@ -8,6 +8,8 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**name** | **String** | Name of the related entity. | [optional] +**atReferredType** | **String** | The actual type of the target instance when needed for disambiguation. | [optional] **href** | **String** | Hyperlink reference | [optional] **id** | **String** | unique identifier | [optional] **atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md index 9dafa2d6b220..f88727e11aa8 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/BarRefOrValue.md @@ -8,11 +8,16 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- -**href** | **String** | Hyperlink reference | [optional] **id** | **String** | unique identifier | +**barPropA** | **String** | | [optional] +**fooPropB** | **String** | | [optional] +**foo** | [**FooRefOrValue**](FooRefOrValue.md) | | [optional] +**href** | **String** | Hyperlink reference | [optional] **atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] **atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] **atType** | **String** | When sub-classing, this defines the sub-class Extensible name | +**name** | **String** | Name of the related entity. | [optional] +**atReferredType** | **String** | The actual type of the target instance when needed for disambiguation. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md index 68104b227292..bfa62bd4f54b 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRef.md @@ -9,6 +9,8 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **foorefPropA** | **String** | | [optional] +**name** | **String** | Name of the related entity. | [optional] +**atReferredType** | **String** | The actual type of the target instance when needed for disambiguation. | [optional] **href** | **String** | Hyperlink reference | [optional] **id** | **String** | unique identifier | [optional] **atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md index 35e9fd114e1d..9bc8dec10571 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/FooRefOrValue.md @@ -8,11 +8,16 @@ import 'package:openapi/api.dart'; ## Properties Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**fooPropA** | **String** | | [optional] +**fooPropB** | **String** | | [optional] **href** | **String** | Hyperlink reference | [optional] **id** | **String** | unique identifier | [optional] **atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] **atBaseType** | **String** | When sub-classing, this defines the super-class | [optional] **atType** | **String** | When sub-classing, this defines the sub-class Extensible name | +**foorefPropA** | **String** | | [optional] +**name** | **String** | Name of the related entity. | [optional] +**atReferredType** | **String** | The actual type of the target instance when needed for disambiguation. | [optional] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md index e1d8434c077d..4e3800773dca 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/doc/PizzaSpeziale.md @@ -9,6 +9,7 @@ import 'package:openapi/api.dart'; Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **toppings** | **String** | | [optional] +**pizzaSize** | **num** | | [optional] **href** | **String** | Hyperlink reference | [optional] **id** | **String** | unique identifier | [optional] **atSchemaLocation** | **String** | A URI to a JSON-Schema file that defines additional attributes and relationships | [optional] diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart index 2b9d2727a448..98f0724b35d2 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref.dart @@ -12,6 +12,8 @@ part 'bar_ref.g.dart'; /// BarRef /// /// Properties: +/// * [name] - Name of the related entity. +/// * [atReferredType] - The actual type of the target instance when needed for disambiguation. /// * [href] - Hyperlink reference /// * [id] - unique identifier /// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart index 4af61384ab76..f880cb557955 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/bar_ref_or_value.dart @@ -3,6 +3,7 @@ // // ignore_for_file: unused_element +import 'package:openapi/src/model/foo_ref_or_value.dart'; import 'package:openapi/src/model/bar_ref.dart'; import 'package:openapi/src/model/bar.dart'; import 'package:built_value/built_value.dart'; @@ -14,11 +15,16 @@ part 'bar_ref_or_value.g.dart'; /// BarRefOrValue /// /// Properties: -/// * [href] - Hyperlink reference /// * [id] - unique identifier +/// * [barPropA] +/// * [fooPropB] +/// * [foo] +/// * [href] - Hyperlink reference /// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships /// * [atBaseType] - When sub-classing, this defines the super-class /// * [atType] - When sub-classing, this defines the sub-class Extensible name +/// * [name] - Name of the related entity. +/// * [atReferredType] - The actual type of the target instance when needed for disambiguation. @BuiltValue() abstract class BarRefOrValue implements Built { /// One Of [Bar], [BarRef] diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart index 1f77d990f0e8..3f032ee8e08f 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref.dart @@ -13,6 +13,8 @@ part 'foo_ref.g.dart'; /// /// Properties: /// * [foorefPropA] +/// * [name] - Name of the related entity. +/// * [atReferredType] - The actual type of the target instance when needed for disambiguation. /// * [href] - Hyperlink reference /// * [id] - unique identifier /// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart index af3e4875d9d6..d8164c5b9073 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/foo_ref_or_value.dart @@ -14,11 +14,16 @@ part 'foo_ref_or_value.g.dart'; /// FooRefOrValue /// /// Properties: +/// * [fooPropA] +/// * [fooPropB] /// * [href] - Hyperlink reference /// * [id] - unique identifier /// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships /// * [atBaseType] - When sub-classing, this defines the super-class /// * [atType] - When sub-classing, this defines the sub-class Extensible name +/// * [foorefPropA] +/// * [name] - Name of the related entity. +/// * [atReferredType] - The actual type of the target instance when needed for disambiguation. @BuiltValue() abstract class FooRefOrValue implements Built { /// One Of [Foo], [FooRef] diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart index 673052cc8fcf..73a2295df9ba 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart +++ b/samples/openapi3/client/petstore/dart-dio/oneof_polymorphism_and_inheritance/lib/src/model/pizza_speziale.dart @@ -13,6 +13,7 @@ part 'pizza_speziale.g.dart'; /// /// Properties: /// * [toppings] +/// * [pizzaSize] /// * [href] - Hyperlink reference /// * [id] - unique identifier /// * [atSchemaLocation] - A URI to a JSON-Schema file that defines additional attributes and relationships diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml index 139ad7abf559..16a95850087a 100644 --- a/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/oneof_primitive/analysis_options.yaml @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart errors: diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/README.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/README.md index e5b72ea2f537..026fcf4caea3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/README.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/README.md @@ -75,6 +75,7 @@ Class | Method | HTTP request | Description [*FakeApi*](doc/FakeApi.md) | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [*FakeApi*](doc/FakeApi.md) | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [*FakeApi*](doc/FakeApi.md) | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[*FakeApi*](doc/FakeApi.md) | [**testAdditionalPropertiesReference**](doc/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [*FakeApi*](doc/FakeApi.md) | [**testBodyWithBinary**](doc/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [*FakeApi*](doc/FakeApi.md) | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [*FakeApi*](doc/FakeApi.md) | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/analysis_options.yaml index ac01482530cc..70524126e3fe 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/analysis_options.yaml @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart - lib/src/model/*.g.dart diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/FakeApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/FakeApi.md index 4150c48f581b..d3921e831aad 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/doc/FakeApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | @@ -366,6 +367,48 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testAdditionalPropertiesReference** +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFakeApi(); +final Map requestBody = Object; // Map | request body + +try { + api.testAdditionalPropertiesReference(requestBody); +} catch on DioException (e) { + print('Exception when calling FakeApi->testAdditionalPropertiesReference: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**Map<String, Object>**](Object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithBinary** > testBodyWithBinary(body) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/api/fake_api.dart index 8d73ba412915..01709c06c5b3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/api/fake_api.dart @@ -692,6 +692,71 @@ _responseData = rawData == null ? null : deserialize> testAdditionalPropertiesReference({ + required Map requestBody, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/fake/additionalProperties-reference'; + final _options = Options( + method: r'POST', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'application/json', + validateStatus: validateStatus, + ); + + dynamic _bodyData; + + try { +_bodyData=jsonEncode(requestBody); + } catch(error, stackTrace) { + throw DioException( + requestOptions: _options.compose( + _dio.options, + _path, + ), + type: DioExceptionType.unknown, + error: error, + stackTrace: stackTrace, + ); + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + return _response; + } + /// testBodyWithBinary /// For this test, the body has to be a binary file. /// diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart index 8abf107d98e6..2cecd3b9c72c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/model_enum_class.dart @@ -8,11 +8,18 @@ import 'package:json_annotation/json_annotation.dart'; enum ModelEnumClass { @JsonValue(r'_abc') - abc, + abc(r'_abc'), @JsonValue(r'-efg') - efg, + efg(r'-efg'), @JsonValue(r'(xyz)') - leftParenthesisXyzRightParenthesis, + leftParenthesisXyzRightParenthesis(r'(xyz)'), @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + unknownDefaultOpenApi(r'unknown_default_open_api'); + + const ModelEnumClass(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart index 514507968c66..c3ba7b26a6b6 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum.dart @@ -8,11 +8,18 @@ import 'package:json_annotation/json_annotation.dart'; enum OuterEnum { @JsonValue(r'placed') - placed, + placed(r'placed'), @JsonValue(r'approved') - approved, + approved(r'approved'), @JsonValue(r'delivered') - delivered, + delivered(r'delivered'), @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + unknownDefaultOpenApi(r'unknown_default_open_api'); + + const OuterEnum(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart index 0c8116edea96..955683b929b3 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_default_value.dart @@ -8,11 +8,18 @@ import 'package:json_annotation/json_annotation.dart'; enum OuterEnumDefaultValue { @JsonValue(r'placed') - placed, + placed(r'placed'), @JsonValue(r'approved') - approved, + approved(r'approved'), @JsonValue(r'delivered') - delivered, + delivered(r'delivered'), @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + unknownDefaultOpenApi(r'unknown_default_open_api'); + + const OuterEnumDefaultValue(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart index 34268d0e9c53..b1464c0dda3c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer.dart @@ -8,11 +8,18 @@ import 'package:json_annotation/json_annotation.dart'; enum OuterEnumInteger { @JsonValue(0) - number0, + number0('0'), @JsonValue(1) - number1, + number1('1'), @JsonValue(2) - number2, + number2('2'), @JsonValue(11184809) - unknownDefaultOpenApi, + unknownDefaultOpenApi('11184809'); + + const OuterEnumInteger(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart index 97b325938828..64c416abec7c 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/outer_enum_integer_default_value.dart @@ -8,11 +8,18 @@ import 'package:json_annotation/json_annotation.dart'; enum OuterEnumIntegerDefaultValue { @JsonValue(0) - number0, + number0('0'), @JsonValue(1) - number1, + number1('1'), @JsonValue(2) - number2, + number2('2'), @JsonValue(11184809) - unknownDefaultOpenApi, + unknownDefaultOpenApi('11184809'); + + const OuterEnumIntegerDefaultValue(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart index ca56d9841a5a..9ee2644bf813 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/lib/src/model/single_ref_type.dart @@ -8,9 +8,16 @@ import 'package:json_annotation/json_annotation.dart'; enum SingleRefType { @JsonValue(r'admin') - admin, + admin(r'admin'), @JsonValue(r'user') - user, + user(r'user'), @JsonValue(r'unknown_default_open_api') - unknownDefaultOpenApi, + unknownDefaultOpenApi(r'unknown_default_open_api'); + + const SingleRefType(this.value); + + final String value; + + @override + String toString() => value; } diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/pubspec.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/pubspec.yaml index d005a785419f..dc16507435f0 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/pubspec.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake-json_serializable/pubspec.yaml @@ -4,7 +4,7 @@ description: OpenAPI API client homepage: homepage environment: - sdk: '>=2.15.0 <3.0.0' + sdk: '>=2.17.0 <3.0.0' dependencies: dio: '^5.2.0' diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md index 0e1527c34173..b1810ac23cfb 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/README.md @@ -74,6 +74,7 @@ Class | Method | HTTP request | Description [*FakeApi*](doc/FakeApi.md) | [**fakeOuterNumberSerialize**](doc/FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [*FakeApi*](doc/FakeApi.md) | [**fakeOuterStringSerialize**](doc/FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [*FakeApi*](doc/FakeApi.md) | [**fakePropertyEnumIntegerSerialize**](doc/FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[*FakeApi*](doc/FakeApi.md) | [**testAdditionalPropertiesReference**](doc/FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [*FakeApi*](doc/FakeApi.md) | [**testBodyWithBinary**](doc/FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [*FakeApi*](doc/FakeApi.md) | [**testBodyWithFileSchema**](doc/FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [*FakeApi*](doc/FakeApi.md) | [**testBodyWithQueryParams**](doc/FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml index 139ad7abf559..16a95850087a 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/analysis_options.yaml @@ -2,9 +2,7 @@ analyzer: language: strict-inference: true strict-raw-types: true - strong-mode: - implicit-dynamic: false - implicit-casts: false + strict-casts: false exclude: - test/*.dart errors: diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md index d0ea016b30a8..70492f2658ca 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/doc/FakeApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | @@ -366,6 +367,48 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testAdditionalPropertiesReference** +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example +```dart +import 'package:openapi/api.dart'; + +final api = Openapi().getFakeApi(); +final BuiltMap requestBody = Object; // BuiltMap | request body + +try { + api.testAdditionalPropertiesReference(requestBody); +} catch on DioException (e) { + print('Exception when calling FakeApi->testAdditionalPropertiesReference: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**BuiltMap<String, JsonObject>**](JsonObject.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithBinary** > testBodyWithBinary(body) diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/api/fake_api.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/api/fake_api.dart index eeceedf31928..ff1fe20d363f 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/api/fake_api.dart @@ -9,6 +9,7 @@ import 'package:dio/dio.dart'; import 'dart:typed_data'; import 'package:built_collection/built_collection.dart'; +import 'package:built_value/json_object.dart'; import 'package:openapi/src/api_util.dart'; import 'package:openapi/src/model/child_with_nullable.dart'; import 'package:openapi/src/model/date.dart'; @@ -724,6 +725,73 @@ class FakeApi { ); } + /// test referenced additionalProperties + /// + /// + /// Parameters: + /// * [requestBody] - request body + /// * [cancelToken] - A [CancelToken] that can be used to cancel the operation + /// * [headers] - Can be used to add additional headers to the request + /// * [extras] - Can be used to add flags to the request + /// * [validateStatus] - A [ValidateStatus] callback that can be used to determine request success based on the HTTP status of the response + /// * [onSendProgress] - A [ProgressCallback] that can be used to get the send progress + /// * [onReceiveProgress] - A [ProgressCallback] that can be used to get the receive progress + /// + /// Returns a [Future] + /// Throws [DioException] if API call or serialization fails + Future> testAdditionalPropertiesReference({ + required BuiltMap requestBody, + CancelToken? cancelToken, + Map? headers, + Map? extra, + ValidateStatus? validateStatus, + ProgressCallback? onSendProgress, + ProgressCallback? onReceiveProgress, + }) async { + final _path = r'/fake/additionalProperties-reference'; + final _options = Options( + method: r'POST', + headers: { + ...?headers, + }, + extra: { + 'secure': >[], + ...?extra, + }, + contentType: 'application/json', + validateStatus: validateStatus, + ); + + dynamic _bodyData; + + try { + const _type = FullType(BuiltMap, [FullType(String), FullType(JsonObject)]); + _bodyData = _serializers.serialize(requestBody, specifiedType: _type); + + } catch(error, stackTrace) { + throw DioException( + requestOptions: _options.compose( + _dio.options, + _path, + ), + type: DioExceptionType.unknown, + error: error, + stackTrace: stackTrace, + ); + } + + final _response = await _dio.request( + _path, + data: _bodyData, + options: _options, + cancelToken: cancelToken, + onSendProgress: onSendProgress, + onReceiveProgress: onReceiveProgress, + ); + + return _response; + } + /// testBodyWithBinary /// For this test, the body has to be a binary file. /// diff --git a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart index 483a35e92779..98ec8cd5dfc9 100644 --- a/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart +++ b/samples/openapi3/client/petstore/dart-dio/petstore_client_lib_fake/lib/src/serializers.dart @@ -140,6 +140,10 @@ Serializers serializers = (_$serializers.toBuilder() const FullType(BuiltList, [FullType(Pet)]), () => ListBuilder(), ) + ..addBuilderFactory( + const FullType(BuiltMap, [FullType(String), FullType.nullable(JsonObject)]), + () => MapBuilder(), + ) ..addBuilderFactory( const FullType(BuiltMap, [FullType(String), FullType(int)]), () => MapBuilder(), diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart index 4871871516fe..75f8dbee2240 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib/lib/model/order.dart @@ -201,13 +201,13 @@ class OrderStatusEnum { static const placed = OrderStatusEnum._(r'placed'); static const approved = OrderStatusEnum._(r'approved'); - static const delivered = OrderStatusEnum._(r'delivered'); + static const shipped = OrderStatusEnum._(r'delivered'); /// List of all possible values in this [enum][OrderStatusEnum]. static const values = [ placed, approved, - delivered, + shipped, ]; static OrderStatusEnum? fromJson(dynamic value) => OrderStatusEnumTypeTransformer().decode(value); @@ -248,7 +248,7 @@ class OrderStatusEnumTypeTransformer { switch (data) { case r'placed': return OrderStatusEnum.placed; case r'approved': return OrderStatusEnum.approved; - case r'delivered': return OrderStatusEnum.delivered; + case r'delivered': return OrderStatusEnum.shipped; default: if (!allowNull) { throw ArgumentError('Unknown enum value to decode: $data'); diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md index 5b27fc4cd9e8..9fd780b4e214 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/README.md @@ -68,6 +68,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](doc//FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](doc//FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | *FakeApi* | [**fakePropertyEnumIntegerSerialize**](doc//FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**testAdditionalPropertiesReference**](doc//FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithBinary**](doc//FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | *FakeApi* | [**testBodyWithFileSchema**](doc//FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](doc//FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md index 129189d8ce15..f20a9ec06422 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/doc/FakeApi.md @@ -17,6 +17,7 @@ Method | HTTP request | Description [**fakeOuterNumberSerialize**](FakeApi.md#fakeouternumberserialize) | **POST** /fake/outer/number | [**fakeOuterStringSerialize**](FakeApi.md#fakeouterstringserialize) | **POST** /fake/outer/string | [**fakePropertyEnumIntegerSerialize**](FakeApi.md#fakepropertyenumintegerserialize) | **POST** /fake/property/enum-int | +[**testAdditionalPropertiesReference**](FakeApi.md#testadditionalpropertiesreference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**testBodyWithBinary**](FakeApi.md#testbodywithbinary) | **PUT** /fake/body-with-binary | [**testBodyWithFileSchema**](FakeApi.md#testbodywithfileschema) | **PUT** /fake/body-with-file-schema | [**testBodyWithQueryParams**](FakeApi.md#testbodywithqueryparams) | **PUT** /fake/body-with-query-params | @@ -366,6 +367,48 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **testAdditionalPropertiesReference** +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example +```dart +import 'package:openapi/api.dart'; + +final api_instance = FakeApi(); +final requestBody = Map(); // Map | request body + +try { + api_instance.testAdditionalPropertiesReference(requestBody); +} catch (e) { + print('Exception when calling FakeApi->testAdditionalPropertiesReference: $e\n'); +} +``` + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | [**Map**](Object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **testBodyWithBinary** > testBodyWithBinary(body) diff --git a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart index 50ff096df273..207fc6ddaf93 100644 --- a/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart +++ b/samples/openapi3/client/petstore/dart2/petstore_client_lib_fake/lib/api/fake_api.dart @@ -440,6 +440,56 @@ class FakeApi { return null; } + /// test referenced additionalProperties + /// + /// + /// + /// Note: This method returns the HTTP [Response]. + /// + /// Parameters: + /// + /// * [Map] requestBody (required): + /// request body + Future testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody,) async { + // ignore: prefer_const_declarations + final path = r'/fake/additionalProperties-reference'; + + // ignore: prefer_final_locals + Object? postBody = requestBody; + + final queryParams = []; + final headerParams = {}; + final formParams = {}; + + const contentTypes = ['application/json']; + + + return apiClient.invokeAPI( + path, + 'POST', + queryParams, + postBody, + headerParams, + formParams, + contentTypes.isEmpty ? null : contentTypes.first, + ); + } + + /// test referenced additionalProperties + /// + /// + /// + /// Parameters: + /// + /// * [Map] requestBody (required): + /// request body + Future testAdditionalPropertiesReference(Map requestBody,) async { + final response = await testAdditionalPropertiesReferenceWithHttpInfo(requestBody,); + if (response.statusCode >= HttpStatus.badRequest) { + throw ApiException(response.statusCode, await _decodeBodyBytes(response)); + } + } + /// For this test, the body has to be a binary file. /// /// Note: This method returns the HTTP [Response]. diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.gitignore b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.gitignore new file mode 100644 index 000000000000..daf913b1b347 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.gitignore @@ -0,0 +1,24 @@ +# Compiled Object files, Static and Dynamic libs (Shared Objects) +*.o +*.a +*.so + +# Folders +_obj +_test + +# Architecture specific extensions/prefixes +*.[568vq] +[568vq].out + +*.cgo1.go +*.cgo2.c +_cgo_defun.c +_cgo_gotypes.go +_cgo_export.* + +_testmain.go + +*.exe +*.test +*.prof diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator-ignore b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/FILES b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/FILES new file mode 100644 index 000000000000..c6b0a6bd16db --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/FILES @@ -0,0 +1,19 @@ +.gitignore +.travis.yml +README.md +api/openapi.yaml +api_pet.go +client.go +configuration.go +docs/Category.md +docs/Pet.md +docs/PetAPI.md +docs/Tag.md +git_push.sh +go.mod +go.sum +model_category.go +model_pet.go +model_tag.go +response.go +utils.go diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/VERSION b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.travis.yml b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.travis.yml new file mode 100644 index 000000000000..f5cb2ce9a5aa --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/.travis.yml @@ -0,0 +1,8 @@ +language: go + +install: + - go get -d -v . + +script: + - go build -v ./ + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/README.md b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/README.md new file mode 100644 index 000000000000..d53f59d0635c --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/README.md @@ -0,0 +1,144 @@ +# Go API client for petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview +This API client was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the [OpenAPI-spec](https://www.openapis.org/) from a remote server, you can easily generate an API client. + +- API version: 1.0.0 +- Package version: 1.0.0 +- Build package: org.openapitools.codegen.languages.GoClientCodegen + +## Installation + +Install the following dependencies: + +```sh +go get github.com/stretchr/testify/assert +go get golang.org/x/oauth2 +go get golang.org/x/net/context +``` + +Put the package under your project folder and add the following in import: + +```go +import petstore "github.com/GIT_USER_ID/GIT_REPO_ID" +``` + +To use a proxy, set the environment variable `HTTP_PROXY`: + +```go +os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") +``` + +## Configuration of Server URL + +Default configuration comes with `Servers` field that contains server objects as defined in the OpenAPI specification. + +### Select Server Configuration + +For using other server than the one defined on index 0 set context value `petstore.ContextServerIndex` of type `int`. + +```go +ctx := context.WithValue(context.Background(), petstore.ContextServerIndex, 1) +``` + +### Templated Server URL + +Templated server URL is formatted using default variables from configuration or from context value `petstore.ContextServerVariables` of type `map[string]string`. + +```go +ctx := context.WithValue(context.Background(), petstore.ContextServerVariables, map[string]string{ + "basePath": "v2", +}) +``` + +Note, enum values are always validated and all unused variables are silently ignored. + +### URLs Configuration per Operation + +Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. +An operation is uniquely identified by `"{classname}Service.{nickname}"` string. +Similar rules for overriding default operation server index and variables applies by using `petstore.ContextOperationServerIndices` and `petstore.ContextOperationServerVariables` context maps. + +```go +ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ + "{classname}Service.{nickname}": 2, +}) +ctx = context.WithValue(context.Background(), petstore.ContextOperationServerVariables, map[string]map[string]string{ + "{classname}Service.{nickname}": { + "port": "8443", + }, +}) +``` + +## Documentation for API Endpoints + +All URIs are relative to *http://petstore.swagger.io/v2* + +Class | Method | HTTP request | Description +------------ | ------------- | ------------- | ------------- +*PetAPI* | [**AddPet**](docs/PetAPI.md#addpet) | **Post** /pet | Add a new pet to the store + + +## Documentation For Models + + - [Category](docs/Category.md) + - [Pet](docs/Pet.md) + - [Tag](docs/Tag.md) + + +## Documentation For Authorization + + +Authentication schemes defined for the API: +### petstore_auth + + +- **Type**: OAuth +- **Flow**: implicit +- **Authorization URL**: http://petstore.swagger.io/api/oauth/dialog +- **Scopes**: + - **write:pets**: modify pets in your account + - **read:pets**: read your pets + +Example + +```go +auth := context.WithValue(context.Background(), petstore.ContextAccessToken, "ACCESSTOKENSTRING") +r, err := client.Service.Operation(auth, args) +``` + +Or via OAuth2 module to automatically refresh tokens and perform user authentication. + +```go +import "golang.org/x/oauth2" + +/* Perform OAuth2 round trip request and obtain a token */ + +tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) +auth := context.WithValue(oauth2.NoContext, petstore.ContextOAuth2, tokenSource) +r, err := client.Service.Operation(auth, args) +``` + + +## Documentation for Utility Methods + +Due to the fact that model structure members are all pointers, this package contains +a number of utility functions to easily obtain pointers to values of basic types. +Each of these functions takes a value of the given basic type and returns a pointer to it: + +* `PtrBool` +* `PtrInt` +* `PtrInt32` +* `PtrInt64` +* `PtrFloat` +* `PtrFloat32` +* `PtrFloat64` +* `PtrString` +* `PtrTime` + +## Author + + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api/openapi.yaml b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api/openapi.yaml new file mode 100644 index 000000000000..ba1183b11d2a --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api/openapi.yaml @@ -0,0 +1,151 @@ +openapi: 3.0.0 +info: + description: "This is a sample server Petstore server. For this sample, you can\ + \ use the api key `special-key` to test the authorization filters." + license: + name: Apache-2.0 + url: https://www.apache.org/licenses/LICENSE-2.0.html + title: OpenAPI Petstore + version: 1.0.0 +externalDocs: + description: Find out more about Swagger + url: http://swagger.io +servers: +- url: http://petstore.swagger.io/v2 +tags: +- description: Everything about your Pets + name: pet +paths: + /pet: + post: + description: "" + operationId: addPet + requestBody: + $ref: '#/components/requestBodies/Pet' + responses: + "200": + content: + application/xml: + schema: + $ref: '#/components/schemas/Pet' + application/json: + schema: + $ref: '#/components/schemas/Pet' + description: successful operation + "405": + description: Invalid input + security: + - petstore_auth: + - write:pets + - read:pets + summary: Add a new pet to the store + tags: + - pet +components: + requestBodies: + Pet: + content: + application/json: + schema: + $ref: '#/components/schemas/Pet' + application/xml: + schema: + $ref: '#/components/schemas/Pet' + description: Pet object that needs to be added to the store + required: true + schemas: + Category: + description: A category for a pet + example: + name: name + id: 6 + properties: + id: + format: int64 + type: integer + name: + pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" + type: string + title: Pet category + type: object + xml: + name: Category + Tag: + description: A tag for a pet + example: + name: name + id: 1 + properties: + id: + format: int64 + type: integer + name: + type: string + title: Pet Tag + type: object + xml: + name: Tag + Pet: + description: A pet for sale in the pet store + example: + photoUrls: + - photoUrls + - photoUrls + name: doggie + id: 0 + category: + name: name + id: 6 + tags: + - name: name + id: 1 + - name: name + id: 1 + status: available + properties: + id: + format: int64 + type: integer + category: + $ref: '#/components/schemas/Category' + name: + example: doggie + type: string + photoUrls: + items: + type: string + type: array + xml: + name: photoUrl + wrapped: true + tags: + items: + $ref: '#/components/schemas/Tag' + type: array + xml: + name: tag + wrapped: true + status: + deprecated: true + description: pet status in the store + enum: + - available + - pending + - sold + type: string + required: + - name + - photoUrls + title: a Pet + type: object + xml: + name: Pet + securitySchemes: + petstore_auth: + flows: + implicit: + authorizationUrl: http://petstore.swagger.io/api/oauth/dialog + scopes: + write:pets: modify pets in your account + read:pets: read your pets + type: oauth2 diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api_pet.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api_pet.go new file mode 100644 index 000000000000..b875067e48d3 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/api_pet.go @@ -0,0 +1,134 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "bytes" + "context" + "io" + "net/http" + "net/url" +) + + +// PetAPIService PetAPI service +type PetAPIService service + +type ApiAddPetRequest struct { + ctx context.Context + ApiService *PetAPIService + pet *Pet +} + +// Pet object that needs to be added to the store +func (r ApiAddPetRequest) Pet(pet Pet) ApiAddPetRequest { + r.pet = &pet + return r +} + +func (r ApiAddPetRequest) Execute() (*Pet, *http.Response, error) { + return r.ApiService.AddPetExecute(r) +} + +/* +AddPet Add a new pet to the store + + + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiAddPetRequest +*/ +func (a *PetAPIService) AddPet(ctx context.Context) ApiAddPetRequest { + return ApiAddPetRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +// @return Pet +func (a *PetAPIService) AddPetExecute(r ApiAddPetRequest) (*Pet, *http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + localVarReturnValue *Pet + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "PetAPIService.AddPet") + if err != nil { + return localVarReturnValue, nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/pet" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.pet == nil { + return localVarReturnValue, nil, reportError("pet is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json", "application/xml"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{"application/xml", "application/json"} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.pet + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return localVarReturnValue, nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarReturnValue, localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + err = a.client.decode(&localVarReturnValue, localVarBody, localVarHTTPResponse.Header.Get("Content-Type")) + if err != nil { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: err.Error(), + } + return localVarReturnValue, localVarHTTPResponse, newErr + } + + return localVarReturnValue, localVarHTTPResponse, nil +} diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/client.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/client.go new file mode 100644 index 000000000000..27e965065246 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/client.go @@ -0,0 +1,672 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "bytes" + "context" + "encoding/json" + "encoding/xml" + "errors" + "fmt" + "io" + "log" + "mime/multipart" + "net/http" + "net/http/httputil" + "net/url" + "os" + "path/filepath" + "reflect" + "regexp" + "strconv" + "strings" + "time" + "unicode/utf8" + + "golang.org/x/oauth2" +) + +var ( + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) + queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) + queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) +) + +// APIClient manages communication with the OpenAPI Petstore API v1.0.0 +// In most cases there should be only one, shared, APIClient. +type APIClient struct { + cfg *Configuration + common service // Reuse a single struct instead of allocating one for each service on the heap. + + // API Services + + PetAPI *PetAPIService +} + +type service struct { + client *APIClient +} + +// NewAPIClient creates a new API client. Requires a userAgent string describing your application. +// optionally a custom http.Client to allow for advanced features such as caching. +func NewAPIClient(cfg *Configuration) *APIClient { + if cfg.HTTPClient == nil { + cfg.HTTPClient = http.DefaultClient + } + + c := &APIClient{} + c.cfg = cfg + c.common.client = c + + // API Services + c.PetAPI = (*PetAPIService)(&c.common) + + return c +} + +func atoi(in string) (int, error) { + return strconv.Atoi(in) +} + +// selectHeaderContentType select a content type from the available list. +func selectHeaderContentType(contentTypes []string) string { + if len(contentTypes) == 0 { + return "" + } + if contains(contentTypes, "application/json") { + return "application/json" + } + return contentTypes[0] // use the first content type specified in 'consumes' +} + +// selectHeaderAccept join all accept types and return +func selectHeaderAccept(accepts []string) string { + if len(accepts) == 0 { + return "" + } + + if contains(accepts, "application/json") { + return "application/json" + } + + return strings.Join(accepts, ",") +} + +// contains is a case insensitive match, finding needle in a haystack +func contains(haystack []string, needle string) bool { + for _, a := range haystack { + if strings.EqualFold(a, needle) { + return true + } + } + return false +} + +// Verify optional parameters are of the correct type. +func typeCheckParameter(obj interface{}, expected string, name string) error { + // Make sure there is an object. + if obj == nil { + return nil + } + + // Check the type is as expected. + if reflect.TypeOf(obj).String() != expected { + return fmt.Errorf("expected %s to be of type %s but received %s", name, expected, reflect.TypeOf(obj).String()) + } + return nil +} + +func parameterValueToString( obj interface{}, key string ) string { + if reflect.TypeOf(obj).Kind() != reflect.Ptr { + return fmt.Sprintf("%v", obj) + } + var param,ok = obj.(MappedNullable) + if !ok { + return "" + } + dataMap,err := param.ToMap() + if err != nil { + return "" + } + return fmt.Sprintf("%v", dataMap[key]) +} + +// parameterAddToHeaderOrQuery adds the provided object to the request header or url query +// supporting deep object syntax +func parameterAddToHeaderOrQuery(headerOrQueryParams interface{}, keyPrefix string, obj interface{}, collectionType string) { + var v = reflect.ValueOf(obj) + var value = "" + if v == reflect.ValueOf(nil) { + value = "null" + } else { + switch v.Kind() { + case reflect.Invalid: + value = "invalid" + + case reflect.Struct: + if t,ok := obj.(MappedNullable); ok { + dataMap,err := t.ToMap() + if err != nil { + return + } + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, dataMap, collectionType) + return + } + if t, ok := obj.(time.Time); ok { + parameterAddToHeaderOrQuery(headerOrQueryParams, keyPrefix, t.Format(time.RFC3339), collectionType) + return + } + value = v.Type().String() + " value" + case reflect.Slice: + var indValue = reflect.ValueOf(obj) + if indValue == reflect.ValueOf(nil) { + return + } + var lenIndValue = indValue.Len() + for i:=0;i 0 || (len(formFiles) > 0) { + if body != nil { + return nil, errors.New("Cannot specify postBody and multipart form at the same time.") + } + body = &bytes.Buffer{} + w := multipart.NewWriter(body) + + for k, v := range formParams { + for _, iv := range v { + if strings.HasPrefix(k, "@") { // file + err = addFile(w, k[1:], iv) + if err != nil { + return nil, err + } + } else { // form value + w.WriteField(k, iv) + } + } + } + for _, formFile := range formFiles { + if len(formFile.fileBytes) > 0 && formFile.fileName != "" { + w.Boundary() + part, err := w.CreateFormFile(formFile.formFileName, filepath.Base(formFile.fileName)) + if err != nil { + return nil, err + } + _, err = part.Write(formFile.fileBytes) + if err != nil { + return nil, err + } + } + } + + // Set the Boundary in the Content-Type + headerParams["Content-Type"] = w.FormDataContentType() + + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + w.Close() + } + + if strings.HasPrefix(headerParams["Content-Type"], "application/x-www-form-urlencoded") && len(formParams) > 0 { + if body != nil { + return nil, errors.New("Cannot specify postBody and x-www-form-urlencoded form at the same time.") + } + body = &bytes.Buffer{} + body.WriteString(formParams.Encode()) + // Set Content-Length + headerParams["Content-Length"] = fmt.Sprintf("%d", body.Len()) + } + + // Setup path and query parameters + url, err := url.Parse(path) + if err != nil { + return nil, err + } + + // Override request host, if applicable + if c.cfg.Host != "" { + url.Host = c.cfg.Host + } + + // Override request scheme, if applicable + if c.cfg.Scheme != "" { + url.Scheme = c.cfg.Scheme + } + + // Adding Query Param + query := url.Query() + for k, v := range queryParams { + for _, iv := range v { + query.Add(k, iv) + } + } + + // Encode the parameters. + url.RawQuery = queryParamSplit.ReplaceAllStringFunc(query.Encode(), func(s string) string { + pieces := strings.Split(s, "=") + pieces[0] = queryDescape.Replace(pieces[0]) + return strings.Join(pieces, "=") + }) + + // Generate a new request + if body != nil { + localVarRequest, err = http.NewRequest(method, url.String(), body) + } else { + localVarRequest, err = http.NewRequest(method, url.String(), nil) + } + if err != nil { + return nil, err + } + + // add header parameters, if any + if len(headerParams) > 0 { + headers := http.Header{} + for h, v := range headerParams { + headers[h] = []string{v} + } + localVarRequest.Header = headers + } + + // Add the user agent to the request. + localVarRequest.Header.Add("User-Agent", c.cfg.UserAgent) + + if ctx != nil { + // add context to the request + localVarRequest = localVarRequest.WithContext(ctx) + + // Walk through any authentication. + + // OAuth2 authentication + if tok, ok := ctx.Value(ContextOAuth2).(oauth2.TokenSource); ok { + // We were able to grab an oauth2 token from the context + var latestToken *oauth2.Token + if latestToken, err = tok.Token(); err != nil { + return nil, err + } + + latestToken.SetAuthHeader(localVarRequest) + } + + } + + for header, value := range c.cfg.DefaultHeader { + localVarRequest.Header.Add(header, value) + } + return localVarRequest, nil +} + +func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err error) { + if len(b) == 0 { + return nil + } + if s, ok := v.(*string); ok { + *s = string(b) + return nil + } + if f, ok := v.(*os.File); ok { + f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = f.Write(b) + if err != nil { + return + } + _, err = f.Seek(0, io.SeekStart) + return + } + if f, ok := v.(**os.File); ok { + *f, err = os.CreateTemp("", "HttpClientFile") + if err != nil { + return + } + _, err = (*f).Write(b) + if err != nil { + return + } + _, err = (*f).Seek(0, io.SeekStart) + return + } + if XmlCheck.MatchString(contentType) { + if err = xml.Unmarshal(b, v); err != nil { + return err + } + return nil + } + if JsonCheck.MatchString(contentType) { + if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas + if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined + if err = unmarshalObj.UnmarshalJSON(b); err != nil { + return err + } + } else { + return errors.New("Unknown type with GetActualInstance but no unmarshalObj.UnmarshalJSON defined") + } + } else if err = json.Unmarshal(b, v); err != nil { // simple model + return err + } + return nil + } + return errors.New("undefined response type") +} + +// Add a file to the multipart request +func addFile(w *multipart.Writer, fieldName, path string) error { + file, err := os.Open(filepath.Clean(path)) + if err != nil { + return err + } + err = file.Close() + if err != nil { + return err + } + + part, err := w.CreateFormFile(fieldName, filepath.Base(path)) + if err != nil { + return err + } + _, err = io.Copy(part, file) + + return err +} + +// Prevent trying to import "fmt" +func reportError(format string, a ...interface{}) error { + return fmt.Errorf(format, a...) +} + +// A wrapper for strict JSON decoding +func newStrictDecoder(data []byte) *json.Decoder { + dec := json.NewDecoder(bytes.NewBuffer(data)) + dec.DisallowUnknownFields() + return dec +} + +// Set request body from an interface{} +func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err error) { + if bodyBuf == nil { + bodyBuf = &bytes.Buffer{} + } + + if reader, ok := body.(io.Reader); ok { + _, err = bodyBuf.ReadFrom(reader) + } else if fp, ok := body.(*os.File); ok { + _, err = bodyBuf.ReadFrom(fp) + } else if b, ok := body.([]byte); ok { + _, err = bodyBuf.Write(b) + } else if s, ok := body.(string); ok { + _, err = bodyBuf.WriteString(s) + } else if s, ok := body.(*string); ok { + _, err = bodyBuf.WriteString(*s) + } else if JsonCheck.MatchString(contentType) { + err = json.NewEncoder(bodyBuf).Encode(body) + } else if XmlCheck.MatchString(contentType) { + var bs []byte + bs, err = xml.Marshal(body) + if err == nil { + bodyBuf.Write(bs) + } + } + + if err != nil { + return nil, err + } + + if bodyBuf.Len() == 0 { + err = fmt.Errorf("invalid body type %s\n", contentType) + return nil, err + } + return bodyBuf, nil +} + +// detectContentType method is used to figure out `Request.Body` content type for request header +func detectContentType(body interface{}) string { + contentType := "text/plain; charset=utf-8" + kind := reflect.TypeOf(body).Kind() + + switch kind { + case reflect.Struct, reflect.Map, reflect.Ptr: + contentType = "application/json; charset=utf-8" + case reflect.String: + contentType = "text/plain; charset=utf-8" + default: + if b, ok := body.([]byte); ok { + contentType = http.DetectContentType(b) + } else if kind == reflect.Slice { + contentType = "application/json; charset=utf-8" + } + } + + return contentType +} + +// Ripped from https://github.com/gregjones/httpcache/blob/master/httpcache.go +type cacheControl map[string]string + +func parseCacheControl(headers http.Header) cacheControl { + cc := cacheControl{} + ccHeader := headers.Get("Cache-Control") + for _, part := range strings.Split(ccHeader, ",") { + part = strings.Trim(part, " ") + if part == "" { + continue + } + if strings.ContainsRune(part, '=') { + keyval := strings.Split(part, "=") + cc[strings.Trim(keyval[0], " ")] = strings.Trim(keyval[1], ",") + } else { + cc[part] = "" + } + } + return cc +} + +// CacheExpires helper function to determine remaining time before repeating a request. +func CacheExpires(r *http.Response) time.Time { + // Figure out when the cache expires. + var expires time.Time + now, err := time.Parse(time.RFC1123, r.Header.Get("date")) + if err != nil { + return time.Now() + } + respCacheControl := parseCacheControl(r.Header) + + if maxAge, ok := respCacheControl["max-age"]; ok { + lifetime, err := time.ParseDuration(maxAge + "s") + if err != nil { + expires = now + } else { + expires = now.Add(lifetime) + } + } else { + expiresHeader := r.Header.Get("Expires") + if expiresHeader != "" { + expires, err = time.Parse(time.RFC1123, expiresHeader) + if err != nil { + expires = now + } + } + } + return expires +} + +func strlen(s string) int { + return utf8.RuneCountInString(s) +} + +// GenericOpenAPIError Provides access to the body, error and model on returned errors. +type GenericOpenAPIError struct { + body []byte + error string + model interface{} +} + +// Error returns non-empty string if there was an error. +func (e GenericOpenAPIError) Error() string { + return e.error +} + +// Body returns the raw bytes of the response +func (e GenericOpenAPIError) Body() []byte { + return e.body +} + +// Model returns the unpacked model of the error +func (e GenericOpenAPIError) Model() interface{} { + return e.model +} + +// format error message using title and detail when model implements rfc7807 +func formatErrorMessage(status string, v interface{}) string { + str := "" + metaValue := reflect.ValueOf(v).Elem() + + if metaValue.Kind() == reflect.Struct { + field := metaValue.FieldByName("Title") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s", field.Interface()) + } + + field = metaValue.FieldByName("Detail") + if field != (reflect.Value{}) { + str = fmt.Sprintf("%s (%s)", str, field.Interface()) + } + } + + return strings.TrimSpace(fmt.Sprintf("%s %s", status, str)) +} diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/configuration.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/configuration.go new file mode 100644 index 000000000000..200758876dee --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/configuration.go @@ -0,0 +1,218 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "context" + "fmt" + "net/http" + "strings" +) + +// contextKeys are used to identify the type of value in the context. +// Since these are string, it is possible to get a short description of the +// context key for logging and debugging using key.String(). + +type contextKey string + +func (c contextKey) String() string { + return "auth " + string(c) +} + +var ( + // ContextOAuth2 takes an oauth2.TokenSource as authentication for the request. + ContextOAuth2 = contextKey("token") + + // ContextServerIndex uses a server configuration from the index. + ContextServerIndex = contextKey("serverIndex") + + // ContextOperationServerIndices uses a server configuration from the index mapping. + ContextOperationServerIndices = contextKey("serverOperationIndices") + + // ContextServerVariables overrides a server configuration variables. + ContextServerVariables = contextKey("serverVariables") + + // ContextOperationServerVariables overrides a server configuration variables using operation specific values. + ContextOperationServerVariables = contextKey("serverOperationVariables") +) + +// BasicAuth provides basic http authentication to a request passed via context using ContextBasicAuth +type BasicAuth struct { + UserName string `json:"userName,omitempty"` + Password string `json:"password,omitempty"` +} + +// APIKey provides API key based authentication to a request passed via context using ContextAPIKey +type APIKey struct { + Key string + Prefix string +} + +// ServerVariable stores the information about a server variable +type ServerVariable struct { + Description string + DefaultValue string + EnumValues []string +} + +// ServerConfiguration stores the information about a server +type ServerConfiguration struct { + URL string + Description string + Variables map[string]ServerVariable +} + +// ServerConfigurations stores multiple ServerConfiguration items +type ServerConfigurations []ServerConfiguration + +// Configuration stores the configuration of the API client +type Configuration struct { + Host string `json:"host,omitempty"` + Scheme string `json:"scheme,omitempty"` + DefaultHeader map[string]string `json:"defaultHeader,omitempty"` + UserAgent string `json:"userAgent,omitempty"` + Debug bool `json:"debug,omitempty"` + Servers ServerConfigurations + OperationServers map[string]ServerConfigurations + HTTPClient *http.Client +} + +// NewConfiguration returns a new Configuration object +func NewConfiguration() *Configuration { + cfg := &Configuration{ + DefaultHeader: make(map[string]string), + UserAgent: "OpenAPI-Generator/1.0.0/go", + Debug: false, + Servers: ServerConfigurations{ + { + URL: "http://petstore.swagger.io/v2", + Description: "No description provided", + }, + }, + OperationServers: map[string]ServerConfigurations{ + }, + } + return cfg +} + +// AddDefaultHeader adds a new HTTP header to the default header in the request +func (c *Configuration) AddDefaultHeader(key string, value string) { + c.DefaultHeader[key] = value +} + +// URL formats template on a index using given variables +func (sc ServerConfigurations) URL(index int, variables map[string]string) (string, error) { + if index < 0 || len(sc) <= index { + return "", fmt.Errorf("index %v out of range %v", index, len(sc)-1) + } + server := sc[index] + url := server.URL + + // go through variables and replace placeholders + for name, variable := range server.Variables { + if value, ok := variables[name]; ok { + found := bool(len(variable.EnumValues) == 0) + for _, enumValue := range variable.EnumValues { + if value == enumValue { + found = true + } + } + if !found { + return "", fmt.Errorf("the variable %s in the server URL has invalid value %v. Must be %v", name, value, variable.EnumValues) + } + url = strings.Replace(url, "{"+name+"}", value, -1) + } else { + url = strings.Replace(url, "{"+name+"}", variable.DefaultValue, -1) + } + } + return url, nil +} + +// ServerURL returns URL based on server settings +func (c *Configuration) ServerURL(index int, variables map[string]string) (string, error) { + return c.Servers.URL(index, variables) +} + +func getServerIndex(ctx context.Context) (int, error) { + si := ctx.Value(ContextServerIndex) + if si != nil { + if index, ok := si.(int); ok { + return index, nil + } + return 0, reportError("Invalid type %T should be int", si) + } + return 0, nil +} + +func getServerOperationIndex(ctx context.Context, endpoint string) (int, error) { + osi := ctx.Value(ContextOperationServerIndices) + if osi != nil { + if operationIndices, ok := osi.(map[string]int); !ok { + return 0, reportError("Invalid type %T should be map[string]int", osi) + } else { + index, ok := operationIndices[endpoint] + if ok { + return index, nil + } + } + } + return getServerIndex(ctx) +} + +func getServerVariables(ctx context.Context) (map[string]string, error) { + sv := ctx.Value(ContextServerVariables) + if sv != nil { + if variables, ok := sv.(map[string]string); ok { + return variables, nil + } + return nil, reportError("ctx value of ContextServerVariables has invalid type %T should be map[string]string", sv) + } + return nil, nil +} + +func getServerOperationVariables(ctx context.Context, endpoint string) (map[string]string, error) { + osv := ctx.Value(ContextOperationServerVariables) + if osv != nil { + if operationVariables, ok := osv.(map[string]map[string]string); !ok { + return nil, reportError("ctx value of ContextOperationServerVariables has invalid type %T should be map[string]map[string]string", osv) + } else { + variables, ok := operationVariables[endpoint] + if ok { + return variables, nil + } + } + } + return getServerVariables(ctx) +} + +// ServerURLWithContext returns a new server URL given an endpoint +func (c *Configuration) ServerURLWithContext(ctx context.Context, endpoint string) (string, error) { + sc, ok := c.OperationServers[endpoint] + if !ok { + sc = c.Servers + } + + if ctx == nil { + return sc.URL(0, nil) + } + + index, err := getServerOperationIndex(ctx, endpoint) + if err != nil { + return "", err + } + + variables, err := getServerOperationVariables(ctx, endpoint) + if err != nil { + return "", err + } + + return sc.URL(index, variables) +} diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Category.md b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Category.md new file mode 100644 index 000000000000..9bedc96c5340 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Category.md @@ -0,0 +1,82 @@ +# Category + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Name** | Pointer to **string** | | [optional] + +## Methods + +### NewCategory + +`func NewCategory() *Category` + +NewCategory instantiates a new Category object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewCategoryWithDefaults + +`func NewCategoryWithDefaults() *Category` + +NewCategoryWithDefaults instantiates a new Category object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Category) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Category) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Category) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Category) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetName + +`func (o *Category) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Category) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Category) SetName(v string)` + +SetName sets Name field to given value. + +### HasName + +`func (o *Category) HasName() bool` + +HasName returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Pet.md b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Pet.md new file mode 100644 index 000000000000..a6eae34657d3 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Pet.md @@ -0,0 +1,176 @@ +# Pet + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Category** | Pointer to [**Category**](Category.md) | | [optional] +**Name** | **string** | | +**PhotoUrls** | **[]string** | | +**Tags** | Pointer to [**[]Tag**](Tag.md) | | [optional] +**Status** | Pointer to **string** | pet status in the store | [optional] + +## Methods + +### NewPet + +`func NewPet(name string, photoUrls []string, ) *Pet` + +NewPet instantiates a new Pet object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewPetWithDefaults + +`func NewPetWithDefaults() *Pet` + +NewPetWithDefaults instantiates a new Pet object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Pet) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Pet) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Pet) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Pet) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetCategory + +`func (o *Pet) GetCategory() Category` + +GetCategory returns the Category field if non-nil, zero value otherwise. + +### GetCategoryOk + +`func (o *Pet) GetCategoryOk() (*Category, bool)` + +GetCategoryOk returns a tuple with the Category field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetCategory + +`func (o *Pet) SetCategory(v Category)` + +SetCategory sets Category field to given value. + +### HasCategory + +`func (o *Pet) HasCategory() bool` + +HasCategory returns a boolean if a field has been set. + +### GetName + +`func (o *Pet) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Pet) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Pet) SetName(v string)` + +SetName sets Name field to given value. + + +### GetPhotoUrls + +`func (o *Pet) GetPhotoUrls() []string` + +GetPhotoUrls returns the PhotoUrls field if non-nil, zero value otherwise. + +### GetPhotoUrlsOk + +`func (o *Pet) GetPhotoUrlsOk() (*[]string, bool)` + +GetPhotoUrlsOk returns a tuple with the PhotoUrls field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetPhotoUrls + +`func (o *Pet) SetPhotoUrls(v []string)` + +SetPhotoUrls sets PhotoUrls field to given value. + + +### GetTags + +`func (o *Pet) GetTags() []Tag` + +GetTags returns the Tags field if non-nil, zero value otherwise. + +### GetTagsOk + +`func (o *Pet) GetTagsOk() (*[]Tag, bool)` + +GetTagsOk returns a tuple with the Tags field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetTags + +`func (o *Pet) SetTags(v []Tag)` + +SetTags sets Tags field to given value. + +### HasTags + +`func (o *Pet) HasTags() bool` + +HasTags returns a boolean if a field has been set. + +### GetStatus + +`func (o *Pet) GetStatus() string` + +GetStatus returns the Status field if non-nil, zero value otherwise. + +### GetStatusOk + +`func (o *Pet) GetStatusOk() (*string, bool)` + +GetStatusOk returns a tuple with the Status field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetStatus + +`func (o *Pet) SetStatus(v string)` + +SetStatus sets Status field to given value. + +### HasStatus + +`func (o *Pet) HasStatus() bool` + +HasStatus returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/PetAPI.md b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/PetAPI.md new file mode 100644 index 000000000000..0881d5fe198f --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/PetAPI.md @@ -0,0 +1,75 @@ +# \PetAPI + +All URIs are relative to *http://petstore.swagger.io/v2* + +Method | HTTP request | Description +------------- | ------------- | ------------- +[**AddPet**](PetAPI.md#AddPet) | **Post** /pet | Add a new pet to the store + + + +## AddPet + +> Pet AddPet(ctx).Pet(pet).Execute() + +Add a new pet to the store + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.AddPet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `AddPet`: Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.AddPet`: %v\n", resp) +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiAddPetRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **pet** | [**Pet**](Pet.md) | Pet object that needs to be added to the store | + +### Return type + +[**Pet**](Pet.md) + +### Authorization + +[petstore_auth](../README.md#petstore_auth) + +### HTTP request headers + +- **Content-Type**: application/json, application/xml +- **Accept**: application/xml, application/json + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Tag.md b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Tag.md new file mode 100644 index 000000000000..391be6b49009 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/docs/Tag.md @@ -0,0 +1,82 @@ +# Tag + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**Id** | Pointer to **int64** | | [optional] +**Name** | Pointer to **string** | | [optional] + +## Methods + +### NewTag + +`func NewTag() *Tag` + +NewTag instantiates a new Tag object +This constructor will assign default values to properties that have it defined, +and makes sure properties required by API are set, but the set of arguments +will change when the set of required properties is changed + +### NewTagWithDefaults + +`func NewTagWithDefaults() *Tag` + +NewTagWithDefaults instantiates a new Tag object +This constructor will only assign default values to properties that have it defined, +but it doesn't guarantee that properties required by API are set + +### GetId + +`func (o *Tag) GetId() int64` + +GetId returns the Id field if non-nil, zero value otherwise. + +### GetIdOk + +`func (o *Tag) GetIdOk() (*int64, bool)` + +GetIdOk returns a tuple with the Id field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetId + +`func (o *Tag) SetId(v int64)` + +SetId sets Id field to given value. + +### HasId + +`func (o *Tag) HasId() bool` + +HasId returns a boolean if a field has been set. + +### GetName + +`func (o *Tag) GetName() string` + +GetName returns the Name field if non-nil, zero value otherwise. + +### GetNameOk + +`func (o *Tag) GetNameOk() (*string, bool)` + +GetNameOk returns a tuple with the Name field if it's non-nil, zero value otherwise +and a boolean to check if the value has been set. + +### SetName + +`func (o *Tag) SetName(v string)` + +SetName sets Name field to given value. + +### HasName + +`func (o *Tag) HasName() bool` + +HasName returns a boolean if a field has been set. + + +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/git_push.sh b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/git_push.sh new file mode 100644 index 000000000000..f53a75d4fabe --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/git_push.sh @@ -0,0 +1,57 @@ +#!/bin/sh +# ref: https://help.github.com/articles/adding-an-existing-project-to-github-using-the-command-line/ +# +# Usage example: /bin/sh ./git_push.sh wing328 openapi-petstore-perl "minor update" "gitlab.com" + +git_user_id=$1 +git_repo_id=$2 +release_note=$3 +git_host=$4 + +if [ "$git_host" = "" ]; then + git_host="github.com" + echo "[INFO] No command line input provided. Set \$git_host to $git_host" +fi + +if [ "$git_user_id" = "" ]; then + git_user_id="GIT_USER_ID" + echo "[INFO] No command line input provided. Set \$git_user_id to $git_user_id" +fi + +if [ "$git_repo_id" = "" ]; then + git_repo_id="GIT_REPO_ID" + echo "[INFO] No command line input provided. Set \$git_repo_id to $git_repo_id" +fi + +if [ "$release_note" = "" ]; then + release_note="Minor update" + echo "[INFO] No command line input provided. Set \$release_note to $release_note" +fi + +# Initialize the local directory as a Git repository +git init + +# Adds the files in the local repository and stages them for commit. +git add . + +# Commits the tracked changes and prepares them to be pushed to a remote repository. +git commit -m "$release_note" + +# Sets the new remote +git_remote=$(git remote) +if [ "$git_remote" = "" ]; then # git remote not defined + + if [ "$GIT_TOKEN" = "" ]; then + echo "[INFO] \$GIT_TOKEN (environment variable) is not set. Using the git credential in your environment." + git remote add origin https://${git_host}/${git_user_id}/${git_repo_id}.git + else + git remote add origin https://${git_user_id}:"${GIT_TOKEN}"@${git_host}/${git_user_id}/${git_repo_id}.git + fi + +fi + +git pull origin master + +# Pushes (Forces) the changes in the local repository up to the remote repository +echo "Git pushing to https://${git_host}/${git_user_id}/${git_repo_id}.git" +git push origin master 2>&1 | grep -v 'To https' diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.mod b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.mod new file mode 100644 index 000000000000..7020685dc128 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.mod @@ -0,0 +1,7 @@ +module github.com/GIT_USER_ID/GIT_REPO_ID + +go 1.18 + +require ( + golang.org/x/oauth2 v0.0.0-20210323180902-22b0adad7558 +) diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.sum b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.sum new file mode 100644 index 000000000000..734252e68153 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/go.sum @@ -0,0 +1,13 @@ +cloud.google.com/go v0.34.0/go.mod h1:aQUYkXzVsufM+DwF1aE+0xfcU+56JwCaLick0ClmMTw= +github.com/golang/protobuf v1.2.0 h1:P3YflyNX/ehuJFLhxviNdFxQPkGK5cDcApsge1SqnvM= +github.com/golang/protobuf v1.2.0/go.mod h1:6lQm79b+lXiMfvg/cZm0SGofjICqVBUtrP5yJMmIC1U= +golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e h1:bRhVy7zSSasaqNksaRZiA5EEI+Ei4I1nO5Jh72wfHlg= +golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45 h1:SVwTIAaPC2U/AvvLNZ2a7OVsmBpC8L5BlwK1whH3hm0= +golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4 h1:YUO/7uOKsKeq9UokNS62b8FYywz3ker1l1vDZRCRefw= +golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ= +google.golang.org/appengine v1.4.0 h1:/wp5JvzpHIxhs/dumFmF7BXTf3Z+dd4uXta4kVyO508= +google.golang.org/appengine v1.4.0/go.mod h1:xpcJRLb0r/rnEns0DIKYYv+WjYCduHsrkT7/EB5XEv4= diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_category.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_category.go new file mode 100644 index 000000000000..9a4775dd9cbf --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_category.go @@ -0,0 +1,184 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// checks if the Category type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Category{} + +// Category A category for a pet +type Category struct { + Id *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _Category Category + +// NewCategory instantiates a new Category object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewCategory() *Category { + this := Category{} + return &this +} + +// NewCategoryWithDefaults instantiates a new Category object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewCategoryWithDefaults() *Category { + this := Category{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Category) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Category) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Category) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Category) SetId(v int64) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Category) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Category) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Category) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Category) SetName(v string) { + o.Name = &v +} + +func (o Category) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Category) UnmarshalJSON(data []byte) (err error) { + varCategory := _Category{} + + err = json.Unmarshal(data, &varCategory) + + if err != nil { + return err + } + + *o = Category(varCategory) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableCategory struct { + value *Category + isSet bool +} + +func (v NullableCategory) Get() *Category { + return v.value +} + +func (v *NullableCategory) Set(val *Category) { + v.value = val + v.isSet = true +} + +func (v NullableCategory) IsSet() bool { + return v.isSet +} + +func (v *NullableCategory) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableCategory(val *Category) *NullableCategory { + return &NullableCategory{value: val, isSet: true} +} + +func (v NullableCategory) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableCategory) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_pet.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_pet.go new file mode 100644 index 000000000000..77983744402d --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_pet.go @@ -0,0 +1,342 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" + "fmt" +) + +// checks if the Pet type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Pet{} + +// Pet A pet for sale in the pet store +type Pet struct { + Id *int64 `json:"id,omitempty"` + Category *Category `json:"category,omitempty"` + Name string `json:"name"` + PhotoUrls []string `json:"photoUrls"` + Tags []Tag `json:"tags,omitempty"` + // pet status in the store + // Deprecated + Status *string `json:"status,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _Pet Pet + +// NewPet instantiates a new Pet object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewPet(name string, photoUrls []string) *Pet { + this := Pet{} + this.Name = name + this.PhotoUrls = photoUrls + return &this +} + +// NewPetWithDefaults instantiates a new Pet object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewPetWithDefaults() *Pet { + this := Pet{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Pet) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Pet) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Pet) SetId(v int64) { + o.Id = &v +} + +// GetCategory returns the Category field value if set, zero value otherwise. +func (o *Pet) GetCategory() Category { + if o == nil || IsNil(o.Category) { + var ret Category + return ret + } + return *o.Category +} + +// GetCategoryOk returns a tuple with the Category field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetCategoryOk() (*Category, bool) { + if o == nil || IsNil(o.Category) { + return nil, false + } + return o.Category, true +} + +// HasCategory returns a boolean if a field has been set. +func (o *Pet) HasCategory() bool { + if o != nil && !IsNil(o.Category) { + return true + } + + return false +} + +// SetCategory gets a reference to the given Category and assigns it to the Category field. +func (o *Pet) SetCategory(v Category) { + o.Category = &v +} + +// GetName returns the Name field value +func (o *Pet) GetName() string { + if o == nil { + var ret string + return ret + } + + return o.Name +} + +// GetNameOk returns a tuple with the Name field value +// and a boolean to check if the value has been set. +func (o *Pet) GetNameOk() (*string, bool) { + if o == nil { + return nil, false + } + return &o.Name, true +} + +// SetName sets field value +func (o *Pet) SetName(v string) { + o.Name = v +} + +// GetPhotoUrls returns the PhotoUrls field value +func (o *Pet) GetPhotoUrls() []string { + if o == nil { + var ret []string + return ret + } + + return o.PhotoUrls +} + +// GetPhotoUrlsOk returns a tuple with the PhotoUrls field value +// and a boolean to check if the value has been set. +func (o *Pet) GetPhotoUrlsOk() ([]string, bool) { + if o == nil { + return nil, false + } + return o.PhotoUrls, true +} + +// SetPhotoUrls sets field value +func (o *Pet) SetPhotoUrls(v []string) { + o.PhotoUrls = v +} + +// GetTags returns the Tags field value if set, zero value otherwise. +func (o *Pet) GetTags() []Tag { + if o == nil || IsNil(o.Tags) { + var ret []Tag + return ret + } + return o.Tags +} + +// GetTagsOk returns a tuple with the Tags field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Pet) GetTagsOk() ([]Tag, bool) { + if o == nil || IsNil(o.Tags) { + return nil, false + } + return o.Tags, true +} + +// HasTags returns a boolean if a field has been set. +func (o *Pet) HasTags() bool { + if o != nil && !IsNil(o.Tags) { + return true + } + + return false +} + +// SetTags gets a reference to the given []Tag and assigns it to the Tags field. +func (o *Pet) SetTags(v []Tag) { + o.Tags = v +} + +// GetStatus returns the Status field value if set, zero value otherwise. +// Deprecated +func (o *Pet) GetStatus() string { + if o == nil || IsNil(o.Status) { + var ret string + return ret + } + return *o.Status +} + +// GetStatusOk returns a tuple with the Status field value if set, nil otherwise +// and a boolean to check if the value has been set. +// Deprecated +func (o *Pet) GetStatusOk() (*string, bool) { + if o == nil || IsNil(o.Status) { + return nil, false + } + return o.Status, true +} + +// HasStatus returns a boolean if a field has been set. +func (o *Pet) HasStatus() bool { + if o != nil && !IsNil(o.Status) { + return true + } + + return false +} + +// SetStatus gets a reference to the given string and assigns it to the Status field. +// Deprecated +func (o *Pet) SetStatus(v string) { + o.Status = &v +} + +func (o Pet) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Category) { + toSerialize["category"] = o.Category + } + toSerialize["name"] = o.Name + toSerialize["photoUrls"] = o.PhotoUrls + if !IsNil(o.Tags) { + toSerialize["tags"] = o.Tags + } + if !IsNil(o.Status) { + toSerialize["status"] = o.Status + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Pet) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + "photoUrls", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + + varPet := _Pet{} + + err = json.Unmarshal(data, &varPet) + + if err != nil { + return err + } + + *o = Pet(varPet) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "category") + delete(additionalProperties, "name") + delete(additionalProperties, "photoUrls") + delete(additionalProperties, "tags") + delete(additionalProperties, "status") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullablePet struct { + value *Pet + isSet bool +} + +func (v NullablePet) Get() *Pet { + return v.value +} + +func (v *NullablePet) Set(val *Pet) { + v.value = val + v.isSet = true +} + +func (v NullablePet) IsSet() bool { + return v.isSet +} + +func (v *NullablePet) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullablePet(val *Pet) *NullablePet { + return &NullablePet{value: val, isSet: true} +} + +func (v NullablePet) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullablePet) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_tag.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_tag.go new file mode 100644 index 000000000000..bba4be29c6ce --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/model_tag.go @@ -0,0 +1,184 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" +) + +// checks if the Tag type satisfies the MappedNullable interface at compile time +var _ MappedNullable = &Tag{} + +// Tag A tag for a pet +type Tag struct { + Id *int64 `json:"id,omitempty"` + Name *string `json:"name,omitempty"` + AdditionalProperties map[string]interface{} +} + +type _Tag Tag + +// NewTag instantiates a new Tag object +// This constructor will assign default values to properties that have it defined, +// and makes sure properties required by API are set, but the set of arguments +// will change when the set of required properties is changed +func NewTag() *Tag { + this := Tag{} + return &this +} + +// NewTagWithDefaults instantiates a new Tag object +// This constructor will only assign default values to properties that have it defined, +// but it doesn't guarantee that properties required by API are set +func NewTagWithDefaults() *Tag { + this := Tag{} + return &this +} + +// GetId returns the Id field value if set, zero value otherwise. +func (o *Tag) GetId() int64 { + if o == nil || IsNil(o.Id) { + var ret int64 + return ret + } + return *o.Id +} + +// GetIdOk returns a tuple with the Id field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Tag) GetIdOk() (*int64, bool) { + if o == nil || IsNil(o.Id) { + return nil, false + } + return o.Id, true +} + +// HasId returns a boolean if a field has been set. +func (o *Tag) HasId() bool { + if o != nil && !IsNil(o.Id) { + return true + } + + return false +} + +// SetId gets a reference to the given int64 and assigns it to the Id field. +func (o *Tag) SetId(v int64) { + o.Id = &v +} + +// GetName returns the Name field value if set, zero value otherwise. +func (o *Tag) GetName() string { + if o == nil || IsNil(o.Name) { + var ret string + return ret + } + return *o.Name +} + +// GetNameOk returns a tuple with the Name field value if set, nil otherwise +// and a boolean to check if the value has been set. +func (o *Tag) GetNameOk() (*string, bool) { + if o == nil || IsNil(o.Name) { + return nil, false + } + return o.Name, true +} + +// HasName returns a boolean if a field has been set. +func (o *Tag) HasName() bool { + if o != nil && !IsNil(o.Name) { + return true + } + + return false +} + +// SetName gets a reference to the given string and assigns it to the Name field. +func (o *Tag) SetName(v string) { + o.Name = &v +} + +func (o Tag) ToMap() (map[string]interface{}, error) { + toSerialize := map[string]interface{}{} + if !IsNil(o.Id) { + toSerialize["id"] = o.Id + } + if !IsNil(o.Name) { + toSerialize["name"] = o.Name + } + + for key, value := range o.AdditionalProperties { + toSerialize[key] = value + } + + return toSerialize, nil +} + +func (o *Tag) UnmarshalJSON(data []byte) (err error) { + varTag := _Tag{} + + err = json.Unmarshal(data, &varTag) + + if err != nil { + return err + } + + *o = Tag(varTag) + + additionalProperties := make(map[string]interface{}) + + if err = json.Unmarshal(data, &additionalProperties); err == nil { + delete(additionalProperties, "id") + delete(additionalProperties, "name") + o.AdditionalProperties = additionalProperties + } + + return err +} + +type NullableTag struct { + value *Tag + isSet bool +} + +func (v NullableTag) Get() *Tag { + return v.value +} + +func (v *NullableTag) Set(val *Tag) { + v.value = val + v.isSet = true +} + +func (v NullableTag) IsSet() bool { + return v.isSet +} + +func (v *NullableTag) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTag(val *Tag) *NullableTag { + return &NullableTag{value: val, isSet: true} +} + +func (v NullableTag) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableTag) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/pom.xml b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/pom.xml new file mode 100644 index 000000000000..be97a2bb8bcf --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/pom.xml @@ -0,0 +1,89 @@ + + 4.0.0 + org.openapitools + GoPetstoreUnmarshal + pom + 1.0.0 + Go Petstore Client Unmarshal test + + + + maven-dependency-plugin + + + package + + copy-dependencies + + + ${project.build.directory} + + + + + + org.codehaus.mojo + exec-maven-plugin + 1.2.1 + + + go-get-testify + pre-integration-test + + exec + + + go + + get + github.com/stretchr/testify/assert + + + + + go-get-oauth2 + pre-integration-test + + exec + + + go + + get + golang.org/x/oauth2 + + + + + go-get-context + pre-integration-test + + exec + + + go + + get + golang.org/x/net/context + + + + + go-test + integration-test + + exec + + + go + + test + -v + + + + + + + + diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/response.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/response.go new file mode 100644 index 000000000000..69c0239d6592 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/response.go @@ -0,0 +1,47 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "net/http" +) + +// APIResponse stores the API response returned by the server. +type APIResponse struct { + *http.Response `json:"-"` + Message string `json:"message,omitempty"` + // Operation is the name of the OpenAPI operation. + Operation string `json:"operation,omitempty"` + // RequestURL is the request URL. This value is always available, even if the + // embedded *http.Response is nil. + RequestURL string `json:"url,omitempty"` + // Method is the HTTP method used for the request. This value is always + // available, even if the embedded *http.Response is nil. + Method string `json:"method,omitempty"` + // Payload holds the contents of the response body (which may be nil or empty). + // This is provided here as the raw response.Body() reader will have already + // been drained. + Payload []byte `json:"-"` +} + +// NewAPIResponse returns a new APIResponse object. +func NewAPIResponse(r *http.Response) *APIResponse { + + response := &APIResponse{Response: r} + return response +} + +// NewAPIResponseWithError returns a new APIResponse object with the provided error message. +func NewAPIResponseWithError(errorMessage string) *APIResponse { + + response := &APIResponse{Message: errorMessage} + return response +} diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/test/api_pet_test.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/test/api_pet_test.go new file mode 100644 index 000000000000..b27e25dc0bb0 --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/test/api_pet_test.go @@ -0,0 +1,37 @@ +/* +OpenAPI Petstore + +Testing PetAPIService + +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); + +package petstore + +import ( + "context" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" + "testing" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func Test_petstore_PetAPIService(t *testing.T) { + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + + t.Run("Test PetAPIService AddPet", func(t *testing.T) { + + t.Skip("skip test") // remove to run test + + resp, httpRes, err := apiClient.PetAPI.AddPet(context.Background()).Execute() + + require.Nil(t, err) + require.NotNil(t, resp) + assert.Equal(t, 200, httpRes.StatusCode) + + }) + +} diff --git a/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/utils.go b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/utils.go new file mode 100644 index 000000000000..fd90061c63ff --- /dev/null +++ b/samples/openapi3/client/petstore/go-petstore-generateMarshalJSON-false/utils.go @@ -0,0 +1,347 @@ +/* +OpenAPI Petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +API version: 1.0.0 +*/ + +// Code generated by OpenAPI Generator (https://openapi-generator.tech); DO NOT EDIT. + +package petstore + +import ( + "encoding/json" + "reflect" + "time" +) + +// PtrBool is a helper routine that returns a pointer to given boolean value. +func PtrBool(v bool) *bool { return &v } + +// PtrInt is a helper routine that returns a pointer to given integer value. +func PtrInt(v int) *int { return &v } + +// PtrInt32 is a helper routine that returns a pointer to given integer value. +func PtrInt32(v int32) *int32 { return &v } + +// PtrInt64 is a helper routine that returns a pointer to given integer value. +func PtrInt64(v int64) *int64 { return &v } + +// PtrFloat32 is a helper routine that returns a pointer to given float value. +func PtrFloat32(v float32) *float32 { return &v } + +// PtrFloat64 is a helper routine that returns a pointer to given float value. +func PtrFloat64(v float64) *float64 { return &v } + +// PtrString is a helper routine that returns a pointer to given string value. +func PtrString(v string) *string { return &v } + +// PtrTime is helper routine that returns a pointer to given Time value. +func PtrTime(v time.Time) *time.Time { return &v } + +type NullableBool struct { + value *bool + isSet bool +} + +func (v NullableBool) Get() *bool { + return v.value +} + +func (v *NullableBool) Set(val *bool) { + v.value = val + v.isSet = true +} + +func (v NullableBool) IsSet() bool { + return v.isSet +} + +func (v *NullableBool) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableBool(val *bool) *NullableBool { + return &NullableBool{value: val, isSet: true} +} + +func (v NullableBool) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableBool) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt struct { + value *int + isSet bool +} + +func (v NullableInt) Get() *int { + return v.value +} + +func (v *NullableInt) Set(val *int) { + v.value = val + v.isSet = true +} + +func (v NullableInt) IsSet() bool { + return v.isSet +} + +func (v *NullableInt) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt(val *int) *NullableInt { + return &NullableInt{value: val, isSet: true} +} + +func (v NullableInt) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt32 struct { + value *int32 + isSet bool +} + +func (v NullableInt32) Get() *int32 { + return v.value +} + +func (v *NullableInt32) Set(val *int32) { + v.value = val + v.isSet = true +} + +func (v NullableInt32) IsSet() bool { + return v.isSet +} + +func (v *NullableInt32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt32(val *int32) *NullableInt32 { + return &NullableInt32{value: val, isSet: true} +} + +func (v NullableInt32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableInt64 struct { + value *int64 + isSet bool +} + +func (v NullableInt64) Get() *int64 { + return v.value +} + +func (v *NullableInt64) Set(val *int64) { + v.value = val + v.isSet = true +} + +func (v NullableInt64) IsSet() bool { + return v.isSet +} + +func (v *NullableInt64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableInt64(val *int64) *NullableInt64 { + return &NullableInt64{value: val, isSet: true} +} + +func (v NullableInt64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableInt64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat32 struct { + value *float32 + isSet bool +} + +func (v NullableFloat32) Get() *float32 { + return v.value +} + +func (v *NullableFloat32) Set(val *float32) { + v.value = val + v.isSet = true +} + +func (v NullableFloat32) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat32) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat32(val *float32) *NullableFloat32 { + return &NullableFloat32{value: val, isSet: true} +} + +func (v NullableFloat32) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat32) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableFloat64 struct { + value *float64 + isSet bool +} + +func (v NullableFloat64) Get() *float64 { + return v.value +} + +func (v *NullableFloat64) Set(val *float64) { + v.value = val + v.isSet = true +} + +func (v NullableFloat64) IsSet() bool { + return v.isSet +} + +func (v *NullableFloat64) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableFloat64(val *float64) *NullableFloat64 { + return &NullableFloat64{value: val, isSet: true} +} + +func (v NullableFloat64) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableFloat64) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableString struct { + value *string + isSet bool +} + +func (v NullableString) Get() *string { + return v.value +} + +func (v *NullableString) Set(val *string) { + v.value = val + v.isSet = true +} + +func (v NullableString) IsSet() bool { + return v.isSet +} + +func (v *NullableString) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableString(val *string) *NullableString { + return &NullableString{value: val, isSet: true} +} + +func (v NullableString) MarshalJSON() ([]byte, error) { + return json.Marshal(v.value) +} + +func (v *NullableString) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +type NullableTime struct { + value *time.Time + isSet bool +} + +func (v NullableTime) Get() *time.Time { + return v.value +} + +func (v *NullableTime) Set(val *time.Time) { + v.value = val + v.isSet = true +} + +func (v NullableTime) IsSet() bool { + return v.isSet +} + +func (v *NullableTime) Unset() { + v.value = nil + v.isSet = false +} + +func NewNullableTime(val *time.Time) *NullableTime { + return &NullableTime{value: val, isSet: true} +} + +func (v NullableTime) MarshalJSON() ([]byte, error) { + return v.value.MarshalJSON() +} + +func (v *NullableTime) UnmarshalJSON(src []byte) error { + v.isSet = true + return json.Unmarshal(src, &v.value) +} + +// IsNil checks if an input is nil +func IsNil(i interface{}) bool { + if i == nil { + return true + } + switch reflect.TypeOf(i).Kind() { + case reflect.Chan, reflect.Func, reflect.Map, reflect.Ptr, reflect.UnsafePointer, reflect.Interface, reflect.Slice: + return reflect.ValueOf(i).IsNil() + case reflect.Array: + return reflect.ValueOf(i).IsZero() + } + return false +} + +type MappedNullable interface { + ToMap() (map[string]interface{}, error) +} diff --git a/samples/openapi3/client/petstore/go/api_client_test.go b/samples/openapi3/client/petstore/go/api_client_test.go new file mode 100644 index 000000000000..976eb4de5011 --- /dev/null +++ b/samples/openapi3/client/petstore/go/api_client_test.go @@ -0,0 +1,62 @@ +package main + +import ( + "testing" + + sw "go-petstore" +) + +type testCase struct { + String string + ShouldMatch bool +} + +func TestJsonCheck(t *testing.T) { + testCases := []testCase{ + {"application/json", true}, + {"application/vnd.org.application+json", true}, + {"application/hal+json", true}, + {"text/json", true}, + {"text/vnd.org.application+json", true}, + {"text/hal+json", true}, + + {"application/bson", false}, + {"application/+json", false}, + {"text/bson", false}, + {"text/+json", false}, + + {"zip/json", false}, + } + + for _, c := range testCases { + actual := sw.JsonCheck.MatchString(c.String) + if actual != c.ShouldMatch { + t.Errorf("Expected %s to result in %v but got %v", c.String, c.ShouldMatch, actual) + } + } +} + +func TestXmlRegex(t *testing.T) { + testCases := []testCase{ + {"application/xml", true}, + {"application/vnd.org.application+xml", true}, + {"application/hal+xml", true}, + {"text/xml", true}, + {"text/vnd.org.application+xml", true}, + {"text/hal+xml", true}, + + {"application/bmx", false}, + {"application/+xml", false}, + {"text/bmx", false}, + {"text/+xml", false}, + + {"zip/xml", false}, + } + + for _, c := range testCases { + actual := sw.XmlCheck.MatchString(c.String) + if actual != c.ShouldMatch { + t.Errorf("Expected %s to result in %v but got %v", c.String, c.ShouldMatch, actual) + } + } +} diff --git a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/go/go-petstore/README.md b/samples/openapi3/client/petstore/go/go-petstore/README.md index 262cba3e199a..209ef6366a0e 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/README.md +++ b/samples/openapi3/client/petstore/go/go-petstore/README.md @@ -13,7 +13,7 @@ This API client was generated by the [OpenAPI Generator](https://openapi-generat Install the following dependencies: -```shell +```sh go get github.com/stretchr/testify/assert go get golang.org/x/oauth2 go get golang.org/x/net/context @@ -21,13 +21,13 @@ go get golang.org/x/net/context Put the package under your project folder and add the following in import: -```golang +```go import petstore "github.com/GIT_USER_ID/GIT_REPO_ID" ``` To use a proxy, set the environment variable `HTTP_PROXY`: -```golang +```go os.Setenv("HTTP_PROXY", "http://proxy_name:proxy_port") ``` @@ -37,17 +37,17 @@ Default configuration comes with `Servers` field that contains server objects as ### Select Server Configuration -For using other server than the one defined on index 0 set context value `sw.ContextServerIndex` of type `int`. +For using other server than the one defined on index 0 set context value `petstore.ContextServerIndex` of type `int`. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextServerIndex, 1) ``` ### Templated Server URL -Templated server URL is formatted using default variables from configuration or from context value `sw.ContextServerVariables` of type `map[string]string`. +Templated server URL is formatted using default variables from configuration or from context value `petstore.ContextServerVariables` of type `map[string]string`. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextServerVariables, map[string]string{ "basePath": "v2", }) @@ -59,9 +59,9 @@ Note, enum values are always validated and all unused variables are silently ign Each operation can use different server URL defined using `OperationServers` map in the `Configuration`. An operation is uniquely identified by `"{classname}Service.{nickname}"` string. -Similar rules for overriding default operation server index and variables applies by using `sw.ContextOperationServerIndices` and `sw.ContextOperationServerVariables` context maps. +Similar rules for overriding default operation server index and variables applies by using `petstore.ContextOperationServerIndices` and `petstore.ContextOperationServerVariables` context maps. -```golang +```go ctx := context.WithValue(context.Background(), petstore.ContextOperationServerIndices, map[string]int{ "{classname}Service.{nickname}": 2, }) @@ -86,6 +86,7 @@ Class | Method | HTTP request | Description *FakeAPI* | [**FakeOuterNumberSerialize**](docs/FakeAPI.md#fakeouternumberserialize) | **Post** /fake/outer/number | *FakeAPI* | [**FakeOuterStringSerialize**](docs/FakeAPI.md#fakeouterstringserialize) | **Post** /fake/outer/string | *FakeAPI* | [**GetParameterNameMapping**](docs/FakeAPI.md#getparameternamemapping) | **Get** /fake/parameter-name-mapping | parameter name mapping test +*FakeAPI* | [**TestAdditionalPropertiesReference**](docs/FakeAPI.md#testadditionalpropertiesreference) | **Post** /fake/additionalProperties-reference | test referenced additionalProperties *FakeAPI* | [**TestBodyWithFileSchema**](docs/FakeAPI.md#testbodywithfileschema) | **Put** /fake/body-with-file-schema | *FakeAPI* | [**TestBodyWithQueryParams**](docs/FakeAPI.md#testbodywithqueryparams) | **Put** /fake/body-with-query-params | *FakeAPI* | [**TestClientModel**](docs/FakeAPI.md#testclientmodel) | **Patch** /fake | To test \"client\" model @@ -205,20 +206,20 @@ Authentication schemes defined for the API: Example -```golang -auth := context.WithValue(context.Background(), sw.ContextAccessToken, "ACCESSTOKENSTRING") +```go +auth := context.WithValue(context.Background(), petstore.ContextAccessToken, "ACCESSTOKENSTRING") r, err := client.Service.Operation(auth, args) ``` Or via OAuth2 module to automatically refresh tokens and perform user authentication. -```golang +```go import "golang.org/x/oauth2" /* Perform OAuth2 round trip request and obtain a token */ tokenSource := oauth2cfg.TokenSource(createContext(httpClient), &token) -auth := context.WithValue(oauth2.NoContext, sw.ContextOAuth2, tokenSource) +auth := context.WithValue(oauth2.NoContext, petstore.ContextOAuth2, tokenSource) r, err := client.Service.Operation(auth, args) ``` @@ -232,11 +233,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + petstore.ContextAPIKeys, + map[string]petstore.APIKey{ "api_key": {Key: "API_KEY_STRING"}, }, ) @@ -253,11 +254,11 @@ Note, each API key must be added to a map of `map[string]APIKey` where the key i Example -```golang +```go auth := context.WithValue( context.Background(), - sw.ContextAPIKeys, - map[string]sw.APIKey{ + petstore.ContextAPIKeys, + map[string]petstore.APIKey{ "api_key_query": {Key: "API_KEY_STRING"}, }, ) @@ -270,10 +271,10 @@ r, err := client.Service.Operation(auth, args) Example -```golang -auth := context.WithValue(context.Background(), sw.ContextBasicAuth, sw.BasicAuth{ - UserName: "username", - Password: "password", +```go +auth := context.WithValue(context.Background(), petstore.ContextBasicAuth, petstore.BasicAuth{ + UserName: "username", + Password: "password", }) r, err := client.Service.Operation(auth, args) ``` @@ -284,8 +285,8 @@ r, err := client.Service.Operation(auth, args) Example -```golang -auth := context.WithValue(context.Background(), sw.ContextAccessToken, "BEARER_TOKEN_STRING") +```go +auth := context.WithValue(context.Background(), petstore.ContextAccessToken, "BEARER_TOKEN_STRING") r, err := client.Service.Operation(auth, args) ``` @@ -295,21 +296,21 @@ r, err := client.Service.Operation(auth, args) Example -```golang - authConfig := client.HttpSignatureAuth{ +```go + authConfig := petstore.HttpSignatureAuth{ KeyId: "my-key-id", PrivateKeyPath: "rsa.pem", Passphrase: "my-passphrase", - SigningScheme: sw.HttpSigningSchemeHs2019, + SigningScheme: petstore.HttpSigningSchemeHs2019, SignedHeaders: []string{ - sw.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. - sw.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. + petstore.HttpSignatureParameterRequestTarget, // The special (request-target) parameter expresses the HTTP request target. + petstore.HttpSignatureParameterCreated, // Time when request was signed, formatted as a Unix timestamp integer value. "Host", // The Host request header specifies the domain name of the server, and optionally the TCP port number. "Date", // The date and time at which the message was originated. "Content-Type", // The Media type of the body of the request. "Digest", // A cryptographic digest of the request body. }, - SigningAlgorithm: sw.HttpSigningAlgorithmRsaPSS, + SigningAlgorithm: petstore.HttpSigningAlgorithmRsaPSS, SignatureMaxValidity: 5 * time.Minute, } var authCtx context.Context diff --git a/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml b/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml index f008fd5193ab..f41ffaf5079f 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml +++ b/samples/openapi3/client/petstore/go/go-petstore/api/openapi.yaml @@ -906,6 +906,23 @@ paths: summary: test json serialization of form data tags: - fake + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake /fake/inline-additionalProperties: post: description: "" @@ -1764,6 +1781,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go index 1cccc452d974..afb4a610251f 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_fake.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_fake.go @@ -103,6 +103,19 @@ type FakeAPI interface { // GetParameterNameMappingExecute executes the request GetParameterNameMappingExecute(r ApiGetParameterNameMappingRequest) (*http.Response, error) + /* + TestAdditionalPropertiesReference test referenced additionalProperties + + + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestAdditionalPropertiesReferenceRequest + */ + TestAdditionalPropertiesReference(ctx context.Context) ApiTestAdditionalPropertiesReferenceRequest + + // TestAdditionalPropertiesReferenceExecute executes the request + TestAdditionalPropertiesReferenceExecute(r ApiTestAdditionalPropertiesReferenceRequest) (*http.Response, error) + /* TestBodyWithFileSchema Method for TestBodyWithFileSchema @@ -924,6 +937,106 @@ func (a *FakeAPIService) GetParameterNameMappingExecute(r ApiGetParameterNameMap return localVarHTTPResponse, nil } +type ApiTestAdditionalPropertiesReferenceRequest struct { + ctx context.Context + ApiService FakeAPI + requestBody *map[string]interface{} +} + +// request body +func (r ApiTestAdditionalPropertiesReferenceRequest) RequestBody(requestBody map[string]interface{}) ApiTestAdditionalPropertiesReferenceRequest { + r.requestBody = &requestBody + return r +} + +func (r ApiTestAdditionalPropertiesReferenceRequest) Execute() (*http.Response, error) { + return r.ApiService.TestAdditionalPropertiesReferenceExecute(r) +} + +/* +TestAdditionalPropertiesReference test referenced additionalProperties + + + + @param ctx context.Context - for authentication, logging, cancellation, deadlines, tracing, etc. Passed from http.Request or context.Background(). + @return ApiTestAdditionalPropertiesReferenceRequest +*/ +func (a *FakeAPIService) TestAdditionalPropertiesReference(ctx context.Context) ApiTestAdditionalPropertiesReferenceRequest { + return ApiTestAdditionalPropertiesReferenceRequest{ + ApiService: a, + ctx: ctx, + } +} + +// Execute executes the request +func (a *FakeAPIService) TestAdditionalPropertiesReferenceExecute(r ApiTestAdditionalPropertiesReferenceRequest) (*http.Response, error) { + var ( + localVarHTTPMethod = http.MethodPost + localVarPostBody interface{} + formFiles []formFile + ) + + localBasePath, err := a.client.cfg.ServerURLWithContext(r.ctx, "FakeAPIService.TestAdditionalPropertiesReference") + if err != nil { + return nil, &GenericOpenAPIError{error: err.Error()} + } + + localVarPath := localBasePath + "/fake/additionalProperties-reference" + + localVarHeaderParams := make(map[string]string) + localVarQueryParams := url.Values{} + localVarFormParams := url.Values{} + if r.requestBody == nil { + return nil, reportError("requestBody is required and must be specified") + } + + // to determine the Content-Type header + localVarHTTPContentTypes := []string{"application/json"} + + // set Content-Type header + localVarHTTPContentType := selectHeaderContentType(localVarHTTPContentTypes) + if localVarHTTPContentType != "" { + localVarHeaderParams["Content-Type"] = localVarHTTPContentType + } + + // to determine the Accept header + localVarHTTPHeaderAccepts := []string{} + + // set Accept header + localVarHTTPHeaderAccept := selectHeaderAccept(localVarHTTPHeaderAccepts) + if localVarHTTPHeaderAccept != "" { + localVarHeaderParams["Accept"] = localVarHTTPHeaderAccept + } + // body params + localVarPostBody = r.requestBody + req, err := a.client.prepareRequest(r.ctx, localVarPath, localVarHTTPMethod, localVarPostBody, localVarHeaderParams, localVarQueryParams, localVarFormParams, formFiles) + if err != nil { + return nil, err + } + + localVarHTTPResponse, err := a.client.callAPI(req) + if err != nil || localVarHTTPResponse == nil { + return localVarHTTPResponse, err + } + + localVarBody, err := io.ReadAll(localVarHTTPResponse.Body) + localVarHTTPResponse.Body.Close() + localVarHTTPResponse.Body = io.NopCloser(bytes.NewBuffer(localVarBody)) + if err != nil { + return localVarHTTPResponse, err + } + + if localVarHTTPResponse.StatusCode >= 300 { + newErr := &GenericOpenAPIError{ + body: localVarBody, + error: localVarHTTPResponse.Status, + } + return localVarHTTPResponse, newErr + } + + return localVarHTTPResponse, nil +} + type ApiTestBodyWithFileSchemaRequest struct { ctx context.Context ApiService FakeAPI @@ -1451,8 +1564,6 @@ func (a *FakeAPIService) TestEndpointParametersExecute(r ApiTestEndpointParamete var binaryLocalVarFileBytes []byte binaryLocalVarFormFileName = "binary" - - binaryLocalVarFile := r.binary if binaryLocalVarFile != nil { diff --git a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go index 0435d51af897..6a3556ec4976 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/api_pet.go +++ b/samples/openapi3/client/petstore/go/go-petstore/api_pet.go @@ -999,8 +999,6 @@ func (a *PetAPIService) UploadFileExecute(r ApiUploadFileRequest) (*ApiResponse, var fileLocalVarFileBytes []byte fileLocalVarFormFileName = "file" - - fileLocalVarFile := r.file if fileLocalVarFile != nil { @@ -1139,8 +1137,6 @@ func (a *PetAPIService) UploadFileWithRequiredFileExecute(r ApiUploadFileWithReq var requiredFileLocalVarFileBytes []byte requiredFileLocalVarFormFileName = "requiredFile" - - requiredFileLocalVarFile := r.requiredFile if requiredFileLocalVarFile != nil { diff --git a/samples/openapi3/client/petstore/go/go-petstore/client.go b/samples/openapi3/client/petstore/go/go-petstore/client.go index f807178e4428..aab1677559dc 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/client.go +++ b/samples/openapi3/client/petstore/go/go-petstore/client.go @@ -36,8 +36,8 @@ import ( ) var ( - jsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:vnd\.[^;]+\+)?json)`) - xmlCheck = regexp.MustCompile(`(?i:(?:application|text)/xml)`) + JsonCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?json)`) + XmlCheck = regexp.MustCompile(`(?i:(?:application|text)/(?:[^;]+\+)?xml)`) queryParamSplit = regexp.MustCompile(`(^|&)([^&]+)`) queryDescape = strings.NewReplacer( "%5B", "[", "%5D", "]" ) ) @@ -486,7 +486,6 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = f.Seek(0, io.SeekStart) - err = os.Remove(f.Name()) return } if f, ok := v.(**os.File); ok { @@ -499,16 +498,15 @@ func (c *APIClient) decode(v interface{}, b []byte, contentType string) (err err return } _, err = (*f).Seek(0, io.SeekStart) - err = os.Remove((*f).Name()) return } - if xmlCheck.MatchString(contentType) { + if XmlCheck.MatchString(contentType) { if err = xml.Unmarshal(b, v); err != nil { return err } return nil } - if jsonCheck.MatchString(contentType) { + if JsonCheck.MatchString(contentType) { if actualObj, ok := v.(interface{ GetActualInstance() interface{} }); ok { // oneOf, anyOf schemas if unmarshalObj, ok := actualObj.(interface{ UnmarshalJSON([]byte) error }); ok { // make sure it has UnmarshalJSON defined if err = unmarshalObj.UnmarshalJSON(b); err != nil { @@ -573,9 +571,9 @@ func setBody(body interface{}, contentType string) (bodyBuf *bytes.Buffer, err e _, err = bodyBuf.WriteString(s) } else if s, ok := body.(*string); ok { _, err = bodyBuf.WriteString(*s) - } else if jsonCheck.MatchString(contentType) { + } else if JsonCheck.MatchString(contentType) { err = json.NewEncoder(bodyBuf).Encode(body) - } else if xmlCheck.MatchString(contentType) { + } else if XmlCheck.MatchString(contentType) { var bs []byte bs, err = xml.Marshal(body) if err == nil { diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md index d684cacbae79..3f01ccff9ef9 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/AnotherFakeAPI.md @@ -22,24 +22,24 @@ To test special tags package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - client := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.AnotherFakeAPI.Call123TestSpecialTags(context.Background()).Client(client).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `AnotherFakeAPI.Call123TestSpecialTags``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `Call123TestSpecialTags`: Client - fmt.Fprintf(os.Stdout, "Response from `AnotherFakeAPI.Call123TestSpecialTags`: %v\n", resp) + client := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.AnotherFakeAPI.Call123TestSpecialTags(context.Background()).Client(client).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `AnotherFakeAPI.Call123TestSpecialTags``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `Call123TestSpecialTags`: Client + fmt.Fprintf(os.Stdout, "Response from `AnotherFakeAPI.Call123TestSpecialTags`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/DefaultAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/DefaultAPI.md index b07855b1a535..70aee51f630b 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/DefaultAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/DefaultAPI.md @@ -20,23 +20,23 @@ Method | HTTP request | Description package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.DefaultAPI.FooGet(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `DefaultAPI.FooGet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FooGet`: FooGetDefaultResponse - fmt.Fprintf(os.Stdout, "Response from `DefaultAPI.FooGet`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.DefaultAPI.FooGet(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `DefaultAPI.FooGet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FooGet`: FooGetDefaultResponse + fmt.Fprintf(os.Stdout, "Response from `DefaultAPI.FooGet`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeAPI.md index 87d1d6443e91..a8b1f40e9d0f 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeAPI.md @@ -10,6 +10,7 @@ Method | HTTP request | Description [**FakeOuterNumberSerialize**](FakeAPI.md#FakeOuterNumberSerialize) | **Post** /fake/outer/number | [**FakeOuterStringSerialize**](FakeAPI.md#FakeOuterStringSerialize) | **Post** /fake/outer/string | [**GetParameterNameMapping**](FakeAPI.md#GetParameterNameMapping) | **Get** /fake/parameter-name-mapping | parameter name mapping test +[**TestAdditionalPropertiesReference**](FakeAPI.md#TestAdditionalPropertiesReference) | **Post** /fake/additionalProperties-reference | test referenced additionalProperties [**TestBodyWithFileSchema**](FakeAPI.md#TestBodyWithFileSchema) | **Put** /fake/body-with-file-schema | [**TestBodyWithQueryParams**](FakeAPI.md#TestBodyWithQueryParams) | **Put** /fake/body-with-query-params | [**TestClientModel**](FakeAPI.md#TestClientModel) | **Patch** /fake | To test \"client\" model @@ -37,23 +38,23 @@ Health check endpoint package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeHealthGet(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeHealthGet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeHealthGet`: HealthCheckResult - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeHealthGet`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeHealthGet(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeHealthGet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeHealthGet`: HealthCheckResult + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeHealthGet`: %v\n", resp) } ``` @@ -98,24 +99,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := true // bool | Input boolean as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterBooleanSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterBooleanSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterBooleanSerialize`: bool - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterBooleanSerialize`: %v\n", resp) + body := true // bool | Input boolean as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterBooleanSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterBooleanSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterBooleanSerialize`: bool + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterBooleanSerialize`: %v\n", resp) } ``` @@ -164,24 +165,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - outerComposite := *openapiclient.NewOuterComposite() // OuterComposite | Input composite as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterCompositeSerialize(context.Background()).OuterComposite(outerComposite).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterCompositeSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterCompositeSerialize`: OuterComposite - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterCompositeSerialize`: %v\n", resp) + outerComposite := *openapiclient.NewOuterComposite() // OuterComposite | Input composite as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterCompositeSerialize(context.Background()).OuterComposite(outerComposite).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterCompositeSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterCompositeSerialize`: OuterComposite + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterCompositeSerialize`: %v\n", resp) } ``` @@ -230,24 +231,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := float32(8.14) // float32 | Input number as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterNumberSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterNumberSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterNumberSerialize`: float32 - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterNumberSerialize`: %v\n", resp) + body := float32(8.14) // float32 | Input number as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterNumberSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterNumberSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterNumberSerialize`: float32 + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterNumberSerialize`: %v\n", resp) } ``` @@ -296,24 +297,24 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - body := "body_example" // string | Input string as post body (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.FakeOuterStringSerialize(context.Background()).Body(body).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterStringSerialize``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FakeOuterStringSerialize`: string - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterStringSerialize`: %v\n", resp) + body := "body_example" // string | Input string as post body (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.FakeOuterStringSerialize(context.Background()).Body(body).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.FakeOuterStringSerialize``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FakeOuterStringSerialize`: string + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.FakeOuterStringSerialize`: %v\n", resp) } ``` @@ -360,25 +361,25 @@ parameter name mapping test package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - underscoreType := int64(789) // int64 | _type - type_ := "type__example" // string | type - typeWithUnderscore := "typeWithUnderscore_example" // string | type_ - httpDebugOption := "httpDebugOption_example" // string | http debug option (to test parameter naming option) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.GetParameterNameMapping(context.Background()).UnderscoreType(underscoreType).Type_(type_).TypeWithUnderscore(typeWithUnderscore).HttpDebugOption(httpDebugOption).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.GetParameterNameMapping``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + underscoreType := int64(789) // int64 | _type + type_ := "type__example" // string | type + typeWithUnderscore := "typeWithUnderscore_example" // string | type_ + httpDebugOption := "httpDebugOption_example" // string | http debug option (to test parameter naming option) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.GetParameterNameMapping(context.Background()).UnderscoreType(underscoreType).Type_(type_).TypeWithUnderscore(typeWithUnderscore).HttpDebugOption(httpDebugOption).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.GetParameterNameMapping``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -416,6 +417,70 @@ No authorization required [[Back to README]](../README.md) +## TestAdditionalPropertiesReference + +> TestAdditionalPropertiesReference(ctx).RequestBody(requestBody).Execute() + +test referenced additionalProperties + + + +### Example + +```go +package main + +import ( + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" +) + +func main() { + requestBody := map[string]interface{}{"key": interface{}(123)} // map[string]interface{} | request body + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestAdditionalPropertiesReference(context.Background()).RequestBody(requestBody).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestAdditionalPropertiesReference``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } +} +``` + +### Path Parameters + + + +### Other Parameters + +Other parameters are passed through a pointer to a apiTestAdditionalPropertiesReferenceRequest struct via the builder pattern + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **requestBody** | **map[string]interface{}** | request body | + +### Return type + + (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) +[[Back to Model list]](../README.md#documentation-for-models) +[[Back to README]](../README.md) + + ## TestBodyWithFileSchema > TestBodyWithFileSchema(ctx).FileSchemaTestClass(fileSchemaTestClass).Execute() @@ -430,22 +495,22 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - fileSchemaTestClass := *openapiclient.NewFileSchemaTestClass() // FileSchemaTestClass | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestBodyWithFileSchema(context.Background()).FileSchemaTestClass(fileSchemaTestClass).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithFileSchema``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + fileSchemaTestClass := *openapiclient.NewFileSchemaTestClass() // FileSchemaTestClass | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestBodyWithFileSchema(context.Background()).FileSchemaTestClass(fileSchemaTestClass).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithFileSchema``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -492,23 +557,23 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - query := "query_example" // string | - user := *openapiclient.NewUser() // User | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestBodyWithQueryParams(context.Background()).Query(query).User(user).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithQueryParams``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + query := "query_example" // string | + user := *openapiclient.NewUser() // User | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestBodyWithQueryParams(context.Background()).Query(query).User(user).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestBodyWithQueryParams``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -558,24 +623,24 @@ To test \"client\" model package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - client := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.TestClientModel(context.Background()).Client(client).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestClientModel``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestClientModel`: Client - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestClientModel`: %v\n", resp) + client := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.TestClientModel(context.Background()).Client(client).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestClientModel``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestClientModel`: Client + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestClientModel`: %v\n", resp) } ``` @@ -624,36 +689,36 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン package main import ( - "context" - "fmt" - "os" + "context" + "fmt" + "os" "time" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - number := float32(8.14) // float32 | None - double := float64(1.2) // float64 | None - patternWithoutDelimiter := "patternWithoutDelimiter_example" // string | None - byte_ := string(BYTE_ARRAY_DATA_HERE) // string | None - integer := int32(56) // int32 | None (optional) - int32_ := int32(56) // int32 | None (optional) - int64_ := int64(789) // int64 | None (optional) - float := float32(3.4) // float32 | None (optional) - string_ := "string__example" // string | None (optional) - binary := os.NewFile(1234, "some_file") // *os.File | None (optional) - date := time.Now() // string | None (optional) - dateTime := time.Now() // time.Time | None (optional) - password := "password_example" // string | None (optional) - callback := "callback_example" // string | None (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestEndpointParameters(context.Background()).Number(number).Double(double).PatternWithoutDelimiter(patternWithoutDelimiter).Byte_(byte_).Integer(integer).Int32_(int32_).Int64_(int64_).Float(float).String_(string_).Binary(binary).Date(date).DateTime(dateTime).Password(password).Callback(callback).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEndpointParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + number := float32(8.14) // float32 | None + double := float64(1.2) // float64 | None + patternWithoutDelimiter := "patternWithoutDelimiter_example" // string | None + byte_ := string(BYTE_ARRAY_DATA_HERE) // string | None + integer := int32(56) // int32 | None (optional) + int32_ := int32(56) // int32 | None (optional) + int64_ := int64(789) // int64 | None (optional) + float := float32(3.4) // float32 | None (optional) + string_ := "string__example" // string | None (optional) + binary := os.NewFile(1234, "some_file") // *os.File | None (optional) + date := time.Now() // string | None (optional) + dateTime := time.Now() // time.Time | None (optional) + password := "password_example" // string | None (optional) + callback := "callback_example" // string | None (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestEndpointParameters(context.Background()).Number(number).Double(double).PatternWithoutDelimiter(patternWithoutDelimiter).Byte_(byte_).Integer(integer).Int32_(int32_).Int64_(int64_).Float(float).String_(string_).Binary(binary).Date(date).DateTime(dateTime).Password(password).Callback(callback).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEndpointParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -715,29 +780,29 @@ To test enum parameters package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - enumHeaderStringArray := []string{"EnumHeaderStringArray_example"} // []string | Header parameter enum test (string array) (optional) - enumHeaderString := "enumHeaderString_example" // string | Header parameter enum test (string) (optional) (default to "-efg") - enumQueryStringArray := []string{"EnumQueryStringArray_example"} // []string | Query parameter enum test (string array) (optional) - enumQueryString := "enumQueryString_example" // string | Query parameter enum test (string) (optional) (default to "-efg") - enumQueryInteger := int32(56) // int32 | Query parameter enum test (double) (optional) - enumQueryDouble := float64(1.2) // float64 | Query parameter enum test (double) (optional) - enumFormStringArray := []string{"Inner_example"} // []string | Form parameter enum test (string array) (optional) (default to "$") - enumFormString := "enumFormString_example" // string | Form parameter enum test (string) (optional) (default to "-efg") - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestEnumParameters(context.Background()).EnumHeaderStringArray(enumHeaderStringArray).EnumHeaderString(enumHeaderString).EnumQueryStringArray(enumQueryStringArray).EnumQueryString(enumQueryString).EnumQueryInteger(enumQueryInteger).EnumQueryDouble(enumQueryDouble).EnumFormStringArray(enumFormStringArray).EnumFormString(enumFormString).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEnumParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + enumHeaderStringArray := []string{"EnumHeaderStringArray_example"} // []string | Header parameter enum test (string array) (optional) + enumHeaderString := "enumHeaderString_example" // string | Header parameter enum test (string) (optional) (default to "-efg") + enumQueryStringArray := []string{"EnumQueryStringArray_example"} // []string | Query parameter enum test (string array) (optional) + enumQueryString := "enumQueryString_example" // string | Query parameter enum test (string) (optional) (default to "-efg") + enumQueryInteger := int32(56) // int32 | Query parameter enum test (double) (optional) + enumQueryDouble := float64(1.2) // float64 | Query parameter enum test (double) (optional) + enumFormStringArray := []string{"Inner_example"} // []string | Form parameter enum test (string array) (optional) (default to "$") + enumFormString := "enumFormString_example" // string | Form parameter enum test (string) (optional) (default to "-efg") + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestEnumParameters(context.Background()).EnumHeaderStringArray(enumHeaderStringArray).EnumHeaderString(enumHeaderString).EnumQueryStringArray(enumQueryStringArray).EnumQueryString(enumQueryString).EnumQueryInteger(enumQueryInteger).EnumQueryDouble(enumQueryDouble).EnumFormStringArray(enumFormStringArray).EnumFormString(enumFormString).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestEnumParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -793,27 +858,27 @@ Fake endpoint to test group parameters (optional) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - requiredStringGroup := int32(56) // int32 | Required String in group parameters - requiredBooleanGroup := true // bool | Required Boolean in group parameters - requiredInt64Group := int64(789) // int64 | Required Integer in group parameters - stringGroup := int32(56) // int32 | String in group parameters (optional) - booleanGroup := true // bool | Boolean in group parameters (optional) - int64Group := int64(789) // int64 | Integer in group parameters (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestGroupParameters(context.Background()).RequiredStringGroup(requiredStringGroup).RequiredBooleanGroup(requiredBooleanGroup).RequiredInt64Group(requiredInt64Group).StringGroup(stringGroup).BooleanGroup(booleanGroup).Int64Group(int64Group).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestGroupParameters``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + requiredStringGroup := int32(56) // int32 | Required String in group parameters + requiredBooleanGroup := true // bool | Required Boolean in group parameters + requiredInt64Group := int64(789) // int64 | Required Integer in group parameters + stringGroup := int32(56) // int32 | String in group parameters (optional) + booleanGroup := true // bool | Boolean in group parameters (optional) + int64Group := int64(789) // int64 | Integer in group parameters (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestGroupParameters(context.Background()).RequiredStringGroup(requiredStringGroup).RequiredBooleanGroup(requiredBooleanGroup).RequiredInt64Group(requiredInt64Group).StringGroup(stringGroup).BooleanGroup(booleanGroup).Int64Group(int64Group).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestGroupParameters``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -867,22 +932,22 @@ test inline additionalProperties package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - requestBody := map[string]string{"key": "Inner_example"} // map[string]string | request body - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestInlineAdditionalProperties(context.Background()).RequestBody(requestBody).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineAdditionalProperties``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + requestBody := map[string]string{"key": "Inner_example"} // map[string]string | request body + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestInlineAdditionalProperties(context.Background()).RequestBody(requestBody).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineAdditionalProperties``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -931,22 +996,22 @@ test inline free-form additionalProperties package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - testInlineFreeformAdditionalPropertiesRequest := *openapiclient.NewTestInlineFreeformAdditionalPropertiesRequest() // TestInlineFreeformAdditionalPropertiesRequest | request body - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestInlineFreeformAdditionalProperties(context.Background()).TestInlineFreeformAdditionalPropertiesRequest(testInlineFreeformAdditionalPropertiesRequest).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineFreeformAdditionalProperties``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + testInlineFreeformAdditionalPropertiesRequest := *openapiclient.NewTestInlineFreeformAdditionalPropertiesRequest() // TestInlineFreeformAdditionalPropertiesRequest | request body + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestInlineFreeformAdditionalProperties(context.Background()).TestInlineFreeformAdditionalPropertiesRequest(testInlineFreeformAdditionalPropertiesRequest).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestInlineFreeformAdditionalProperties``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -995,23 +1060,23 @@ test json serialization of form data package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - param := "param_example" // string | field1 - param2 := "param2_example" // string | field2 - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestJsonFormData(context.Background()).Param(param).Param2(param2).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestJsonFormData``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + param := "param_example" // string | field1 + param2 := "param2_example" // string | field2 + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestJsonFormData(context.Background()).Param(param).Param2(param2).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestJsonFormData``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -1059,23 +1124,23 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - testPet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) - inputOptions := *openapiclient.NewCategory("Name_example") // Category | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestQueryDeepObject(context.Background()).TestPet(testPet).InputOptions(inputOptions).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryDeepObject``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + testPet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | (optional) + inputOptions := *openapiclient.NewCategory("Name_example") // Category | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestQueryDeepObject(context.Background()).TestPet(testPet).InputOptions(inputOptions).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryDeepObject``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -1125,26 +1190,26 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pipe := []string{"Inner_example"} // []string | - ioutil := []string{"Inner_example"} // []string | - http := []string{"Inner_example"} // []string | - url := []string{"Inner_example"} // []string | - context := []string{"Inner_example"} // []string | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.FakeAPI.TestQueryParameterCollectionFormat(context.Background()).Pipe(pipe).Ioutil(ioutil).Http(http).Url(url).Context(context).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryParameterCollectionFormat``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + pipe := []string{"Inner_example"} // []string | + ioutil := []string{"Inner_example"} // []string | + http := []string{"Inner_example"} // []string | + url := []string{"Inner_example"} // []string | + context := []string{"Inner_example"} // []string | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.FakeAPI.TestQueryParameterCollectionFormat(context.Background()).Pipe(pipe).Ioutil(ioutil).Http(http).Url(url).Context(context).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestQueryParameterCollectionFormat``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -1197,25 +1262,25 @@ No authorization required package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - queryUnique := []string{"Inner_example"} // []string | - headerUnique := []string{"Inner_example"} // []string | - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat(context.Background()).QueryUnique(queryUnique).HeaderUnique(headerUnique).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestUniqueItemsHeaderAndQueryParameterCollectionFormat`: []Pet - fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat`: %v\n", resp) + queryUnique := []string{"Inner_example"} // []string | + headerUnique := []string{"Inner_example"} // []string | + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat(context.Background()).QueryUnique(queryUnique).HeaderUnique(headerUnique).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestUniqueItemsHeaderAndQueryParameterCollectionFormat`: []Pet + fmt.Fprintf(os.Stdout, "Response from `FakeAPI.TestUniqueItemsHeaderAndQueryParameterCollectionFormat`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md index 07adebe5325c..ad04c336e9f5 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/FakeClassnameTags123API.md @@ -22,24 +22,24 @@ To test class name in snake case package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - client := *openapiclient.NewClient() // Client | client model - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.FakeClassnameTags123API.TestClassname(context.Background()).Client(client).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `FakeClassnameTags123API.TestClassname``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `TestClassname`: Client - fmt.Fprintf(os.Stdout, "Response from `FakeClassnameTags123API.TestClassname`: %v\n", resp) + client := *openapiclient.NewClient() // Client | client model + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.FakeClassnameTags123API.TestClassname(context.Background()).Client(client).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `FakeClassnameTags123API.TestClassname``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `TestClassname`: Client + fmt.Fprintf(os.Stdout, "Response from `FakeClassnameTags123API.TestClassname`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnum.md b/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnum.md index 4b7e19717726..0147d5ea1a46 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnum.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnum.md @@ -7,7 +7,7 @@ * `APPROVED` (value: `"approved"`) -* `DELIVERED` (value: `"delivered"`) +* `SHIPPED` (value: `"delivered"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnumDefaultValue.md b/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnumDefaultValue.md index af1747f3e092..4ca450acbabc 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnumDefaultValue.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/OuterEnumDefaultValue.md @@ -7,7 +7,7 @@ * `APPROVED` (value: `"approved"`) -* `DELIVERED` (value: `"delivered"`) +* `SHIPPED` (value: `"delivered"`) [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/PetAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/PetAPI.md index 74c734b684ac..f034e1b6c6fd 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/PetAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/PetAPI.md @@ -30,22 +30,22 @@ Add a new pet to the store package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.AddPet(context.Background()).Pet(pet).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.AddPet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.AddPet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -94,23 +94,23 @@ Deletes a pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | Pet id to delete - apiKey := "apiKey_example" // string | (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.DeletePet(context.Background(), petId).ApiKey(apiKey).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.DeletePet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + petId := int64(789) // int64 | Pet id to delete + apiKey := "apiKey_example" // string | (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.DeletePet(context.Background(), petId).ApiKey(apiKey).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.DeletePet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -164,24 +164,24 @@ Finds Pets by status package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - status := []string{"Status_example"} // []string | Status values that need to be considered for filter - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.FindPetsByStatus(context.Background()).Status(status).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByStatus``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FindPetsByStatus`: []Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByStatus`: %v\n", resp) + status := []string{"Status_example"} // []string | Status values that need to be considered for filter + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.FindPetsByStatus(context.Background()).Status(status).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByStatus``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FindPetsByStatus`: []Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByStatus`: %v\n", resp) } ``` @@ -230,24 +230,24 @@ Finds Pets by tags package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - tags := []string{"Inner_example"} // []string | Tags to filter by - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.FindPetsByTags(context.Background()).Tags(tags).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByTags``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `FindPetsByTags`: []Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByTags`: %v\n", resp) + tags := []string{"Inner_example"} // []string | Tags to filter by + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.FindPetsByTags(context.Background()).Tags(tags).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.FindPetsByTags``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `FindPetsByTags`: []Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.FindPetsByTags`: %v\n", resp) } ``` @@ -296,24 +296,24 @@ Find pet by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to return - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.GetPetById(context.Background(), petId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.GetPetById``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetPetById`: Pet - fmt.Fprintf(os.Stdout, "Response from `PetAPI.GetPetById`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to return + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.GetPetById(context.Background(), petId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.GetPetById``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetPetById`: Pet + fmt.Fprintf(os.Stdout, "Response from `PetAPI.GetPetById`: %v\n", resp) } ``` @@ -366,22 +366,22 @@ Update an existing pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.UpdatePet(context.Background()).Pet(pet).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePet``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + pet := *openapiclient.NewPet("doggie", []string{"PhotoUrls_example"}) // Pet | Pet object that needs to be added to the store + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.UpdatePet(context.Background()).Pet(pet).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePet``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -430,24 +430,24 @@ Updates a pet in the store with form data package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet that needs to be updated - name := "name_example" // string | Updated name of the pet (optional) - status := "status_example" // string | Updated status of the pet (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.PetAPI.UpdatePetWithForm(context.Background(), petId).Name(name).Status(status).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePetWithForm``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + petId := int64(789) // int64 | ID of pet that needs to be updated + name := "name_example" // string | Updated name of the pet (optional) + status := "status_example" // string | Updated status of the pet (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.PetAPI.UpdatePetWithForm(context.Background(), petId).Name(name).Status(status).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UpdatePetWithForm``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -502,26 +502,26 @@ uploads an image package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to update - additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) - file := os.NewFile(1234, "some_file") // *os.File | file to upload (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.UploadFile(context.Background(), petId).AdditionalMetadata(additionalMetadata).File(file).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFile``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `UploadFile`: ApiResponse - fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFile`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to update + additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) + file := os.NewFile(1234, "some_file") // *os.File | file to upload (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.UploadFile(context.Background(), petId).AdditionalMetadata(additionalMetadata).File(file).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFile``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `UploadFile`: ApiResponse + fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFile`: %v\n", resp) } ``` @@ -576,26 +576,26 @@ uploads an image (required) package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - petId := int64(789) // int64 | ID of pet to update - requiredFile := os.NewFile(1234, "some_file") // *os.File | file to upload - additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.PetAPI.UploadFileWithRequiredFile(context.Background(), petId).RequiredFile(requiredFile).AdditionalMetadata(additionalMetadata).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFileWithRequiredFile``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `UploadFileWithRequiredFile`: ApiResponse - fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFileWithRequiredFile`: %v\n", resp) + petId := int64(789) // int64 | ID of pet to update + requiredFile := os.NewFile(1234, "some_file") // *os.File | file to upload + additionalMetadata := "additionalMetadata_example" // string | Additional data to pass to server (optional) + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.PetAPI.UploadFileWithRequiredFile(context.Background(), petId).RequiredFile(requiredFile).AdditionalMetadata(additionalMetadata).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `PetAPI.UploadFileWithRequiredFile``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `UploadFileWithRequiredFile`: ApiResponse + fmt.Fprintf(os.Stdout, "Response from `PetAPI.UploadFileWithRequiredFile`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/StoreAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/StoreAPI.md index a1b97436465f..441c9dc8393b 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/StoreAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/StoreAPI.md @@ -25,22 +25,22 @@ Delete purchase order by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - orderId := "orderId_example" // string | ID of the order that needs to be deleted - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.StoreAPI.DeleteOrder(context.Background(), orderId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.DeleteOrder``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + orderId := "orderId_example" // string | ID of the order that needs to be deleted + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.StoreAPI.DeleteOrder(context.Background(), orderId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.DeleteOrder``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -93,23 +93,23 @@ Returns pet inventories by status package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.GetInventory(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetInventory``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetInventory`: map[string]int32 - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetInventory`: %v\n", resp) + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.GetInventory(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetInventory``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetInventory`: map[string]int32 + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetInventory`: %v\n", resp) } ``` @@ -154,24 +154,24 @@ Find purchase order by ID package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - orderId := int64(789) // int64 | ID of pet that needs to be fetched - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.GetOrderById(context.Background(), orderId).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetOrderById``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetOrderById`: Order - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetOrderById`: %v\n", resp) + orderId := int64(789) // int64 | ID of pet that needs to be fetched + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.GetOrderById(context.Background(), orderId).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.GetOrderById``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetOrderById`: Order + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.GetOrderById`: %v\n", resp) } ``` @@ -224,24 +224,24 @@ Place an order for a pet package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - order := *openapiclient.NewOrder() // Order | order placed for purchasing the pet - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.StoreAPI.PlaceOrder(context.Background()).Order(order).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.PlaceOrder``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `PlaceOrder`: Order - fmt.Fprintf(os.Stdout, "Response from `StoreAPI.PlaceOrder`: %v\n", resp) + order := *openapiclient.NewOrder() // Order | order placed for purchasing the pet + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.StoreAPI.PlaceOrder(context.Background()).Order(order).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `StoreAPI.PlaceOrder``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `PlaceOrder`: Order + fmt.Fprintf(os.Stdout, "Response from `StoreAPI.PlaceOrder`: %v\n", resp) } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/docs/UserAPI.md b/samples/openapi3/client/petstore/go/go-petstore/docs/UserAPI.md index 03cb03aef2c1..62ee16ad0204 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/docs/UserAPI.md +++ b/samples/openapi3/client/petstore/go/go-petstore/docs/UserAPI.md @@ -29,22 +29,22 @@ Create user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - user := *openapiclient.NewUser() // User | Created user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUser(context.Background()).User(user).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + user := *openapiclient.NewUser() // User | Created user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUser(context.Background()).User(user).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -93,22 +93,22 @@ Creates list of users with given input array package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - user := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUsersWithArrayInput(context.Background()).User(user).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithArrayInput``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + user := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUsersWithArrayInput(context.Background()).User(user).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithArrayInput``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -157,22 +157,22 @@ Creates list of users with given input array package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - user := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.CreateUsersWithListInput(context.Background()).User(user).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithListInput``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + user := []openapiclient.User{*openapiclient.NewUser()} // []User | List of user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.CreateUsersWithListInput(context.Background()).User(user).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.CreateUsersWithListInput``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -221,22 +221,22 @@ Delete user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The name that needs to be deleted - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.DeleteUser(context.Background(), username).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.DeleteUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + username := "username_example" // string | The name that needs to be deleted + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.DeleteUser(context.Background(), username).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.DeleteUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -289,24 +289,24 @@ Get user by user name package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The name that needs to be fetched. Use user1 for testing. - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UserAPI.GetUserByName(context.Background(), username).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.GetUserByName``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `GetUserByName`: User - fmt.Fprintf(os.Stdout, "Response from `UserAPI.GetUserByName`: %v\n", resp) + username := "username_example" // string | The name that needs to be fetched. Use user1 for testing. + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UserAPI.GetUserByName(context.Background(), username).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.GetUserByName``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `GetUserByName`: User + fmt.Fprintf(os.Stdout, "Response from `UserAPI.GetUserByName`: %v\n", resp) } ``` @@ -359,25 +359,25 @@ Logs user into the system package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | The user name for login - password := "password_example" // string | The password for login in clear text - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - resp, r, err := apiClient.UserAPI.LoginUser(context.Background()).Username(username).Password(password).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LoginUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } - // response from `LoginUser`: string - fmt.Fprintf(os.Stdout, "Response from `UserAPI.LoginUser`: %v\n", resp) + username := "username_example" // string | The user name for login + password := "password_example" // string | The password for login in clear text + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + resp, r, err := apiClient.UserAPI.LoginUser(context.Background()).Username(username).Password(password).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LoginUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } + // response from `LoginUser`: string + fmt.Fprintf(os.Stdout, "Response from `UserAPI.LoginUser`: %v\n", resp) } ``` @@ -427,21 +427,21 @@ Logs out current logged in user session package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.LogoutUser(context.Background()).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LogoutUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.LogoutUser(context.Background()).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.LogoutUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` @@ -486,23 +486,23 @@ Updated user package main import ( - "context" - "fmt" - "os" - openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" + "context" + "fmt" + "os" + openapiclient "github.com/GIT_USER_ID/GIT_REPO_ID" ) func main() { - username := "username_example" // string | name that need to be deleted - user := *openapiclient.NewUser() // User | Updated user object - - configuration := openapiclient.NewConfiguration() - apiClient := openapiclient.NewAPIClient(configuration) - r, err := apiClient.UserAPI.UpdateUser(context.Background(), username).User(user).Execute() - if err != nil { - fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.UpdateUser``: %v\n", err) - fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) - } + username := "username_example" // string | name that need to be deleted + user := *openapiclient.NewUser() // User | Updated user object + + configuration := openapiclient.NewConfiguration() + apiClient := openapiclient.NewAPIClient(configuration) + r, err := apiClient.UserAPI.UpdateUser(context.Background(), username).User(user).Execute() + if err != nil { + fmt.Fprintf(os.Stderr, "Error when calling `UserAPI.UpdateUser``: %v\n", err) + fmt.Fprintf(os.Stderr, "Full HTTP response: %v\n", r) + } } ``` diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_200_response.go b/samples/openapi3/client/petstore/go/go-petstore/model_200_response.go index 2bf31c269bb4..0af08b3fa6c1 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_200_response.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_200_response.go @@ -131,10 +131,10 @@ func (o Model200Response) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Model200Response) UnmarshalJSON(bytes []byte) (err error) { +func (o *Model200Response) UnmarshalJSON(data []byte) (err error) { varModel200Response := _Model200Response{} - err = json.Unmarshal(bytes, &varModel200Response) + err = json.Unmarshal(data, &varModel200Response) if err != nil { return err @@ -144,7 +144,7 @@ func (o *Model200Response) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") delete(additionalProperties, "class") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model__foo_get_default_response.go b/samples/openapi3/client/petstore/go/go-petstore/model__foo_get_default_response.go index 3e64a6b310ca..8eac10b55615 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model__foo_get_default_response.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model__foo_get_default_response.go @@ -95,10 +95,10 @@ func (o FooGetDefaultResponse) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *FooGetDefaultResponse) UnmarshalJSON(bytes []byte) (err error) { +func (o *FooGetDefaultResponse) UnmarshalJSON(data []byte) (err error) { varFooGetDefaultResponse := _FooGetDefaultResponse{} - err = json.Unmarshal(bytes, &varFooGetDefaultResponse) + err = json.Unmarshal(data, &varFooGetDefaultResponse) if err != nil { return err @@ -108,7 +108,7 @@ func (o *FooGetDefaultResponse) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "string") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model__special_model_name_.go b/samples/openapi3/client/petstore/go/go-petstore/model__special_model_name_.go index 0509ff5da5d8..194a9bcc0597 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model__special_model_name_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model__special_model_name_.go @@ -95,10 +95,10 @@ func (o SpecialModelName) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *SpecialModelName) UnmarshalJSON(bytes []byte) (err error) { +func (o *SpecialModelName) UnmarshalJSON(data []byte) (err error) { varSpecialModelName := _SpecialModelName{} - err = json.Unmarshal(bytes, &varSpecialModelName) + err = json.Unmarshal(data, &varSpecialModelName) if err != nil { return err @@ -108,7 +108,7 @@ func (o *SpecialModelName) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "$special[property.name]") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_additional_properties_class.go b/samples/openapi3/client/petstore/go/go-petstore/model_additional_properties_class.go index d9210014d80d..933a6d1d1842 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_additional_properties_class.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_additional_properties_class.go @@ -131,10 +131,10 @@ func (o AdditionalPropertiesClass) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AdditionalPropertiesClass) UnmarshalJSON(bytes []byte) (err error) { +func (o *AdditionalPropertiesClass) UnmarshalJSON(data []byte) (err error) { varAdditionalPropertiesClass := _AdditionalPropertiesClass{} - err = json.Unmarshal(bytes, &varAdditionalPropertiesClass) + err = json.Unmarshal(data, &varAdditionalPropertiesClass) if err != nil { return err @@ -144,7 +144,7 @@ func (o *AdditionalPropertiesClass) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "map_property") delete(additionalProperties, "map_of_map_property") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_all_of_primitive_types.go b/samples/openapi3/client/petstore/go/go-petstore/model_all_of_primitive_types.go index 8c6f26889502..b86077b3c48a 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_all_of_primitive_types.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_all_of_primitive_types.go @@ -96,10 +96,10 @@ func (o AllOfPrimitiveTypes) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AllOfPrimitiveTypes) UnmarshalJSON(bytes []byte) (err error) { +func (o *AllOfPrimitiveTypes) UnmarshalJSON(data []byte) (err error) { varAllOfPrimitiveTypes := _AllOfPrimitiveTypes{} - err = json.Unmarshal(bytes, &varAllOfPrimitiveTypes) + err = json.Unmarshal(data, &varAllOfPrimitiveTypes) if err != nil { return err @@ -109,7 +109,7 @@ func (o *AllOfPrimitiveTypes) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "test") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_animal.go b/samples/openapi3/client/petstore/go/go-petstore/model_animal.go index c01aa9aeadc2..1e5c17f0a1ef 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_animal.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_animal.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Animal type satisfies the MappedNullable interface at compile time @@ -126,10 +127,31 @@ func (o Animal) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Animal) UnmarshalJSON(bytes []byte) (err error) { +func (o *Animal) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varAnimal := _Animal{} - err = json.Unmarshal(bytes, &varAnimal) + err = json.Unmarshal(data, &varAnimal) if err != nil { return err @@ -139,7 +161,7 @@ func (o *Animal) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "className") delete(additionalProperties, "color") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_api_response.go b/samples/openapi3/client/petstore/go/go-petstore/model_api_response.go index c8d0d91baabe..a466bd47454f 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_api_response.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_api_response.go @@ -167,10 +167,10 @@ func (o ApiResponse) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ApiResponse) UnmarshalJSON(bytes []byte) (err error) { +func (o *ApiResponse) UnmarshalJSON(data []byte) (err error) { varApiResponse := _ApiResponse{} - err = json.Unmarshal(bytes, &varApiResponse) + err = json.Unmarshal(data, &varApiResponse) if err != nil { return err @@ -180,7 +180,7 @@ func (o *ApiResponse) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "code") delete(additionalProperties, "type") delete(additionalProperties, "message") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_apple.go b/samples/openapi3/client/petstore/go/go-petstore/model_apple.go index 19df0b7b57b1..98cbf5dbc6e4 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_apple.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_apple.go @@ -95,10 +95,10 @@ func (o Apple) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Apple) UnmarshalJSON(bytes []byte) (err error) { +func (o *Apple) UnmarshalJSON(data []byte) (err error) { varApple := _Apple{} - err = json.Unmarshal(bytes, &varApple) + err = json.Unmarshal(data, &varApple) if err != nil { return err @@ -108,7 +108,7 @@ func (o *Apple) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "cultivar") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_apple_req.go b/samples/openapi3/client/petstore/go/go-petstore/model_apple_req.go index 23fa5ed2867b..4d398c185ccd 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_apple_req.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_apple_req.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the AppleReq type satisfies the MappedNullable interface at compile time @@ -122,10 +123,31 @@ func (o AppleReq) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *AppleReq) UnmarshalJSON(bytes []byte) (err error) { +func (o *AppleReq) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "cultivar", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varAppleReq := _AppleReq{} - err = json.Unmarshal(bytes, &varAppleReq) + err = json.Unmarshal(data, &varAppleReq) if err != nil { return err @@ -135,7 +157,7 @@ func (o *AppleReq) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "cultivar") delete(additionalProperties, "mealy") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_array_of_array_of_number_only.go b/samples/openapi3/client/petstore/go/go-petstore/model_array_of_array_of_number_only.go index 6d4c67f246e2..2a9b51afdc77 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_array_of_array_of_number_only.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_array_of_array_of_number_only.go @@ -95,10 +95,10 @@ func (o ArrayOfArrayOfNumberOnly) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ArrayOfArrayOfNumberOnly) UnmarshalJSON(bytes []byte) (err error) { +func (o *ArrayOfArrayOfNumberOnly) UnmarshalJSON(data []byte) (err error) { varArrayOfArrayOfNumberOnly := _ArrayOfArrayOfNumberOnly{} - err = json.Unmarshal(bytes, &varArrayOfArrayOfNumberOnly) + err = json.Unmarshal(data, &varArrayOfArrayOfNumberOnly) if err != nil { return err @@ -108,7 +108,7 @@ func (o *ArrayOfArrayOfNumberOnly) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "ArrayArrayNumber") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_array_of_number_only.go b/samples/openapi3/client/petstore/go/go-petstore/model_array_of_number_only.go index d45cec963658..55856aacd5eb 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_array_of_number_only.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_array_of_number_only.go @@ -95,10 +95,10 @@ func (o ArrayOfNumberOnly) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ArrayOfNumberOnly) UnmarshalJSON(bytes []byte) (err error) { +func (o *ArrayOfNumberOnly) UnmarshalJSON(data []byte) (err error) { varArrayOfNumberOnly := _ArrayOfNumberOnly{} - err = json.Unmarshal(bytes, &varArrayOfNumberOnly) + err = json.Unmarshal(data, &varArrayOfNumberOnly) if err != nil { return err @@ -108,7 +108,7 @@ func (o *ArrayOfNumberOnly) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "ArrayNumber") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_array_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_array_test_.go index 2851c2f46843..d337ead6e4b4 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_array_test_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_array_test_.go @@ -167,10 +167,10 @@ func (o ArrayTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ArrayTest) UnmarshalJSON(bytes []byte) (err error) { +func (o *ArrayTest) UnmarshalJSON(data []byte) (err error) { varArrayTest := _ArrayTest{} - err = json.Unmarshal(bytes, &varArrayTest) + err = json.Unmarshal(data, &varArrayTest) if err != nil { return err @@ -180,7 +180,7 @@ func (o *ArrayTest) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "array_of_string") delete(additionalProperties, "array_array_of_integer") delete(additionalProperties, "array_array_of_model") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_banana.go b/samples/openapi3/client/petstore/go/go-petstore/model_banana.go index 4d757fbf9925..87b5dacac7a0 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_banana.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_banana.go @@ -95,10 +95,10 @@ func (o Banana) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Banana) UnmarshalJSON(bytes []byte) (err error) { +func (o *Banana) UnmarshalJSON(data []byte) (err error) { varBanana := _Banana{} - err = json.Unmarshal(bytes, &varBanana) + err = json.Unmarshal(data, &varBanana) if err != nil { return err @@ -108,7 +108,7 @@ func (o *Banana) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "lengthCm") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_banana_req.go b/samples/openapi3/client/petstore/go/go-petstore/model_banana_req.go index 5d5923fc5a7c..173e41024d92 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_banana_req.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_banana_req.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the BananaReq type satisfies the MappedNullable interface at compile time @@ -122,10 +123,31 @@ func (o BananaReq) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *BananaReq) UnmarshalJSON(bytes []byte) (err error) { +func (o *BananaReq) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "lengthCm", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varBananaReq := _BananaReq{} - err = json.Unmarshal(bytes, &varBananaReq) + err = json.Unmarshal(data, &varBananaReq) if err != nil { return err @@ -135,7 +157,7 @@ func (o *BananaReq) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "lengthCm") delete(additionalProperties, "sweet") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_capitalization.go b/samples/openapi3/client/petstore/go/go-petstore/model_capitalization.go index 8b09f0d813e4..bbe4c67769ce 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_capitalization.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_capitalization.go @@ -276,10 +276,10 @@ func (o Capitalization) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Capitalization) UnmarshalJSON(bytes []byte) (err error) { +func (o *Capitalization) UnmarshalJSON(data []byte) (err error) { varCapitalization := _Capitalization{} - err = json.Unmarshal(bytes, &varCapitalization) + err = json.Unmarshal(data, &varCapitalization) if err != nil { return err @@ -289,7 +289,7 @@ func (o *Capitalization) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "smallCamel") delete(additionalProperties, "CapitalCamel") delete(additionalProperties, "small_Snake") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_cat.go b/samples/openapi3/client/petstore/go/go-petstore/model_cat.go index 440973ad5140..16b541f887b7 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_cat.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_cat.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" "reflect" "strings" ) @@ -109,14 +110,35 @@ func (o Cat) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Cat) UnmarshalJSON(bytes []byte) (err error) { +func (o *Cat) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + type CatWithoutEmbeddedStruct struct { Declawed *bool `json:"declawed,omitempty"` } varCatWithoutEmbeddedStruct := CatWithoutEmbeddedStruct{} - err = json.Unmarshal(bytes, &varCatWithoutEmbeddedStruct) + err = json.Unmarshal(data, &varCatWithoutEmbeddedStruct) if err == nil { varCat := _Cat{} varCat.Declawed = varCatWithoutEmbeddedStruct.Declawed @@ -127,7 +149,7 @@ func (o *Cat) UnmarshalJSON(bytes []byte) (err error) { varCat := _Cat{} - err = json.Unmarshal(bytes, &varCat) + err = json.Unmarshal(data, &varCat) if err == nil { o.Animal = varCat.Animal } else { @@ -136,7 +158,7 @@ func (o *Cat) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "declawed") // remove fields from embedded structs diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_category.go b/samples/openapi3/client/petstore/go/go-petstore/model_category.go index bd4d6815e72e..ff0f7231279c 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_category.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_category.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Category type satisfies the MappedNullable interface at compile time @@ -124,10 +125,31 @@ func (o Category) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Category) UnmarshalJSON(bytes []byte) (err error) { +func (o *Category) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varCategory := _Category{} - err = json.Unmarshal(bytes, &varCategory) + err = json.Unmarshal(data, &varCategory) if err != nil { return err @@ -137,7 +159,7 @@ func (o *Category) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "id") delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_class_model.go b/samples/openapi3/client/petstore/go/go-petstore/model_class_model.go index 72fe2596231c..2560433fbbcd 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_class_model.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_class_model.go @@ -95,10 +95,10 @@ func (o ClassModel) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ClassModel) UnmarshalJSON(bytes []byte) (err error) { +func (o *ClassModel) UnmarshalJSON(data []byte) (err error) { varClassModel := _ClassModel{} - err = json.Unmarshal(bytes, &varClassModel) + err = json.Unmarshal(data, &varClassModel) if err != nil { return err @@ -108,7 +108,7 @@ func (o *ClassModel) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "_class") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_client.go b/samples/openapi3/client/petstore/go/go-petstore/model_client.go index e635b0546e07..79501a88b234 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_client.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_client.go @@ -95,10 +95,10 @@ func (o Client) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Client) UnmarshalJSON(bytes []byte) (err error) { +func (o *Client) UnmarshalJSON(data []byte) (err error) { varClient := _Client{} - err = json.Unmarshal(bytes, &varClient) + err = json.Unmarshal(data, &varClient) if err != nil { return err @@ -108,7 +108,7 @@ func (o *Client) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "client") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_dog.go b/samples/openapi3/client/petstore/go/go-petstore/model_dog.go index 000bcf7e45fa..258364c75f59 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_dog.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_dog.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" "reflect" "strings" ) @@ -109,14 +110,35 @@ func (o Dog) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Dog) UnmarshalJSON(bytes []byte) (err error) { +func (o *Dog) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + type DogWithoutEmbeddedStruct struct { Breed *string `json:"breed,omitempty"` } varDogWithoutEmbeddedStruct := DogWithoutEmbeddedStruct{} - err = json.Unmarshal(bytes, &varDogWithoutEmbeddedStruct) + err = json.Unmarshal(data, &varDogWithoutEmbeddedStruct) if err == nil { varDog := _Dog{} varDog.Breed = varDogWithoutEmbeddedStruct.Breed @@ -127,7 +149,7 @@ func (o *Dog) UnmarshalJSON(bytes []byte) (err error) { varDog := _Dog{} - err = json.Unmarshal(bytes, &varDog) + err = json.Unmarshal(data, &varDog) if err == nil { o.Animal = varDog.Animal } else { @@ -136,7 +158,7 @@ func (o *Dog) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "breed") // remove fields from embedded structs diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go index 76a5fba804d5..87f205f824e5 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_child.go @@ -107,7 +107,7 @@ func (o DuplicatedPropChild) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *DuplicatedPropChild) UnmarshalJSON(bytes []byte) (err error) { +func (o *DuplicatedPropChild) UnmarshalJSON(data []byte) (err error) { type DuplicatedPropChildWithoutEmbeddedStruct struct { // A discriminator value DupProp *string `json:"dup-prop,omitempty"` @@ -115,7 +115,7 @@ func (o *DuplicatedPropChild) UnmarshalJSON(bytes []byte) (err error) { varDuplicatedPropChildWithoutEmbeddedStruct := DuplicatedPropChildWithoutEmbeddedStruct{} - err = json.Unmarshal(bytes, &varDuplicatedPropChildWithoutEmbeddedStruct) + err = json.Unmarshal(data, &varDuplicatedPropChildWithoutEmbeddedStruct) if err == nil { varDuplicatedPropChild := _DuplicatedPropChild{} varDuplicatedPropChild.DupProp = varDuplicatedPropChildWithoutEmbeddedStruct.DupProp @@ -126,7 +126,7 @@ func (o *DuplicatedPropChild) UnmarshalJSON(bytes []byte) (err error) { varDuplicatedPropChild := _DuplicatedPropChild{} - err = json.Unmarshal(bytes, &varDuplicatedPropChild) + err = json.Unmarshal(data, &varDuplicatedPropChild) if err == nil { o.DuplicatedPropParent = varDuplicatedPropChild.DuplicatedPropParent } else { @@ -135,7 +135,7 @@ func (o *DuplicatedPropChild) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "dup-prop") // remove fields from embedded structs diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go index bb2e2132e122..8e0c89f06f27 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_duplicated_prop_parent.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the DuplicatedPropParent type satisfies the MappedNullable interface at compile time @@ -87,10 +88,31 @@ func (o DuplicatedPropParent) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *DuplicatedPropParent) UnmarshalJSON(bytes []byte) (err error) { +func (o *DuplicatedPropParent) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "dup-prop", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varDuplicatedPropParent := _DuplicatedPropParent{} - err = json.Unmarshal(bytes, &varDuplicatedPropParent) + err = json.Unmarshal(data, &varDuplicatedPropParent) if err != nil { return err @@ -100,7 +122,7 @@ func (o *DuplicatedPropParent) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "dup-prop") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_enum_arrays.go b/samples/openapi3/client/petstore/go/go-petstore/model_enum_arrays.go index cbb59df3be01..c6c519297f80 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_enum_arrays.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_enum_arrays.go @@ -131,10 +131,10 @@ func (o EnumArrays) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *EnumArrays) UnmarshalJSON(bytes []byte) (err error) { +func (o *EnumArrays) UnmarshalJSON(data []byte) (err error) { varEnumArrays := _EnumArrays{} - err = json.Unmarshal(bytes, &varEnumArrays) + err = json.Unmarshal(data, &varEnumArrays) if err != nil { return err @@ -144,7 +144,7 @@ func (o *EnumArrays) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "just_symbol") delete(additionalProperties, "array_enum") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_enum_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_enum_test_.go index eb00c70e14f6..8a6d6b6c7125 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_enum_test_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_enum_test_.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the EnumTest type satisfies the MappedNullable interface at compile time @@ -356,10 +357,31 @@ func (o EnumTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *EnumTest) UnmarshalJSON(bytes []byte) (err error) { +func (o *EnumTest) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "enum_string_required", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varEnumTest := _EnumTest{} - err = json.Unmarshal(bytes, &varEnumTest) + err = json.Unmarshal(data, &varEnumTest) if err != nil { return err @@ -369,7 +391,7 @@ func (o *EnumTest) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "enum_string") delete(additionalProperties, "enum_string_required") delete(additionalProperties, "enum_integer") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_file.go b/samples/openapi3/client/petstore/go/go-petstore/model_file.go index bf26cb96bf35..a56fccfeef44 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_file.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_file.go @@ -96,10 +96,10 @@ func (o File) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *File) UnmarshalJSON(bytes []byte) (err error) { +func (o *File) UnmarshalJSON(data []byte) (err error) { varFile := _File{} - err = json.Unmarshal(bytes, &varFile) + err = json.Unmarshal(data, &varFile) if err != nil { return err @@ -109,7 +109,7 @@ func (o *File) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "sourceURI") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_file_schema_test_class.go b/samples/openapi3/client/petstore/go/go-petstore/model_file_schema_test_class.go index ab98b53cba46..78e477435c10 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_file_schema_test_class.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_file_schema_test_class.go @@ -131,10 +131,10 @@ func (o FileSchemaTestClass) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *FileSchemaTestClass) UnmarshalJSON(bytes []byte) (err error) { +func (o *FileSchemaTestClass) UnmarshalJSON(data []byte) (err error) { varFileSchemaTestClass := _FileSchemaTestClass{} - err = json.Unmarshal(bytes, &varFileSchemaTestClass) + err = json.Unmarshal(data, &varFileSchemaTestClass) if err != nil { return err @@ -144,7 +144,7 @@ func (o *FileSchemaTestClass) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "file") delete(additionalProperties, "files") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_foo.go b/samples/openapi3/client/petstore/go/go-petstore/model_foo.go index 76e88bfaa2e2..b90222254ba3 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_foo.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_foo.go @@ -99,10 +99,10 @@ func (o Foo) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Foo) UnmarshalJSON(bytes []byte) (err error) { +func (o *Foo) UnmarshalJSON(data []byte) (err error) { varFoo := _Foo{} - err = json.Unmarshal(bytes, &varFoo) + err = json.Unmarshal(data, &varFoo) if err != nil { return err @@ -112,7 +112,7 @@ func (o *Foo) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "bar") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_format_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_format_test_.go index 499ceba4acb0..6aef735d91ee 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_format_test_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_format_test_.go @@ -14,6 +14,7 @@ import ( "encoding/json" "os" "time" + "fmt" ) // checks if the FormatTest type satisfies the MappedNullable interface at compile time @@ -567,10 +568,34 @@ func (o FormatTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *FormatTest) UnmarshalJSON(bytes []byte) (err error) { +func (o *FormatTest) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "number", + "byte", + "date", + "password", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varFormatTest := _FormatTest{} - err = json.Unmarshal(bytes, &varFormatTest) + err = json.Unmarshal(data, &varFormatTest) if err != nil { return err @@ -580,7 +605,7 @@ func (o *FormatTest) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "integer") delete(additionalProperties, "int32") delete(additionalProperties, "int64") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_has_only_read_only.go b/samples/openapi3/client/petstore/go/go-petstore/model_has_only_read_only.go index c7f8236ee236..ce71066d8454 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_has_only_read_only.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_has_only_read_only.go @@ -131,10 +131,10 @@ func (o HasOnlyReadOnly) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *HasOnlyReadOnly) UnmarshalJSON(bytes []byte) (err error) { +func (o *HasOnlyReadOnly) UnmarshalJSON(data []byte) (err error) { varHasOnlyReadOnly := _HasOnlyReadOnly{} - err = json.Unmarshal(bytes, &varHasOnlyReadOnly) + err = json.Unmarshal(data, &varHasOnlyReadOnly) if err != nil { return err @@ -144,7 +144,7 @@ func (o *HasOnlyReadOnly) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "bar") delete(additionalProperties, "foo") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_health_check_result.go b/samples/openapi3/client/petstore/go/go-petstore/model_health_check_result.go index 3617d9b3f8b7..094f0777d5fc 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_health_check_result.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_health_check_result.go @@ -105,10 +105,10 @@ func (o HealthCheckResult) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *HealthCheckResult) UnmarshalJSON(bytes []byte) (err error) { +func (o *HealthCheckResult) UnmarshalJSON(data []byte) (err error) { varHealthCheckResult := _HealthCheckResult{} - err = json.Unmarshal(bytes, &varHealthCheckResult) + err = json.Unmarshal(data, &varHealthCheckResult) if err != nil { return err @@ -118,7 +118,7 @@ func (o *HealthCheckResult) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "NullableMessage") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_list.go b/samples/openapi3/client/petstore/go/go-petstore/model_list.go index 8af38e91ef3b..2d629fda5db3 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_list.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_list.go @@ -95,10 +95,10 @@ func (o List) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *List) UnmarshalJSON(bytes []byte) (err error) { +func (o *List) UnmarshalJSON(data []byte) (err error) { varList := _List{} - err = json.Unmarshal(bytes, &varList) + err = json.Unmarshal(data, &varList) if err != nil { return err @@ -108,7 +108,7 @@ func (o *List) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "123-list") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go index c86070564546..380d2df569d6 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_map_of_file_test_.go @@ -97,10 +97,10 @@ func (o MapOfFileTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *MapOfFileTest) UnmarshalJSON(bytes []byte) (err error) { +func (o *MapOfFileTest) UnmarshalJSON(data []byte) (err error) { varMapOfFileTest := _MapOfFileTest{} - err = json.Unmarshal(bytes, &varMapOfFileTest) + err = json.Unmarshal(data, &varMapOfFileTest) if err != nil { return err @@ -110,7 +110,7 @@ func (o *MapOfFileTest) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "prop_test") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_map_test_.go b/samples/openapi3/client/petstore/go/go-petstore/model_map_test_.go index f7fefb0c1036..6282f65b6cf3 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_map_test_.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_map_test_.go @@ -203,10 +203,10 @@ func (o MapTest) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *MapTest) UnmarshalJSON(bytes []byte) (err error) { +func (o *MapTest) UnmarshalJSON(data []byte) (err error) { varMapTest := _MapTest{} - err = json.Unmarshal(bytes, &varMapTest) + err = json.Unmarshal(data, &varMapTest) if err != nil { return err @@ -216,7 +216,7 @@ func (o *MapTest) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "map_map_of_string") delete(additionalProperties, "map_of_enum_string") delete(additionalProperties, "direct_map") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_mixed_properties_and_additional_properties_class.go b/samples/openapi3/client/petstore/go/go-petstore/model_mixed_properties_and_additional_properties_class.go index 8470ccb66320..bcb53631ca5c 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_mixed_properties_and_additional_properties_class.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_mixed_properties_and_additional_properties_class.go @@ -168,10 +168,10 @@ func (o MixedPropertiesAndAdditionalPropertiesClass) ToMap() (map[string]interfa return toSerialize, nil } -func (o *MixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(bytes []byte) (err error) { +func (o *MixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(data []byte) (err error) { varMixedPropertiesAndAdditionalPropertiesClass := _MixedPropertiesAndAdditionalPropertiesClass{} - err = json.Unmarshal(bytes, &varMixedPropertiesAndAdditionalPropertiesClass) + err = json.Unmarshal(data, &varMixedPropertiesAndAdditionalPropertiesClass) if err != nil { return err @@ -181,7 +181,7 @@ func (o *MixedPropertiesAndAdditionalPropertiesClass) UnmarshalJSON(bytes []byte additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "uuid") delete(additionalProperties, "dateTime") delete(additionalProperties, "map") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_name.go b/samples/openapi3/client/petstore/go/go-petstore/model_name.go index 84a92878766a..14674c8e01bf 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_name.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_name.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Name type satisfies the MappedNullable interface at compile time @@ -194,10 +195,31 @@ func (o Name) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Name) UnmarshalJSON(bytes []byte) (err error) { +func (o *Name) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varName := _Name{} - err = json.Unmarshal(bytes, &varName) + err = json.Unmarshal(data, &varName) if err != nil { return err @@ -207,7 +229,7 @@ func (o *Name) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") delete(additionalProperties, "snake_case") delete(additionalProperties, "property") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of.go b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of.go index 3f7029b787da..5d74973b3995 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of.go @@ -105,10 +105,10 @@ func (o NullableAllOf) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *NullableAllOf) UnmarshalJSON(bytes []byte) (err error) { +func (o *NullableAllOf) UnmarshalJSON(data []byte) (err error) { varNullableAllOf := _NullableAllOf{} - err = json.Unmarshal(bytes, &varNullableAllOf) + err = json.Unmarshal(data, &varNullableAllOf) if err != nil { return err @@ -118,7 +118,7 @@ func (o *NullableAllOf) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "child") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of_child.go b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of_child.go index 0aec0ac62550..50a070c79628 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of_child.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_all_of_child.go @@ -95,10 +95,10 @@ func (o NullableAllOfChild) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *NullableAllOfChild) UnmarshalJSON(bytes []byte) (err error) { +func (o *NullableAllOfChild) UnmarshalJSON(data []byte) (err error) { varNullableAllOfChild := _NullableAllOfChild{} - err = json.Unmarshal(bytes, &varNullableAllOfChild) + err = json.Unmarshal(data, &varNullableAllOfChild) if err != nil { return err @@ -108,7 +108,7 @@ func (o *NullableAllOfChild) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go index a323a2e59524..9754307946d4 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_nullable_class.go @@ -560,10 +560,10 @@ func (o NullableClass) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *NullableClass) UnmarshalJSON(bytes []byte) (err error) { +func (o *NullableClass) UnmarshalJSON(data []byte) (err error) { varNullableClass := _NullableClass{} - err = json.Unmarshal(bytes, &varNullableClass) + err = json.Unmarshal(data, &varNullableClass) if err != nil { return err @@ -573,7 +573,7 @@ func (o *NullableClass) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "integer_prop") delete(additionalProperties, "number_prop") delete(additionalProperties, "boolean_prop") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_number_only.go b/samples/openapi3/client/petstore/go/go-petstore/model_number_only.go index 95b416db196f..d8b4e4ecc542 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_number_only.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_number_only.go @@ -95,10 +95,10 @@ func (o NumberOnly) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *NumberOnly) UnmarshalJSON(bytes []byte) (err error) { +func (o *NumberOnly) UnmarshalJSON(data []byte) (err error) { varNumberOnly := _NumberOnly{} - err = json.Unmarshal(bytes, &varNumberOnly) + err = json.Unmarshal(data, &varNumberOnly) if err != nil { return err @@ -108,7 +108,7 @@ func (o *NumberOnly) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "JustNumber") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_one_of_primitive_type_child.go b/samples/openapi3/client/petstore/go/go-petstore/model_one_of_primitive_type_child.go index 1fa6693b43b3..56412f1dda65 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_one_of_primitive_type_child.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_one_of_primitive_type_child.go @@ -95,10 +95,10 @@ func (o OneOfPrimitiveTypeChild) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *OneOfPrimitiveTypeChild) UnmarshalJSON(bytes []byte) (err error) { +func (o *OneOfPrimitiveTypeChild) UnmarshalJSON(data []byte) (err error) { varOneOfPrimitiveTypeChild := _OneOfPrimitiveTypeChild{} - err = json.Unmarshal(bytes, &varOneOfPrimitiveTypeChild) + err = json.Unmarshal(data, &varOneOfPrimitiveTypeChild) if err != nil { return err @@ -108,7 +108,7 @@ func (o *OneOfPrimitiveTypeChild) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_order.go b/samples/openapi3/client/petstore/go/go-petstore/model_order.go index 15f139933399..8606747f525b 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_order.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_order.go @@ -281,10 +281,10 @@ func (o Order) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Order) UnmarshalJSON(bytes []byte) (err error) { +func (o *Order) UnmarshalJSON(data []byte) (err error) { varOrder := _Order{} - err = json.Unmarshal(bytes, &varOrder) + err = json.Unmarshal(data, &varOrder) if err != nil { return err @@ -294,7 +294,7 @@ func (o *Order) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "id") delete(additionalProperties, "petId") delete(additionalProperties, "quantity") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_outer_composite.go b/samples/openapi3/client/petstore/go/go-petstore/model_outer_composite.go index 279f46eeac46..de368f5af6cd 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_outer_composite.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_outer_composite.go @@ -167,10 +167,10 @@ func (o OuterComposite) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *OuterComposite) UnmarshalJSON(bytes []byte) (err error) { +func (o *OuterComposite) UnmarshalJSON(data []byte) (err error) { varOuterComposite := _OuterComposite{} - err = json.Unmarshal(bytes, &varOuterComposite) + err = json.Unmarshal(data, &varOuterComposite) if err != nil { return err @@ -180,7 +180,7 @@ func (o *OuterComposite) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "my_number") delete(additionalProperties, "my_string") delete(additionalProperties, "my_boolean") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum.go b/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum.go index d6a867b09be8..f7598bf9885d 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum.go @@ -22,7 +22,7 @@ type OuterEnum string const ( OUTERENUM_PLACED OuterEnum = "placed" OUTERENUM_APPROVED OuterEnum = "approved" - OUTERENUM_DELIVERED OuterEnum = "delivered" + OUTERENUM_SHIPPED OuterEnum = "delivered" ) // All allowed values of OuterEnum enum diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum_default_value.go b/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum_default_value.go index 31778851a4d0..0b122920d023 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum_default_value.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_outer_enum_default_value.go @@ -22,7 +22,7 @@ type OuterEnumDefaultValue string const ( OUTERENUMDEFAULTVALUE_PLACED OuterEnumDefaultValue = "placed" OUTERENUMDEFAULTVALUE_APPROVED OuterEnumDefaultValue = "approved" - OUTERENUMDEFAULTVALUE_DELIVERED OuterEnumDefaultValue = "delivered" + OUTERENUMDEFAULTVALUE_SHIPPED OuterEnumDefaultValue = "delivered" ) // All allowed values of OuterEnumDefaultValue enum diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_pet.go b/samples/openapi3/client/petstore/go/go-petstore/model_pet.go index 0f1ffe373e5b..2fcb77442379 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_pet.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_pet.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Pet type satisfies the MappedNullable interface at compile time @@ -262,10 +263,32 @@ func (o Pet) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Pet) UnmarshalJSON(bytes []byte) (err error) { +func (o *Pet) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "name", + "photoUrls", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varPet := _Pet{} - err = json.Unmarshal(bytes, &varPet) + err = json.Unmarshal(data, &varPet) if err != nil { return err @@ -275,7 +298,7 @@ func (o *Pet) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "id") delete(additionalProperties, "category") delete(additionalProperties, "name") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_property_name_mapping.go b/samples/openapi3/client/petstore/go/go-petstore/model_property_name_mapping.go index c621f708467d..7aaa0c5979ef 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_property_name_mapping.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_property_name_mapping.go @@ -203,10 +203,10 @@ func (o PropertyNameMapping) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *PropertyNameMapping) UnmarshalJSON(bytes []byte) (err error) { +func (o *PropertyNameMapping) UnmarshalJSON(data []byte) (err error) { varPropertyNameMapping := _PropertyNameMapping{} - err = json.Unmarshal(bytes, &varPropertyNameMapping) + err = json.Unmarshal(data, &varPropertyNameMapping) if err != nil { return err @@ -216,7 +216,7 @@ func (o *PropertyNameMapping) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "http_debug_operation") delete(additionalProperties, "_type") delete(additionalProperties, "type") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_read_only_first.go b/samples/openapi3/client/petstore/go/go-petstore/model_read_only_first.go index 3b240abf82b7..87acb5753426 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_read_only_first.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_read_only_first.go @@ -131,10 +131,10 @@ func (o ReadOnlyFirst) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ReadOnlyFirst) UnmarshalJSON(bytes []byte) (err error) { +func (o *ReadOnlyFirst) UnmarshalJSON(data []byte) (err error) { varReadOnlyFirst := _ReadOnlyFirst{} - err = json.Unmarshal(bytes, &varReadOnlyFirst) + err = json.Unmarshal(data, &varReadOnlyFirst) if err != nil { return err @@ -144,7 +144,7 @@ func (o *ReadOnlyFirst) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "bar") delete(additionalProperties, "baz") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_read_only_with_default.go b/samples/openapi3/client/petstore/go/go-petstore/model_read_only_with_default.go index 5bf6817a9c9b..623d1aea12b7 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_read_only_with_default.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_read_only_with_default.go @@ -323,10 +323,10 @@ func (o ReadOnlyWithDefault) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *ReadOnlyWithDefault) UnmarshalJSON(bytes []byte) (err error) { +func (o *ReadOnlyWithDefault) UnmarshalJSON(data []byte) (err error) { varReadOnlyWithDefault := _ReadOnlyWithDefault{} - err = json.Unmarshal(bytes, &varReadOnlyWithDefault) + err = json.Unmarshal(data, &varReadOnlyWithDefault) if err != nil { return err @@ -336,7 +336,7 @@ func (o *ReadOnlyWithDefault) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "prop1") delete(additionalProperties, "prop2") delete(additionalProperties, "prop3") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_return.go b/samples/openapi3/client/petstore/go/go-petstore/model_return.go index 991ccc4bd796..0b487e63841b 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_return.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_return.go @@ -95,10 +95,10 @@ func (o Return) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Return) UnmarshalJSON(bytes []byte) (err error) { +func (o *Return) UnmarshalJSON(data []byte) (err error) { varReturn := _Return{} - err = json.Unmarshal(bytes, &varReturn) + err = json.Unmarshal(data, &varReturn) if err != nil { return err @@ -108,7 +108,7 @@ func (o *Return) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "return") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_tag.go b/samples/openapi3/client/petstore/go/go-petstore/model_tag.go index 822a5a12c015..379b5b352802 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_tag.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_tag.go @@ -131,10 +131,10 @@ func (o Tag) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Tag) UnmarshalJSON(bytes []byte) (err error) { +func (o *Tag) UnmarshalJSON(data []byte) (err error) { varTag := _Tag{} - err = json.Unmarshal(bytes, &varTag) + err = json.Unmarshal(data, &varTag) if err != nil { return err @@ -144,7 +144,7 @@ func (o *Tag) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "id") delete(additionalProperties, "name") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_test_inline_freeform_additional_properties_request.go b/samples/openapi3/client/petstore/go/go-petstore/model_test_inline_freeform_additional_properties_request.go index 6e3866edc910..d4f4604247ee 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_test_inline_freeform_additional_properties_request.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_test_inline_freeform_additional_properties_request.go @@ -95,10 +95,10 @@ func (o TestInlineFreeformAdditionalPropertiesRequest) ToMap() (map[string]inter return toSerialize, nil } -func (o *TestInlineFreeformAdditionalPropertiesRequest) UnmarshalJSON(bytes []byte) (err error) { +func (o *TestInlineFreeformAdditionalPropertiesRequest) UnmarshalJSON(data []byte) (err error) { varTestInlineFreeformAdditionalPropertiesRequest := _TestInlineFreeformAdditionalPropertiesRequest{} - err = json.Unmarshal(bytes, &varTestInlineFreeformAdditionalPropertiesRequest) + err = json.Unmarshal(data, &varTestInlineFreeformAdditionalPropertiesRequest) if err != nil { return err @@ -108,7 +108,7 @@ func (o *TestInlineFreeformAdditionalPropertiesRequest) UnmarshalJSON(bytes []by additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "someProperty") o.AdditionalProperties = additionalProperties } diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_user.go b/samples/openapi3/client/petstore/go/go-petstore/model_user.go index 08a1961af341..40bbc886acb1 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_user.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_user.go @@ -499,10 +499,10 @@ func (o User) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *User) UnmarshalJSON(bytes []byte) (err error) { +func (o *User) UnmarshalJSON(data []byte) (err error) { varUser := _User{} - err = json.Unmarshal(bytes, &varUser) + err = json.Unmarshal(data, &varUser) if err != nil { return err @@ -512,7 +512,7 @@ func (o *User) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "id") delete(additionalProperties, "username") delete(additionalProperties, "firstName") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_whale.go b/samples/openapi3/client/petstore/go/go-petstore/model_whale.go index 7e450a046cd9..7d418d153bfe 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_whale.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_whale.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Whale type satisfies the MappedNullable interface at compile time @@ -158,10 +159,31 @@ func (o Whale) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Whale) UnmarshalJSON(bytes []byte) (err error) { +func (o *Whale) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varWhale := _Whale{} - err = json.Unmarshal(bytes, &varWhale) + err = json.Unmarshal(data, &varWhale) if err != nil { return err @@ -171,7 +193,7 @@ func (o *Whale) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "hasBaleen") delete(additionalProperties, "hasTeeth") delete(additionalProperties, "className") diff --git a/samples/openapi3/client/petstore/go/go-petstore/model_zebra.go b/samples/openapi3/client/petstore/go/go-petstore/model_zebra.go index 01a0ae804d41..acb4acc5b1f8 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/model_zebra.go +++ b/samples/openapi3/client/petstore/go/go-petstore/model_zebra.go @@ -12,6 +12,7 @@ package petstore import ( "encoding/json" + "fmt" ) // checks if the Zebra type satisfies the MappedNullable interface at compile time @@ -122,10 +123,31 @@ func (o Zebra) ToMap() (map[string]interface{}, error) { return toSerialize, nil } -func (o *Zebra) UnmarshalJSON(bytes []byte) (err error) { +func (o *Zebra) UnmarshalJSON(data []byte) (err error) { + // This validates that all required properties are included in the JSON object + // by unmarshalling the object into a generic map with string keys and checking + // that every required field exists as a key in the generic map. + requiredProperties := []string{ + "className", + } + + allProperties := make(map[string]interface{}) + + err = json.Unmarshal(data, &allProperties) + + if err != nil { + return err; + } + + for _, requiredProperty := range(requiredProperties) { + if _, exists := allProperties[requiredProperty]; !exists { + return fmt.Errorf("no value given for required property %v", requiredProperty) + } + } + varZebra := _Zebra{} - err = json.Unmarshal(bytes, &varZebra) + err = json.Unmarshal(data, &varZebra) if err != nil { return err @@ -135,7 +157,7 @@ func (o *Zebra) UnmarshalJSON(bytes []byte) (err error) { additionalProperties := make(map[string]interface{}) - if err = json.Unmarshal(bytes, &additionalProperties); err == nil { + if err = json.Unmarshal(data, &additionalProperties); err == nil { delete(additionalProperties, "type") delete(additionalProperties, "className") o.AdditionalProperties = additionalProperties diff --git a/samples/openapi3/client/petstore/go/go-petstore/signing.go b/samples/openapi3/client/petstore/go/go-petstore/signing.go index 4800302ad439..540080b1ff44 100644 --- a/samples/openapi3/client/petstore/go/go-petstore/signing.go +++ b/samples/openapi3/client/petstore/go/go-petstore/signing.go @@ -116,6 +116,7 @@ var supportedSigningSchemes = map[string]bool{ type HttpSignatureAuth struct { KeyId string // A key identifier. PrivateKeyPath string // The path to the private key. + PrivateKeyReader io.Reader // provide the APIKey using the types which implement io.Reader interface. Passphrase string // The passphrase to decrypt the private key, if the key is encrypted. SigningScheme string // The signature scheme, when signing HTTP requests. Supported value is 'hs2019'. // The signature algorithm, when signing HTTP requests. @@ -143,9 +144,12 @@ func (h *HttpSignatureAuth) ContextWithValue(ctx context.Context) (context.Conte if h.KeyId == "" { return nil, fmt.Errorf("key ID must be specified") } - if h.PrivateKeyPath == "" && h.privateKey == nil { + if (len(h.PrivateKeyPath) == 0 && h.PrivateKeyReader == nil) && h.privateKey == nil { return nil, fmt.Errorf("private key path must be specified") } + if len(h.PrivateKeyPath) > 0 && h.PrivateKeyReader != nil{ + return nil, fmt.Errorf("Specify only one of PrivateKeyPath or PrivateKeyReader") + } if _, ok := supportedSigningSchemes[h.SigningScheme]; !ok { return nil, fmt.Errorf("invalid signing scheme: '%v'", h.SigningScheme) } @@ -193,17 +197,21 @@ func (h *HttpSignatureAuth) loadPrivateKey() (err error) { if h.privateKey != nil { return nil } - var file *os.File - file, err = os.Open(h.PrivateKeyPath) - if err != nil { - return fmt.Errorf("cannot load private key '%s'. Error: %v", h.PrivateKeyPath, err) - } - defer func() { - err = file.Close() - }() var priv []byte - priv, err = io.ReadAll(file) - if err != nil { + keyReader := h.PrivateKeyReader + if keyReader == nil { + var file *os.File + file, err = os.Open(h.PrivateKeyPath) + if err != nil { + return fmt.Errorf("cannot load private key '%s'. Error: %v", h.PrivateKeyPath, err) + } + keyReader = file + defer func() { + err = file.Close() + }() + } + priv, err = io.ReadAll(keyReader) + if err != nil{ return err } return h.parsePrivateKey(priv) diff --git a/samples/openapi3/client/petstore/go/model_test.go b/samples/openapi3/client/petstore/go/model_test.go index 34868a43fdb7..cc6eabbeaa0a 100644 --- a/samples/openapi3/client/petstore/go/model_test.go +++ b/samples/openapi3/client/petstore/go/model_test.go @@ -4,8 +4,9 @@ import ( "encoding/json" "testing" - "github.com/stretchr/testify/assert" sw "go-petstore" + + "github.com/stretchr/testify/assert" ) func TestBanana(t *testing.T) { @@ -51,3 +52,14 @@ func TestReadOnlyFirst(t *testing.T) { assert.Equal(expected, (string)(json), "ReadOnlyFirst JSON is incorrect") } + +func TestRequiredFieldsAreValidated(t *testing.T) { + assert := assert.New(t) + + newPet := (sw.Pet{}) + jsonPet := `{"foo": "Foo value"}` + err := newPet.UnmarshalJSON([]byte(jsonPet)) + expected := "no value given for required property" + + assert.ErrorContains(err, expected, "Pet should return error when missing required fields") +} diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml index 2bfcc8d5e155..4593aa61a371 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml +++ b/samples/openapi3/client/petstore/java/jersey2-java8-special-characters/api/openapi.yaml @@ -49,4 +49,7 @@ components: \ characters. The sanitization rules should make it possible to generate a\ \ language-specific classname with allowed characters in that programming\ \ language." + example: + prop2: prop2 + objectType: objectType diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8-swagger2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION b/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/java/jersey2-java8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/README.md b/samples/openapi3/client/petstore/java/jersey2-java8/README.md index 15d325d63ac4..f29fdc674617 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/README.md +++ b/samples/openapi3/client/petstore/java/jersey2-java8/README.md @@ -146,6 +146,7 @@ Class | Method | HTTP request | Description *FakeApi* | [**fakeOuterNumberSerialize**](docs/FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | *FakeApi* | [**fakeOuterStringSerialize**](docs/FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | *FakeApi* | [**getArrayOfEnums**](docs/FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums +*FakeApi* | [**testAdditionalPropertiesReference**](docs/FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**testBodyWithFileSchema**](docs/FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**testBodyWithQueryParams**](docs/FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | *FakeApi* | [**testClientModel**](docs/FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml index 2dcf21ae0b3d..814354567b04 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml +++ b/samples/openapi3/client/petstore/java/jersey2-java8/api/openapi.yaml @@ -937,6 +937,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1760,6 +1779,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/docs/FakeApi.md b/samples/openapi3/client/petstore/java/jersey2-java8/docs/FakeApi.md index 83f469863c9a..55a9c935065e 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/java/jersey2-java8/docs/FakeApi.md @@ -10,6 +10,7 @@ All URIs are relative to *http://petstore.swagger.io:80/v2* | [**fakeOuterNumberSerialize**](FakeApi.md#fakeOuterNumberSerialize) | **POST** /fake/outer/number | | | [**fakeOuterStringSerialize**](FakeApi.md#fakeOuterStringSerialize) | **POST** /fake/outer/string | | | [**getArrayOfEnums**](FakeApi.md#getArrayOfEnums) | **GET** /fake/array-of-enums | Array of Enums | +| [**testAdditionalPropertiesReference**](FakeApi.md#testAdditionalPropertiesReference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties | | [**testBodyWithFileSchema**](FakeApi.md#testBodyWithFileSchema) | **PUT** /fake/body-with-file-schema | | | [**testBodyWithQueryParams**](FakeApi.md#testBodyWithQueryParams) | **PUT** /fake/body-with-query-params | | | [**testClientModel**](FakeApi.md#testClientModel) | **PATCH** /fake | To test \"client\" model | @@ -402,6 +403,70 @@ No authorization required | **200** | Got named array of enums | - | +## testAdditionalPropertiesReference + +> testAdditionalPropertiesReference(requestBody) + +test referenced additionalProperties + + + +### Example + +```java +// Import classes: +import org.openapitools.client.ApiClient; +import org.openapitools.client.ApiException; +import org.openapitools.client.Configuration; +import org.openapitools.client.model.*; +import org.openapitools.client.api.FakeApi; + +public class Example { + public static void main(String[] args) { + ApiClient defaultClient = Configuration.getDefaultApiClient(); + defaultClient.setBasePath("http://petstore.swagger.io:80/v2"); + + FakeApi apiInstance = new FakeApi(defaultClient); + Map requestBody = null; // Map | request body + try { + apiInstance.testAdditionalPropertiesReference(requestBody); + } catch (ApiException e) { + System.err.println("Exception when calling FakeApi#testAdditionalPropertiesReference"); + System.err.println("Status code: " + e.getCode()); + System.err.println("Reason: " + e.getResponseBody()); + System.err.println("Response headers: " + e.getResponseHeaders()); + e.printStackTrace(); + } + } +} +``` + +### Parameters + + +| Name | Type | Description | Notes | +|------------- | ------------- | ------------- | -------------| +| **requestBody** | **Map<String,Object>**| request body | | + +### Return type + +null (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + +- **Content-Type**: application/json +- **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +| **200** | successful operation | - | + + ## testBodyWithFileSchema > testBodyWithFileSchema(fileSchemaTestClass) diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java index be2aa6952f09..93ac0bd8b56f 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/api/FakeApi.java @@ -268,6 +268,45 @@ public ApiResponse> getArrayOfEnumsWithHttpInfo() throws ApiExce new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(), localVarAccept, localVarContentType, null, localVarReturnType, false); } + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @throws ApiException if fails to make API call + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public void testAdditionalPropertiesReference(Map requestBody) throws ApiException { + testAdditionalPropertiesReferenceWithHttpInfo(requestBody); + } + + /** + * test referenced additionalProperties + * + * @param requestBody request body (required) + * @return ApiResponse<Void> + * @throws ApiException if fails to make API call + * @http.response.details + + + +
              Status Code Description Response Headers
              200 successful operation -
              + */ + public ApiResponse testAdditionalPropertiesReferenceWithHttpInfo(Map requestBody) throws ApiException { + // Check required parameters + if (requestBody == null) { + throw new ApiException(400, "Missing the required parameter 'requestBody' when calling testAdditionalPropertiesReference"); + } + + String localVarAccept = apiClient.selectHeaderAccept(); + String localVarContentType = apiClient.selectHeaderContentType("application/json"); + return apiClient.invokeAPI("FakeApi.testAdditionalPropertiesReference", "/fake/additionalProperties-reference", "POST", new ArrayList<>(), requestBody, + new LinkedHashMap<>(), new LinkedHashMap<>(), new LinkedHashMap<>(), localVarAccept, localVarContentType, + null, null, false); + } /** * * For this test, the body for this request much reference a schema named `File`. diff --git a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java index e473f1eee239..7971240f8b49 100644 --- a/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java +++ b/samples/openapi3/client/petstore/java/jersey2-java8/src/main/java/org/openapitools/client/model/FormatTest.java @@ -568,7 +568,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES index 00dc818606f1..b85011e97909 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/FILES @@ -12,7 +12,6 @@ docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md docs/AnyOfPig.md -docs/ApiResponse.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md @@ -54,6 +53,7 @@ docs/MapOfArrayOfModel.md docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md +docs/ModelApiResponse.md docs/ModelReturn.md docs/Name.md docs/NullableClass.md @@ -84,6 +84,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TestErrorResponsesWithModel400Response.md +docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md @@ -114,7 +116,6 @@ petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py petstore_api/models/any_of_pig.py -petstore_api/models/api_response.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py @@ -153,6 +154,7 @@ petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py petstore_api/models/mixed_properties_and_additional_properties_class.py petstore_api/models/model200_response.py +petstore_api/models/model_api_response.py petstore_api/models/model_return.py petstore_api/models/name.py petstore_api/models/nullable_class.py @@ -181,6 +183,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/test_error_responses_with_model400_response.py +petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py diff --git a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python-aiohttp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-aiohttp/README.md b/samples/openapi3/client/petstore/python-aiohttp/README.md index 88ea04ad16ef..e9b47709917f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-aiohttp/README.md @@ -50,7 +50,6 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python import datetime -import time import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -96,14 +95,18 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**fake_ref_enum_string**](docs/FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string *FakeApi* | [**fake_return_list_of_objects**](docs/FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects *FakeApi* | [**fake_uuid_example**](docs/FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +*FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_date_time_query_parameter**](docs/FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +*FakeApi* | [**test_empty_and_non_empty_responses**](docs/FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_error_responses_with_model**](docs/FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model *FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_inline_freeform_additional_properties**](docs/FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -143,7 +146,6 @@ Class | Method | HTTP request | Description - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) - [AnyOfPig](docs/AnyOfPig.md) - - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) @@ -182,6 +184,7 @@ Class | Method | HTTP request | Description - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) - [NullableClass](docs/NullableClass.md) @@ -210,6 +213,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) + - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md index beedef76c051..f9556560ea43 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesAnyType.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md index 6abc3136b9ca..dd6a13fd8e90 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_property** | **Dict[str, str]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md index 8b9259c687f6..3e5dc0557c4f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesObject.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md index d66094f18e57..540511bfdfa5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md index 1a8b4df7ecc5..64ec2aece749 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AllOfWithSingleRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **username** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md index b62f19690994..c052862c7b35 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Animal.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnotherFakeApi.md index 95447def35e4..59bc936ed5e0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnotherFakeApi.md @@ -16,9 +16,8 @@ To test special tags and operation ID starting with number ### Example + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -50,6 +49,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -68,6 +68,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md index 9b161ccba1c0..0b36e7623305 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfColor.md @@ -3,6 +3,7 @@ Any of RGB array, RGBA array, or hex string. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md index 2da7ca6eefe7..a88832b1a221 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/AnyOfPig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md index 094061592613..7928604f14c9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **another_property** | **List[List[Tag]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md index 3f0c127d4fa3..5d9baca180b5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfArrayOfNumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_array_number** | **List[List[float]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md index c10191915a70..efaf6adb623e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayOfNumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_number** | **List[float]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md index 0a40fb36d26f..97e52ef5d6b3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ArrayTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_of_string** | **List[str]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md index 552b9390c7e5..19a5ba6a0aac 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/BasquePig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md index 99e6fae88fde..26dcd554b18f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Capitalization.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **small_camel** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md index 4b509dda7ea3..1a69ead05378 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Cat.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **declawed** | **bool** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md index c49514ef8023..42ac5ce00d61 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Category.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md index d5e97934d2be..99e42d961c53 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/CircularReferenceModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md index 1b6fb7cfc77d..196e4d77bace 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ClassModel.md @@ -3,6 +3,7 @@ Model for testing model with \"_class\" property ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_class** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md index b0ded10dd762..5eb04e6a5097 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Client.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **client** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md index 07fcd01991ac..769f47b82a69 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Color.md @@ -3,6 +3,7 @@ RGB array, RGBA array, or hex string. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md index 54249d5871e0..1df27fe75a53 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Creature.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **info** | [**CreatureInfo**](CreatureInfo.md) | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md index 5a600b9f3374..7211f27546d5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/CreatureInfo.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md index 253616c2fc32..04b55ec828bc 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DanishPig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DefaultApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DefaultApi.md index 558535484016..d1ffeafbca36 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DefaultApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DefaultApi.md @@ -14,9 +14,8 @@ Method | HTTP request | Description ### Example + ```python -import time -import os import petstore_api from petstore_api.models.foo_get_default_response import FooGetDefaultResponse from petstore_api.rest import ApiException @@ -45,6 +44,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -61,6 +61,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | response | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md index e6cf57189634..2a081e0710cf 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DeprecatedObject.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md index 3469be73a761..958fc3dae084 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Dog.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **breed** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md index e690a8874f8c..8ecb4948523c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/DummyModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md index d21f58a66087..19b048165d00 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumArrays.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_symbol** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumClass.md index 64830e3d1dee..8097457bd55a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString1.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString1.md index 194d65b48fa0..1e2b5eaa0390 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString1.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString1.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString2.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString2.md index 0d8568bfbeff..15a466f322d4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString2.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumString2.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md index 5bcb8e7027e3..e5c6e6dee0b9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/EnumTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enum_string** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md index 5ffe9b3f068d..5f02b061a811 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeApi.md @@ -13,14 +13,18 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**fake_ref_enum_string**](FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string [**fake_return_list_of_objects**](FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects [**fake_uuid_example**](FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +[**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_date_time_query_parameter**](FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +[**test_empty_and_non_empty_responses**](FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_error_responses_with_model**](FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model [**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_inline_freeform_additional_properties**](FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -35,9 +39,8 @@ test any type request body ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -66,6 +69,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **object**| | [optional] @@ -84,6 +88,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | OK | - | @@ -97,9 +102,8 @@ test enum reference query parameter ### Example + ```python -import time -import os import petstore_api from petstore_api.models.enum_class import EnumClass from petstore_api.rest import ApiException @@ -129,6 +133,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **enum_ref** | [**EnumClass**](.md)| enum reference | [optional] @@ -147,6 +152,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Get successful | - | @@ -160,9 +166,8 @@ Health check endpoint ### Example + ```python -import time -import os import petstore_api from petstore_api.models.health_check_result import HealthCheckResult from petstore_api.rest import ApiException @@ -192,6 +197,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -208,6 +214,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | The instance started successfully | - | @@ -221,9 +228,8 @@ test http signature authentication ### Example + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -322,6 +328,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -342,6 +349,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | The instance started successfully | - | @@ -357,9 +365,8 @@ Test serialization of outer boolean types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -389,6 +396,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bool**| Input boolean as post body | [optional] @@ -407,6 +415,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output boolean | - | @@ -422,9 +431,8 @@ Test serialization of object with outer number type ### Example + ```python -import time -import os import petstore_api from petstore_api.models.outer_composite import OuterComposite from petstore_api.rest import ApiException @@ -455,6 +463,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **outer_composite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] @@ -473,6 +482,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output composite | - | @@ -488,9 +498,8 @@ Test serialization of outer number types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -520,6 +529,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **float**| Input number as post body | [optional] @@ -538,6 +548,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output number | - | @@ -553,9 +564,8 @@ Test serialization of outer string types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -585,6 +595,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **str**| Input string as post body | [optional] @@ -603,6 +614,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output string | - | @@ -618,9 +630,8 @@ Test serialization of enum (int) properties with examples ### Example + ```python -import time -import os import petstore_api from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty from petstore_api.rest import ApiException @@ -651,6 +662,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **outer_object_with_enum_property** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body | @@ -669,12 +681,75 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output enum (int) | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **fake_ref_enum_string** +> EnumClass fake_ref_enum_string() + +test ref to enum string + +### Example + + +```python +import petstore_api +from petstore_api.models.enum_class import EnumClass +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test ref to enum string + api_response = await api_instance.fake_ref_enum_string() + print("The response of FakeApi->fake_ref_enum_string:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->fake_ref_enum_string: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**EnumClass**](EnumClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: plain/text + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fake_return_list_of_objects** > List[List[Tag]] fake_return_list_of_objects() @@ -682,9 +757,8 @@ test returning list of objects ### Example + ```python -import time -import os import petstore_api from petstore_api.models.tag import Tag from petstore_api.rest import ApiException @@ -714,6 +788,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -730,6 +805,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | OK | - | @@ -743,9 +819,8 @@ test uuid example ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -774,6 +849,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **uuid_example** | **str**| uuid example | @@ -792,12 +868,78 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Get successful | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_additional_properties_reference** +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + request_body = None # Dict[str, object] | request body + + try: + # test referenced additionalProperties + await api_instance.test_additional_properties_reference(request_body) + except Exception as e: + print("Exception when calling FakeApi->test_additional_properties_reference: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**Dict[str, object]**](object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_binary** > test_body_with_binary(body) @@ -807,9 +949,8 @@ For this test, the body has to be a binary file. ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -837,6 +978,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bytearray**| image to upload | @@ -855,6 +997,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -870,9 +1013,8 @@ For this test, the body for this request must reference a schema named `File`. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.rest import ApiException @@ -901,6 +1043,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **file_schema_test_class** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | @@ -919,6 +1062,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -932,9 +1076,8 @@ No authorization required ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -964,6 +1107,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query** | **str**| | @@ -983,6 +1127,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -998,9 +1143,8 @@ To test \"client\" model ### Example + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -1032,6 +1176,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -1050,6 +1195,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1063,9 +1209,8 @@ No authorization required ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1094,6 +1239,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **date_time_query** | **datetime**| | @@ -1113,12 +1259,75 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_empty_and_non_empty_responses** +> test_empty_and_non_empty_responses() + +test empty and non-empty responses + + + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test empty and non-empty responses + await api_instance.test_empty_and_non_empty_responses() + except Exception as e: + print("Exception when calling FakeApi->test_empty_and_non_empty_responses: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**206** | Partial response content | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_endpoint_parameters** > test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, var_float=var_float, string=string, binary=binary, byte_with_max_length=byte_with_max_length, var_date=var_date, date_time=date_time, password=password, param_callback=param_callback) @@ -1129,9 +1338,8 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example * Basic Authentication (http_basic_test): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1184,6 +1392,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | @@ -1216,6 +1425,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid username supplied | - | @@ -1223,6 +1433,67 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_error_responses_with_model** +> test_error_responses_with_model() + +test error responses with model + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test error responses with model + await api_instance.test_error_responses_with_model() + except Exception as e: + print("Exception when calling FakeApi->test_error_responses_with_model: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**400** | | - | +**404** | | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_group_parameters** > test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) @@ -1233,9 +1504,8 @@ Fake endpoint to test group parameters (optional) ### Example * Bearer (JWT) Authentication (bearer_test): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1278,6 +1548,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **required_string_group** | **int**| Required String in group parameters | @@ -1301,6 +1572,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Someting wrong | - | @@ -1316,9 +1588,8 @@ test inline additionalProperties ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1347,6 +1618,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **request_body** | [**Dict[str, str]**](str.md)| request body | @@ -1365,6 +1637,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1380,9 +1653,8 @@ test inline free-form additionalProperties ### Example + ```python -import time -import os import petstore_api from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.rest import ApiException @@ -1412,6 +1684,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **test_inline_freeform_additional_properties_request** | [**TestInlineFreeformAdditionalPropertiesRequest**](TestInlineFreeformAdditionalPropertiesRequest.md)| request body | @@ -1430,6 +1703,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1445,9 +1719,8 @@ test json serialization of form data ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1477,6 +1750,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **param** | **str**| field1 | @@ -1496,6 +1770,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1511,9 +1786,8 @@ To test the collection format in query parameters ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1547,6 +1821,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pipe** | [**List[str]**](str.md)| | @@ -1571,6 +1846,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeClassnameTags123Api.md index 3f833a270cd7..d0d98577a5a2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FakeClassnameTags123Api.md @@ -17,9 +17,8 @@ To test class name in snake case ### Example * Api Key Authentication (api_key_query): + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -61,6 +60,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -79,6 +79,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/File.md b/samples/openapi3/client/petstore/python-aiohttp/docs/File.md index 586da8e32559..af7192f8d60c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/File.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/File.md @@ -3,6 +3,7 @@ Must be named `File` for test. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **source_uri** | **str** | Test capitalization | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md index fb967a8d9924..55abbcc14d7e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FileSchemaTestClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**File**](File.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md index b5e7ab766b45..0d4d44cf5f42 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FirstRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md index 8062d08df1dd..9cd6e8f56c53 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Foo.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [default to 'bar'] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md index 550fbe78fa17..96211ac791f5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FooGetDefaultResponse.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **string** | [**Foo**](Foo.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md index 4f1950492c07..eec9904cef5c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/FormatTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **integer** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md index 99573bd28a2f..e960a679b2ad 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/HasOnlyReadOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md index b8723e018aa1..8c26c2a47c39 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/HealthCheckResult.md @@ -3,6 +3,7 @@ Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **nullable_message** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md index 45d76ad458c4..5fc372302446 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/InnerDictWithProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **a_property** | **object** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md b/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md index 0a441f186dbc..f1dc942fa7ab 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/IntOrString.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/List.md b/samples/openapi3/client/petstore/python-aiohttp/docs/List.md deleted file mode 100644 index 7643e4ea92dd..000000000000 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/List.md +++ /dev/null @@ -1,28 +0,0 @@ -# List - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**var_123_list** | **str** | | [optional] - -## Example - -```python -from petstore_api.models.list import List - -# TODO update the JSON string below -json = "{}" -# create an instance of List from a JSON string -list_instance = List.from_json(json) -# print the JSON string representation of the object -print List.to_json() - -# convert the object into a dict -list_dict = list_instance.to_dict() -# create an instance of List from a dict -list_form_dict = list.from_dict(list_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md index ceb1f50705bd..7cf3da96c1d8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ListClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_123_list** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md index b97ace0f42c8..8380cbd6ffd1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MapOfArrayOfModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **shop_id_to_org_online_lip_map** | **Dict[str, List[Tag]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md index ba87758a5220..8c2f507e6964 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MapTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | **Dict[str, Dict[str, str]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 8f628d133abf..c3a2ec9609aa 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md index 6a20cefe99cb..c4306a646ffb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Model200Response.md @@ -3,6 +3,7 @@ Model for testing model name starting with number ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ApiResponse.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md similarity index 55% rename from samples/openapi3/client/petstore/python/docs/ApiResponse.md rename to samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md index ba35ea9e2f0e..659823b8051f 100644 --- a/samples/openapi3/client/petstore/python/docs/ApiResponse.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelApiResponse.md @@ -1,7 +1,8 @@ -# ApiResponse +# ModelApiResponse ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | [optional] @@ -11,19 +12,19 @@ Name | Type | Description | Notes ## Example ```python -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" -# create an instance of ApiResponse from a JSON string -api_response_instance = ApiResponse.from_json(json) +# create an instance of ModelApiResponse from a JSON string +model_api_response_instance = ModelApiResponse.from_json(json) # print the JSON string representation of the object -print ApiResponse.to_json() +print ModelApiResponse.to_json() # convert the object into a dict -api_response_dict = api_response_instance.to_dict() -# create an instance of ApiResponse from a dict -api_response_form_dict = api_response.from_dict(api_response_dict) +model_api_response_dict = model_api_response_instance.to_dict() +# create an instance of ModelApiResponse from a dict +model_api_response_form_dict = model_api_response.from_dict(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md index a5b47f423c81..861de1b9324b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ModelReturn.md @@ -3,6 +3,7 @@ Model for testing reserved words ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_return** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md index 4ccd0ce09aa2..01284e603d04 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Name.md @@ -3,6 +3,7 @@ Model for testing model name same as property name ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md index 1658756b50e4..93fa80af2eaf 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **required_integer_prop** | **int** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md index fd9cbbc51aaa..0ca7715cc961 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NullableProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md b/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md index f49216ddaa4e..5a80bd15c6da 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/NumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_number** | **float** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md index c4ba9a958503..6711cbfc07d4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectToTestAdditionalProperties.md @@ -3,6 +3,7 @@ Minimal object ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_property** | **bool** | Property | [optional] [default to False] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md index 8daa55a39161..c73370addc81 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ObjectWithDeprecatedFields.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfEnumString.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfEnumString.md index c7c28bc29440..63c06158223d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfEnumString.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OneOfEnumString.md @@ -3,6 +3,7 @@ oneOf enum strings ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md index e71e955a11dd..bd4c124320c7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Order.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md index 504e266f9a14..13f271f268db 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterComposite.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **my_number** | **float** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnum.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnum.md index 4cb31437c7e2..948ce460ac39 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnum.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnum.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumDefaultValue.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumDefaultValue.md index 4a5ba6428d83..bcb71d067649 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumDefaultValue.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumDefaultValue.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumInteger.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumInteger.md index fc84ec365851..c60cb25ddd65 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumInteger.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumInteger.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumIntegerDefaultValue.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumIntegerDefaultValue.md index 0de4199a8401..0f982a2609b5 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumIntegerDefaultValue.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterEnumIntegerDefaultValue.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md index c6a1cdcbc193..b8001294de6d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/OuterObjectWithEnumProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **str_value** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md index 9a963a6b722d..620ed9c2f4c1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Parent.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md index 04bf94942019..0c530c421647 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ParentWithOptionalDict.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md index 05a466f880a3..cc8fa36537f7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Pet.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PetApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PetApi.md index e6817874690a..5c94968b7caf 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PetApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PetApi.md @@ -25,9 +25,8 @@ Add a new pet to the store ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -126,6 +125,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -144,6 +144,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -161,9 +162,8 @@ Deletes a pet ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -199,6 +199,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| Pet id to delete | @@ -218,6 +219,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -235,9 +237,8 @@ Multiple status values can be provided with comma separated strings ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -338,6 +339,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **status** | [**List[str]**](str.md)| Status values that need to be considered for filter | @@ -356,6 +358,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -373,9 +376,8 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -476,6 +478,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **tags** | [**List[str]**](str.md)| Tags to filter by | @@ -494,6 +497,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -511,9 +515,8 @@ Returns a single pet ### Example * Api Key Authentication (api_key): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -555,6 +558,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to return | @@ -573,6 +577,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -591,9 +596,8 @@ Update an existing pet ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -692,6 +696,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -710,6 +715,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -729,9 +735,8 @@ Updates a pet in the store with form data ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -768,6 +773,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet that needs to be updated | @@ -788,6 +794,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -796,7 +803,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **upload_file** -> ApiResponse upload_file(pet_id, additional_metadata=additional_metadata, file=file) +> ModelApiResponse upload_file(pet_id, additional_metadata=additional_metadata, file=file) uploads an image @@ -805,11 +812,10 @@ uploads an image ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.rest import ApiException from pprint import pprint @@ -847,6 +853,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | @@ -855,7 +862,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**ModelApiResponse**](ModelApiResponse.md) ### Authorization @@ -867,6 +874,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -874,7 +882,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **upload_file_with_required_file** -> ApiResponse upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) +> ModelApiResponse upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) uploads an image (required) @@ -883,11 +891,10 @@ uploads an image (required) ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.rest import ApiException from pprint import pprint @@ -925,6 +932,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | @@ -933,7 +941,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**ModelApiResponse**](ModelApiResponse.md) ### Authorization @@ -945,6 +953,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md index 398d6c6c6e38..241a54b33099 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Pig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md index 2cc1898be69b..0893df6055d0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/PropertyNameCollision.md @@ -2,11 +2,12 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- +**underscore_type** | **str** | | [optional] **type** | **str** | | [optional] -**type** | **str** | | [optional] -**type_** | **str** | | [optional] +**type_with_underscore** | **str** | | [optional] ## Example diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md index 22b5acca70c7..f42def3b2e9c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/ReadOnlyFirst.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md index e6fb1e2d4f7c..a1af8f281fa9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SecondRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md index dbf9589d576b..50f9bf79663d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SelfReferenceModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SingleRefType.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SingleRefType.md index 4178ac3b505e..728e7c214aa3 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SingleRefType.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SingleRefType.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialCharacterEnum.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialCharacterEnum.md index 801c3b5c8459..b36a28316577 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialCharacterEnum.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialCharacterEnum.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md index 3d27640abb04..c59bb655a0d8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialModelName.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **special_property_name** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md index 0b4129525978..2c3491adc6b0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/SpecialName.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_property** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/StoreApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/StoreApi.md index 9d7a7b781701..27f240911fcb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/StoreApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/StoreApi.md @@ -19,9 +19,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -50,6 +49,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order_id** | **str**| ID of the order that needs to be deleted | @@ -68,6 +68,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid ID supplied | - | @@ -85,9 +86,8 @@ Returns a map of status codes to quantities ### Example * Api Key Authentication (api_key): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -126,6 +126,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -142,6 +143,7 @@ This endpoint does not need any parameter. - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -157,9 +159,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example + ```python -import time -import os import petstore_api from petstore_api.models.order import Order from petstore_api.rest import ApiException @@ -191,6 +192,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order_id** | **int**| ID of pet that needs to be fetched | @@ -209,6 +211,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -226,9 +229,8 @@ Place an order for a pet ### Example + ```python -import time -import os import petstore_api from petstore_api.models.order import Order from petstore_api.rest import ApiException @@ -260,6 +262,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order** | [**Order**](Order.md)| order placed for purchasing the pet | @@ -278,6 +281,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md index e680c68bedd8..a09b1949ce80 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Tag.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md new file mode 100644 index 000000000000..902a9c7c3a74 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel400Response.md @@ -0,0 +1,29 @@ +# TestErrorResponsesWithModel400Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason400** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel400Response from a JSON string +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel400Response.to_json() + +# convert the object into a dict +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel400Response from a dict +test_error_responses_with_model400_response_form_dict = test_error_responses_with_model400_response.from_dict(test_error_responses_with_model400_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md new file mode 100644 index 000000000000..bbcb7975db78 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestErrorResponsesWithModel404Response.md @@ -0,0 +1,29 @@ +# TestErrorResponsesWithModel404Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason404** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel404Response from a JSON string +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel404Response.to_json() + +# convert the object into a dict +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel404Response from a dict +test_error_responses_with_model404_response_form_dict = test_error_responses_with_model404_response.from_dict(test_error_responses_with_model404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 7cf86c5244e3..fe79a4322c63 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **some_property** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md b/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md index 6ce50a31f5ae..2d8b755e9670 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/Tiger.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **skill** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md index c102bb86bebf..2982c29e5d54 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dict_property** | **Dict[str, List[CreatureInfo]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md index 926404ccd6ee..a06bd36d74cb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dict_property** | **Dict[str, List[str]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/User.md b/samples/openapi3/client/petstore/python-aiohttp/docs/User.md index 6d7c357ea865..721a9d4401e1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/User.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/User.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/UserApi.md b/samples/openapi3/client/petstore/python-aiohttp/docs/UserApi.md index 0bd69e33d903..5bb4ccfdf228 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/UserApi.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/UserApi.md @@ -23,9 +23,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -55,6 +54,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**User**](User.md)| Created user object | @@ -73,6 +73,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -88,9 +89,8 @@ Creates list of users with given input array ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -120,6 +120,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**List[User]**](User.md)| List of user object | @@ -138,6 +139,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -153,9 +155,8 @@ Creates list of users with given input array ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -185,6 +186,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**List[User]**](User.md)| List of user object | @@ -203,6 +205,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -218,9 +221,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -249,6 +251,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The name that needs to be deleted | @@ -267,6 +270,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid username supplied | - | @@ -283,9 +287,8 @@ Get user by user name ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -317,6 +320,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The name that needs to be fetched. Use user1 for testing. | @@ -335,6 +339,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -352,9 +357,8 @@ Logs user into the system ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -386,6 +390,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The user name for login | @@ -405,6 +410,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | @@ -421,9 +427,8 @@ Logs out current logged in user session ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -450,6 +455,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -466,6 +472,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -481,9 +488,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -514,6 +520,7 @@ async with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| name that need to be deleted | @@ -533,6 +540,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid user supplied | - | diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md index 247afcab99da..c46f89e66f1d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python-aiohttp/docs/WithNestedOneOf.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py index c1c56eb81159..f791bc531127 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/__init__.py @@ -46,7 +46,6 @@ from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor from petstore_api.models.any_of_pig import AnyOfPig -from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.models.array_of_number_only import ArrayOfNumberOnly @@ -85,6 +84,7 @@ from petstore_api.models.map_test import MapTest from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.models.model200_response import Model200Response +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.model_return import ModelReturn from petstore_api.models.name import Name from petstore_api.models.nullable_class import NullableClass @@ -113,6 +113,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/another_fake_api.py index f5bab68542e5..591b44d0442d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/another_fake_api.py @@ -11,24 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import Field from typing_extensions import Annotated from petstore_api.models.client import Client -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class AnotherFakeApi: @@ -43,145 +37,272 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def call_123_test_special_tags( self, client: Annotated[Client, Field(description="client model")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Client: - """To test special tags # noqa: E501 + """To test special tags - To test special tags and operation ID starting with number # noqa: E501 + To test special tags and operation ID starting with number :param client: client model (required) :type client: Client - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the call_123_test_special_tags_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.call_123_test_special_tags_with_http_info.raw_function( - client, - **kwargs, + """ # noqa: E501 + + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def call_123_test_special_tags_with_http_info( self, client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test special tags # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test special tags - To test special tags and operation ID starting with number # noqa: E501 + To test special tags and operation ID starting with number :param client: client model (required) :type client: Client - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def call_123_test_special_tags_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test special tags + + To test special tags and operation ID starting with number + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method call_123_test_special_tags" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _call_123_test_special_tags_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + if client is not None: + _body_params = client + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/another-fake/dummy', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PATCH', + resource_path='/another-fake/dummy', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/default_api.py index 47a045335e3d..550b3a904e45 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/default_api.py @@ -11,22 +11,16 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from petstore_api.models.foo_get_default_response import FooGetDefaultResponse -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class DefaultApi: @@ -41,124 +35,238 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def foo_get( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FooGetDefaultResponse: - """foo_get # noqa: E501 + """foo_get - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: FooGetDefaultResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the foo_get_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.foo_get_with_http_info.raw_function( - **kwargs, + """ # noqa: E501 + + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def foo_get_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """foo_get # noqa: E501 - - - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FooGetDefaultResponse]: + """foo_get + + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(FooGetDefaultResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def foo_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """foo_get + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method foo_get" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _foo_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - } + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/foo', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/foo', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py index 0a106d3c5828..85725365c3e9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_api.py @@ -11,22 +11,15 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from datetime import date, datetime - -from pydantic import StrictBool, StrictBytes, StrictInt, StrictStr, field_validator +from datetime import date, datetime +from pydantic import Field, StrictBool, StrictBytes, StrictInt, StrictStr, field_validator from typing import Any, Dict, List, Optional, Union - +from typing_extensions import Annotated from petstore_api.models.client import Client from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass @@ -38,12 +31,9 @@ from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.user import User -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class FakeApi: @@ -58,391 +48,756 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def fake_any_type_request_body( self, body: Optional[Dict[str, Any]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test any type request body # noqa: E501 + """test any type request body :param body: :type body: object - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_any_type_request_body_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_any_type_request_body_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_any_type_request_body_with_http_info( self, body: Optional[Dict[str, Any]] = None, - **kwargs, - ) -> ApiResponse: - """test any type request body # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test any type request body :param body: :type body: object - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def fake_any_type_request_body_without_preload_content( + self, + body: Optional[Dict[str, Any]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test any type request body + + + :param body: + :type body: object + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_any_type_request_body" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_any_type_request_body_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/any_type_body', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/any_type_body', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_enum_ref_query_parameter( self, enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test enum reference query parameter # noqa: E501 + """test enum reference query parameter :param enum_ref: enum reference :type enum_ref: EnumClass - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_enum_ref_query_parameter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_enum_ref_query_parameter_with_http_info.raw_function( - enum_ref, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_enum_ref_query_parameter_with_http_info( self, enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, - **kwargs, - ) -> ApiResponse: - """test enum reference query parameter # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test enum reference query parameter :param enum_ref: enum reference :type enum_ref: EnumClass - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'enum_ref' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def fake_enum_ref_query_parameter_without_preload_content( + self, + enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test enum reference query parameter + + + :param enum_ref: enum reference + :type enum_ref: EnumClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_enum_ref_query_parameter" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _fake_enum_ref_query_parameter_serialize( + self, + enum_ref, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('enum_ref') is not None: # noqa: E501 - _query_params.append(('enum_ref', _params['enum_ref'].value)) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if enum_ref is not None: + + _query_params.append(('enum_ref', enum_ref.value)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/fake/enum_ref_query_parameter', 'GET', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/enum_ref_query_parameter', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_health_get( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> HealthCheckResult: - """Health check endpoint # noqa: E501 + """Health check endpoint - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: HealthCheckResult - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_health_get_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return await self.fake_health_get_with_http_info.raw_function( - **kwargs, + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def fake_health_get_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Health check endpoint # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HealthCheckResult]: + """Health check endpoint - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(HealthCheckResult, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def fake_health_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Health check endpoint + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_health_get" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_health_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "HealthCheckResult", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/health', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/health', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_http_signature_test( @@ -450,9 +805,20 @@ async def fake_http_signature_test( pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test http signature authentication # noqa: E501 + """test http signature authentication :param pet: Pet object that needs to be added to the store (required) @@ -461,26 +827,51 @@ async def fake_http_signature_test( :type query_1: str :param header_1: header parameter :type header_1: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_http_signature_test_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_http_signature_test_with_http_info.raw_function( - pet, - query_1, - header_1, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_http_signature_test_with_http_info( @@ -488,9 +879,20 @@ async def fake_http_signature_test_with_http_info( pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, - **kwargs, - ) -> ApiResponse: - """test http signature authentication # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test http signature authentication :param pet: Pet object that needs to be added to the store (required) @@ -499,1786 +901,4269 @@ async def fake_http_signature_test_with_http_info( :type query_1: str :param header_1: header parameter :type header_1: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'pet', - 'query_1', - 'header_1' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_http_signature_test" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + @validate_call + async def fake_http_signature_test_without_preload_content( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, + header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test http signature authentication - # process the path parameters - _path_params: Dict[str, str] = {} - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('query_1') is not None: # noqa: E501 - _query_params.append(('query_1', _params['query_1'])) + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param query_1: query parameter + :type query_1: str + :param header_1: header parameter + :type header_1: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['header_1'] is not None: - _header_params['header_1'] = _params['header_1'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - # process the form parameters + + def _fake_http_signature_test_serialize( + self, + pet, + query_1, + header_1, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if query_1 is not None: + + _query_params.append(('query_1', query_1)) + + # process the header parameters + if header_1 is not None: + _header_params['header_1'] = header_1 + # process the form parameters # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'http_signature_test' + ] - return await self.api_client.call_api( - '/fake/http-signature-test', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/http-signature-test', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_outer_boolean_serialize( self, body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> bool: - """fake_outer_boolean_serialize # noqa: E501 + """fake_outer_boolean_serialize - Test serialization of outer boolean types # noqa: E501 + Test serialization of outer boolean types :param body: Input boolean as post body :type body: bool - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: bool - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_boolean_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_outer_boolean_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_outer_boolean_serialize_with_http_info( self, body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_boolean_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[bool]: + """fake_outer_boolean_serialize - Test serialization of outer boolean types # noqa: E501 + Test serialization of outer boolean types :param body: Input boolean as post body :type body: bool - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(bool, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def fake_outer_boolean_serialize_without_preload_content( + self, + body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_boolean_serialize + + Test serialization of outer boolean types + + :param body: Input boolean as post body + :type body: bool + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_boolean_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_outer_boolean_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "bool", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/outer/boolean', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/boolean', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_outer_composite_serialize( self, outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> OuterComposite: - """fake_outer_composite_serialize # noqa: E501 + """fake_outer_composite_serialize - Test serialization of object with outer number type # noqa: E501 + Test serialization of object with outer number type :param outer_composite: Input composite as post body :type outer_composite: OuterComposite - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: OuterComposite - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_composite_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_outer_composite_serialize_with_http_info.raw_function( - outer_composite, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_outer_composite_serialize_with_http_info( self, outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_composite_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[OuterComposite]: + """fake_outer_composite_serialize - Test serialization of object with outer number type # noqa: E501 + Test serialization of object with outer number type :param outer_composite: Input composite as post body :type outer_composite: OuterComposite - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(OuterComposite, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'outer_composite' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def fake_outer_composite_serialize_without_preload_content( + self, + outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_composite_serialize + + Test serialization of object with outer number type + + :param outer_composite: Input composite as post body + :type outer_composite: OuterComposite + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_composite_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_outer_composite_serialize_serialize( + self, + outer_composite, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['outer_composite'] is not None: - _body_params = _params['outer_composite'] + if outer_composite is not None: + _body_params = outer_composite + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "OuterComposite", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/outer/composite', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/composite', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_outer_number_serialize( self, body: Annotated[Optional[float], Field(description="Input number as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> float: - """fake_outer_number_serialize # noqa: E501 + """fake_outer_number_serialize - Test serialization of outer number types # noqa: E501 + Test serialization of outer number types :param body: Input number as post body :type body: float - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: float - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_number_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_outer_number_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_outer_number_serialize_with_http_info( self, body: Annotated[Optional[float], Field(description="Input number as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_number_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[float]: + """fake_outer_number_serialize - Test serialization of outer number types # noqa: E501 + Test serialization of outer number types :param body: Input number as post body :type body: float - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(float, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def fake_outer_number_serialize_without_preload_content( + self, + body: Annotated[Optional[float], Field(description="Input number as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_number_serialize + + Test serialization of outer number types + + :param body: Input number as post body + :type body: float + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_number_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_outer_number_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "float", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/outer/number', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/number', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_outer_string_serialize( self, body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """fake_outer_string_serialize # noqa: E501 + """fake_outer_string_serialize - Test serialization of outer string types # noqa: E501 + Test serialization of outer string types :param body: Input string as post body :type body: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_string_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_outer_string_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_outer_string_serialize_with_http_info( self, body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_string_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """fake_outer_string_serialize - Test serialization of outer string types # noqa: E501 + Test serialization of outer string types :param body: Input string as post body :type body: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def fake_outer_string_serialize_without_preload_content( + self, + body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_string_serialize + + Test serialization of outer string types + + :param body: Input string as post body + :type body: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_string_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_outer_string_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/outer/string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def fake_property_enum_integer_serialize( self, outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> OuterObjectWithEnumProperty: - """fake_property_enum_integer_serialize # noqa: E501 + """fake_property_enum_integer_serialize - Test serialization of enum (int) properties with examples # noqa: E501 + Test serialization of enum (int) properties with examples :param outer_object_with_enum_property: Input enum (int) as post body (required) :type outer_object_with_enum_property: OuterObjectWithEnumProperty - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: OuterObjectWithEnumProperty - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_property_enum_integer_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.fake_property_enum_integer_serialize_with_http_info.raw_function( - outer_object_with_enum_property, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def fake_property_enum_integer_serialize_with_http_info( self, outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], - **kwargs, - ) -> ApiResponse: - """fake_property_enum_integer_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[OuterObjectWithEnumProperty]: + """fake_property_enum_integer_serialize - Test serialization of enum (int) properties with examples # noqa: E501 + Test serialization of enum (int) properties with examples :param outer_object_with_enum_property: Input enum (int) as post body (required) :type outer_object_with_enum_property: OuterObjectWithEnumProperty - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(OuterObjectWithEnumProperty, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'outer_object_with_enum_property' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def fake_property_enum_integer_serialize_without_preload_content( + self, + outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_property_enum_integer_serialize + + Test serialization of enum (int) properties with examples + + :param outer_object_with_enum_property: Input enum (int) as post body (required) + :type outer_object_with_enum_property: OuterObjectWithEnumProperty + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_property_enum_integer_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_property_enum_integer_serialize_serialize( + self, + outer_object_with_enum_property, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['outer_object_with_enum_property'] is not None: - _body_params = _params['outer_object_with_enum_property'] + if outer_object_with_enum_property is not None: + _body_params = outer_object_with_enum_property + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "OuterObjectWithEnumProperty", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/property/enum-int', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/property/enum-int', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - async def fake_return_list_of_objects( - self, - **kwargs, - ) -> List[List[Tag]]: - """test returning list of objects # noqa: E501 + _host=_host, + _request_auth=_request_auth + ) - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[List[Tag]] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_return_list_of_objects_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return await self.fake_return_list_of_objects_with_http_info.raw_function( - **kwargs, - ) @validate_call - async def fake_return_list_of_objects_with_http_info( + async def fake_ref_enum_string( self, - **kwargs, - ) -> ApiResponse: - """test returning list of objects # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> EnumClass: + """test ref to enum string - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[List[Tag]], status_code(int), headers(HTTPHeaderDict)) - """ - - _params = locals() + """ # noqa: E501 - _all_params = [ - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_return_list_of_objects" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats: Dict[str, str] = {} - - # process the path parameters - _path_params: Dict[str, str] = {} - - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[List[Tag]]", + '200': "EnumClass", } - - return await self.api_client.call_api( - '/fake/return_list_of_object', 'GET', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, response_types_map=_response_types_map, - auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + ).data + @validate_call - async def fake_uuid_example( + async def fake_ref_enum_string_with_http_info( self, - uuid_example: Annotated[StrictStr, Field(description="uuid example")], - **kwargs, - ) -> None: - """test uuid example # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[EnumClass]: + """test ref to enum string - :param uuid_example: uuid example (required) - :type uuid_example: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_uuid_example_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return await self.fake_uuid_example_with_http_info.raw_function( - uuid_example, - **kwargs, + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "EnumClass", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + @validate_call - async def fake_uuid_example_with_http_info( + async def fake_ref_enum_string_without_preload_content( self, - uuid_example: Annotated[StrictStr, Field(description="uuid example")], - **kwargs, - ) -> ApiResponse: - """test uuid example # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test ref to enum string - :param uuid_example: uuid example (required) - :type uuid_example: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'uuid_example' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': "EnumClass", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_uuid_example" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _fake_ref_enum_string_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the path parameters - _path_params: Dict[str, str] = {} + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('uuid_example') is not None: # noqa: E501 - _query_params.append(('uuid_example', _params['uuid_example'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/fake/uuid_example', 'GET', - _path_params, - _query_params, - _header_params, + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'plain/text' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/ref_enum_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - async def test_body_with_binary( + async def fake_return_list_of_objects( self, - body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], - **kwargs, - ) -> None: - """test_body_with_binary # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[List[Tag]]: + """test returning list of objects - For this test, the body has to be a binary file. # noqa: E501 - :param body: image to upload (required) - :type body: bytearray - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_body_with_binary_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - async def test_body_with_binary_with_http_info( + async def fake_return_list_of_objects_with_http_info( self, - body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], - **kwargs, - ) -> ApiResponse: - """test_body_with_binary # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[List[Tag]]]: + """test returning list of objects - For this test, the body has to be a binary file. # noqa: E501 - :param body: image to upload (required) - :type body: bytearray - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 - _all_params = [ - 'body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats: Dict[str, str] = {} - - # process the path parameters - _path_params: Dict[str, str] = {} - - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] - # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['image/png'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} - - return await self.api_client.call_api( - '/fake/body-with-binary', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, response_types_map=_response_types_map, - auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - async def test_body_with_file_schema( - self, - file_schema_test_class: FileSchemaTestClass, - **kwargs, - ) -> None: - """test_body_with_file_schema # noqa: E501 - - For this test, the body for this request must reference a schema named `File`. # noqa: E501 - - :param file_schema_test_class: (required) - :type file_schema_test_class: FileSchemaTestClass - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_file_schema_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.test_body_with_file_schema_with_http_info.raw_function( - file_schema_test_class, - **kwargs, ) + @validate_call - async def test_body_with_file_schema_with_http_info( + async def fake_return_list_of_objects_without_preload_content( self, - file_schema_test_class: FileSchemaTestClass, - **kwargs, - ) -> ApiResponse: - """test_body_with_file_schema # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test returning list of objects - For this test, the body for this request must reference a schema named `File`. # noqa: E501 - :param file_schema_test_class: (required) - :type file_schema_test_class: FileSchemaTestClass - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'file_schema_test_class' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_file_schema" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _fake_return_list_of_objects_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['file_schema_test_class'] is not None: - _body_params = _params['file_schema_test_class'] - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + - _response_types_map: Dict[str, Optional[str]] = {} + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/body-with-file-schema', 'PUT', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/return_list_of_object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - async def test_body_with_query_params( + async def fake_uuid_example( self, - query: StrictStr, - user: User, - **kwargs, + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test_body_with_query_params # noqa: E501 + """test uuid example - :param query: (required) - :type query: str - :param user: (required) - :type user: User - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param uuid_example: uuid example (required) + :type uuid_example: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_query_params_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_body_with_query_params_with_http_info.raw_function( - query, - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - async def test_body_with_query_params_with_http_info( + async def fake_uuid_example_with_http_info( self, - query: StrictStr, - user: User, - **kwargs, - ) -> ApiResponse: - """test_body_with_query_params # noqa: E501 + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test uuid example - :param query: (required) - :type query: str - :param user: (required) - :type user: User - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + :param uuid_example: uuid example (required) + :type uuid_example: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'query', - 'user' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def fake_uuid_example_without_preload_content( + self, + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test uuid example + + + :param uuid_example: uuid example (required) + :type uuid_example: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_query_params" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _fake_uuid_example_serialize( + self, + uuid_example, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('query') is not None: # noqa: E501 - _query_params.append(('query', _params['query'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if uuid_example is not None: + + _query_params.append(('uuid_example', uuid_example)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/fake/body-with-query-params', 'PUT', - _path_params, - _query_params, - _header_params, + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/uuid_example', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - async def test_client_model( + async def test_additional_properties_reference( self, - client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> Client: - """To test \"client\" model # noqa: E501 + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test referenced additionalProperties - To test \"client\" model # noqa: E501 + - :param client: client model (required) - :type client: Client - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_client_model_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_client_model_with_http_info.raw_function( - client, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - async def test_client_model_with_http_info( + async def test_additional_properties_reference_with_http_info( self, - client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test \"client\" model # noqa: E501 + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test referenced additionalProperties - To test \"client\" model # noqa: E501 + - :param client: client model (required) - :type client: Client - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + :param request_body: request body (required) + :type request_body: Dict[str, object] :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def test_additional_properties_reference_without_preload_content( + self, + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test referenced additionalProperties + + + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_client_model" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_additional_properties_reference_serialize( + self, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + if request_body is not None: + _body_params = request_body + - # set the HTTP header `Accept` - _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/additionalProperties-reference', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - async def test_date_time_query_parameter( - self, - date_time_query: datetime, - str_query: StrictStr, - **kwargs, - ) -> None: - """test_date_time_query_parameter # noqa: E501 + _host=_host, + _request_auth=_request_auth + ) - :param date_time_query: (required) - :type date_time_query: datetime - :param str_query: (required) - :type str_query: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_date_time_query_parameter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return await self.test_date_time_query_parameter_with_http_info.raw_function( - date_time_query, - str_query, - **kwargs, - ) @validate_call - async def test_date_time_query_parameter_with_http_info( + async def test_body_with_binary( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_body_with_binary_with_http_info( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_body_with_binary_without_preload_content( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_binary_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + # convert to byte array if the input is a file name (str) + if isinstance(body, str): + with open(body, "rb") as _fp: + _body_params = _fp.read() + else: + _body_params = body + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'image/png' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_body_with_file_schema( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_body_with_file_schema_with_http_info( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_body_with_file_schema_without_preload_content( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_file_schema_serialize( + self, + file_schema_test_class, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if file_schema_test_class is not None: + _body_params = file_schema_test_class + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-file-schema', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_body_with_query_params( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_body_with_query_params_with_http_info( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_body_with_query_params_without_preload_content( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_query_params_serialize( + self, + query, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if query is not None: + + _query_params.append(('query', query)) + + # process the header parameters + # process the form parameters + # process the body parameter + if user is not None: + _body_params = user + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-query-params', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_client_model( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Client: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_client_model_with_http_info( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_client_model_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_client_model_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if client is not None: + _body_params = client + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_date_time_query_parameter( self, date_time_query: datetime, str_query: StrictStr, - **kwargs, - ) -> ApiResponse: - """test_date_time_query_parameter # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_date_time_query_parameter :param date_time_query: (required) :type date_time_query: datetime :param str_query: (required) :type str_query: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data - _params = locals() - _all_params = [ - 'date_time_query', - 'str_query' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def test_date_time_query_parameter_with_http_info( + self, + date_time_query: datetime, + str_query: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_date_time_query_parameter + + + :param date_time_query: (required) + :type date_time_query: datetime + :param str_query: (required) + :type str_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_date_time_query_parameter" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters + @validate_call + async def test_date_time_query_parameter_without_preload_content( + self, + date_time_query: datetime, + str_query: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_date_time_query_parameter + + + :param date_time_query: (required) + :type date_time_query: datetime + :param str_query: (required) + :type str_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_date_time_query_parameter_serialize( + self, + date_time_query, + str_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('date_time_query') is not None: # noqa: E501 - if isinstance(_params['date_time_query'], datetime): - _query_params.append(('date_time_query', _params['date_time_query'].strftime(self.api_client.configuration.datetime_format))) + if date_time_query is not None: + if isinstance(date_time_query, datetime): + _query_params.append( + ( + 'date_time_query', + date_time_query.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) else: - _query_params.append(('date_time_query', _params['date_time_query'])) - - if _params.get('str_query') is not None: # noqa: E501 - _query_params.append(('str_query', _params['str_query'])) - + _query_params.append(('date_time_query', date_time_query)) + + if str_query is not None: + + _query_params.append(('str_query', str_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/date-time-query-params', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_empty_and_non_empty_responses( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test empty and non-empty responses + + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_empty_and_non_empty_responses_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test empty and non-empty responses + + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_empty_and_non_empty_responses_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test empty and non-empty responses + + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_empty_and_non_empty_responses_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/fake/date-time-query-params', 'PUT', - _path_params, - _query_params, - _header_params, + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'text/plain' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/empty_and_non_empty_responses', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + async def test_endpoint_parameters( + self, + number: Annotated[float, Field(le=543.2, ge=32.1, description="None")], + double: Annotated[float, Field(le=123.4, ge=67.8, description="None")], + pattern_without_delimiter: Annotated[str, Field(strict=True, description="None")], + byte: Annotated[Union[StrictBytes, StrictStr], Field(description="None")], + integer: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=10)]], Field(description="None")] = None, + int32: Annotated[Optional[Annotated[int, Field(le=200, strict=True, ge=20)]], Field(description="None")] = None, + int64: Annotated[Optional[StrictInt], Field(description="None")] = None, + var_float: Annotated[Optional[Annotated[float, Field(le=987.6)]], Field(description="None")] = None, + string: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="None")] = None, + binary: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="None")] = None, + byte_with_max_length: Annotated[Optional[Union[Annotated[bytes, Field(strict=True, max_length=64)], Annotated[str, Field(strict=True, max_length=64)]]], Field(description="None")] = None, + var_date: Annotated[Optional[date], Field(description="None")] = None, + date_time: Annotated[Optional[datetime], Field(description="None")] = None, + password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, + param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 + + :param number: None (required) + :type number: float + :param double: None (required) + :type double: float + :param pattern_without_delimiter: None (required) + :type pattern_without_delimiter: str + :param byte: None (required) + :type byte: bytearray + :param integer: None + :type integer: int + :param int32: None + :type int32: int + :param int64: None + :type int64: int + :param var_float: None + :type var_float: float + :param string: None + :type string: str + :param binary: None + :type binary: bytearray + :param byte_with_max_length: None + :type byte_with_max_length: bytearray + :param var_date: None + :type var_date: date + :param date_time: None + :type date_time: datetime + :param password: None + :type password: str + :param param_callback: None + :type param_callback: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - async def test_endpoint_parameters( + async def test_endpoint_parameters_with_http_info( self, number: Annotated[float, Field(le=543.2, ge=32.1, description="None")], double: Annotated[float, Field(le=123.4, ge=67.8, description="None")], @@ -2295,11 +5180,22 @@ async def test_endpoint_parameters( date_time: Annotated[Optional[datetime], Field(description="None")] = None, password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, - **kwargs, - ) -> None: - """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 :param number: None (required) :type number: float @@ -2331,41 +5227,67 @@ async def test_endpoint_parameters( :type password: str :param param_callback: None :type param_callback: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_endpoint_parameters_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.test_endpoint_parameters_with_http_info.raw_function( - number, - double, - pattern_without_delimiter, - byte, - integer, - int32, - int64, - var_float, - string, - binary, - byte_with_max_length, - var_date, - date_time, - password, - param_callback, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - async def test_endpoint_parameters_with_http_info( + async def test_endpoint_parameters_without_preload_content( self, number: Annotated[float, Field(le=543.2, ge=32.1, description="None")], double: Annotated[float, Field(le=123.4, ge=67.8, description="None")], @@ -2382,11 +5304,22 @@ async def test_endpoint_parameters_with_http_info( date_time: Annotated[Optional[datetime], Field(description="None")] = None, password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, - **kwargs, - ) -> ApiResponse: - """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 :param number: None (required) :type number: float @@ -2418,155 +5351,415 @@ async def test_endpoint_parameters_with_http_info( :type password: str :param param_callback: None :type param_callback: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'number', - 'double', - 'pattern_without_delimiter', - 'byte', - 'integer', - 'int32', - 'int64', - 'var_float', - 'string', - 'binary', - 'byte_with_max_length', - 'var_date', - 'date_time', - 'password', - 'param_callback' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_endpoint_parameters" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_endpoint_parameters_serialize( + self, + number, + double, + pattern_without_delimiter, + byte, + integer, + int32, + int64, + var_float, + string, + binary, + byte_with_max_length, + var_date, + date_time, + password, + param_callback, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['integer'] is not None: - _form_params.append(('integer', _params['integer'])) + if integer is not None: + _form_params.append(('integer', integer)) + if int32 is not None: + _form_params.append(('int32', int32)) + if int64 is not None: + _form_params.append(('int64', int64)) + if number is not None: + _form_params.append(('number', number)) + if var_float is not None: + _form_params.append(('float', var_float)) + if double is not None: + _form_params.append(('double', double)) + if string is not None: + _form_params.append(('string', string)) + if pattern_without_delimiter is not None: + _form_params.append(('pattern_without_delimiter', pattern_without_delimiter)) + if byte is not None: + _form_params.append(('byte', byte)) + if binary is not None: + _files['binary'] = binary + if byte_with_max_length is not None: + _form_params.append(('byte_with_max_length', byte_with_max_length)) + if var_date is not None: + _form_params.append(('date', var_date)) + if date_time is not None: + _form_params.append(('dateTime', date_time)) + if password is not None: + _form_params.append(('password', password)) + if param_callback is not None: + _form_params.append(('callback', param_callback)) + # process the body parameter + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'http_basic_test' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + - if _params['int32'] is not None: - _form_params.append(('int32', _params['int32'])) + @validate_call + async def test_error_responses_with_model( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test error responses with model + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_error_responses_with_model_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test error responses with model + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 - if _params['int64'] is not None: - _form_params.append(('int64', _params['int64'])) + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['number'] is not None: - _form_params.append(('number', _params['number'])) + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - if _params['var_float'] is not None: - _form_params.append(('float', _params['var_float'])) - if _params['double'] is not None: - _form_params.append(('double', _params['double'])) + @validate_call + async def test_error_responses_with_model_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test error responses with model - if _params['string'] is not None: - _form_params.append(('string', _params['string'])) - if _params['pattern_without_delimiter'] is not None: - _form_params.append(('pattern_without_delimiter', _params['pattern_without_delimiter'])) + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 - if _params['byte'] is not None: - _form_params.append(('byte', _params['byte'])) + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['binary'] is not None: - _files['binary'] = _params['binary'] + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['byte_with_max_length'] is not None: - _form_params.append(('byte_with_max_length', _params['byte_with_max_length'])) - if _params['var_date'] is not None: - _form_params.append(('date', _params['var_date'])) + def _test_error_responses_with_model_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - if _params['date_time'] is not None: - _form_params.append(('dateTime', _params['date_time'])) + _host = None - if _params['password'] is not None: - _form_params.append(('password', _params['password'])) + _collection_formats: Dict[str, str] = { + } - if _params['param_callback'] is not None: - _form_params.append(('callback', _params['param_callback'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = ['http_basic_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + - return await self.api_client.call_api( - '/fake', 'POST', - _path_params, - _query_params, - _header_params, + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/error_responses_with_model', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def test_group_parameters( @@ -2577,11 +5770,22 @@ async def test_group_parameters( string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Fake endpoint to test group parameters (optional) # noqa: E501 + """Fake endpoint to test group parameters (optional) - Fake endpoint to test group parameters (optional) # noqa: E501 + Fake endpoint to test group parameters (optional) :param required_string_group: Required String in group parameters (required) :type required_string_group: int @@ -2595,30 +5799,55 @@ async def test_group_parameters( :type boolean_group: bool :param int64_group: Integer in group parameters :type int64_group: int - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_group_parameters_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.test_group_parameters_with_http_info.raw_function( - required_string_group, - required_boolean_group, - required_int64_group, - string_group, - boolean_group, - int64_group, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def test_group_parameters_with_http_info( self, @@ -2628,11 +5857,22 @@ async def test_group_parameters_with_http_info( string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, - **kwargs, - ) -> ApiResponse: - """Fake endpoint to test group parameters (optional) # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Fake endpoint to test group parameters (optional) - Fake endpoint to test group parameters (optional) # noqa: E501 + Fake endpoint to test group parameters (optional) :param required_string_group: Required String in group parameters (required) :type required_string_group: int @@ -2646,534 +5886,1022 @@ async def test_group_parameters_with_http_info( :type boolean_group: bool :param int64_group: Integer in group parameters :type int64_group: int - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'required_string_group', - 'required_boolean_group', - 'required_int64_group', - 'string_group', - 'boolean_group', - 'int64_group' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def test_group_parameters_without_preload_content( + self, + required_string_group: Annotated[StrictInt, Field(description="Required String in group parameters")], + required_boolean_group: Annotated[StrictBool, Field(description="Required Boolean in group parameters")], + required_int64_group: Annotated[StrictInt, Field(description="Required Integer in group parameters")], + string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, + boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, + int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Fake endpoint to test group parameters (optional) + + Fake endpoint to test group parameters (optional) + + :param required_string_group: Required String in group parameters (required) + :type required_string_group: int + :param required_boolean_group: Required Boolean in group parameters (required) + :type required_boolean_group: bool + :param required_int64_group: Required Integer in group parameters (required) + :type required_int64_group: int + :param string_group: String in group parameters + :type string_group: int + :param boolean_group: Boolean in group parameters + :type boolean_group: bool + :param int64_group: Integer in group parameters + :type int64_group: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_group_parameters" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _test_group_parameters_serialize( + self, + required_string_group, + required_boolean_group, + required_int64_group, + string_group, + boolean_group, + int64_group, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the query parameters + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('required_string_group') is not None: # noqa: E501 - _query_params.append(('required_string_group', _params['required_string_group'])) - - if _params.get('required_int64_group') is not None: # noqa: E501 - _query_params.append(('required_int64_group', _params['required_int64_group'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None - if _params.get('string_group') is not None: # noqa: E501 - _query_params.append(('string_group', _params['string_group'])) + # process the path parameters + # process the query parameters + if required_string_group is not None: + + _query_params.append(('required_string_group', required_string_group)) + + if required_int64_group is not None: + + _query_params.append(('required_int64_group', required_int64_group)) + + if string_group is not None: + + _query_params.append(('string_group', string_group)) + + if int64_group is not None: + + _query_params.append(('int64_group', int64_group)) + + # process the header parameters + if required_boolean_group is not None: + _header_params['required_boolean_group'] = required_boolean_group + if boolean_group is not None: + _header_params['boolean_group'] = boolean_group + # process the form parameters + # process the body parameter - if _params.get('int64_group') is not None: # noqa: E501 - _query_params.append(('int64_group', _params['int64_group'])) - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['required_boolean_group'] is not None: - _header_params['required_boolean_group'] = _params['required_boolean_group'] - if _params['boolean_group'] is not None: - _header_params['boolean_group'] = _params['boolean_group'] - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None # authentication setting - _auth_settings: List[str] = ['bearer_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'bearer_test' + ] - return await self.api_client.call_api( - '/fake', 'DELETE', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='DELETE', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def test_inline_additional_properties( self, request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test inline additionalProperties # noqa: E501 + """test inline additionalProperties + + + + :param request_body: request body (required) + :type request_body: Dict[str, str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # noqa: E501 + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def test_inline_additional_properties_with_http_info( + self, + request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test inline additionalProperties + + :param request_body: request body (required) :type request_body: Dict[str, str] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_inline_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_inline_additional_properties_with_http_info.raw_function( - request_body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - async def test_inline_additional_properties_with_http_info( + async def test_inline_additional_properties_without_preload_content( self, request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], - **kwargs, - ) -> ApiResponse: - """test inline additionalProperties # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test inline additionalProperties - # noqa: E501 + :param request_body: request body (required) :type request_body: Dict[str, str] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'request_body' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_inline_additional_properties" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _test_inline_additional_properties_serialize( + self, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['request_body'] is not None: - _body_params = _params['request_body'] + if request_body is not None: + _body_params = request_body + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/inline-additionalProperties', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/inline-additionalProperties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def test_inline_freeform_additional_properties( self, test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test inline free-form additionalProperties # noqa: E501 + """test inline free-form additionalProperties - # noqa: E501 + :param test_inline_freeform_additional_properties_request: request body (required) :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_inline_freeform_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_inline_freeform_additional_properties_with_http_info.raw_function( - test_inline_freeform_additional_properties_request, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def test_inline_freeform_additional_properties_with_http_info( self, test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], - **kwargs, - ) -> ApiResponse: - """test inline free-form additionalProperties # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test inline free-form additionalProperties - # noqa: E501 + :param test_inline_freeform_additional_properties_request: request body (required) :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'test_inline_freeform_additional_properties_request' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def test_inline_freeform_additional_properties_without_preload_content( + self, + test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test inline free-form additionalProperties + + + + :param test_inline_freeform_additional_properties_request: request body (required) + :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_inline_freeform_additional_properties" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_inline_freeform_additional_properties_serialize( + self, + test_inline_freeform_additional_properties_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['test_inline_freeform_additional_properties_request'] is not None: - _body_params = _params['test_inline_freeform_additional_properties_request'] + if test_inline_freeform_additional_properties_request is not None: + _body_params = test_inline_freeform_additional_properties_request + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/inline-freeform-additionalProperties', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/inline-freeform-additionalProperties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def test_json_form_data( self, param: Annotated[StrictStr, Field(description="field1")], param2: Annotated[StrictStr, Field(description="field2")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test json serialization of form data # noqa: E501 + """test json serialization of form data - # noqa: E501 + :param param: field1 (required) :type param: str :param param2: field2 (required) :type param2: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_json_form_data_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.test_json_form_data_with_http_info.raw_function( - param, - param2, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def test_json_form_data_with_http_info( self, param: Annotated[StrictStr, Field(description="field1")], param2: Annotated[StrictStr, Field(description="field2")], - **kwargs, - ) -> ApiResponse: - """test json serialization of form data # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test json serialization of form data - # noqa: E501 + :param param: field1 (required) :type param: str :param param2: field2 (required) :type param2: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'param', - 'param2' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def test_json_form_data_without_preload_content( + self, + param: Annotated[StrictStr, Field(description="field1")], + param2: Annotated[StrictStr, Field(description="field2")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test json serialization of form data + + + + :param param: field1 (required) + :type param: str + :param param2: field2 (required) + :type param2: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_json_form_data" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_json_form_data_serialize( + self, + param, + param2, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['param'] is not None: - _form_params.append(('param', _params['param'])) + if param is not None: + _form_params.append(('param', param)) + if param2 is not None: + _form_params.append(('param2', param2)) + # process the body parameter + - if _params['param2'] is not None: - _form_params.append(('param2', _params['param2'])) - # process the body parameter - _body_params = None # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/fake/jsonFormData', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/jsonFormData', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def test_query_parameter_collection_format( @@ -3185,11 +6913,22 @@ async def test_query_parameter_collection_format( context: List[StrictStr], allow_empty: StrictStr, language: Optional[Dict[str, StrictStr]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test_query_parameter_collection_format # noqa: E501 + """test_query_parameter_collection_format - To test the collection format in query parameters # noqa: E501 + To test the collection format in query parameters :param pipe: (required) :type pipe: List[str] @@ -3205,30 +6944,55 @@ async def test_query_parameter_collection_format( :type allow_empty: str :param language: :type language: Dict[str, str] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_parameter_collection_format_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.test_query_parameter_collection_format_with_http_info.raw_function( - pipe, - ioutil, - http, - url, - context, - allow_empty, - language, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def test_query_parameter_collection_format_with_http_info( @@ -3240,11 +7004,22 @@ async def test_query_parameter_collection_format_with_http_info( context: List[StrictStr], allow_empty: StrictStr, language: Optional[Dict[str, StrictStr]] = None, - **kwargs, - ) -> ApiResponse: - """test_query_parameter_collection_format # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_query_parameter_collection_format - To test the collection format in query parameters # noqa: E501 + To test the collection format in query parameters :param pipe: (required) :type pipe: List[str] @@ -3260,118 +7035,229 @@ async def test_query_parameter_collection_format_with_http_info( :type allow_empty: str :param language: :type language: Dict[str, str] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'pipe', - 'ioutil', - 'http', - 'url', - 'context', - 'allow_empty', - 'language' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_parameter_collection_format" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats: Dict[str, str] = {} + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - # process the path parameters - _path_params: Dict[str, str] = {} - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('pipe') is not None: # noqa: E501 - _query_params.append(('pipe', _params['pipe'])) - _collection_formats['pipe'] = 'pipes' + @validate_call + async def test_query_parameter_collection_format_without_preload_content( + self, + pipe: List[StrictStr], + ioutil: List[StrictStr], + http: List[StrictStr], + url: List[StrictStr], + context: List[StrictStr], + allow_empty: StrictStr, + language: Optional[Dict[str, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_query_parameter_collection_format - if _params.get('ioutil') is not None: # noqa: E501 - _query_params.append(('ioutil', _params['ioutil'])) - _collection_formats['ioutil'] = 'csv' + To test the collection format in query parameters - if _params.get('http') is not None: # noqa: E501 - _query_params.append(('http', _params['http'])) - _collection_formats['http'] = 'ssv' + :param pipe: (required) + :type pipe: List[str] + :param ioutil: (required) + :type ioutil: List[str] + :param http: (required) + :type http: List[str] + :param url: (required) + :type url: List[str] + :param context: (required) + :type context: List[str] + :param allow_empty: (required) + :type allow_empty: str + :param language: + :type language: Dict[str, str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params.get('url') is not None: # noqa: E501 - _query_params.append(('url', _params['url'])) - _collection_formats['url'] = 'csv' + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params.get('context') is not None: # noqa: E501 - _query_params.append(('context', _params['context'])) - _collection_formats['context'] = 'multi' - if _params.get('language') is not None: # noqa: E501 - _query_params.append(('language', _params['language'])) + def _test_query_parameter_collection_format_serialize( + self, + pipe, + ioutil, + http, + url, + context, + allow_empty, + language, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'pipe': 'pipes', + 'ioutil': 'csv', + 'http': 'ssv', + 'url': 'csv', + 'context': 'multi', + } - if _params.get('allow_empty') is not None: # noqa: E501 - _query_params.append(('allowEmpty', _params['allow_empty'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if pipe is not None: + + _query_params.append(('pipe', pipe)) + + if ioutil is not None: + + _query_params.append(('ioutil', ioutil)) + + if http is not None: + + _query_params.append(('http', http)) + + if url is not None: + + _query_params.append(('url', url)) + + if context is not None: + + _query_params.append(('context', context)) + + if language is not None: + + _query_params.append(('language', language)) + + if allow_empty is not None: + + _query_params.append(('allowEmpty', allow_empty)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/fake/test-query-parameters', 'PUT', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/test-query-parameters', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_classname_tags123_api.py index 8154ce3f86d5..0c702d8d7229 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_classname_tags123_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/fake_classname_tags123_api.py @@ -11,24 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import Field from typing_extensions import Annotated from petstore_api.models.client import Client -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class FakeClassnameTags123Api: @@ -43,145 +37,273 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def test_classname( self, client: Annotated[Client, Field(description="client model")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Client: - """To test class name in snake case # noqa: E501 + """To test class name in snake case - To test class name in snake case # noqa: E501 + To test class name in snake case :param client: client model (required) :type client: Client - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_classname_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.test_classname_with_http_info.raw_function( - client, - **kwargs, + """ # noqa: E501 + + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def test_classname_with_http_info( self, client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test class name in snake case # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test class name in snake case - To test class name in snake case # noqa: E501 + To test class name in snake case :param client: client model (required) :type client: Client - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def test_classname_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test class name in snake case + + To test class name in snake case + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_classname" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_classname_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + if client is not None: + _body_params = client + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['api_key_query'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + 'api_key_query' + ] - return await self.api_client.call_api( - '/fake_classname_test', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PATCH', + resource_path='/fake_classname_test', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/pet_api.py index daf6ddf66267..7a849d50a618 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/pet_api.py @@ -11,29 +11,20 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictBytes, StrictInt, StrictStr, field_validator +from pydantic import Field, StrictBytes, StrictInt, StrictStr, field_validator from typing import List, Optional, Union - -from petstore_api.models.api_response import ApiResponse +from typing_extensions import Annotated +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.pet import Pet -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class PetApi: @@ -48,836 +39,1622 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def add_pet( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Add a new pet to the store # noqa: E501 + """Add a new pet to the store - # noqa: E501 + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the add_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.add_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def add_pet_with_http_info( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, - ) -> ApiResponse: - """Add a new pet to the store # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Add a new pet to the store - # noqa: E501 + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def add_pet_without_preload_content( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Add a new pet to the store + + + + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method add_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _add_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return await self.api_client.call_api( - '/pet', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def delete_pet( self, pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], api_key: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Deletes a pet # noqa: E501 + """Deletes a pet - # noqa: E501 + :param pet_id: Pet id to delete (required) :type pet_id: int :param api_key: :type api_key: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.delete_pet_with_http_info.raw_function( - pet_id, - api_key, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def delete_pet_with_http_info( self, pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], api_key: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Deletes a pet # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Deletes a pet - # noqa: E501 + :param pet_id: Pet id to delete (required) :type pet_id: int :param api_key: :type api_key: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet_id', - 'api_key' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def delete_pet_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], + api_key: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Deletes a pet + + + + :param pet_id: Pet id to delete (required) + :type pet_id: int + :param api_key: + :type api_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _delete_pet_serialize( + self, + pet_id, + api_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['api_key'] is not None: - _header_params['api_key'] = _params['api_key'] + _collection_formats: Dict[str, str] = { + } - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id + # process the query parameters + # process the header parameters + if api_key is not None: + _header_params['api_key'] = api_key + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/pet/{petId}', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def find_pets_by_status( self, status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> List[Pet]: - """Finds Pets by status # noqa: E501 + """Finds Pets by status - Multiple status values can be provided with comma separated strings # noqa: E501 + Multiple status values can be provided with comma separated strings :param status: Status values that need to be considered for filter (required) :type status: List[str] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[Pet] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the find_pets_by_status_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.find_pets_by_status_with_http_info.raw_function( - status, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def find_pets_by_status_with_http_info( self, status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], - **kwargs, - ) -> ApiResponse: - """Finds Pets by status # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Pet]]: + """Finds Pets by status - Multiple status values can be provided with comma separated strings # noqa: E501 + Multiple status values can be provided with comma separated strings :param status: Status values that need to be considered for filter (required) :type status: List[str] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[Pet], status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'status' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def find_pets_by_status_without_preload_content( + self, + status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Finds Pets by status + + Multiple status values can be provided with comma separated strings + + :param status: Status values that need to be considered for filter (required) + :type status: List[str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method find_pets_by_status" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _find_pets_by_status_serialize( + self, + status, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + 'status': 'csv', + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('status') is not None: # noqa: E501 - _query_params.append(('status', _params['status'])) - _collection_formats['status'] = 'csv' + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if status is not None: + + _query_params.append(('status', status)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[Pet]", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return await self.api_client.call_api( - '/pet/findByStatus', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/findByStatus', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def find_pets_by_tags( self, tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> List[Pet]: - """(Deprecated) Finds Pets by tags # noqa: E501 + """(Deprecated) Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. :param tags: Tags to filter by (required) :type tags: List[str] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[Pet] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the find_pets_by_tags_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) - return await self.find_pets_by_tags_with_http_info.raw_function( - tags, - **kwargs, + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def find_pets_by_tags_with_http_info( self, tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], - **kwargs, - ) -> ApiResponse: - """(Deprecated) Finds Pets by tags # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Pet]]: + """(Deprecated) Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. :param tags: Tags to filter by (required) :type tags: List[str] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[Pet], status_code(int), headers(HTTPHeaderDict)) - """ - + """ # noqa: E501 warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) - _params = locals() + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'tags' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def find_pets_by_tags_without_preload_content( + self, + tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """(Deprecated) Finds Pets by tags + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + + :param tags: Tags to filter by (required) + :type tags: List[str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) + + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method find_pets_by_tags" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _find_pets_by_tags_serialize( + self, + tags, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + 'tags': 'csv', + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('tags') is not None: # noqa: E501 - _query_params.append(('tags', _params['tags'])) - _collection_formats['tags'] = 'csv' + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if tags is not None: + + _query_params.append(('tags', tags)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[Pet]", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return await self.api_client.call_api( - '/pet/findByTags', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/findByTags', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def get_pet_by_id( self, pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Pet: - """Find pet by ID # noqa: E501 + """Find pet by ID - Returns a single pet # noqa: E501 + Returns a single pet :param pet_id: ID of pet to return (required) :type pet_id: int - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Pet - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_pet_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.get_pet_by_id_with_http_info.raw_function( - pet_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def get_pet_by_id_with_http_info( self, pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], - **kwargs, - ) -> ApiResponse: - """Find pet by ID # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Find pet by ID - Returns a single pet # noqa: E501 + Returns a single pet :param pet_id: ID of pet to return (required) :type pet_id: int - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Pet, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet_id' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def get_pet_by_id_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Find pet by ID + + Returns a single pet + + :param pet_id: ID of pet to return (required) + :type pet_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_pet_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _get_pet_by_id_serialize( + self, + pet_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['api_key'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Pet", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'api_key' + ] - return await self.api_client.call_api( - '/pet/{petId}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def update_pet( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Update an existing pet # noqa: E501 + """Update an existing pet + + + + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + async def update_pet_with_http_info( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Update an existing pet - # noqa: E501 + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.update_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - async def update_pet_with_http_info( + async def update_pet_without_preload_content( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, - ) -> ApiResponse: - """Update an existing pet # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update an existing pet - # noqa: E501 + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _update_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return await self.api_client.call_api( - '/pet', 'PUT', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PUT', + resource_path='/pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def update_pet_with_form( @@ -885,11 +1662,22 @@ async def update_pet_with_form( pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Updates a pet in the store with form data # noqa: E501 + """Updates a pet in the store with form data - # noqa: E501 + :param pet_id: ID of pet that needs to be updated (required) :type pet_id: int @@ -897,26 +1685,52 @@ async def update_pet_with_form( :type name: str :param status: Updated status of the pet :type status: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_pet_with_form_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.update_pet_with_form_with_http_info.raw_function( - pet_id, - name, - status, - **kwargs, + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def update_pet_with_form_with_http_info( @@ -924,11 +1738,22 @@ async def update_pet_with_form_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, - **kwargs, - ) -> ApiResponse: - """Updates a pet in the store with form data # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Updates a pet in the store with form data - # noqa: E501 + :param pet_id: ID of pet that needs to be updated (required) :type pet_id: int @@ -936,107 +1761,198 @@ async def update_pet_with_form_with_http_info( :type name: str :param status: Updated status of the pet :type status: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet_id', - 'name', - 'status' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def update_pet_with_form_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], + name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, + status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Updates a pet in the store with form data + + + + :param pet_id: ID of pet that needs to be updated (required) + :type pet_id: int + :param name: Updated name of the pet + :type name: str + :param status: Updated status of the pet + :type status: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet_with_form" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _update_pet_with_form_serialize( + self, + pet_id, + name, + status, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['name'] is not None: - _form_params.append(('name', _params['name'])) + if name is not None: + _form_params.append(('name', name)) + if status is not None: + _form_params.append(('status', status)) + # process the body parameter + - if _params['status'] is not None: - _form_params.append(('status', _params['status'])) - # process the body parameter - _body_params = None # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return await self.api_client.call_api( - '/pet/{petId}', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def upload_file( @@ -1044,11 +1960,22 @@ async def upload_file( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads an image - # noqa: E501 + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1056,26 +1983,51 @@ async def upload_file( :type additional_metadata: str :param file: file to upload :type file: bytearray - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ApiResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the upload_file_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.upload_file_with_http_info.raw_function( - pet_id, - additional_metadata, - file, - **kwargs, + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def upload_file_with_http_info( @@ -1083,11 +2035,22 @@ async def upload_file_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads an image - # noqa: E501 + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1095,113 +2058,202 @@ async def upload_file_with_http_info( :type additional_metadata: str :param file: file to upload :type file: bytearray - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet_id', - 'additional_metadata', - 'file' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def upload_file_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], + additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, + file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads an image + + + + :param pet_id: ID of pet to update (required) + :type pet_id: int + :param additional_metadata: Additional data to pass to server + :type additional_metadata: str + :param file: file to upload + :type file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method upload_file" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _upload_file_serialize( + self, + pet_id, + additional_metadata, + file, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['additional_metadata'] is not None: - _form_params.append(('additionalMetadata', _params['additional_metadata'])) + if additional_metadata is not None: + _form_params.append(('additionalMetadata', additional_metadata)) + if file is not None: + _files['file'] = file + # process the body parameter - if _params['file'] is not None: - _files['file'] = _params['file'] - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ApiResponse", - } + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return await self.api_client.call_api( - '/pet/{petId}/uploadImage', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet/{petId}/uploadImage', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def upload_file_with_required_file( @@ -1209,11 +2261,22 @@ async def upload_file_with_required_file( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image (required) # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads an image (required) - # noqa: E501 + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1221,26 +2284,51 @@ async def upload_file_with_required_file( :type required_file: bytearray :param additional_metadata: Additional data to pass to server :type additional_metadata: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ApiResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the upload_file_with_required_file_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return await self.upload_file_with_required_file_with_http_info.raw_function( - pet_id, - required_file, - additional_metadata, - **kwargs, + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def upload_file_with_required_file_with_http_info( @@ -1248,11 +2336,22 @@ async def upload_file_with_required_file_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image (required) # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads an image (required) - # noqa: E501 + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1260,110 +2359,198 @@ async def upload_file_with_required_file_with_http_info( :type required_file: bytearray :param additional_metadata: Additional data to pass to server :type additional_metadata: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet_id', - 'required_file', - 'additional_metadata' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def upload_file_with_required_file_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], + required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], + additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads an image (required) + + + + :param pet_id: ID of pet to update (required) + :type pet_id: int + :param required_file: file to upload (required) + :type required_file: bytearray + :param additional_metadata: Additional data to pass to server + :type additional_metadata: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method upload_file_with_required_file" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _upload_file_with_required_file_serialize( + self, + pet_id, + required_file, + additional_metadata, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['additional_metadata'] is not None: - _form_params.append(('additionalMetadata', _params['additional_metadata'])) + if additional_metadata is not None: + _form_params.append(('additionalMetadata', additional_metadata)) + if required_file is not None: + _files['requiredFile'] = required_file + # process the body parameter - if _params['required_file'] is not None: - _files['requiredFile'] = _params['required_file'] - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ApiResponse", - } + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return await self.api_client.call_api( - '/fake/{petId}/uploadImageWithRequiredFile', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/{petId}/uploadImageWithRequiredFile', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/store_api.py index e80781620869..fcdbd02ce6de 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/store_api.py @@ -11,28 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictStr - -from typing import Dict +from pydantic import Field, StrictStr +from typing_extensions import Annotated from petstore_api.models.order import Order -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class StoreApi: @@ -47,539 +37,1037 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def delete_order( self, order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Delete purchase order by ID # noqa: E501 + """Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted (required) :type order_id: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_order_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.delete_order_with_http_info.raw_function( - order_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def delete_order_with_http_info( self, order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], - **kwargs, - ) -> ApiResponse: - """Delete purchase order by ID # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete purchase order by ID - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted (required) :type order_id: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'order_id' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def delete_order_without_preload_content( + self, + order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + :param order_id: ID of the order that needs to be deleted (required) + :type order_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_order" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['order_id'] is not None: - _path_params['order_id'] = _params['order_id'] + def _delete_order_serialize( + self, + order_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if order_id is not None: + _path_params['order_id'] = order_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/store/order/{order_id}', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/store/order/{order_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def get_inventory( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Dict[str, int]: - """Returns pet inventories by status # noqa: E501 + """Returns pet inventories by status - Returns a map of status codes to quantities # noqa: E501 + Returns a map of status codes to quantities - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Dict[str, int] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_inventory_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return await self.get_inventory_with_http_info.raw_function( - **kwargs, + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def get_inventory_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Returns pet inventories by status # noqa: E501 - - Returns a map of status codes to quantities # noqa: E501 - - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Dict[str, int]]: + """Returns pet inventories by status + + Returns a map of status codes to quantities + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Dict[str, int], status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def get_inventory_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Returns pet inventories by status + + Returns a map of status codes to quantities + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_inventory" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _get_inventory_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['api_key'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Dict[str, int]", - } + # authentication setting + _auth_settings: List[str] = [ + 'api_key' + ] - return await self.api_client.call_api( - '/store/inventory', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/store/inventory', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def get_order_by_id( self, order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Order: - """Find purchase order by ID # noqa: E501 + """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions :param order_id: ID of pet that needs to be fetched (required) :type order_id: int - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Order - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_order_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.get_order_by_id_with_http_info.raw_function( - order_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def get_order_by_id_with_http_info( self, order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], - **kwargs, - ) -> ApiResponse: - """Find purchase order by ID # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Order]: + """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions :param order_id: ID of pet that needs to be fetched (required) :type order_id: int - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Order, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'order_id' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def get_order_by_id_without_preload_content( + self, + order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + :param order_id: ID of pet that needs to be fetched (required) + :type order_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_order_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['order_id'] is not None: - _path_params['order_id'] = _params['order_id'] + def _get_order_by_id_serialize( + self, + order_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if order_id is not None: + _path_params['order_id'] = order_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Order", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/store/order/{order_id}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/store/order/{order_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def place_order( self, order: Annotated[Order, Field(description="order placed for purchasing the pet")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Order: - """Place an order for a pet # noqa: E501 + """Place an order for a pet - # noqa: E501 + :param order: order placed for purchasing the pet (required) :type order: Order - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Order - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the place_order_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.place_order_with_http_info.raw_function( - order, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def place_order_with_http_info( self, order: Annotated[Order, Field(description="order placed for purchasing the pet")], - **kwargs, - ) -> ApiResponse: - """Place an order for a pet # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Order]: + """Place an order for a pet - # noqa: E501 + :param order: order placed for purchasing the pet (required) :type order: Order - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Order, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'order' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def place_order_without_preload_content( + self, + order: Annotated[Order, Field(description="order placed for purchasing the pet")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Place an order for a pet + + + + :param order: order placed for purchasing the pet (required) + :type order: Order + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method place_order" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _place_order_serialize( + self, + order, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['order'] is not None: - _body_params = _params['order'] + if order is not None: + _body_params = order + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Order", - '400': None, - } + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/store/order', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/store/order', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/user_api.py index d4413bf3d890..f642abb3e1d9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api/user_api.py @@ -11,28 +11,19 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictStr +from pydantic import Field, StrictStr from typing import List - +from typing_extensions import Annotated from petstore_api.models.user import User -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class UserApi: @@ -47,1111 +38,2105 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call async def create_user( self, user: Annotated[User, Field(description="Created user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, ) -> None: - """Create user # noqa: E501 + """Create user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param user: Created user object (required) :type user: User - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.create_user_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def create_user_with_http_info( self, user: Annotated[User, Field(description="Created user object")], - **kwargs, - ) -> ApiResponse: - """Create user # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, + ) -> ApiResponse[None]: + """Create user + + This can only be done by the logged in user. + + :param user: Created user object (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def create_user_without_preload_content( + self, + user: Annotated[User, Field(description="Created user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, + ) -> RESTResponseType: + """Create user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param user: Created user object (required) :type user: User - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_user_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: _hosts = [ 'http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2', 'http://{server}.swagger.io:{port}/v2' ] - _host = _hosts[0] - if kwargs.get('_host_index'): - _host_index = int(kwargs.get('_host_index')) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" - % len(_host) - ) - _host = _hosts[_host_index] - _params = locals() - - _all_params = [ - 'user' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _host = _hosts[_host_index] - _collection_formats: Dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - _host=_host, collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def create_users_with_array_input( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Creates list of users with given input array # noqa: E501 + """Creates list of users with given input array - # noqa: E501 + :param user: List of user object (required) :type user: List[User] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_users_with_array_input_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.create_users_with_array_input_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def create_users_with_array_input_with_http_info( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, - ) -> ApiResponse: - """Creates list of users with given input array # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates list of users with given input array - # noqa: E501 + :param user: List of user object (required) :type user: List[User] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'user' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def create_users_with_array_input_without_preload_content( + self, + user: Annotated[List[User], Field(description="List of user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates list of users with given input array + + + + :param user: List of user object (required) + :type user: List[User] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_users_with_array_input" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _create_users_with_array_input_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'User': '', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user/createWithArray', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user/createWithArray', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def create_users_with_list_input( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Creates list of users with given input array # noqa: E501 + """Creates list of users with given input array - # noqa: E501 + :param user: List of user object (required) :type user: List[User] - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_users_with_list_input_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.create_users_with_list_input_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def create_users_with_list_input_with_http_info( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, - ) -> ApiResponse: - """Creates list of users with given input array # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates list of users with given input array - # noqa: E501 + :param user: List of user object (required) :type user: List[User] - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'user' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def create_users_with_list_input_without_preload_content( + self, + user: Annotated[List[User], Field(description="List of user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates list of users with given input array + + + + :param user: List of user object (required) + :type user: List[User] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_users_with_list_input" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _create_users_with_list_input_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'User': '', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user/createWithList', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user/createWithList', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def delete_user( self, username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Delete user # noqa: E501 + """Delete user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param username: The name that needs to be deleted (required) :type username: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.delete_user_with_http_info.raw_function( - username, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def delete_user_with_http_info( self, username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], - **kwargs, - ) -> ApiResponse: - """Delete user # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param username: The name that needs to be deleted (required) :type username: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'username' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def delete_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] - ) + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete user - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + This can only be done by the logged in user. - _collection_formats: Dict[str, str] = {} + :param username: The name that needs to be deleted (required) + :type username: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - # process the query parameters + def _delete_user_serialize( + self, + username, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/user/{username}', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def get_user_by_name( self, username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> User: - """Get user by user name # noqa: E501 + """Get user by user name - # noqa: E501 + :param username: The name that needs to be fetched. Use user1 for testing. (required) :type username: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: User - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_user_by_name_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.get_user_by_name_with_http_info.raw_function( - username, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def get_user_by_name_with_http_info( self, username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], - **kwargs, - ) -> ApiResponse: - """Get user by user name # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[User]: + """Get user by user name - # noqa: E501 + :param username: The name that needs to be fetched. Use user1 for testing. (required) :type username: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(User, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'username' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def get_user_by_name_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get user by user name + + + + :param username: The name that needs to be fetched. Use user1 for testing. (required) + :type username: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_user_by_name" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + def _get_user_by_name_serialize( + self, + username, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "User", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user/{username}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def login_user( self, username: Annotated[StrictStr, Field(description="The user name for login")], password: Annotated[StrictStr, Field(description="The password for login in clear text")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Logs user into the system # noqa: E501 + """Logs user into the system - # noqa: E501 + :param username: The user name for login (required) :type username: str :param password: The password for login in clear text (required) :type password: str - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the login_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.login_user_with_http_info.raw_function( - username, - password, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def login_user_with_http_info( self, username: Annotated[StrictStr, Field(description="The user name for login")], password: Annotated[StrictStr, Field(description="The password for login in clear text")], - **kwargs, - ) -> ApiResponse: - """Logs user into the system # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Logs user into the system - # noqa: E501 + :param username: The user name for login (required) :type username: str :param password: The password for login in clear text (required) :type password: str - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'username', - 'password' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + async def login_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The user name for login")], + password: Annotated[StrictStr, Field(description="The password for login in clear text")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Logs user into the system + + + + :param username: The user name for login (required) + :type username: str + :param password: The password for login in clear text (required) + :type password: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method login_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _login_user_serialize( + self, + username, + password, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('username') is not None: # noqa: E501 - _query_params.append(('username', _params['username'])) + _host = None - if _params.get('password') is not None: # noqa: E501 - _query_params.append(('password', _params['password'])) + _collection_formats: Dict[str, str] = { + } - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if username is not None: + + _query_params.append(('username', username)) + + if password is not None: + + _query_params.append(('password', password)) + + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user/login', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/user/login', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def logout_user( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Logs out current logged in user session # noqa: E501 + """Logs out current logged in user session - # noqa: E501 + - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the logout_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return await self.logout_user_with_http_info.raw_function( - **kwargs, + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call async def logout_user_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Logs out current logged in user session # noqa: E501 - - # noqa: E501 - - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Logs out current logged in user session + + + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 - _params = locals() + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + async def logout_user_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Logs out current logged in user session + + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method logout_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _logout_user_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return await self.api_client.call_api( - '/user/logout', 'GET', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/user/logout', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call async def update_user( self, username: Annotated[StrictStr, Field(description="name that need to be deleted")], user: Annotated[User, Field(description="Updated user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Updated user # noqa: E501 + """Updated user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param username: name that need to be deleted (required) :type username: str :param user: Updated user object (required) :type user: User - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return await self.update_user_with_http_info.raw_function( - username, - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call async def update_user_with_http_info( self, username: Annotated[StrictStr, Field(description="name that need to be deleted")], user: Annotated[User, Field(description="Updated user object")], - **kwargs, - ) -> ApiResponse: - """Updated user # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Updated user - This can only be done by the logged in user. # noqa: E501 + This can only be done by the logged in user. :param username: name that need to be deleted (required) :type username: str :param user: Updated user object (required) :type user: User - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + await response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'username', - 'user' - ] - _all_params.extend( - [ - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + async def update_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="name that need to be deleted")], + user: Annotated[User, Field(description="Updated user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Updated user + + This can only be done by the logged in user. + + :param username: name that need to be deleted (required) + :type username: str + :param user: Updated user object (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = await self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + def _update_user_serialize( + self, + username, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return await self.api_client.call_api( - '/user/{username}', 'PUT', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PUT', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py index 733ddaed7c3e..5e403f5a51ae 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_client.py @@ -12,7 +12,6 @@ """ # noqa: E501 -import atexit import datetime from dateutil.parser import parse import json @@ -22,13 +21,23 @@ import tempfile from urllib.parse import quote +from typing import Tuple, Optional, List, Dict from petstore_api.configuration import Configuration -from petstore_api.api_response import ApiResponse +from petstore_api.api_response import ApiResponse, T as ApiResponseT import petstore_api.models from petstore_api import rest -from petstore_api.exceptions import ApiValueError, ApiException - +from petstore_api.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -59,8 +68,13 @@ class ApiClient: } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None) -> None: + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() @@ -123,13 +137,42 @@ def set_default(cls, default): """ cls._default = default - async def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -140,14 +183,17 @@ async def __call_api( header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -159,15 +205,22 @@ async def __call_api( if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: @@ -183,59 +236,99 @@ async def __call_api( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query + return method, url, header_params, body, post_params + + + async def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + try: # perform request and return response - response_data = await self.request( + response_data = await self.rest_client.request( method, url, - query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') raise e - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -256,15 +349,17 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except @@ -274,10 +369,12 @@ def sanitize_for_serialization(self, obj): # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -286,16 +383,12 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -312,12 +405,16 @@ def __deserialize(self, data, klass): if isinstance(klass, str): if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -338,126 +435,6 @@ def __deserialize(self, data, klass): else: return self.__deserialize_model(data, klass) - async def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - The response. - """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - return await self.__call_api(*args) - - async def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return await self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return await self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return await self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return await self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return await self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return await self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return await self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -465,10 +442,10 @@ def parameters_to_tuples(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -495,14 +472,14 @@ def parameters_to_url_query(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) + for k, v in params.items() if isinstance(params, dict) else params: if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) @@ -520,7 +497,8 @@ def parameters_to_url_query(self, params, collection_formats): else: # csv is the default delimiter = ',' new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -543,21 +521,24 @@ def files_parameters(self, files=None): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None for accept in accepts: if re.search('json', accept, re.IGNORECASE): @@ -580,9 +561,16 @@ def select_header_content_type(self, content_types): return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -599,21 +587,36 @@ def update_params_for_auth(self, headers, queries, auth_settings, return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -649,6 +652,9 @@ def __deserialize_file(self, response): Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -658,8 +664,12 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_response.py index a0b62b95246c..9bc7c11f6b9f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/api_response.py @@ -1,25 +1,21 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel -class ApiResponse: +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): """ API response object """ - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data + model_config = { + "arbitrary_types_allowed": True + } diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/configuration.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/configuration.py index 1e0b9acbc97c..98ba8abce92d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/configuration.py @@ -14,7 +14,9 @@ import copy import logging +from logging import FileHandler import sys +from typing import Optional import urllib3 import http.client as httplib @@ -197,7 +199,7 @@ def __init__(self, host=None, self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -234,7 +236,7 @@ def __init__(self, host=None, Default values is 100, None means no-limit. """ - self.proxy = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/exceptions.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/exceptions.py index 6c4ae9c4e02f..0cb484becbdb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/exceptions.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/exceptions.py @@ -11,6 +11,8 @@ Do not edit the class manually. """ # noqa: E501 +from typing import Any, Optional +from typing_extensions import Self class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" @@ -101,17 +103,56 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) def __str__(self): """Custom error messages for exception""" @@ -121,38 +162,30 @@ def __str__(self): error_message += "HTTP response headers: {0}\n".format( self.headers) - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message + class BadRequestException(ApiException): + pass - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + pass class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + pass class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + pass class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + pass def render_path(path_to_item): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py index dd9388d355da..945dd198de1a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/__init__.py @@ -22,7 +22,6 @@ from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor from petstore_api.models.any_of_pig import AnyOfPig -from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.models.array_of_number_only import ArrayOfNumberOnly @@ -61,6 +60,7 @@ from petstore_api.models.map_test import MapTest from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.models.model200_response import Model200Response +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.model_return import ModelReturn from petstore_api.models.name import Name from petstore_api.models.nullable_class import NullableClass @@ -89,6 +89,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py index 3d6f78e1748c..43a139dc1749 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_any_type.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesAnyType(BaseModel): """ AdditionalPropertiesAnyType - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesAnyType from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesAnyType from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py index 14fbcc1e4425..7635dc54330d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_class.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Dict, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesClass(BaseModel): """ AdditionalPropertiesClass - """ + """ # noqa: E501 map_property: Optional[Dict[str, StrictStr]] = None map_of_map_property: Optional[Dict[str, Dict[str, StrictStr]]] = None __properties: ClassVar[List[str]] = ["map_property", "map_of_map_property"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py index 9933c9ac2335..03735c7429c9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_object.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesObject(BaseModel): """ AdditionalPropertiesObject - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesObject from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesObject from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py index 15d29a1d241e..7e3f920ab3cb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/additional_properties_with_description_only.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ AdditionalPropertiesWithDescriptionOnly - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py index 09693f82e07c..30b6645755ee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/all_of_with_single_ref.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.single_ref_type import SingleRefType -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class AllOfWithSingleRef(BaseModel): """ AllOfWithSingleRef - """ + """ # noqa: E501 username: Optional[StrictStr] = None single_ref_type: Optional[SingleRefType] = Field(default=None, alias="SingleRefType") __properties: ClassVar[List[str]] = ["username", "SingleRefType"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AllOfWithSingleRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AllOfWithSingleRef from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py index a1763f52a566..772b2bc93203 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/animal.py @@ -17,32 +17,28 @@ import re # noqa: F401 import json - -from typing import Optional, Union -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional, Union +from typing import Optional, Set +from typing_extensions import Self class Animal(BaseModel): """ Animal - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") color: Optional[StrictStr] = 'red' __properties: ClassVar[List[str]] = ["className", "color"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } # JSON field name that stores the object type - __discriminator_property_name: ClassVar[List[str]] = 'className' + __discriminator_property_name: ClassVar[str] = 'className' # discriminator mappings __discriminator_value_class_map: ClassVar[Dict[str, str]] = { @@ -50,7 +46,7 @@ class Animal(BaseModel): } @classmethod - def get_discriminator_value(cls, obj: dict) -> str: + def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: """Returns the discriminator value (object type) of the data""" discriminator_value = obj[cls.__discriminator_property_name] if discriminator_value: @@ -68,7 +64,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Union[Self, Self]: + def from_json(cls, json_str: str) -> Optional[Union[Self, Self]]: """Create an instance of Animal from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -82,16 +78,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Union[Self, Self]: + def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Self, Self]]: """Create an instance of Animal from a dict""" # look up the object type based on discriminator mapping object_type = cls.get_discriminator_value(obj) @@ -105,9 +103,6 @@ def from_dict(cls, obj: dict) -> Union[Self, Self]: from petstore_api.models.cat import Cat from petstore_api.models.dog import Dog -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # Animal.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +Animal.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py index db4718b868b0..b952c65ffcce 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_color.py @@ -17,18 +17,12 @@ import json import pprint import re # noqa: F401 - -from typing import List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import List, Optional from typing_extensions import Annotated from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal -from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Literal, Self +from pydantic import Field ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -47,10 +41,11 @@ class AnyOfColor(BaseModel): actual_instance: Optional[Union[List[int], str]] = None else: actual_instance: Any = None - any_of_schemas: List[str] = Literal[ANYOFCOLOR_ANY_OF_SCHEMAS] + any_of_schemas: List[str] = Field(default=Literal["List[int]", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } def __init__(self, *args, **kwargs) -> None: @@ -92,7 +87,7 @@ def actual_instance_must_validate_anyof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -139,22 +134,20 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: - return "null" + return None - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py index 2a2a04932225..3dff97862165 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/any_of_pig.py @@ -17,18 +17,13 @@ import json import pprint import re # noqa: F401 - -from typing import Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal -from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Literal, Self +from pydantic import Field ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -45,10 +40,11 @@ class AnyOfPig(BaseModel): actual_instance: Optional[Union[BasquePig, DanishPig]] = None else: actual_instance: Any = None - any_of_schemas: List[str] = Literal[ANYOFPIG_ANY_OF_SCHEMAS] + any_of_schemas: List[str] = Field(default=Literal["BasquePig", "DanishPig"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } def __init__(self, *args, **kwargs) -> None: @@ -84,7 +80,7 @@ def actual_instance_must_validate_anyof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -116,22 +112,20 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: - return "null" + return None - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py index 9293e3d9ef85..b1318218a1e9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_model.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayOfArrayOfModel(BaseModel): """ ArrayOfArrayOfModel - """ + """ # noqa: E501 another_property: Optional[List[List[Tag]]] = None __properties: ClassVar[List[str]] = ["another_property"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfArrayOfModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) @@ -82,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfArrayOfModel from a dict""" if obj is None: return None @@ -93,7 +92,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "another_property": [ [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("another_property") + for _item in obj["another_property"] ] if obj.get("another_property") is not None else None }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py index 77bccbdcedbd..9ff34ea19ec0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_array_of_number_only.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ArrayOfArrayOfNumberOnly(BaseModel): """ ArrayOfArrayOfNumberOnly - """ + """ # noqa: E501 array_array_number: Optional[List[List[float]]] = Field(default=None, alias="ArrayArrayNumber") __properties: ClassVar[List[str]] = ["ArrayArrayNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py index b9457cc86954..4385be8a0560 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_of_number_only.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ArrayOfNumberOnly(BaseModel): """ ArrayOfNumberOnly - """ + """ # noqa: E501 array_number: Optional[List[float]] = Field(default=None, alias="ArrayNumber") __properties: ClassVar[List[str]] = ["ArrayNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfNumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfNumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py index ada718465ba7..c1c0bd954046 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/array_test.py @@ -17,22 +17,17 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayTest(BaseModel): """ ArrayTest - """ + """ # noqa: E501 array_of_string: Optional[Annotated[List[StrictStr], Field(min_length=0, max_length=3)]] = None array_array_of_integer: Optional[List[List[StrictInt]]] = None array_array_of_model: Optional[List[List[ReadOnlyFirst]]] = None @@ -40,7 +35,8 @@ class ArrayTest(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,10 +64,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) @@ -86,7 +84,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayTest from a dict""" if obj is None: return None @@ -99,7 +97,7 @@ def from_dict(cls, obj: dict) -> Self: "array_array_of_integer": obj.get("array_array_of_integer"), "array_array_of_model": [ [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("array_array_of_model") + for _item in obj["array_array_of_model"] ] if obj.get("array_array_of_model") is not None else None }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py index c0602950bbe0..23ab0585d517 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/basque_pig.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - - -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self class BasquePig(BaseModel): """ BasquePig - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") color: StrictStr __properties: ClassVar[List[str]] = ["className", "color"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BasquePig from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BasquePig from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py index fbcb8b78eaf3..3a28f990d061 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/capitalization.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Capitalization(BaseModel): """ Capitalization - """ + """ # noqa: E501 small_camel: Optional[StrictStr] = Field(default=None, alias="smallCamel") capital_camel: Optional[StrictStr] = Field(default=None, alias="CapitalCamel") small_snake: Optional[StrictStr] = Field(default=None, alias="small_Snake") @@ -41,7 +36,8 @@ class Capitalization(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -55,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Capitalization from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -69,16 +65,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Capitalization from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py index 0af38b8a65f7..c215d0924705 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/cat.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import StrictBool +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Cat(Animal): """ Cat - """ + """ # noqa: E501 declawed: Optional[StrictBool] = None __properties: ClassVar[List[str]] = ["className", "color", "declawed"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Cat from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Cat from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py index 78ee4fecb971..f3e78641caa6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/category.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Category(BaseModel): """ Category - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: StrictStr __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Category from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Category from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py index 934c6ea455c4..3cafde6710ab 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/circular_reference_model.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class CircularReferenceModel(BaseModel): """ CircularReferenceModel - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested: Optional[FirstRef] = None __properties: ClassVar[List[str]] = ["size", "nested"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CircularReferenceModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CircularReferenceModel from a dict""" if obj is None: return None @@ -86,14 +85,11 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested": FirstRef.from_dict(obj.get("nested")) if obj.get("nested") is not None else None + "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None }) return _obj from petstore_api.models.first_ref import FirstRef -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # CircularReferenceModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +CircularReferenceModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py index ae918ce100fc..58c3db52adac 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/class_model.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ClassModel(BaseModel): """ - Model for testing model with \"_class\" property # noqa: E501 - """ + Model for testing model with \"_class\" property + """ # noqa: E501 var_class: Optional[StrictStr] = Field(default=None, alias="_class") __properties: ClassVar[List[str]] = ["_class"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ClassModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ClassModel from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py index 4033f37205ee..90c36a468676 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/client.py @@ -17,25 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Client(BaseModel): """ Client - """ + """ # noqa: E501 client: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["client"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -49,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Client from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -63,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Client from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py index b5abaccbd0ba..bfcbcfc03f27 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/color.py @@ -13,22 +13,14 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import Any, List, Optional from typing_extensions import Annotated -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -43,10 +35,11 @@ class Color(BaseModel): # data type: str oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: List[str] = Literal["List[int]", "str"] + one_of_schemas: List[str] = Field(default=Literal["List[int]", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -96,11 +89,11 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: Optional[str]) -> Self: """Returns the object represented by the json string""" instance = cls.model_construct() if json_str is None: @@ -151,19 +144,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py index 1ed4c3360497..73b1edc237cc 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - - from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List from petstore_api.models.creature_info import CreatureInfo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Creature(BaseModel): """ Creature - """ + """ # noqa: E501 info: CreatureInfo type: StrictStr __properties: ClassVar[List[str]] = ["info", "type"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Creature from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +62,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of info @@ -77,7 +76,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Creature from a dict""" if obj is None: return None @@ -86,7 +85,7 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj.get("info")) if obj.get("info") is not None else None, + "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, "type": obj.get("type") }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py index 93ab7f145749..511ec5191a44 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/creature_info.py @@ -17,25 +17,22 @@ import re # noqa: F401 import json - - from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self class CreatureInfo(BaseModel): """ CreatureInfo - """ + """ # noqa: E501 name: StrictStr __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -49,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreatureInfo from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -63,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreatureInfo from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py index 95676eefdfca..56a78bbea26d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/danish_pig.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - - -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self class DanishPig(BaseModel): """ DanishPig - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") size: StrictInt __properties: ClassVar[List[str]] = ["className", "size"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DanishPig from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DanishPig from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py index 6a8ea126a3b2..d7c0fa761b4b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/deprecated_object.py @@ -17,25 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class DeprecatedObject(BaseModel): """ DeprecatedObject - """ + """ # noqa: E501 name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -49,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DeprecatedObject from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -63,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DeprecatedObject from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py index f038da3dd481..71b1bd01bc95 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dog.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import StrictStr +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Dog(Animal): """ Dog - """ + """ # noqa: E501 breed: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["className", "color", "breed"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Dog from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Dog from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py index bb8682915ad6..9da3d978f52a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/dummy_model.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class DummyModel(BaseModel): """ DummyModel - """ + """ # noqa: E501 category: Optional[StrictStr] = None self_ref: Optional[SelfReferenceModel] = None __properties: ClassVar[List[str]] = ["category", "self_ref"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DummyModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of self_ref @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DummyModel from a dict""" if obj is None: return None @@ -86,14 +85,11 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj.get("self_ref")) if obj.get("self_ref") is not None else None + "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None }) return _obj from petstore_api.models.self_reference_model import SelfReferenceModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # DummyModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +DummyModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py index 333440a11658..1e957885f837 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_arrays.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel, StrictStr, field_validator -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class EnumArrays(BaseModel): """ EnumArrays - """ + """ # noqa: E501 just_symbol: Optional[StrictStr] = None array_enum: Optional[List[StrictStr]] = None __properties: ClassVar[List[str]] = ["just_symbol", "array_enum"] @@ -57,7 +53,8 @@ def array_enum_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -71,7 +68,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EnumArrays from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -85,16 +82,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EnumArrays from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_class.py index 11255f418979..1ba5af8036df 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_class.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumClass(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string1.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string1.py index efe9a6056218..678b4e12661f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string1.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string1.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumString1(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string2.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string2.py index 222c5dc6b824..a959f554e0af 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string2.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_string2.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumString2(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py index 0aaab02139d2..45308ff4da4e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/enum_test.py @@ -17,24 +17,19 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class EnumTest(BaseModel): """ EnumTest - """ + """ # noqa: E501 enum_string: Optional[StrictStr] = None enum_string_required: StrictStr enum_integer_default: Optional[StrictInt] = 5 @@ -95,7 +90,8 @@ def enum_number_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -109,7 +105,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EnumTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -123,10 +119,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if outer_enum (nullable) is None @@ -137,7 +135,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EnumTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py index a4009a1ade9b..c43c9ffa91a7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class File(BaseModel): """ - Must be named `File` for test. # noqa: E501 - """ + Must be named `File` for test. + """ # noqa: E501 source_uri: Optional[StrictStr] = Field(default=None, description="Test capitalization", alias="sourceURI") __properties: ClassVar[List[str]] = ["sourceURI"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of File from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of File from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py index 0a6d4ed4a806..44324be0cb5f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/file_schema_test_class.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - -from typing import List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FileSchemaTestClass(BaseModel): """ FileSchemaTestClass - """ + """ # noqa: E501 file: Optional[File] = None files: Optional[List[File]] = None __properties: ClassVar[List[str]] = ["file", "files"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FileSchemaTestClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +62,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of file @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FileSchemaTestClass from a dict""" if obj is None: return None @@ -93,8 +92,8 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "file": File.from_dict(obj.get("file")) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj.get("files")] if obj.get("files") is not None else None + "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, + "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py index 568eca6f756b..8c6b8b45bd27 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/first_ref.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class FirstRef(BaseModel): """ FirstRef - """ + """ # noqa: E501 category: Optional[StrictStr] = None self_ref: Optional[SecondRef] = None __properties: ClassVar[List[str]] = ["category", "self_ref"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FirstRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of self_ref @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FirstRef from a dict""" if obj is None: return None @@ -86,14 +85,11 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj.get("self_ref")) if obj.get("self_ref") is not None else None + "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None }) return _obj from petstore_api.models.second_ref import SecondRef -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # FirstRef.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +FirstRef.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py index cb55c8357340..b2c6fafde0cb 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo.py @@ -17,25 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Foo(BaseModel): """ Foo - """ + """ # noqa: E501 bar: Optional[StrictStr] = 'bar' __properties: ClassVar[List[str]] = ["bar"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -49,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Foo from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -63,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Foo from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py index c439ed8825e9..205de5807608 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/foo_get_default_response.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FooGetDefaultResponse(BaseModel): """ FooGetDefaultResponse - """ + """ # noqa: E501 string: Optional[Foo] = None __properties: ClassVar[List[str]] = ["string"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FooGetDefaultResponse from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of string @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FooGetDefaultResponse from a dict""" if obj is None: return None @@ -85,7 +84,7 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "string": Foo.from_dict(obj.get("string")) if obj.get("string") is not None else None + "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py index 41ea9b696cd8..afa5024f7904 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/format_test.py @@ -18,21 +18,17 @@ import json from datetime import date, datetime -from typing import Optional, Union -from pydantic import BaseModel, StrictBytes, StrictInt, StrictStr, field_validator from decimal import Decimal -from pydantic import Field +from pydantic import BaseModel, Field, StrictBytes, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FormatTest(BaseModel): """ FormatTest - """ + """ # noqa: E501 integer: Optional[Annotated[int, Field(le=100, strict=True, ge=10)]] = None int32: Optional[Annotated[int, Field(le=200, strict=True, ge=20)]] = None int64: Optional[StrictInt] = None @@ -94,7 +90,8 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -108,7 +105,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FormatTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -122,16 +119,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FormatTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py index 9f85595a0449..ee0c50cdeb4a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/has_only_read_only.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class HasOnlyReadOnly(BaseModel): """ HasOnlyReadOnly - """ + """ # noqa: E501 bar: Optional[StrictStr] = None foo: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["bar", "foo"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of HasOnlyReadOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,18 +63,20 @@ def to_dict(self) -> Dict[str, Any]: * OpenAPI `readOnly` fields are excluded. * OpenAPI `readOnly` fields are excluded. """ + excluded_fields: Set[str] = set([ + "bar", + "foo", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "bar", - "foo", - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of HasOnlyReadOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py index 851598bedcf0..325f13a4c3a7 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/health_check_result.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class HealthCheckResult(BaseModel): """ - Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. # noqa: E501 - """ + Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + """ # noqa: E501 nullable_message: Optional[StrictStr] = Field(default=None, alias="NullableMessage") __properties: ClassVar[List[str]] = ["NullableMessage"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of HealthCheckResult from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +60,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if nullable_message (nullable) is None @@ -78,7 +76,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of HealthCheckResult from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py index 5e40e20bc9a3..c1c3f5370053 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/inner_dict_with_property.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Any, Dict, Optional, Union -from pydantic import BaseModel -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class InnerDictWithProperty(BaseModel): """ InnerDictWithProperty - """ - a_property: Optional[Union[str, Any]] = Field(default=None, alias="aProperty") + """ # noqa: E501 + a_property: Optional[Dict[str, Any]] = Field(default=None, alias="aProperty") __properties: ClassVar[List[str]] = ["aProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of InnerDictWithProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of InnerDictWithProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py index cd6f56fdeba5..def00e1558c4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/int_or_string.py @@ -13,22 +13,14 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import Any, List, Optional from typing_extensions import Annotated -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -41,10 +33,11 @@ class IntOrString(BaseModel): # data type: str oneof_schema_2_validator: Optional[StrictStr] = None actual_instance: Optional[Union[int, str]] = None - one_of_schemas: List[str] = Literal["int", "str"] + one_of_schemas: List[str] = Field(default=Literal["int", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -85,7 +78,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -128,19 +121,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py index a19ae927fc3b..b0c6db34dc6f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list_class.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ListClass(BaseModel): """ ListClass - """ + """ # noqa: E501 var_123_list: Optional[StrictStr] = Field(default=None, alias="123-list") __properties: ClassVar[List[str]] = ["123-list"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ListClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ListClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py index ed7287da6db1..fbcdc17f6928 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_of_array_of_model.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class MapOfArrayOfModel(BaseModel): """ MapOfArrayOfModel - """ + """ # noqa: E501 shop_id_to_org_online_lip_map: Optional[Dict[str, List[Tag]]] = Field(default=None, alias="shopIdToOrgOnlineLipMap") __properties: ClassVar[List[str]] = ["shopIdToOrgOnlineLipMap"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MapOfArrayOfModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) @@ -83,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MapOfArrayOfModel from a dict""" if obj is None: return None @@ -98,7 +96,7 @@ def from_dict(cls, obj: dict) -> Self: if _v is not None else None ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap").items() + for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() ) }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py index 60a0eacea0ad..8d0e5a8ad628 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/map_test.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Dict, Optional from pydantic import BaseModel, StrictBool, StrictStr, field_validator -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class MapTest(BaseModel): """ MapTest - """ + """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None map_of_enum_string: Optional[Dict[str, StrictStr]] = None direct_map: Optional[Dict[str, StrictBool]] = None @@ -48,7 +44,8 @@ def map_of_enum_string_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -62,7 +59,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MapTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -76,16 +73,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MapTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py index 960da22186d4..1bc0a518afc9 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -18,20 +18,16 @@ import json from datetime import datetime -from typing import Dict, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ MixedPropertiesAndAdditionalPropertiesClass - """ + """ # noqa: E501 uuid: Optional[StrictStr] = None date_time: Optional[datetime] = Field(default=None, alias="dateTime") map: Optional[Dict[str, Animal]] = None @@ -39,7 +35,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,10 +64,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in map (dict) @@ -83,7 +82,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" if obj is None: return None @@ -96,7 +95,7 @@ def from_dict(cls, obj: dict) -> Self: "dateTime": obj.get("dateTime"), "map": dict( (_k, Animal.from_dict(_v)) - for _k, _v in obj.get("map").items() + for _k, _v in obj["map"].items() ) if obj.get("map") is not None else None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py index cf37acaae518..b74ff91feb9c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model200_response.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Model200Response(BaseModel): """ - Model for testing model name starting with number # noqa: E501 - """ + Model for testing model name starting with number + """ # noqa: E501 name: Optional[StrictInt] = None var_class: Optional[StrictStr] = Field(default=None, alias="class") __properties: ClassVar[List[str]] = ["name", "class"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Model200Response from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Model200Response from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/api_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py similarity index 77% rename from samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/api_response.py rename to samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py index c8a08ad07d62..5e87689a9861 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/api_response.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_api_response.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self -class ApiResponse(BaseModel): - """ - ApiResponse +class ModelApiResponse(BaseModel): """ + ModelApiResponse + """ # noqa: E501 code: Optional[StrictInt] = None type: Optional[StrictStr] = None message: Optional[StrictStr] = None @@ -37,7 +33,8 @@ class ApiResponse(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,8 +48,8 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of ApiResponse from a JSON string""" + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ModelApiResponse from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -65,17 +62,19 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: - """Create an instance of ApiResponse from a dict""" + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ModelApiResponse from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py index 7bfc61b95a23..86b6d51177ee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/model_return.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ModelReturn(BaseModel): """ - Model for testing reserved words # noqa: E501 - """ + Model for testing reserved words + """ # noqa: E501 var_return: Optional[StrictInt] = Field(default=None, alias="return") __properties: ClassVar[List[str]] = ["return"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ModelReturn from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ModelReturn from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py index 3cf8fb2c48ec..55a50ac01bd0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/name.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Name(BaseModel): """ - Model for testing model name same as property name # noqa: E501 - """ + Model for testing model name same as property name + """ # noqa: E501 name: StrictInt snake_case: Optional[StrictInt] = None var_property: Optional[StrictStr] = Field(default=None, alias="property") @@ -39,7 +34,8 @@ class Name(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Name from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -69,18 +65,20 @@ def to_dict(self) -> Dict[str, Any]: * OpenAPI `readOnly` fields are excluded. * OpenAPI `readOnly` fields are excluded. """ + excluded_fields: Set[str] = set([ + "snake_case", + "var_123_number", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "snake_case", - "var_123_number", - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Name from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py index 97a741cec728..101f1a96b6a0 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_class.py @@ -18,18 +18,15 @@ import json from datetime import date, datetime -from typing import Any, Dict, List, Optional, Union from pydantic import BaseModel, StrictBool, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class NullableClass(BaseModel): """ NullableClass - """ + """ # noqa: E501 required_integer_prop: Optional[StrictInt] integer_prop: Optional[StrictInt] = None number_prop: Optional[float] = None @@ -37,18 +34,19 @@ class NullableClass(BaseModel): string_prop: Optional[StrictStr] = None date_prop: Optional[date] = None datetime_prop: Optional[datetime] = None - array_nullable_prop: Optional[List[Union[str, Any]]] = None - array_and_items_nullable_prop: Optional[List[Union[str, Any]]] = None - array_items_nullable: Optional[List[Union[str, Any]]] = None - object_nullable_prop: Optional[Dict[str, Union[str, Any]]] = None - object_and_items_nullable_prop: Optional[Dict[str, Union[str, Any]]] = None - object_items_nullable: Optional[Dict[str, Union[str, Any]]] = None + array_nullable_prop: Optional[List[Dict[str, Any]]] = None + array_and_items_nullable_prop: Optional[List[Dict[str, Any]]] = None + array_items_nullable: Optional[List[Dict[str, Any]]] = None + object_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None + object_and_items_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None + object_items_nullable: Optional[Dict[str, Dict[str, Any]]] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["required_integer_prop", "integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -62,7 +60,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NullableClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -77,11 +75,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -147,7 +147,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NullableClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py index 440830fe53e9..fe618807e9da 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/nullable_property.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, field_validator +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class NullableProperty(BaseModel): """ NullableProperty - """ + """ # noqa: E501 id: StrictInt name: Optional[Annotated[str, Field(strict=True)]] __properties: ClassVar[List[str]] = ["id", "name"] @@ -48,7 +43,8 @@ def name_validate_regular_expression(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -62,7 +58,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NullableProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -76,10 +72,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if name (nullable) is None @@ -90,7 +88,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NullableProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py index c4c5e83f8b3c..7ed7b422b52a 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/number_only.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class NumberOnly(BaseModel): """ NumberOnly - """ + """ # noqa: E501 just_number: Optional[float] = Field(default=None, alias="JustNumber") __properties: ClassVar[List[str]] = ["JustNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py index 0d9a69aeda11..7e3aa7a202ff 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_to_test_additional_properties.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictBool -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictBool +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ObjectToTestAdditionalProperties(BaseModel): """ - Minimal object # noqa: E501 - """ + Minimal object + """ # noqa: E501 var_property: Optional[StrictBool] = Field(default=False, description="Property", alias="property") __properties: ClassVar[List[str]] = ["property"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ObjectToTestAdditionalProperties from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py index 37ea3c8b169c..8b5c19ebd53d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/object_with_deprecated_fields.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.deprecated_object import DeprecatedObject -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ObjectWithDeprecatedFields(BaseModel): """ ObjectWithDeprecatedFields - """ + """ # noqa: E501 uuid: Optional[StrictStr] = None id: Optional[float] = None deprecated_ref: Optional[DeprecatedObject] = Field(default=None, alias="deprecatedRef") @@ -40,7 +35,8 @@ class ObjectWithDeprecatedFields(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ObjectWithDeprecatedFields from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,10 +64,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of deprecated_ref @@ -80,7 +78,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ObjectWithDeprecatedFields from a dict""" if obj is None: return None @@ -91,7 +89,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "uuid": obj.get("uuid"), "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj.get("deprecatedRef")) if obj.get("deprecatedRef") is not None else None, + "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, "bars": obj.get("bars") }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_enum_string.py index 3e9c111a4a73..181582f8830d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/one_of_enum_string.py @@ -13,22 +13,15 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] @@ -41,10 +34,11 @@ class OneOfEnumString(BaseModel): # data type: EnumString2 oneof_schema_2_validator: Optional[EnumString2] = None actual_instance: Optional[Union[EnumString1, EnumString2]] = None - one_of_schemas: List[str] = Literal["EnumString1", "EnumString2"] + one_of_schemas: List[str] = Field(default=Literal["EnumString1", "EnumString2"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -83,7 +77,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -120,19 +114,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py index 1481a686d1ac..94f1a306b27d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/order.py @@ -18,19 +18,15 @@ import json from datetime import datetime -from typing import Optional -from pydantic import BaseModel, StrictBool, StrictInt, StrictStr, field_validator -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Order(BaseModel): """ Order - """ + """ # noqa: E501 id: Optional[StrictInt] = None pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None @@ -51,7 +47,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -65,7 +62,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Order from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -79,16 +76,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Order from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py index 7d76d2da971a..52a6e044d097 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_composite.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictBool, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class OuterComposite(BaseModel): """ OuterComposite - """ + """ # noqa: E501 my_number: Optional[float] = None my_string: Optional[StrictStr] = None my_boolean: Optional[StrictBool] = None @@ -37,7 +33,8 @@ class OuterComposite(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of OuterComposite from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of OuterComposite from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum.py index 89b19cbcf664..ac48cc0dc4d8 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnum(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_default_value.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_default_value.py index 51ca91443e27..99d6fd5fc042 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_default_value.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_default_value.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumDefaultValue(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer.py index 8947df650469..b771b7a61f55 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumInteger(int, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer_default_value.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer_default_value.py index 970487bb0c4d..8df41b2bd320 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer_default_value.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_enum_integer_default_value.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumIntegerDefaultValue(int, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py index 476ce266f6bf..83f4c1b8ef32 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/outer_object_with_enum_property.py @@ -17,28 +17,25 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class OuterObjectWithEnumProperty(BaseModel): """ OuterObjectWithEnumProperty - """ + """ # noqa: E501 str_value: Optional[OuterEnum] = None value: OuterEnumInteger __properties: ClassVar[List[str]] = ["str_value", "value"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of OuterObjectWithEnumProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,10 +63,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # set to None if str_value (nullable) is None @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of OuterObjectWithEnumProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py index 6db76ae9dc1b..dba6f038d89c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Dict, Optional -from pydantic import BaseModel -from pydantic import Field +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Parent(BaseModel): """ Parent - """ + """ # noqa: E501 optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(default=None, alias="optionalDict") __properties: ClassVar[List[str]] = ["optionalDict"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Parent from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Parent from a dict""" if obj is None: return None @@ -92,7 +90,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "optionalDict": dict( (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj.get("optionalDict").items() + for _k, _v in obj["optionalDict"].items() ) if obj.get("optionalDict") is not None else None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py index 1dc94bddede3..3c81088b3b49 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/parent_with_optional_dict.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Dict, Optional -from pydantic import BaseModel -from pydantic import Field +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.inner_dict_with_property import InnerDictWithProperty -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ParentWithOptionalDict(BaseModel): """ ParentWithOptionalDict - """ + """ # noqa: E501 optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(default=None, alias="optionalDict") __properties: ClassVar[List[str]] = ["optionalDict"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ParentWithOptionalDict from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ParentWithOptionalDict from a dict""" if obj is None: return None @@ -92,7 +90,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "optionalDict": dict( (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj.get("optionalDict").items() + for _k, _v in obj["optionalDict"].items() ) if obj.get("optionalDict") is not None else None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py index 863a4c1c2b06..3812cfa2a15e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pet.py @@ -17,23 +17,18 @@ import re # noqa: F401 import json - -from typing import List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from typing_extensions import Annotated from petstore_api.models.category import Category from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Pet(BaseModel): """ Pet - """ + """ # noqa: E501 id: Optional[StrictInt] = None category: Optional[Category] = None name: StrictStr @@ -54,7 +49,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -68,7 +64,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Pet from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -82,10 +78,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of category @@ -101,7 +99,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Pet from a dict""" if obj is None: return None @@ -111,10 +109,10 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "id": obj.get("id"), - "category": Category.from_dict(obj.get("category")) if obj.get("category") is not None else None, + "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, "name": obj.get("name"), "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj.get("tags")] if obj.get("tags") is not None else None, + "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, "status": obj.get("status") }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py index 89db853d2ec5..9b791be19f36 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/pig.py @@ -13,22 +13,15 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -41,10 +34,11 @@ class Pig(BaseModel): # data type: DanishPig oneof_schema_2_validator: Optional[DanishPig] = None actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: List[str] = Literal["BasquePig", "DanishPig"] + one_of_schemas: List[str] = Field(default=Literal["BasquePig", "DanishPig"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -86,7 +80,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -123,19 +117,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py index d72994935fc7..65135e04cd01 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/property_name_collision.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class PropertyNameCollision(BaseModel): """ PropertyNameCollision - """ - type: Optional[StrictStr] = Field(default=None, alias="_type") + """ # noqa: E501 + underscore_type: Optional[StrictStr] = Field(default=None, alias="_type") type: Optional[StrictStr] = None - type_: Optional[StrictStr] = None + type_with_underscore: Optional[StrictStr] = Field(default=None, alias="type_") __properties: ClassVar[List[str]] = ["_type", "type", "type_"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of PropertyNameCollision from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,16 +62,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of PropertyNameCollision from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py index 0a50bf6362d9..b2265203a59f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/read_only_first.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ReadOnlyFirst(BaseModel): """ ReadOnlyFirst - """ + """ # noqa: E501 bar: Optional[StrictStr] = None baz: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["bar", "baz"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ReadOnlyFirst from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,17 +62,19 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * OpenAPI `readOnly` fields are excluded. """ + excluded_fields: Set[str] = set([ + "bar", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "bar", - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ReadOnlyFirst from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py index 9140870ee899..e57459a81490 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/second_ref.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class SecondRef(BaseModel): """ SecondRef - """ + """ # noqa: E501 category: Optional[StrictStr] = None circular_ref: Optional[CircularReferenceModel] = None __properties: ClassVar[List[str]] = ["category", "circular_ref"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SecondRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of circular_ref @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SecondRef from a dict""" if obj is None: return None @@ -86,14 +85,11 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj.get("circular_ref")) if obj.get("circular_ref") is not None else None + "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None }) return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # SecondRef.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +SecondRef.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py index 2eaf5838dbbf..afd8d48a85f2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/self_reference_model.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class SelfReferenceModel(BaseModel): """ SelfReferenceModel - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested: Optional[DummyModel] = None __properties: ClassVar[List[str]] = ["size", "nested"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SelfReferenceModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested @@ -76,7 +75,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SelfReferenceModel from a dict""" if obj is None: return None @@ -86,14 +85,11 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested": DummyModel.from_dict(obj.get("nested")) if obj.get("nested") is not None else None + "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None }) return _obj from petstore_api.models.dummy_model import DummyModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # SelfReferenceModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +SelfReferenceModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/single_ref_type.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/single_ref_type.py index 3c41c4118654..91ab07e2535c 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/single_ref_type.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/single_ref_type.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class SingleRefType(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_character_enum.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_character_enum.py index 77ed288a94b4..1d85fd148d4b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_character_enum.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_character_enum.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class SpecialCharacterEnum(str, Enum): diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py index dcc61fa6f4c8..dbf0f7c7a718 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_model_name.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class SpecialModelName(BaseModel): """ SpecialModelName - """ + """ # noqa: E501 special_property_name: Optional[StrictInt] = Field(default=None, alias="$special[property.name]") __properties: ClassVar[List[str]] = ["$special[property.name]"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SpecialModelName from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SpecialModelName from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py index 5bff4d8a2c67..caff65e97c1d 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/special_name.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.category import Category -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class SpecialName(BaseModel): """ SpecialName - """ + """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") @@ -49,7 +44,8 @@ def var_schema_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -63,7 +59,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SpecialName from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -77,10 +73,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of var_async @@ -89,7 +87,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SpecialName from a dict""" if obj is None: return None @@ -99,7 +97,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "property": obj.get("property"), - "async": Category.from_dict(obj.get("async")) if obj.get("async") is not None else None, + "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, "schema": obj.get("schema") }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py index be906a578ed2..b3cc7b7bbb7e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tag.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tag(BaseModel): """ Tag - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["id", "name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tag from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +61,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tag from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..a456097bc7b5 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class TestErrorResponsesWithModel400Response(BaseModel): + """ + TestErrorResponsesWithModel400Response + """ # noqa: E501 + reason400: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["reason400"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True, + "protected_namespaces": (), + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel400Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reason400": obj.get("reason400") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..c4c88b202686 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py @@ -0,0 +1,87 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class TestErrorResponsesWithModel404Response(BaseModel): + """ + TestErrorResponsesWithModel404Response + """ # noqa: E501 + reason404: Optional[StrictStr] = None + __properties: ClassVar[List[str]] = ["reason404"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True, + "protected_namespaces": (), + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + """ + excluded_fields: Set[str] = set([ + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel404Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reason404": obj.get("reason404") + }) + return _obj + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py index 81ae90565082..2fb96a50dd78 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ TestInlineFreeformAdditionalPropertiesRequest - """ + """ # noqa: E501 some_property: Optional[StrictStr] = Field(default=None, alias="someProperty") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["someProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py index c47e200a43d8..cd9bb8f356ff 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/tiger.py @@ -17,25 +17,22 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tiger(BaseModel): """ Tiger - """ + """ # noqa: E501 skill: Optional[StrictStr] = None __properties: ClassVar[List[str]] = ["skill"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -49,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tiger from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -63,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tiger from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index abd2f06aa8ff..9e5f2dae96e4 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.creature_info import CreatureInfo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ UnnamedDictWithAdditionalModelListProperties - """ + """ # noqa: E501 dict_property: Optional[Dict[str, List[CreatureInfo]]] = Field(default=None, alias="dictProperty") __properties: ClassVar[List[str]] = ["dictProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,10 +61,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) @@ -83,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" if obj is None: return None @@ -98,7 +96,7 @@ def from_dict(cls, obj: dict) -> Self: if _v is not None else None ) - for _k, _v in obj.get("dictProperty").items() + for _k, _v in obj.get("dictProperty", {}).items() ) }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index 5fad957d5bf8..20840faa9950 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -17,26 +17,22 @@ import re # noqa: F401 import json - -from typing import Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ UnnamedDictWithAdditionalStringListProperties - """ + """ # noqa: E501 dict_property: Optional[Dict[str, List[StrictStr]]] = Field(default=None, alias="dictProperty") __properties: ClassVar[List[str]] = ["dictProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +46,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -64,16 +60,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py index af930f09dd5d..28ada093f19b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/user.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - -from typing import Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field, StrictInt, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class User(BaseModel): """ User - """ + """ # noqa: E501 id: Optional[StrictInt] = None username: Optional[StrictStr] = None first_name: Optional[StrictStr] = Field(default=None, alias="firstName") @@ -43,7 +38,8 @@ class User(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -57,7 +53,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of User from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -71,16 +67,18 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of User from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py index 72130e4dcf30..5ca2df46c9b6 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/with_nested_one_of.py @@ -17,21 +17,17 @@ import re # noqa: F401 import json - -from typing import Optional from pydantic import BaseModel, StrictInt +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class WithNestedOneOf(BaseModel): """ WithNestedOneOf - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested_pig: Optional[Pig] = None nested_oneof_enum_string: Optional[OneOfEnumString] = None @@ -39,7 +35,8 @@ class WithNestedOneOf(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WithNestedOneOf from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,10 +64,12 @@ def to_dict(self) -> Dict[str, Any]: were set at model initialization. Other fields with value `None` are ignored. """ + excluded_fields: Set[str] = set([ + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested_pig @@ -82,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WithNestedOneOf from a dict""" if obj is None: return None @@ -92,8 +91,8 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj.get("nested_pig")) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": OneOfEnumString.from_dict(obj.get("nested_oneof_enum_string")) if obj.get("nested_oneof_enum_string") is not None else None + "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, + "nested_oneof_enum_string": OneOfEnumString.from_dict(obj["nested_oneof_enum_string"]) if obj.get("nested_oneof_enum_string") is not None else None }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py index 7daf8c921c84..147076895fcc 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/rest.py @@ -14,44 +14,51 @@ import io import json -import logging import re import ssl +from typing import Optional, Union import aiohttp -from urllib.parse import urlencode, quote_plus +import aiohttp_retry from petstore_api.exceptions import ApiException, ApiValueError -logger = logging.getLogger(__name__) +RESTResponseType = aiohttp.ClientResponse +ALLOW_RETRY_METHODS = frozenset({'DELETE', 'GET', 'HEAD', 'OPTIONS', 'PUT', 'TRACE'}) class RESTResponse(io.IOBase): - def __init__(self, resp, data) -> None: - self.aiohttp_response = resp + def __init__(self, resp) -> None: + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = data + self.data = None + + async def read(self): + if self.data is None: + self.data = await self.response.read() + return self.data def getheaders(self): """Returns a CIMultiDictProxy of the response headers.""" - return self.aiohttp_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.aiohttp_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # maxsize is number of requests to host that are allowed in parallel - if maxsize is None: - maxsize = configuration.connection_pool_maxsize + maxsize = configuration.connection_pool_maxsize - ssl_context = ssl.create_default_context(cafile=configuration.ssl_ca_cert) + ssl_context = ssl.create_default_context( + cafile=configuration.ssl_ca_cert + ) if configuration.cert_file: ssl_context.load_cert_chain( configuration.cert_file, keyfile=configuration.key_file @@ -75,32 +82,59 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: trust_env=True ) + retries = configuration.retries + self.retry_client: Optional[aiohttp_retry.RetryClient] + if retries is not None: + self.retry_client = aiohttp_retry.RetryClient( + client_session=self.pool_manager, + retry_options=aiohttp_retry.ExponentialRetry( + attempts=retries, + factor=0.0, + start_timeout=0.0, + max_timeout=120.0 + ) + ) + else: + self.retry_client = None + async def close(self): await self.pool_manager.close() - - async def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + if self.retry_client is not None: + await self.retry_client.close() + + async def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Execute request :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: this is a non-applicable field for - the AiohttpClient. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -110,8 +144,6 @@ async def request(self, method, url, query_params=None, headers=None, post_params = post_params or {} headers = headers or {} # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = _request_timeout or 5 * 60 if 'Content-Type' not in headers: @@ -129,16 +161,13 @@ async def request(self, method, url, query_params=None, headers=None, if self.proxy_headers: args["proxy_headers"] = self.proxy_headers - if query_params: - args["url"] += '?' + urlencode(query_params) - # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: if re.search('json', headers['Content-Type'], re.IGNORECASE): if body is not None: body = json.dumps(body) args["data"] = body - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + elif headers['Content-Type'] == 'application/x-www-form-urlencoded': args["data"] = aiohttp.FormData(post_params) elif headers['Content-Type'] == 'multipart/form-data': # must del headers['Content-Type'], or the correct @@ -148,10 +177,12 @@ async def request(self, method, url, query_params=None, headers=None, for param in post_params: k, v = param if isinstance(v, tuple) and len(v) == 3: - data.add_field(k, - value=v[1], - filename=v[0], - content_type=v[2]) + data.add_field( + k, + value=v[1], + filename=v[0], + content_type=v[2] + ) else: data.add_field(k, v) args["data"] = data @@ -168,84 +199,17 @@ async def request(self, method, url, query_params=None, headers=None, declared content type.""" raise ApiException(status=0, reason=msg) - r = await self.pool_manager.request(**args) - if _preload_content: - - data = await r.read() - r = RESTResponse(r, data) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - raise ApiException(http_resp=r) - - return r - - async def get_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def head_request(self, url, headers=None, query_params=None, - _preload_content=True, _request_timeout=None): - return (await self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params)) - - async def options_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return (await self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def post_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return (await self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) - - async def patch_request(self, url, headers=None, query_params=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - return (await self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body)) + pool_manager: Union[aiohttp.ClientSession, aiohttp_retry.RetryClient] + if self.retry_client is not None and method in ALLOW_RETRY_METHODS: + pool_manager = self.retry_client + else: + pool_manager = self.pool_manager + + r = await pool_manager.request(**args) + + return RESTResponse(r) + + + + + diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/signing.py b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/signing.py index ec4d7d2a67fd..e0ef058f4677 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/signing.py +++ b/samples/openapi3/client/petstore/python-aiohttp/petstore_api/signing.py @@ -13,13 +13,16 @@ from base64 import b64encode from Crypto.IO import PEM, PKCS8 from Crypto.Hash import SHA256, SHA512 +from Crypto.Hash.SHA512 import SHA512Hash +from Crypto.Hash.SHA256 import SHA256Hash from Crypto.PublicKey import RSA, ECC from Crypto.Signature import PKCS1_v1_5, pss, DSS +from datetime import timedelta from email.utils import formatdate -import json import os import re from time import time +from typing import List, Optional, Union from urllib.parse import urlencode, urlparse # The constants below define a subset of HTTP headers that can be included in the @@ -68,18 +71,20 @@ class HttpSigningConfiguration: """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key which is in possession of the API client. - An 'Authorization' header is calculated by creating a hash of select headers, + + An ``Authorization`` header is calculated by creating a hash of select headers, and optionally the body of the HTTP request, then signing the hash value using - a private key. The 'Authorization' header is added to outbound HTTP requests. + a private key. The ``Authorization`` header is added to outbound HTTP requests. :param key_id: A string value specifying the identifier of the cryptographic key, when signing HTTP requests. :param signing_scheme: A string value specifying the signature scheme, when signing HTTP requests. - Supported value are hs2019, rsa-sha256, rsa-sha512. - Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + Supported value are: ``hs2019``, ``rsa-sha256``, ``rsa-sha512``. + Avoid using ``rsa-sha256``, ``rsa-sha512`` as they are deprecated. These values are available for server-side applications that only support the older HTTP signature algorithms. :param private_key_path: A string value specifying the path of the file containing @@ -88,18 +93,19 @@ class HttpSigningConfiguration: the private key. :param signed_headers: A list of strings. Each value is the name of a HTTP header that must be included in the HTTP signature calculation. - The two special signature headers '(request-target)' and '(created)' SHOULD be + The two special signature headers ``(request-target)`` and ``(created)`` SHOULD be included in SignedHeaders. - The '(created)' header expresses when the signature was created. - The '(request-target)' header is a concatenation of the lowercased :method, an + The ``(created)`` header expresses when the signature was created. + The ``(request-target)`` header is a concatenation of the lowercased :method, an ASCII space, and the :path pseudo-headers. When signed_headers is not specified, the client defaults to a single value, - '(created)', in the list of HTTP headers. + ``(created)``, in the list of HTTP headers. When SignedHeaders contains the 'Digest' value, the client performs the following operations: - 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. - 2. Set the 'Digest' header in the request body. - 3. Include the 'Digest' header and value in the HTTP signature. + 1. Calculate a digest of request body, as specified in `RFC3230, + section 4.3.2`_. + 2. Set the ``Digest`` header in the request body. + 3. Include the ``Digest`` header and value in the HTTP signature. :param signing_algorithm: A string value specifying the signature algorithm, when signing HTTP requests. Supported values are: @@ -117,12 +123,16 @@ class HttpSigningConfiguration: :param signature_max_validity: The signature max validity, expressed as a datetime.timedelta value. It must be a positive value. """ - def __init__(self, key_id, signing_scheme, private_key_path, - private_key_passphrase=None, - signed_headers=None, - signing_algorithm=None, - hash_algorithm=None, - signature_max_validity=None) -> None: + def __init__(self, + key_id: str, + signing_scheme: str, + private_key_path: str, + private_key_passphrase: Union[None, str]=None, + signed_headers: Optional[List[str]]=None, + signing_algorithm: Optional[str]=None, + hash_algorithm: Optional[str]=None, + signature_max_validity: Optional[timedelta]=None, + ) -> None: self.key_id = key_id if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) @@ -166,11 +176,11 @@ def __init__(self, key_id, signing_scheme, private_key_path, if HEADER_AUTHORIZATION in signed_headers: raise Exception("'Authorization' header cannot be included in signed headers") self.signed_headers = signed_headers - self.private_key = None + self.private_key: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None """The private key used to sign HTTP requests. Initialized when the PEM-encoded private key is loaded from a file. """ - self.host = None + self.host: Optional[str] = None """The host name, optionally followed by a colon and TCP port number. """ self._load_private_key() @@ -208,7 +218,7 @@ def get_http_signature_headers(self, resource_path, method, headers, body, query def get_public_key(self): """Returns the public key object associated with the private key. """ - pubkey = None + pubkey: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None if isinstance(self.private_key, RSA.RsaKey): pubkey = self.private_key.publickey() elif isinstance(self.private_key, ECC.EccKey): @@ -237,8 +247,11 @@ def _load_private_key(self): elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: # Key is in PKCS8 format, which is capable of holding many different # types of private keys, not just EC keys. - (key_binary, pem_header, is_encrypted) = \ - PEM.decode(pem_data, self.private_key_passphrase) + if self.private_key_passphrase is not None: + passphrase = self.private_key_passphrase.encode("utf-8") + else: + passphrase = None + (key_binary, pem_header, is_encrypted) = PEM.decode(pem_data, passphrase) (oid, privkey, params) = \ PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) if oid == '1.2.840.10045.2.1': @@ -319,8 +332,11 @@ def _get_signed_header_info(self, resource_path, method, headers, body, query_pa request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( digest_prefix, b64_body_digest.decode('ascii')) elif hdr_key == HEADER_HOST.lower(): - value = target_host - request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + if isinstance(target_host, bytes): + value = target_host.decode('ascii') + else: + value = target_host + request_headers_dict[HEADER_HOST] = value else: value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) if value is None: @@ -341,6 +357,9 @@ def _get_message_digest(self, data): The prefix is a string that identifies the cryptographic hash. It is used to generate the 'Digest' header as specified in RFC 3230. """ + + digest: Union[SHA256Hash, SHA512Hash] + if self.hash_algorithm == HASH_SHA512: digest = SHA512.new() prefix = 'SHA-512=' diff --git a/samples/openapi3/client/petstore/python-aiohttp/pyproject.toml b/samples/openapi3/client/petstore/python-aiohttp/pyproject.toml index 6747ce2b9135..1263eb6a3562 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/pyproject.toml +++ b/samples/openapi3/client/petstore/python-aiohttp/pyproject.toml @@ -15,6 +15,7 @@ python = "^3.7" urllib3 = ">= 1.25.3" python-dateutil = ">=2.8.2" aiohttp = ">= 3.8.4" +aiohttp-retry = ">= 2.8.3" pem = ">= 19.3.0" pycryptodome = ">= 3.9.0" pydantic = ">=2" @@ -24,6 +25,9 @@ typing-extensions = ">=4.7.1" pytest = ">=7.2.1" tox = ">=3.9.0" flake8 = ">=4.0.0" +types-python-dateutil = ">=2.8.19.14" +mypy = "1.4.1" + [build-system] requires = ["setuptools"] @@ -31,3 +35,41 @@ build-backend = "setuptools.build_meta" [tool.pylint.'MESSAGES CONTROL'] extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "petstore_api", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +strict_concatenate = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true diff --git a/samples/openapi3/client/petstore/python-aiohttp/requirements.txt b/samples/openapi3/client/petstore/python-aiohttp/requirements.txt index 870cfc37f343..3564e66b316e 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/requirements.txt +++ b/samples/openapi3/client/petstore/python-aiohttp/requirements.txt @@ -4,4 +4,5 @@ urllib3 >= 1.25.3, < 2.1.0 pydantic >= 2 typing-extensions >= 4.7.1 aiohttp >= 3.0.0 +aiohttp-retry >= 2.8.3 pycryptodome >= 3.9.0 diff --git a/samples/openapi3/client/petstore/python-aiohttp/setup.py b/samples/openapi3/client/petstore/python-aiohttp/setup.py index 4c8c7663615b..a51834b09ae1 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/setup.py +++ b/samples/openapi3/client/petstore/python-aiohttp/setup.py @@ -27,6 +27,7 @@ "urllib3 >= 1.25.3, < 2.1.0", "python-dateutil", "aiohttp >= 3.0.0", + "aiohttp-retry >= 2.8.3", "pem>=19.3.0", "pycryptodome>=3.9.0", "pydantic >= 2", diff --git a/samples/openapi3/client/petstore/python-aiohttp/test-requirements.txt b/samples/openapi3/client/petstore/python-aiohttp/test-requirements.txt index 3a0d0b939a1e..8e6d8cb13749 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/test-requirements.txt +++ b/samples/openapi3/client/petstore/python-aiohttp/test-requirements.txt @@ -1,3 +1,5 @@ pytest~=7.1.3 pytest-cov>=2.8.1 pytest-randomly>=3.12.0 +mypy>=1.4.1 +types-python-dateutil>=2.8.19 diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_api_response.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_api_response.py deleted file mode 100644 index 54871268a190..000000000000 --- a/samples/openapi3/client/petstore/python-aiohttp/test/test_api_response.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.api_response import ApiResponse # noqa: E501 -from petstore_api.rest import ApiException - -class TestApiResponse(unittest.TestCase): - """ApiResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ApiResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.api_response.ApiResponse() # noqa: E501 - if include_optional : - return ApiResponse( - code = 56, - type = '', - message = '' - ) - else : - return ApiResponse( - ) - - def testApiResponse(self): - """Test ApiResponse""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_list.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_list.py deleted file mode 100644 index 7b001d818e89..000000000000 --- a/samples/openapi3/client/petstore/python-aiohttp/test/test_list.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.list import List # noqa: E501 -from petstore_api.rest import ApiException - -class TestList(unittest.TestCase): - """List unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test List - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.list.List() # noqa: E501 - if include_optional : - return List( - _123_list = '' - ) - else : - return List( - ) - - def testList(self): - """Test List""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_model_api_response.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_model_api_response.py new file mode 100644 index 000000000000..f37f34084401 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_model_api_response.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.model_api_response import ModelApiResponse + +class TestModelApiResponse(unittest.TestCase): + """ModelApiResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ModelApiResponse: + """Test ModelApiResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ModelApiResponse` + """ + model = ModelApiResponse() + if include_optional: + return ModelApiResponse( + code = 56, + type = '', + message = '' + ) + else: + return ModelApiResponse( + ) + """ + + def testModelApiResponse(self): + """Test ModelApiResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..35db7ba74fb7 --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model400_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +class TestTestErrorResponsesWithModel400Response(unittest.TestCase): + """TestErrorResponsesWithModel400Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel400Response: + """Test TestErrorResponsesWithModel400Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel400Response` + """ + model = TestErrorResponsesWithModel400Response() + if include_optional: + return TestErrorResponsesWithModel400Response( + reason400 = '' + ) + else: + return TestErrorResponsesWithModel400Response( + ) + """ + + def testTestErrorResponsesWithModel400Response(self): + """Test TestErrorResponsesWithModel400Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..e9c97c0f484b --- /dev/null +++ b/samples/openapi3/client/petstore/python-aiohttp/test/test_test_error_responses_with_model404_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +class TestTestErrorResponsesWithModel404Response(unittest.TestCase): + """TestErrorResponsesWithModel404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel404Response: + """Test TestErrorResponsesWithModel404Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel404Response` + """ + model = TestErrorResponsesWithModel404Response() + if include_optional: + return TestErrorResponsesWithModel404Response( + reason404 = '' + ) + else: + return TestErrorResponsesWithModel404Response( + ) + """ + + def testTestErrorResponsesWithModel404Response(self): + """Test TestErrorResponsesWithModel404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_model.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_model.py index d0fc363f5e04..c7dc4132135b 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/tests/test_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_model.py @@ -3,6 +3,7 @@ # flake8: noqa +from datetime import date import os import time import unittest @@ -118,6 +119,7 @@ def test_oneOf(self): nested_json = nested.to_json() nested2 = petstore_api.WithNestedOneOf.from_json(nested_json) + assert nested2 is not None self.assertEqual(nested2.to_json(), nested_json) def test_anyOf(self): @@ -172,6 +174,7 @@ def test_inheritance(self): self.assertEqual(dog.to_dict(), {'breed': 'bulldog', 'className': 'dog', 'color': 'white'}) dog2 = petstore_api.Dog.from_json(dog.to_json()) + assert dog2 is not None self.assertEqual(dog2.breed, 'bulldog') self.assertEqual(dog2.class_name, "dog") self.assertEqual(dog2.color, 'white') @@ -180,7 +183,8 @@ def test_inheritance(self): def test_list(self): # should throw exception as var_123_list should be string try: - l3 = petstore_api.List(var_123_list=123) + # Don't check the typing, because we are actually testing a typing error. + l3 = petstore_api.ListClass(**{"123-list": 123}) # type: ignore self.assertTrue(False) # this line shouldn't execute except ValueError as e: #error_message = ( @@ -189,13 +193,14 @@ def test_list(self): # " str type expected (type=type_error.str)\n") self.assertTrue("str type expected" in str(e)) - l = petstore_api.List(var_123_list="bulldog") + l = petstore_api.ListClass(**{"123-list": "bulldog"}) self.assertEqual(l.to_json(), '{"123-list":"bulldog"}') self.assertEqual(l.to_dict(), {'123-list': 'bulldog'}) - l2 = petstore_api.List.from_json(l.to_json()) - self.assertEqual(l2.var_123_list, 'bulldog') - self.assertTrue(isinstance(l2, petstore_api.List)) + l2 = petstore_api.ListClass.from_json(l.to_json()) + assert l2 is not None + self.assertEqual(l2.var_123_list, 'bulldog') + self.assertTrue(isinstance(l2, petstore_api.ListClass)) def test_enum_ref_property(self): # test enum ref property @@ -204,26 +209,28 @@ def test_enum_ref_property(self): self.assertEqual(d.to_json(), '{"value": 1}') d2 = petstore_api.OuterObjectWithEnumProperty(value=petstore_api.OuterEnumInteger.NUMBER_1, str_value=petstore_api.OuterEnum.DELIVERED) self.assertEqual(d2.to_json(), '{"str_value": "delivered", "value": 1}') + # test from_json (round trip) d3 = petstore_api.OuterObjectWithEnumProperty.from_json(d2.to_json()) + assert d3 is not None self.assertEqual(d3.str_value, petstore_api.OuterEnum.DELIVERED) self.assertEqual(d3.value, petstore_api.OuterEnumInteger.NUMBER_1) self.assertEqual(d3.to_json(), '{"str_value": "delivered", "value": 1}') - @unittest.skip("TODO: pydantic v2: 'float' field alias the 'float' type used by 'number'") def test_float_strict_type(self): # assigning 123 to float shouldn't throw an exception - a = petstore_api.FormatTest(number=39.8, float=123, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876") - self.assertEqual(a.float, 123.0) + a = petstore_api.FormatTest(number=39.8, float=123, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876") + self.assertEqual(a.var_float, 123.0) json_str = "{\"number\": 34.5, \"float\": \"456\", \"date\": \"2013-12-08\", \"password\": \"empty1234567\", \"pattern_with_digits\": \"1234567890\", \"pattern_with_digits_and_delimiter\": \"image_123\", \"string_with_double_quote_pattern\": \"this is \\\"something\\\"\", \"string\": \"string\"}" # no exception thrown when assigning 456 (integer) to float type since strict is set to false f = petstore_api.FormatTest.from_json(json_str) - self.assertEqual(f.float, 456.0) + assert f is not None + self.assertEqual(f.var_float, 456.0) def test_valdiator(self): # test regular expression - a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876") + a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876") try: a.pattern_with_digits_and_delimiter = "123" self.assertTrue(False) # this line shouldn't execute diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_api.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_api.py index 7e7f0cc54560..2746c923ffb2 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_api.py +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_api.py @@ -10,9 +10,11 @@ """ import os +import sys import unittest import asyncio import pytest +import aiohttp import petstore_api from petstore_api import Configuration @@ -69,6 +71,7 @@ def test_separate_default_config_instances(self): @async_test async def test_async_with_result(self): await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None tasks = [ asyncio.create_task(coro) @@ -98,38 +101,56 @@ async def test_exception(self): @async_test async def test_add_pet_and_get_pet_by_id(self): await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None fetched = await self.pet_api.get_pet_by_id(pet_id=self.pet.id) - self.assertIsNotNone(fetched) self.assertEqual(self.pet.id, fetched.id) - self.assertIsNotNone(fetched.category) + assert self.pet.category is not None + assert fetched.category is not None self.assertEqual(self.pet.category.name, fetched.category.name) @async_test async def test_add_pet_and_get_pet_by_id_with_http_info(self): await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None fetched = await self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id) - self.assertIsNotNone(fetched) self.assertEqual(self.pet.id, fetched.data.id) - self.assertIsNotNone(fetched.data.category) + assert self.pet.category is not None + assert fetched.data.category is not None self.assertEqual(self.pet.category.name, fetched.data.category.name) + @async_test + async def test_add_pet_and_get_pet_by_id_without_preload_content(self): + await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None + + fetched = await self.pet_api.get_pet_by_id_without_preload_content(pet_id=self.pet.id) + self.assertIsInstance(fetched, aiohttp.ClientResponse) + read = await fetched.content.read() + self.assertTrue(fetched.closed) + self.assertTrue(fetched.content._eof) + self.assertIsInstance(read, bytes) + self.assertEqual(await fetched.content.read(), b'') + self.assertTrue(read.decode("utf-8").startswith('{"id":')) + @async_test async def test_update_pet(self): self.pet.name = "hello kity with updated" await self.pet_api.update_pet(self.pet) + assert self.pet.id is not None fetched = await self.pet_api.get_pet_by_id(pet_id=self.pet.id) - self.assertIsNotNone(fetched) self.assertEqual(self.pet.id, fetched.id) self.assertEqual(self.pet.name, fetched.name) - self.assertIsNotNone(fetched.category) + assert self.pet.category is not None + assert fetched.category is not None self.assertEqual(fetched.category.name, self.pet.category.name) @async_test async def test_find_pets_by_status(self): await self.pet_api.add_pet(self.pet) + assert self.pet.status is not None pets = await self.pet_api.find_pets_by_status(status=[self.pet.status]) self.assertIn( self.pet.id, @@ -139,6 +160,7 @@ async def test_find_pets_by_status(self): @async_test async def test_find_pets_by_tags(self): await self.pet_api.add_pet(self.pet) + assert self.tag.name is not None pets = await self.pet_api.find_pets_by_tags(tags=[self.tag.name]) self.assertIn( self.pet.id, @@ -148,6 +170,7 @@ async def test_find_pets_by_tags(self): @async_test async def test_update_pet_with_form(self): await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None name = "hello kity with form updated" status = "pending" @@ -163,6 +186,7 @@ async def test_upload_file(self): # upload file with form parameter try: additional_metadata = "special" + assert self.pet.id is not None await self.pet_api.upload_file( pet_id=self.pet.id, additional_metadata=additional_metadata, @@ -180,6 +204,7 @@ async def test_upload_file(self): @async_test async def test_delete_pet(self): await self.pet_api.add_pet(self.pet) + assert self.pet.id is not None await self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") try: @@ -196,6 +221,7 @@ async def test_proxy(self): config.proxy = 'http://localhost:8080/proxy' async with petstore_api.ApiClient(config) as client: pet_api = petstore_api.PetApi(client) + assert self.pet.id is not None with self.assertRaisesRegex(petstore_api.rest.aiohttp.client_exceptions.ClientProxyConnectionError, 'Cannot connect to host localhost:8080'): diff --git a/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_model.py b/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_model.py index 915fe777fc83..e4738e86b3ee 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_model.py +++ b/samples/openapi3/client/petstore/python-aiohttp/tests/test_pet_model.py @@ -72,11 +72,14 @@ def test_from_to_methods(self): " \"status\": \"available\",\n" " \"tags\": [{\"id\": 1, \"name\": \"None\"}]}") pet = petstore_api.Pet.from_json(json_str) + assert pet is not None self.assertEqual(pet.id, 1) self.assertEqual(pet.status, "available") self.assertEqual(pet.photo_urls, ["string"]) + assert pet.tags is not None self.assertEqual(pet.tags[0].id, 1) self.assertEqual(pet.tags[0].name, "None") + assert pet.category is not None self.assertEqual(pet.category.id, 1) # test to_json self.assertEqual(pet.to_json(), @@ -90,16 +93,22 @@ def test_from_to_methods(self): # test from_dict pet2 = petstore_api.Pet.from_dict(pet.to_dict()) + assert pet2 is not None self.assertEqual(pet2.id, 1) self.assertEqual(pet2.status, "available") self.assertEqual(pet2.photo_urls, ["string"]) + assert pet2.tags is not None self.assertEqual(pet2.tags[0].id, 1) self.assertEqual(pet2.tags[0].name, "None") + assert pet2.category is not None self.assertEqual(pet2.category.id, 1) def test_unpack_operator(self): - d = {"name": "required name", "id": 123, "photoUrls": ["https://a.com", "https://b.com"]} - pet = petstore_api.Pet(**d) + pet = petstore_api.Pet( + name="required name", + id=123, + photoUrls=["https://a.com", "https://b.com"], + ) self.assertEqual(pet.to_json(), '{"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]}') self.assertEqual(pet.to_dict(), {"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]}) def test_optional_fields(self): diff --git a/samples/openapi3/client/petstore/python-nextgen/.coverage b/samples/openapi3/client/petstore/python-nextgen/.coverage deleted file mode 100644 index fbc2acd5d971..000000000000 Binary files a/samples/openapi3/client/petstore/python-nextgen/.coverage and /dev/null differ diff --git a/samples/openapi3/client/petstore/python-nextgen/dev-requirements.txt.log b/samples/openapi3/client/petstore/python-nextgen/dev-requirements.txt.log deleted file mode 100644 index da25838df6c6..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/dev-requirements.txt.log +++ /dev/null @@ -1,115 +0,0 @@ -Defaulting to user installation because normal site-packages is not writeable -Collecting tox - Downloading tox-4.4.12-py3-none-any.whl (148 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 149.0/149.0 KB 3.0 MB/s eta 0:00:00 -Collecting flake8 - Downloading flake8-6.0.0-py2.py3-none-any.whl (57 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 57.8/57.8 KB 10.7 MB/s eta 0:00:00 -Collecting chardet>=5.1 - Downloading chardet-5.1.0-py3-none-any.whl (199 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 199.1/199.1 KB 8.7 MB/s eta 0:00:00 -Collecting tomli>=2.0.1 - Downloading tomli-2.0.1-py3-none-any.whl (12 kB) -Collecting filelock>=3.11 - Downloading filelock-3.12.0-py3-none-any.whl (10 kB) -Collecting platformdirs>=3.2 - Downloading platformdirs-3.2.0-py3-none-any.whl (14 kB) -Collecting pyproject-api>=1.5.1 - Downloading pyproject_api-1.5.1-py3-none-any.whl (12 kB) -Collecting packaging>=23 - Downloading packaging-23.1-py3-none-any.whl (48 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 48.9/48.9 KB 6.8 MB/s eta 0:00:00 -Collecting pluggy>=1 - Downloading pluggy-1.0.0-py2.py3-none-any.whl (13 kB) -Collecting virtualenv>=20.21 - Downloading virtualenv-20.22.0-py3-none-any.whl (3.2 MB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 3.2/3.2 MB 14.5 MB/s eta 0:00:00 -Collecting colorama>=0.4.6 - Downloading colorama-0.4.6-py2.py3-none-any.whl (25 kB) -Collecting cachetools>=5.3 - Downloading cachetools-5.3.0-py3-none-any.whl (9.3 kB) -Collecting mccabe<0.8.0,>=0.7.0 - Downloading mccabe-0.7.0-py2.py3-none-any.whl (7.3 kB) -Collecting pycodestyle<2.11.0,>=2.10.0 - Downloading pycodestyle-2.10.0-py2.py3-none-any.whl (41 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 41.3/41.3 KB 5.0 MB/s eta 0:00:00 -Collecting pyflakes<3.1.0,>=3.0.0 - Downloading pyflakes-3.0.1-py2.py3-none-any.whl (62 kB) - ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 62.8/62.8 KB 14.3 MB/s eta 0:00:00 -Requirement already satisfied: distlib<1,>=0.3.6 in /home/robbert/.local/lib/python3.10/site-packages (from virtualenv>=20.21->tox->-r dev-requirements.txt (line 1)) (0.3.6) -Installing collected packages: tomli, pyflakes, pycodestyle, pluggy, platformdirs, packaging, mccabe, filelock, colorama, chardet, cachetools, virtualenv, pyproject-api, flake8, tox - Attempting uninstall: filelock - Found existing installation: filelock 3.10.4 - Uninstalling filelock-3.10.4: - Successfully uninstalled filelock-3.10.4 - Attempting uninstall: virtualenv - Found existing installation: virtualenv 20.4.2 - Uninstalling virtualenv-20.4.2: - Successfully uninstalled virtualenv-20.4.2 -Successfully installed cachetools-5.3.0 chardet-5.1.0 colorama-0.4.6 filelock-3.12.0 flake8-6.0.0 mccabe-0.7.0 packaging-23.1 platformdirs-3.2.0 pluggy-1.0.0 pycodestyle-2.10.0 pyflakes-3.0.1 pyproject-api-1.5.1 tomli-2.0.1 tox-4.4.12 virtualenv-20.22.0 -Collecting tox (from -r dev-requirements.txt (line 1)) - Using cached tox-4.4.12-py3-none-any.whl (148 kB) -Collecting flake8 (from -r dev-requirements.txt (line 2)) - Using cached flake8-6.0.0-py2.py3-none-any.whl (57 kB) -Collecting cachetools>=5.3 (from tox->-r dev-requirements.txt (line 1)) - Using cached cachetools-5.3.0-py3-none-any.whl (9.3 kB) -Collecting chardet>=5.1 (from tox->-r dev-requirements.txt (line 1)) - Using cached chardet-5.1.0-py3-none-any.whl (199 kB) -Collecting colorama>=0.4.6 (from tox->-r dev-requirements.txt (line 1)) - Using cached colorama-0.4.6-py2.py3-none-any.whl (25 kB) -Collecting filelock>=3.11 (from tox->-r dev-requirements.txt (line 1)) - Using cached filelock-3.12.0-py3-none-any.whl (10 kB) -Collecting packaging>=23 (from tox->-r dev-requirements.txt (line 1)) - Using cached packaging-23.1-py3-none-any.whl (48 kB) -Collecting platformdirs>=3.2 (from tox->-r dev-requirements.txt (line 1)) - Using cached platformdirs-3.2.0-py3-none-any.whl (14 kB) -Collecting pluggy>=1 (from tox->-r dev-requirements.txt (line 1)) - Using cached pluggy-1.0.0-py2.py3-none-any.whl (13 kB) -Collecting pyproject-api>=1.5.1 (from tox->-r dev-requirements.txt (line 1)) - Using cached pyproject_api-1.5.1-py3-none-any.whl (12 kB) -Collecting tomli>=2.0.1 (from tox->-r dev-requirements.txt (line 1)) - Using cached tomli-2.0.1-py3-none-any.whl (12 kB) -Collecting virtualenv>=20.21 (from tox->-r dev-requirements.txt (line 1)) - Using cached virtualenv-20.22.0-py3-none-any.whl (3.2 MB) -Collecting mccabe<0.8.0,>=0.7.0 (from flake8->-r dev-requirements.txt (line 2)) - Using cached mccabe-0.7.0-py2.py3-none-any.whl (7.3 kB) -Collecting pycodestyle<2.11.0,>=2.10.0 (from flake8->-r dev-requirements.txt (line 2)) - Using cached pycodestyle-2.10.0-py2.py3-none-any.whl (41 kB) -Collecting pyflakes<3.1.0,>=3.0.0 (from flake8->-r dev-requirements.txt (line 2)) - Using cached pyflakes-3.0.1-py2.py3-none-any.whl (62 kB) -Collecting distlib<1,>=0.3.6 (from virtualenv>=20.21->tox->-r dev-requirements.txt (line 1)) - Using cached distlib-0.3.6-py2.py3-none-any.whl (468 kB) -Installing collected packages: distlib, tomli, pyflakes, pycodestyle, pluggy, platformdirs, packaging, mccabe, filelock, colorama, chardet, cachetools, virtualenv, pyproject-api, flake8, tox -Successfully installed cachetools-5.3.0 chardet-5.1.0 colorama-0.4.6 distlib-0.3.6 filelock-3.12.0 flake8-6.0.0 mccabe-0.7.0 packaging-23.1 platformdirs-3.2.0 pluggy-1.0.0 pycodestyle-2.10.0 pyflakes-3.0.1 pyproject-api-1.5.1 tomli-2.0.1 tox-4.4.12 virtualenv-20.22.0 -Requirement already satisfied: tox in ./venv/lib/python3.10/site-packages (from -r dev-requirements.txt (line 1)) (4.4.12) -Requirement already satisfied: flake8 in ./venv/lib/python3.10/site-packages (from -r dev-requirements.txt (line 2)) (6.0.0) -Requirement already satisfied: cachetools>=5.3 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (5.3.0) -Requirement already satisfied: chardet>=5.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (5.1.0) -Requirement already satisfied: colorama>=0.4.6 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (0.4.6) -Requirement already satisfied: filelock>=3.11 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (3.12.0) -Requirement already satisfied: packaging>=23 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (23.1) -Requirement already satisfied: platformdirs>=3.2 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (3.2.0) -Requirement already satisfied: pluggy>=1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (1.0.0) -Requirement already satisfied: pyproject-api>=1.5.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (1.5.1) -Requirement already satisfied: tomli>=2.0.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (2.0.1) -Requirement already satisfied: virtualenv>=20.21 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (20.22.0) -Requirement already satisfied: mccabe<0.8.0,>=0.7.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (0.7.0) -Requirement already satisfied: pycodestyle<2.11.0,>=2.10.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (2.10.0) -Requirement already satisfied: pyflakes<3.1.0,>=3.0.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (3.0.1) -Requirement already satisfied: distlib<1,>=0.3.6 in ./venv/lib/python3.10/site-packages (from virtualenv>=20.21->tox->-r dev-requirements.txt (line 1)) (0.3.6) -Requirement already satisfied: tox in ./venv/lib/python3.10/site-packages (from -r dev-requirements.txt (line 1)) (4.4.12) -Requirement already satisfied: flake8 in ./venv/lib/python3.10/site-packages (from -r dev-requirements.txt (line 2)) (6.0.0) -Requirement already satisfied: cachetools>=5.3 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (5.3.0) -Requirement already satisfied: chardet>=5.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (5.1.0) -Requirement already satisfied: colorama>=0.4.6 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (0.4.6) -Requirement already satisfied: filelock>=3.11 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (3.12.0) -Requirement already satisfied: packaging>=23 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (23.1) -Requirement already satisfied: platformdirs>=3.2 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (3.2.0) -Requirement already satisfied: pluggy>=1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (1.0.0) -Requirement already satisfied: pyproject-api>=1.5.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (1.5.1) -Requirement already satisfied: tomli>=2.0.1 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (2.0.1) -Requirement already satisfied: virtualenv>=20.21 in ./venv/lib/python3.10/site-packages (from tox->-r dev-requirements.txt (line 1)) (20.22.0) -Requirement already satisfied: mccabe<0.8.0,>=0.7.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (0.7.0) -Requirement already satisfied: pycodestyle<2.11.0,>=2.10.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (2.10.0) -Requirement already satisfied: pyflakes<3.1.0,>=3.0.0 in ./venv/lib/python3.10/site-packages (from flake8->-r dev-requirements.txt (line 2)) (3.0.1) -Requirement already satisfied: distlib<1,>=0.3.6 in ./venv/lib/python3.10/site-packages (from virtualenv>=20.21->tox->-r dev-requirements.txt (line 1)) (0.3.6) diff --git a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/PKG-INFO b/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/PKG-INFO deleted file mode 100644 index e196af9440dc..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/PKG-INFO +++ /dev/null @@ -1,13 +0,0 @@ -Metadata-Version: 2.1 -Name: petstore-api -Version: 1.0.0 -Summary: OpenAPI Petstore -Home-page: -Author: OpenAPI Generator community -Author-email: team@openapitools.org -License: Apache-2.0 -Keywords: OpenAPI,OpenAPI-Generator,OpenAPI Petstore -Description-Content-Type: text/markdown - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \ # noqa: E501 - diff --git a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/SOURCES.txt b/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/SOURCES.txt deleted file mode 100644 index 9a144d3d954f..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/SOURCES.txt +++ /dev/null @@ -1,176 +0,0 @@ -README.md -pyproject.toml -setup.cfg -setup.py -petstore_api/__init__.py -petstore_api/api_client.py -petstore_api/configuration.py -petstore_api/exceptions.py -petstore_api/rest.py -petstore_api/signing.py -petstore_api.egg-info/PKG-INFO -petstore_api.egg-info/SOURCES.txt -petstore_api.egg-info/dependency_links.txt -petstore_api.egg-info/requires.txt -petstore_api.egg-info/top_level.txt -petstore_api/api/__init__.py -petstore_api/api/another_fake_api.py -petstore_api/api/default_api.py -petstore_api/api/fake_api.py -petstore_api/api/fake_classname_tags123_api.py -petstore_api/api/fake_classname_tags_123_api.py -petstore_api/api/pet_api.py -petstore_api/api/store_api.py -petstore_api/api/user_api.py -petstore_api/models/__init__.py -petstore_api/models/additional_properties_class.py -petstore_api/models/all_of_with_single_ref.py -petstore_api/models/animal.py -petstore_api/models/any_of_color.py -petstore_api/models/any_of_pig.py -petstore_api/models/api_response.py -petstore_api/models/array_of_array_of_number_only.py -petstore_api/models/array_of_number_only.py -petstore_api/models/array_test.py -petstore_api/models/basque_pig.py -petstore_api/models/capitalization.py -petstore_api/models/cat.py -petstore_api/models/cat_all_of.py -petstore_api/models/category.py -petstore_api/models/circular_reference_model.py -petstore_api/models/class_model.py -petstore_api/models/client.py -petstore_api/models/color.py -petstore_api/models/danish_pig.py -petstore_api/models/deprecated_object.py -petstore_api/models/dog.py -petstore_api/models/dog_all_of.py -petstore_api/models/dummy_model.py -petstore_api/models/enum_arrays.py -petstore_api/models/enum_class.py -petstore_api/models/enum_test.py -petstore_api/models/file.py -petstore_api/models/file_schema_test_class.py -petstore_api/models/first_ref.py -petstore_api/models/foo.py -petstore_api/models/foo_get_default_response.py -petstore_api/models/format_test.py -petstore_api/models/has_only_read_only.py -petstore_api/models/health_check_result.py -petstore_api/models/inner_dict_with_property.py -petstore_api/models/list.py -petstore_api/models/map_test.py -petstore_api/models/mixed_properties_and_additional_properties_class.py -petstore_api/models/model200_response.py -petstore_api/models/model_return.py -petstore_api/models/name.py -petstore_api/models/nullable_class.py -petstore_api/models/number_only.py -petstore_api/models/object_with_deprecated_fields.py -petstore_api/models/order.py -petstore_api/models/outer_composite.py -petstore_api/models/outer_enum.py -petstore_api/models/outer_enum_default_value.py -petstore_api/models/outer_enum_integer.py -petstore_api/models/outer_enum_integer_default_value.py -petstore_api/models/outer_object_with_enum_property.py -petstore_api/models/parent.py -petstore_api/models/parent_with_optional_dict.py -petstore_api/models/pet.py -petstore_api/models/pig.py -petstore_api/models/read_only_first.py -petstore_api/models/second_ref.py -petstore_api/models/self_reference_model.py -petstore_api/models/single_ref_type.py -petstore_api/models/special_character_enum.py -petstore_api/models/special_model_name.py -petstore_api/models/special_name.py -petstore_api/models/tag.py -petstore_api/models/user.py -petstore_api/models/with_nested_one_of.py -test/test_additional_properties_class.py -test/test_all_of_with_single_ref.py -test/test_animal.py -test/test_another_fake_api.py -test/test_any_of_color.py -test/test_any_of_pig.py -test/test_api_response.py -test/test_array_of_array_of_number_only.py -test/test_array_of_number_only.py -test/test_array_test.py -test/test_basque_pig.py -test/test_capitalization.py -test/test_cat.py -test/test_cat_all_of.py -test/test_category.py -test/test_circular_reference_model.py -test/test_class_model.py -test/test_client.py -test/test_color.py -test/test_configuration.py -test/test_danish_pig.py -test/test_default_api.py -test/test_deprecated_object.py -test/test_dog.py -test/test_dog_all_of.py -test/test_dummy_model.py -test/test_enum_arrays.py -test/test_enum_class.py -test/test_enum_test.py -test/test_fake_api.py -test/test_fake_classname_tags123_api.py -test/test_fake_classname_tags_123_api.py -test/test_file.py -test/test_file_schema_test_class.py -test/test_first_ref.py -test/test_foo.py -test/test_foo_get_default_response.py -test/test_format_test.py -test/test_has_only_read_only.py -test/test_health_check_result.py -test/test_inner_dict_with_property.py -test/test_list.py -test/test_map_test.py -test/test_mixed_properties_and_additional_properties_class.py -test/test_model200_response.py -test/test_model_return.py -test/test_name.py -test/test_nullable_class.py -test/test_number_only.py -test/test_object_with_deprecated_fields.py -test/test_order.py -test/test_outer_composite.py -test/test_outer_enum.py -test/test_outer_enum_default_value.py -test/test_outer_enum_integer.py -test/test_outer_enum_integer_default_value.py -test/test_outer_object_with_enum_property.py -test/test_parent.py -test/test_parent_with_optional_dict.py -test/test_pet.py -test/test_pet_api.py -test/test_pig.py -test/test_read_only_first.py -test/test_second_ref.py -test/test_self_reference_model.py -test/test_single_ref_type.py -test/test_special_character_enum.py -test/test_special_model_name.py -test/test_special_name.py -test/test_store_api.py -test/test_tag.py -test/test_user.py -test/test_user_api.py -test/test_with_nested_one_of.py -tests/test_api_client.py -tests/test_api_exception.py -tests/test_api_validation.py -tests/test_configuration.py -tests/test_deserialization.py -tests/test_http_signature.py -tests/test_map_test.py -tests/test_model.py -tests/test_order_model.py -tests/test_pet_api.py -tests/test_pet_model.py -tests/test_store_api.py \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/dependency_links.txt b/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/dependency_links.txt deleted file mode 100644 index 8b137891791f..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/dependency_links.txt +++ /dev/null @@ -1 +0,0 @@ - diff --git a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/requires.txt b/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/requires.txt deleted file mode 100644 index 89b3b11d6a4d..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/requires.txt +++ /dev/null @@ -1,6 +0,0 @@ -urllib3>=1.25.3 -python-dateutil -pem>=19.3.0 -pycryptodome>=3.9.0 -pydantic<2,>=1.10.5 -aenum diff --git a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/top_level.txt b/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/top_level.txt deleted file mode 100644 index 81e243dca697..000000000000 --- a/samples/openapi3/client/petstore/python-nextgen/petstore_api.egg-info/top_level.txt +++ /dev/null @@ -1 +0,0 @@ -petstore_api diff --git a/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py b/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py deleted file mode 100644 index c5c62b7b8310..000000000000 --- a/samples/openapi3/client/petstore/python-prior/petstore_api/model/mammal.py +++ /dev/null @@ -1,349 +0,0 @@ -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -import re # noqa: F401 -import sys # noqa: F401 - -from petstore_api.model_utils import ( # noqa: F401 - ApiTypeError, - ModelComposed, - ModelNormal, - ModelSimple, - cached_property, - change_keys_js_to_python, - convert_js_args_to_python_args, - date, - datetime, - file_type, - none_type, - validate_get_composed_info, - OpenApiModel -) -from petstore_api.exceptions import ApiAttributeError - - -def lazy_import(): - from petstore_api.model.pig import Pig - from petstore_api.model.whale import Whale - from petstore_api.model.zebra import Zebra - globals()['Pig'] = Pig - globals()['Whale'] = Whale - globals()['Zebra'] = Zebra - - -class Mammal(ModelComposed): - """NOTE: This class is auto generated by OpenAPI Generator. - Ref: https://openapi-generator.tech - - Do not edit the class manually. - - Attributes: - allowed_values (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - with a capitalized key describing the allowed value and an allowed - value. These dicts store the allowed enum values. - attribute_map (dict): The key is attribute name - and the value is json key in definition. - discriminator_value_class_map (dict): A dict to go from the discriminator - variable value to the discriminator class name. - validations (dict): The key is the tuple path to the attribute - and the for var_name this is (var_name,). The value is a dict - that stores validations for max_length, min_length, max_items, - min_items, exclusive_maximum, inclusive_maximum, exclusive_minimum, - inclusive_minimum, and regex. - additional_properties_type (tuple): A tuple of classes accepted - as additional properties values. - """ - - allowed_values = { - ('type',): { - 'PLAINS': "plains", - 'MOUNTAIN': "mountain", - 'GREVYS': "grevys", - }, - } - - validations = { - } - - @cached_property - def additional_properties_type(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - """ - lazy_import() - return (bool, date, datetime, dict, float, int, list, str, none_type,) # noqa: E501 - - _nullable = False - - @cached_property - def openapi_types(): - """ - This must be a method because a model may have properties that are - of type self, this must run after the class is loaded - - Returns - openapi_types (dict): The key is attribute name - and the value is attribute type. - """ - lazy_import() - return { - 'class_name': (str,), # noqa: E501 - 'has_baleen': (bool,), # noqa: E501 - 'has_teeth': (bool,), # noqa: E501 - 'type': (str,), # noqa: E501 - } - - @cached_property - def discriminator(): - lazy_import() - val = { - 'whale': Whale, - 'zebra': Zebra, - 'Pig': Pig, - } - if not val: - return None - return {'class_name': val} - - attribute_map = { - 'class_name': 'className', # noqa: E501 - 'has_baleen': 'hasBaleen', # noqa: E501 - 'has_teeth': 'hasTeeth', # noqa: E501 - 'type': 'type', # noqa: E501 - } - - read_only_vars = { - } - - @classmethod - @convert_js_args_to_python_args - def _from_openapi_data(cls, *args, **kwargs): # noqa: E501 - """Mammal - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - self = super(OpenApiModel, cls).__new__(cls) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - - return self - - required_properties = set([ - '_data_store', - '_check_type', - '_spec_property_naming', - '_path_to_item', - '_configuration', - '_visited_composed_classes', - '_composed_instances', - '_var_name_to_model_instances', - '_additional_properties_model_instances', - ]) - - @convert_js_args_to_python_args - def __init__(self, *args, **kwargs): # noqa: E501 - """Mammal - a model defined in OpenAPI - - Keyword Args: - class_name (str): - _check_type (bool): if True, values for parameters in openapi_types - will be type checked and a TypeError will be - raised if the wrong type is input. - Defaults to True - _path_to_item (tuple/list): This is a list of keys or values to - drill down to the model in received_data - when deserializing a response - _spec_property_naming (bool): True if the variable names in the input data - are serialized names, as specified in the OpenAPI document. - False if the variable names in the input data - are pythonic names, e.g. snake case (default) - _configuration (Configuration): the instance to use when - deserializing a file_type parameter. - If passed, type conversion is attempted - If omitted no type conversion is done. - _visited_composed_classes (tuple): This stores a tuple of - classes that we have traveled through so that - if we see that class again we will not use its - discriminator again. - When traveling through a discriminator, the - composed schema that is - is traveled through is added to this set. - For example if Animal has a discriminator - petType and we pass in "Dog", and the class Dog - allOf includes Animal, we move through Animal - once using the discriminator, and pick Dog. - Then in Dog, we will make an instance of the - Animal class but this time we won't travel - through its discriminator because we passed in - _visited_composed_classes = (Animal,) - has_baleen (bool): [optional] # noqa: E501 - has_teeth (bool): [optional] # noqa: E501 - type (str): [optional] # noqa: E501 - """ - - _check_type = kwargs.pop('_check_type', True) - _spec_property_naming = kwargs.pop('_spec_property_naming', False) - _path_to_item = kwargs.pop('_path_to_item', ()) - _configuration = kwargs.pop('_configuration', None) - _visited_composed_classes = kwargs.pop('_visited_composed_classes', ()) - - if args: - for arg in args: - if isinstance(arg, dict): - kwargs.update(arg) - else: - raise ApiTypeError( - "Invalid positional arguments=%s passed to %s. Remove those invalid positional arguments." % ( - args, - self.__class__.__name__, - ), - path_to_item=_path_to_item, - valid_classes=(self.__class__,), - ) - - self._data_store = {} - self._check_type = _check_type - self._spec_property_naming = _spec_property_naming - self._path_to_item = _path_to_item - self._configuration = _configuration - self._visited_composed_classes = _visited_composed_classes + (self.__class__,) - - constant_args = { - '_check_type': _check_type, - '_path_to_item': _path_to_item, - '_spec_property_naming': _spec_property_naming, - '_configuration': _configuration, - '_visited_composed_classes': self._visited_composed_classes, - } - composed_info = validate_get_composed_info( - constant_args, kwargs, self) - self._composed_instances = composed_info[0] - self._var_name_to_model_instances = composed_info[1] - self._additional_properties_model_instances = composed_info[2] - discarded_args = composed_info[3] - - for var_name, var_value in kwargs.items(): - if var_name in discarded_args and \ - self._configuration is not None and \ - self._configuration.discard_unknown_keys and \ - self._additional_properties_model_instances: - # discard variable. - continue - setattr(self, var_name, var_value) - if var_name in self.read_only_vars: - raise ApiAttributeError(f"`{var_name}` is a read-only attribute. Use `from_openapi_data` to instantiate " - f"class with read only attributes.") - - @cached_property - def _composed_schemas(): - # we need this here to make our import statements work - # we must store _composed_schemas in here so the code is only run - # when we invoke this method. If we kept this at the class - # level we would get an error because the class level - # code would be run when this module is imported, and these composed - # classes don't exist yet because their module has not finished - # loading - lazy_import() - return { - 'anyOf': [ - ], - 'allOf': [ - ], - 'oneOf': [ - Pig, - Whale, - Zebra, - ], - } diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES index 00dc818606f1..1ef5f596fa14 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/FILES @@ -84,6 +84,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TestErrorResponsesWithModel400Response.md +docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md @@ -181,6 +183,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/test_error_responses_with_model400_response.py +petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md index 9aa800b4f2bf..1fce8fd01d1c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/README.md @@ -96,14 +96,18 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**fake_ref_enum_string**](docs/FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string *FakeApi* | [**fake_return_list_of_objects**](docs/FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects *FakeApi* | [**fake_uuid_example**](docs/FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +*FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_date_time_query_parameter**](docs/FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +*FakeApi* | [**test_empty_and_non_empty_responses**](docs/FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_error_responses_with_model**](docs/FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model *FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_inline_freeform_additional_properties**](docs/FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -210,6 +214,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) + - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md index be5d5e850c79..7f9563a2ec49 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/FakeApi.md @@ -13,14 +13,18 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**fake_ref_enum_string**](FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string [**fake_return_list_of_objects**](FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects [**fake_uuid_example**](FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +[**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_date_time_query_parameter**](FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +[**test_empty_and_non_empty_responses**](FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_error_responses_with_model**](FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model [**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_inline_freeform_additional_properties**](FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -675,6 +679,67 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **fake_ref_enum_string** +> EnumClass fake_ref_enum_string() + +test ref to enum string + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.enum_class import EnumClass +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test ref to enum string + api_response = await api_instance.fake_ref_enum_string() + print("The response of FakeApi->fake_ref_enum_string:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->fake_ref_enum_string: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**EnumClass**](EnumClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: plain/text + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fake_return_list_of_objects** > List[List[Tag]] fake_return_list_of_objects() @@ -798,6 +863,70 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_additional_properties_reference** +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + request_body = None # Dict[str, object] | request body + + try: + # test referenced additionalProperties + await api_instance.test_additional_properties_reference(request_body) + except Exception as e: + print("Exception when calling FakeApi->test_additional_properties_reference: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**Dict[str, object]**](object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_binary** > test_body_with_binary(body) @@ -1119,6 +1248,67 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_empty_and_non_empty_responses** +> test_empty_and_non_empty_responses() + +test empty and non-empty responses + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test empty and non-empty responses + await api_instance.test_empty_and_non_empty_responses() + except Exception as e: + print("Exception when calling FakeApi->test_empty_and_non_empty_responses: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**206** | Partial response content | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_endpoint_parameters** > test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, byte_with_max_length=byte_with_max_length, var_date=var_date, date_time=date_time, password=password, param_callback=param_callback) @@ -1223,6 +1413,66 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_error_responses_with_model** +> test_error_responses_with_model() + +test error responses with model + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +async with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test error responses with model + await api_instance.test_error_responses_with_model() + except Exception as e: + print("Exception when calling FakeApi->test_error_responses_with_model: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**400** | | - | +**404** | | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_group_parameters** > test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/List.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/List.md deleted file mode 100644 index 7643e4ea92dd..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/List.md +++ /dev/null @@ -1,28 +0,0 @@ -# List - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**var_123_list** | **str** | | [optional] - -## Example - -```python -from petstore_api.models.list import List - -# TODO update the JSON string below -json = "{}" -# create an instance of List from a JSON string -list_instance = List.from_json(json) -# print the JSON string representation of the object -print List.to_json() - -# convert the object into a dict -list_dict = list_instance.to_dict() -# create an instance of List from a dict -list_form_dict = list.from_dict(list_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel400Response.md new file mode 100644 index 000000000000..1ef43ce4cadc --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel400Response.md @@ -0,0 +1,28 @@ +# TestErrorResponsesWithModel400Response + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason400** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel400Response from a JSON string +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel400Response.to_json() + +# convert the object into a dict +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel400Response from a dict +test_error_responses_with_model400_response_form_dict = test_error_responses_with_model400_response.from_dict(test_error_responses_with_model400_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel404Response.md new file mode 100644 index 000000000000..9fda95537846 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/docs/TestErrorResponsesWithModel404Response.md @@ -0,0 +1,28 @@ +# TestErrorResponsesWithModel404Response + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason404** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel404Response from a JSON string +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel404Response.to_json() + +# convert the object into a dict +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel404Response from a dict +test_error_responses_with_model404_response_form_dict = test_error_responses_with_model404_response.from_dict(test_error_responses_with_model404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py index c1c56eb81159..72d39b9c55e6 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/__init__.py @@ -113,6 +113,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py index 975e70cad808..39615b9e8074 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api/fake_api.py @@ -1204,6 +1204,120 @@ async def fake_property_enum_integer_serialize_with_http_info(self, outer_object collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + async def fake_ref_enum_string(self, **kwargs) -> EnumClass: # noqa: E501 + """test ref to enum string # noqa: E501 + + + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: EnumClass + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the fake_ref_enum_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.fake_ref_enum_string_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + async def fake_ref_enum_string_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test ref to enum string # noqa: E501 + + + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(EnumClass, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method fake_ref_enum_string" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['plain/text']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "EnumClass", + } + + return await self.api_client.call_api( + '/fake/ref_enum_string', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments async def fake_return_list_of_objects(self, **kwargs) -> List[List[Tag]]: # noqa: E501 """test returning list of objects # noqa: E501 @@ -1434,6 +1548,131 @@ async def fake_uuid_example_with_http_info(self, uuid_example : Annotated[Strict collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + async def test_additional_properties_reference(self, request_body : Annotated[Dict[str, Any], Field(..., description="request body")], **kwargs) -> None: # noqa: E501 + """test referenced additionalProperties # noqa: E501 + + # noqa: E501 + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_additional_properties_reference_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.test_additional_properties_reference_with_http_info(request_body, **kwargs) # noqa: E501 + + @validate_arguments + async def test_additional_properties_reference_with_http_info(self, request_body : Annotated[Dict[str, Any], Field(..., description="request body")], **kwargs) -> ApiResponse: # noqa: E501 + """test referenced additionalProperties # noqa: E501 + + # noqa: E501 + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + 'request_body' + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_additional_properties_reference" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['request_body'] is not None: + _body_params = _params['request_body'] + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return await self.api_client.call_api( + '/fake/additionalProperties-reference', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments async def test_body_with_binary(self, body : Annotated[Optional[Union[StrictBytes, StrictStr]], Field(..., description="image to upload")], **kwargs) -> None: # noqa: E501 """test_body_with_binary # noqa: E501 @@ -2078,6 +2317,120 @@ async def test_date_time_query_parameter_with_http_info(self, date_time_query : collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + async def test_empty_and_non_empty_responses(self, **kwargs) -> None: # noqa: E501 + """test empty and non-empty responses # noqa: E501 + + # noqa: E501 + + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_empty_and_non_empty_responses_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.test_empty_and_non_empty_responses_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + async def test_empty_and_non_empty_responses_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test empty and non-empty responses # noqa: E501 + + # noqa: E501 + + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_empty_and_non_empty_responses" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['text/plain']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return await self.api_client.call_api( + '/fake/empty_and_non_empty_responses', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments async def test_endpoint_parameters(self, number : Annotated[confloat(le=543.2, ge=32.1), Field(..., description="None")], double : Annotated[confloat(le=123.4, ge=67.8), Field(..., description="None")], pattern_without_delimiter : Annotated[constr(strict=True), Field(..., description="None")], byte : Annotated[Union[StrictBytes, StrictStr], Field(..., description="None")], integer : Annotated[Optional[conint(strict=True, le=100, ge=10)], Field(description="None")] = None, int32 : Annotated[Optional[conint(strict=True, le=200, ge=20)], Field(description="None")] = None, int64 : Annotated[Optional[StrictInt], Field(description="None")] = None, float : Annotated[Optional[confloat(le=987.6)], Field(description="None")] = None, string : Annotated[Optional[constr(strict=True)], Field(description="None")] = None, binary : Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="None")] = None, byte_with_max_length : Annotated[Optional[Union[conbytes(strict=True, max_length=64), constr(strict=True, max_length=64)]], Field(description="None")] = None, var_date : Annotated[Optional[date], Field(description="None")] = None, date_time : Annotated[Optional[datetime], Field(description="None")] = None, password : Annotated[Optional[constr(strict=True, max_length=64, min_length=10)], Field(description="None")] = None, param_callback : Annotated[Optional[StrictStr], Field(description="None")] = None, **kwargs) -> None: # noqa: E501 """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 @@ -2315,6 +2668,118 @@ async def test_endpoint_parameters_with_http_info(self, number : Annotated[confl collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + async def test_error_responses_with_model(self, **kwargs) -> None: # noqa: E501 + """test error responses with model # noqa: E501 + + + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_error_responses_with_model_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return await self.test_error_responses_with_model_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + async def test_error_responses_with_model_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test error responses with model # noqa: E501 + + + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_error_responses_with_model" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return await self.api_client.call_api( + '/fake/error_responses_with_model', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments async def test_group_parameters(self, required_string_group : Annotated[StrictInt, Field(..., description="Required String in group parameters")], required_boolean_group : Annotated[StrictBool, Field(..., description="Required Boolean in group parameters")], required_int64_group : Annotated[StrictInt, Field(..., description="Required Integer in group parameters")], string_group : Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group : Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group : Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, **kwargs) -> None: # noqa: E501 """Fake endpoint to test group parameters (optional) # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api_client.py index 733ddaed7c3e..dbef903bdd62 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/api_client.py @@ -499,10 +499,10 @@ def parameters_to_url_query(self, params, collection_formats): if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py index dd9388d355da..c106409daa97 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/__init__.py @@ -89,6 +89,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py similarity index 65% rename from samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/list.py rename to samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py index 4c6868146ad0..c4904af2905c 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model400_response.py @@ -19,14 +19,14 @@ from typing import Optional -from pydantic import BaseModel, Field, StrictStr +from pydantic import BaseModel, StrictStr -class List(BaseModel): +class TestErrorResponsesWithModel400Response(BaseModel): """ - List + TestErrorResponsesWithModel400Response """ - var_123_list: Optional[StrictStr] = Field(None, alias="123-list") - __properties = ["123-list"] + reason400: Optional[StrictStr] = None + __properties = ["reason400"] class Config: """Pydantic configuration""" @@ -42,8 +42,8 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> List: - """Create an instance of List from a JSON string""" + def from_json(cls, json_str: str) -> TestErrorResponsesWithModel400Response: + """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): @@ -55,16 +55,16 @@ def to_dict(self): return _dict @classmethod - def from_dict(cls, obj: dict) -> List: - """Create an instance of List from a dict""" + def from_dict(cls, obj: dict) -> TestErrorResponsesWithModel400Response: + """Create an instance of TestErrorResponsesWithModel400Response from a dict""" if obj is None: return None if not isinstance(obj, dict): - return List.parse_obj(obj) + return TestErrorResponsesWithModel400Response.parse_obj(obj) - _obj = List.parse_obj({ - "var_123_list": obj.get("123-list") + _obj = TestErrorResponsesWithModel400Response.parse_obj({ + "reason400": obj.get("reason400") }) return _obj diff --git a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py similarity index 57% rename from samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list.py rename to samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py index e1a3d53f6d5d..96b5f6c58715 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,59 +20,51 @@ from typing import Optional from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self - -class List(BaseModel): + +class TestErrorResponsesWithModel404Response(BaseModel): """ - List + TestErrorResponsesWithModel404Response """ - var_123_list: Optional[StrictStr] = Field(default=None, alias="123-list") - __properties = ["123-list"] - - model_config = { - "populate_by_name": True, - "validate_assignment": True - } + reason404: Optional[StrictStr] = None + __properties = ["reason404"] + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) + return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of List from a JSON string""" + def from_json(cls, json_str: str) -> TestErrorResponsesWithModel404Response: + """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.model_dump(by_alias=True, + _dict = self.dict(by_alias=True, exclude={ }, exclude_none=True) return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: - """Create an instance of List from a dict""" + def from_dict(cls, obj: dict) -> TestErrorResponsesWithModel404Response: + """Create an instance of TestErrorResponsesWithModel404Response from a dict""" if obj is None: return None if not isinstance(obj, dict): - return cls.model_validate(obj) + return TestErrorResponsesWithModel404Response.parse_obj(obj) - _obj = cls.model_validate({ - "123-list": obj.get("123-list") + _obj = TestErrorResponsesWithModel404Response.parse_obj({ + "reason404": obj.get("reason404") }) return _obj diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_list.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_list.py deleted file mode 100644 index 7b001d818e89..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_list.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.list import List # noqa: E501 -from petstore_api.rest import ApiException - -class TestList(unittest.TestCase): - """List unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test List - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.list.List() # noqa: E501 - if include_optional : - return List( - _123_list = '' - ) - else : - return List( - ) - - def testList(self): - """Test List""" - # inst_req_only = self.make_instance(include_optional=False) - # inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..b4e2d50dc6fe --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model400_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response # noqa: E501 + +class TestTestErrorResponsesWithModel400Response(unittest.TestCase): + """TestErrorResponsesWithModel400Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel400Response: + """Test TestErrorResponsesWithModel400Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel400Response` + """ + model = TestErrorResponsesWithModel400Response() # noqa: E501 + if include_optional: + return TestErrorResponsesWithModel400Response( + reason400 = '' + ) + else: + return TestErrorResponsesWithModel400Response( + ) + """ + + def testTestErrorResponsesWithModel400Response(self): + """Test TestErrorResponsesWithModel400Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..caf587ddb033 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1-aiohttp/test/test_test_error_responses_with_model404_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response # noqa: E501 + +class TestTestErrorResponsesWithModel404Response(unittest.TestCase): + """TestErrorResponsesWithModel404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel404Response: + """Test TestErrorResponsesWithModel404Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel404Response` + """ + model = TestErrorResponsesWithModel404Response() # noqa: E501 + if include_optional: + return TestErrorResponsesWithModel404Response( + reason404 = '' + ) + else: + return TestErrorResponsesWithModel404Response( + ) + """ + + def testTestErrorResponsesWithModel404Response(self): + """Test TestErrorResponsesWithModel404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES index 00dc818606f1..1ef5f596fa14 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/FILES @@ -84,6 +84,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TestErrorResponsesWithModel400Response.md +docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md @@ -181,6 +183,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/test_error_responses_with_model400_response.py +petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python-pydantic-v1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/README.md b/samples/openapi3/client/petstore/python-pydantic-v1/README.md index 3628ec73d276..be2a4c20fcfa 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/README.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/README.md @@ -96,14 +96,18 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**fake_ref_enum_string**](docs/FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string *FakeApi* | [**fake_return_list_of_objects**](docs/FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects *FakeApi* | [**fake_uuid_example**](docs/FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +*FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_date_time_query_parameter**](docs/FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +*FakeApi* | [**test_empty_and_non_empty_responses**](docs/FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_error_responses_with_model**](docs/FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model *FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_inline_freeform_additional_properties**](docs/FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -210,6 +214,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) + - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md index 5bd0489ae550..1612ebbd0724 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/FakeApi.md @@ -13,14 +13,18 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**fake_ref_enum_string**](FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string [**fake_return_list_of_objects**](FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects [**fake_uuid_example**](FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +[**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_date_time_query_parameter**](FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +[**test_empty_and_non_empty_responses**](FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_error_responses_with_model**](FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model [**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_inline_freeform_additional_properties**](FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -675,6 +679,67 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **fake_ref_enum_string** +> EnumClass fake_ref_enum_string() + +test ref to enum string + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.models.enum_class import EnumClass +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test ref to enum string + api_response = api_instance.fake_ref_enum_string() + print("The response of FakeApi->fake_ref_enum_string:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->fake_ref_enum_string: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +[**EnumClass**](EnumClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: plain/text + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fake_return_list_of_objects** > List[List[Tag]] fake_return_list_of_objects() @@ -798,6 +863,70 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_additional_properties_reference** +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + request_body = None # Dict[str, object] | request body + + try: + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) + except Exception as e: + print("Exception when calling FakeApi->test_additional_properties_reference: %s\n" % e) +``` + + + +### Parameters + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**Dict[str, object]**](object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_binary** > test_body_with_binary(body) @@ -1119,6 +1248,67 @@ No authorization required [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_empty_and_non_empty_responses** +> test_empty_and_non_empty_responses() + +test empty and non-empty responses + + + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test empty and non-empty responses + api_instance.test_empty_and_non_empty_responses() + except Exception as e: + print("Exception when calling FakeApi->test_empty_and_non_empty_responses: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**206** | Partial response content | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_endpoint_parameters** > test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, float=float, string=string, binary=binary, byte_with_max_length=byte_with_max_length, var_date=var_date, date_time=date_time, password=password, param_callback=param_callback) @@ -1223,6 +1413,66 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_error_responses_with_model** +> test_error_responses_with_model() + +test error responses with model + +### Example + +```python +import time +import os +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test error responses with model + api_instance.test_error_responses_with_model() + except Exception as e: + print("Exception when calling FakeApi->test_error_responses_with_model: %s\n" % e) +``` + + + +### Parameters +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**400** | | - | +**404** | | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_group_parameters** > test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/List.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/List.md deleted file mode 100644 index 7643e4ea92dd..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1/docs/List.md +++ /dev/null @@ -1,28 +0,0 @@ -# List - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**var_123_list** | **str** | | [optional] - -## Example - -```python -from petstore_api.models.list import List - -# TODO update the JSON string below -json = "{}" -# create an instance of List from a JSON string -list_instance = List.from_json(json) -# print the JSON string representation of the object -print List.to_json() - -# convert the object into a dict -list_dict = list_instance.to_dict() -# create an instance of List from a dict -list_form_dict = list.from_dict(list_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel400Response.md new file mode 100644 index 000000000000..1ef43ce4cadc --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel400Response.md @@ -0,0 +1,28 @@ +# TestErrorResponsesWithModel400Response + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason400** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel400Response from a JSON string +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel400Response.to_json() + +# convert the object into a dict +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel400Response from a dict +test_error_responses_with_model400_response_form_dict = test_error_responses_with_model400_response.from_dict(test_error_responses_with_model400_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel404Response.md new file mode 100644 index 000000000000..9fda95537846 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/docs/TestErrorResponsesWithModel404Response.md @@ -0,0 +1,28 @@ +# TestErrorResponsesWithModel404Response + + +## Properties +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason404** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel404Response from a JSON string +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel404Response.to_json() + +# convert the object into a dict +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel404Response from a dict +test_error_responses_with_model404_response_form_dict = test_error_responses_with_model404_response.from_dict(test_error_responses_with_model404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py index c1c56eb81159..72d39b9c55e6 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/__init__.py @@ -113,6 +113,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py index a5c02f94ab71..debba27e4f77 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_api.py @@ -1347,6 +1347,136 @@ def fake_property_enum_integer_serialize_with_http_info(self, outer_object_with_ collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def fake_ref_enum_string(self, **kwargs) -> EnumClass: # noqa: E501 + """test ref to enum string # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.fake_ref_enum_string(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: EnumClass + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the fake_ref_enum_string_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.fake_ref_enum_string_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def fake_ref_enum_string_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test ref to enum string # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.fake_ref_enum_string_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: tuple(EnumClass, status_code(int), headers(HTTPHeaderDict)) + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method fake_ref_enum_string" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['plain/text']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = { + '200': "EnumClass", + } + + return self.api_client.call_api( + '/fake/ref_enum_string', 'GET', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def fake_return_list_of_objects(self, **kwargs) -> List[List[Tag]]: # noqa: E501 """test returning list of objects # noqa: E501 @@ -1609,6 +1739,147 @@ def fake_uuid_example_with_http_info(self, uuid_example : Annotated[StrictStr, F collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def test_additional_properties_reference(self, request_body : Annotated[Dict[str, Any], Field(..., description="request body")], **kwargs) -> None: # noqa: E501 + """test referenced additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_additional_properties_reference(request_body, async_req=True) + >>> result = thread.get() + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_additional_properties_reference_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_additional_properties_reference_with_http_info(request_body, **kwargs) # noqa: E501 + + @validate_arguments + def test_additional_properties_reference_with_http_info(self, request_body : Annotated[Dict[str, Any], Field(..., description="request body")], **kwargs) -> ApiResponse: # noqa: E501 + """test referenced additionalProperties # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_additional_properties_reference_with_http_info(request_body, async_req=True) + >>> result = thread.get() + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + 'request_body' + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_additional_properties_reference" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + if _params['request_body'] is not None: + _body_params = _params['request_body'] + + # set the HTTP header `Content-Type` + _content_types_list = _params.get('_content_type', + self.api_client.select_header_content_type( + ['application/json'])) + if _content_types_list: + _header_params['Content-Type'] = _content_types_list + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/fake/additionalProperties-reference', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def test_body_with_binary(self, body : Annotated[Optional[Union[StrictBytes, StrictStr]], Field(..., description="image to upload")], **kwargs) -> None: # noqa: E501 """test_body_with_binary # noqa: E501 @@ -2333,6 +2604,136 @@ def test_date_time_query_parameter_with_http_info(self, date_time_query : dateti collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def test_empty_and_non_empty_responses(self, **kwargs) -> None: # noqa: E501 + """test empty and non-empty responses # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_empty_and_non_empty_responses(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_empty_and_non_empty_responses_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_empty_and_non_empty_responses_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def test_empty_and_non_empty_responses_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test empty and non-empty responses # noqa: E501 + + # noqa: E501 + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_empty_and_non_empty_responses_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_empty_and_non_empty_responses" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['text/plain']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/fake/empty_and_non_empty_responses', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def test_endpoint_parameters(self, number : Annotated[confloat(le=543.2, ge=32.1, strict=True), Field(..., description="None")], double : Annotated[confloat(le=123.4, ge=67.8, strict=True), Field(..., description="None")], pattern_without_delimiter : Annotated[constr(strict=True), Field(..., description="None")], byte : Annotated[Union[StrictBytes, StrictStr], Field(..., description="None")], integer : Annotated[Optional[conint(strict=True, le=100, ge=10)], Field(description="None")] = None, int32 : Annotated[Optional[conint(strict=True, le=200, ge=20)], Field(description="None")] = None, int64 : Annotated[Optional[StrictInt], Field(description="None")] = None, float : Annotated[Optional[confloat(le=987.6, strict=True)], Field(description="None")] = None, string : Annotated[Optional[constr(strict=True)], Field(description="None")] = None, binary : Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="None")] = None, byte_with_max_length : Annotated[Optional[Union[conbytes(strict=True, max_length=64), constr(strict=True, max_length=64)]], Field(description="None")] = None, var_date : Annotated[Optional[date], Field(description="None")] = None, date_time : Annotated[Optional[datetime], Field(description="None")] = None, password : Annotated[Optional[constr(strict=True, max_length=64, min_length=10)], Field(description="None")] = None, param_callback : Annotated[Optional[StrictStr], Field(description="None")] = None, **kwargs) -> None: # noqa: E501 """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 @@ -2586,6 +2987,134 @@ def test_endpoint_parameters_with_http_info(self, number : Annotated[confloat(le collection_formats=_collection_formats, _request_auth=_params.get('_request_auth')) + @validate_arguments + def test_error_responses_with_model(self, **kwargs) -> None: # noqa: E501 + """test error responses with model # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_error_responses_with_model(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _request_timeout: timeout setting for this request. + If one number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + kwargs['_return_http_data_only'] = True + if '_preload_content' in kwargs: + message = "Error! Please call the test_error_responses_with_model_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 + raise ValueError(message) + return self.test_error_responses_with_model_with_http_info(**kwargs) # noqa: E501 + + @validate_arguments + def test_error_responses_with_model_with_http_info(self, **kwargs) -> ApiResponse: # noqa: E501 + """test error responses with model # noqa: E501 + + This method makes a synchronous HTTP request by default. To make an + asynchronous HTTP request, please pass async_req=True + + >>> thread = api.test_error_responses_with_model_with_http_info(async_req=True) + >>> result = thread.get() + + :param async_req: Whether to execute the request asynchronously. + :type async_req: bool, optional + :param _preload_content: if False, the ApiResponse.data will + be set to none and raw_data will store the + HTTP response body without reading/decoding. + Default is True. + :type _preload_content: bool, optional + :param _return_http_data_only: response data instead of ApiResponse + object with status code, headers, etc + :type _return_http_data_only: bool, optional + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :type _request_auth: dict, optional + :type _content_type: string, optional: force content-type for the request + :return: Returns the result object. + If the method is called asynchronously, + returns the request thread. + :rtype: None + """ + + _params = locals() + + _all_params = [ + ] + _all_params.extend( + [ + 'async_req', + '_return_http_data_only', + '_preload_content', + '_request_timeout', + '_request_auth', + '_content_type', + '_headers' + ] + ) + + # validate the arguments + for _key, _val in _params['kwargs'].items(): + if _key not in _all_params: + raise ApiTypeError( + "Got an unexpected keyword argument '%s'" + " to method test_error_responses_with_model" % _key + ) + _params[_key] = _val + del _params['kwargs'] + + _collection_formats = {} + + # process the path parameters + _path_params = {} + + # process the query parameters + _query_params = [] + # process the header parameters + _header_params = dict(_params.get('_headers', {})) + # process the form parameters + _form_params = [] + _files = {} + # process the body parameter + _body_params = None + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + ['application/json']) # noqa: E501 + + # authentication setting + _auth_settings = [] # noqa: E501 + + _response_types_map = {} + + return self.api_client.call_api( + '/fake/error_responses_with_model', 'POST', + _path_params, + _query_params, + _header_params, + body=_body_params, + post_params=_form_params, + files=_files, + response_types_map=_response_types_map, + auth_settings=_auth_settings, + async_req=_params.get('async_req'), + _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 + _preload_content=_params.get('_preload_content', True), + _request_timeout=_params.get('_request_timeout'), + collection_formats=_collection_formats, + _request_auth=_params.get('_request_auth')) + @validate_arguments def test_group_parameters(self, required_string_group : Annotated[StrictInt, Field(..., description="Required String in group parameters")], required_boolean_group : Annotated[StrictBool, Field(..., description="Required Boolean in group parameters")], required_int64_group : Annotated[StrictInt, Field(..., description="Required Integer in group parameters")], string_group : Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group : Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group : Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, **kwargs) -> None: # noqa: E501 """Fake endpoint to test group parameters (optional) # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_classname_tags_123_api.py deleted file mode 100755 index c4d582464d68..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api/fake_classname_tags_123_api.py +++ /dev/null @@ -1,178 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import re # noqa: F401 - -from petstore_api.api_client import ApiClient -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class FakeClassnameTags123Api(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def test_classname(self, client, **kwargs): # noqa: E501 - """To test class name in snake case # noqa: E501 - - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_classname(client, async_req=True) - >>> result = thread.get() - - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - return self.test_classname_with_http_info(client, **kwargs) # noqa: E501 - - def test_classname_with_http_info(self, client, **kwargs): # noqa: E501 - """To test class name in snake case # noqa: E501 - - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_classname_with_http_info(client, async_req=True) - >>> result = thread.get() - - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _return_http_data_only: response data without head status code - and headers - :type _return_http_data_only: bool, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ - - local_var_params = locals() - - all_params = [ - 'client' - ] - all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - for key, val in local_var_params['kwargs'].items(): - if key not in all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_classname" % key - ) - local_var_params[key] = val - del local_var_params['kwargs'] - # verify the required parameter 'client' is set - if self.api_client.client_side_validation and ('client' not in local_var_params or # noqa: E501 - local_var_params['client'] is None): # noqa: E501 - raise ApiValueError("Missing the required parameter `client` when calling `test_classname`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = dict(local_var_params.get('_headers', {})) - - form_params = [] - local_var_files = {} - - body_params = None - if 'client' in local_var_params: - body_params = local_var_params['client'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = local_var_params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'], - 'PATCH', body_params)) # noqa: E501 - - # Authentication setting - auth_settings = ['api_key_query'] # noqa: E501 - - response_types_map = { - 200: "Client", - } - - return self.api_client.call_api( - '/fake_classname_test', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_types_map=response_types_map, - auth_settings=auth_settings, - async_req=local_var_params.get('async_req'), - _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=local_var_params.get('_preload_content', True), - _request_timeout=local_var_params.get('_request_timeout'), - collection_formats=collection_formats, - _request_auth=local_var_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api_client.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api_client.py index 9579cce1349c..2a74a7d70049 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/api_client.py @@ -528,10 +528,10 @@ def parameters_to_url_query(self, params, collection_formats): if collection_formats is None: collection_formats = {} for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py index dd9388d355da..c106409daa97 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/__init__.py @@ -89,6 +89,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model400_response.py similarity index 72% rename from samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/list.py rename to samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model400_response.py index d4381879ccb3..40855d008cce 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model400_response.py @@ -19,15 +19,15 @@ from typing import Any, Dict, Optional -from pydantic import BaseModel, Field, StrictStr +from pydantic import BaseModel, StrictStr -class List(BaseModel): +class TestErrorResponsesWithModel400Response(BaseModel): """ - List + TestErrorResponsesWithModel400Response """ - var_123_list: Optional[StrictStr] = Field(None, alias="123-list") + reason400: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["123-list"] + __properties = ["reason400"] class Config: """Pydantic configuration""" @@ -43,8 +43,8 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> List: - """Create an instance of List from a JSON string""" + def from_json(cls, json_str: str) -> TestErrorResponsesWithModel400Response: + """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): @@ -62,16 +62,16 @@ def to_dict(self): return _dict @classmethod - def from_dict(cls, obj: dict) -> List: - """Create an instance of List from a dict""" + def from_dict(cls, obj: dict) -> TestErrorResponsesWithModel400Response: + """Create an instance of TestErrorResponsesWithModel400Response from a dict""" if obj is None: return None if not isinstance(obj, dict): - return List.parse_obj(obj) + return TestErrorResponsesWithModel400Response.parse_obj(obj) - _obj = List.parse_obj({ - "var_123_list": obj.get("123-list") + _obj = TestErrorResponsesWithModel400Response.parse_obj({ + "reason400": obj.get("reason400") }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/list.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model404_response.py similarity index 63% rename from samples/openapi3/client/petstore/python/petstore_api/models/list.py rename to samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model404_response.py index 95f27b25f95a..77c77d903f53 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/list.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/models/test_error_responses_with_model404_response.py @@ -20,44 +20,36 @@ from typing import Any, Dict, Optional from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self - -class List(BaseModel): + +class TestErrorResponsesWithModel404Response(BaseModel): """ - List + TestErrorResponsesWithModel404Response """ - var_123_list: Optional[StrictStr] = Field(default=None, alias="123-list") + reason404: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} - __properties = ["123-list"] - - model_config = { - "populate_by_name": True, - "validate_assignment": True - } + __properties = ["reason404"] + class Config: + """Pydantic configuration""" + allow_population_by_field_name = True + validate_assignment = True def to_str(self) -> str: """Returns the string representation of the model using alias""" - return pprint.pformat(self.model_dump(by_alias=True)) + return pprint.pformat(self.dict(by_alias=True)) def to_json(self) -> str: """Returns the JSON representation of the model using alias""" - # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of List from a JSON string""" + def from_json(cls, json_str: str) -> TestErrorResponsesWithModel404Response: + """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self): """Returns the dictionary representation of the model using alias""" - _dict = self.model_dump(by_alias=True, + _dict = self.dict(by_alias=True, exclude={ "additional_properties" }, @@ -70,20 +62,20 @@ def to_dict(self): return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: - """Create an instance of List from a dict""" + def from_dict(cls, obj: dict) -> TestErrorResponsesWithModel404Response: + """Create an instance of TestErrorResponsesWithModel404Response from a dict""" if obj is None: return None if not isinstance(obj, dict): - return cls.model_validate(obj) + return TestErrorResponsesWithModel404Response.parse_obj(obj) - _obj = cls.model_validate({ - "123-list": obj.get("123-list") + _obj = TestErrorResponsesWithModel404Response.parse_obj({ + "reason404": obj.get("reason404") }) # store additional fields in additional_properties for _key in obj.keys(): - if _key not in cls.__properties.default: + if _key not in cls.__properties: _obj.additional_properties[_key] = obj.get(_key) return _obj diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py index df9aca008048..fcbbdab49ab9 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/petstore_api/rest.py @@ -26,6 +26,18 @@ logger = logging.getLogger(__name__) +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} + + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES + class RESTResponse(io.IOBase): @@ -81,17 +93,29 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: # https pool manager if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + self.pool_manager = SOCKSProxyManager( + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + headers=configuration.proxy_headers, + **addition_pool_args + ) + else: + self.pool_manager = urllib3.ProxyManager( + num_pools=pools_size, + maxsize=maxsize, + cert_reqs=cert_reqs, + ca_certs=configuration.ssl_ca_cert, + cert_file=configuration.cert_file, + key_file=configuration.key_file, + proxy_url=configuration.proxy, + proxy_headers=configuration.proxy_headers, + **addition_pool_args + ) else: self.pool_manager = urllib3.PoolManager( num_pools=pools_size, diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_configuration.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_configuration.py deleted file mode 100755 index d41ffa63ba8a..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_configuration.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - OpenAPI spec version: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest - -import petstore_api -from petstore_api import Configuration # noqa: E501 -from petstore_api.rest import ApiException - - -class TestConfiguration(unittest.TestCase): - """Configuration unit test stubs""" - - def setUp(self): - self.config= Configuration() - - def tearDown(self): - pass - - def test_configuration(self): - """Test configuration - - Test host settings # noqa: E501 - """ - host_settings = self.config.get_host_settings() - - self.assertEqual('http://{server}.swagger.io:{port}/v2', host_settings[0]['url']) - self.assertEqual('petstore', host_settings[0]['variables']['server']['default_value']) - - self.assertEqual('https://localhost:8080/{version}', host_settings[1]['url']) - self.assertEqual('v2', host_settings[1]['variables']['version']['default_value']) - - def test_get_host_from_settings(self): - """ Test get_host_from_settings - - Test get URL from host settings - """ - self.assertEqual("http://petstore.swagger.io:80/v2", self.config.get_host_from_settings(0)) - self.assertEqual("http://petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'port': '8080'})) - self.assertEqual("http://dev-petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'server': 'dev-petstore', 'port': '8080'})) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags123_api.py index f54e0d06644f..25088624aea3 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags123_api.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags123_api.py @@ -3,32 +3,30 @@ """ OpenAPI Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" + Generated by OpenAPI Generator (https://openapi-generator.tech) + Do not edit the class manually. +""" # noqa: E501 -from __future__ import absolute_import import unittest -import petstore_api -from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 -from petstore_api.rest import ApiException +from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api # noqa: E501 class TestFakeClassnameTags123Api(unittest.TestCase): """FakeClassnameTags123Api unit test stubs""" - def setUp(self): - self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 + def setUp(self) -> None: + self.api = FakeClassnameTags123Api() # noqa: E501 - def tearDown(self): + def tearDown(self) -> None: pass - def test_test_classname(self): + def test_test_classname(self) -> None: """Test case for test_classname To test class name in snake case # noqa: E501 diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags_123_api.py deleted file mode 100644 index f54e0d06644f..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_fake_classname_tags_123_api.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest - -import petstore_api -from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 -from petstore_api.rest import ApiException - - -class TestFakeClassnameTags123Api(unittest.TestCase): - """FakeClassnameTags123Api unit test stubs""" - - def setUp(self): - self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 - - def tearDown(self): - pass - - def test_test_classname(self): - """Test case for test_classname - - To test class name in snake case # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_list.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_list.py deleted file mode 100644 index 4c603a5e9b1e..000000000000 --- a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_list.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.list import List # noqa: E501 -from petstore_api.rest import ApiException - -class TestList(unittest.TestCase): - """List unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test List - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.list.List() # noqa: E501 - if include_optional : - return List( - _123_list = '' - ) - else : - return List( - ) - - def testList(self): - """Test List""" - inst_req_only = self.make_instance(include_optional=False) - inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..b4e2d50dc6fe --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model400_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response # noqa: E501 + +class TestTestErrorResponsesWithModel400Response(unittest.TestCase): + """TestErrorResponsesWithModel400Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel400Response: + """Test TestErrorResponsesWithModel400Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel400Response` + """ + model = TestErrorResponsesWithModel400Response() # noqa: E501 + if include_optional: + return TestErrorResponsesWithModel400Response( + reason400 = '' + ) + else: + return TestErrorResponsesWithModel400Response( + ) + """ + + def testTestErrorResponsesWithModel400Response(self): + """Test TestErrorResponsesWithModel400Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..caf587ddb033 --- /dev/null +++ b/samples/openapi3/client/petstore/python-pydantic-v1/test/test_test_error_responses_with_model404_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response # noqa: E501 + +class TestTestErrorResponsesWithModel404Response(unittest.TestCase): + """TestErrorResponsesWithModel404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel404Response: + """Test TestErrorResponsesWithModel404Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel404Response` + """ + model = TestErrorResponsesWithModel404Response() # noqa: E501 + if include_optional: + return TestErrorResponsesWithModel404Response( + reason404 = '' + ) + else: + return TestErrorResponsesWithModel404Response( + ) + """ + + def testTestErrorResponsesWithModel404Response(self): + """Test TestErrorResponsesWithModel404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_api_client.py b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_api_client.py index ee9afd740cd1..d254d28010db 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_api_client.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_api_client.py @@ -257,5 +257,6 @@ def test_parameters_to_url_query(self): result = self.api_client.parameters_to_url_query([('value', dictionary)], {}) self.assertEqual(result, 'value=%7B%22strValues%22%3A%20%5B%22one%22%2C%20%22two%22%2C%20%22three%22%5D%2C%20%22dictValues%22%3A%20%5B%7B%22name%22%3A%20%22value1%22%2C%20%22age%22%3A%2014%7D%2C%20%7B%22name%22%3A%20%22value2%22%2C%20%22age%22%3A%2012%7D%5D%7D') - - + def test_parameters_to_url_query_boolean_value(self): + result = self.api_client.parameters_to_url_query([('boolean', True)], {}) + self.assertEqual(result, "boolean=true") diff --git a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_configuration.py b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_configuration.py index 04c2781f5e29..571c79ed034b 100644 --- a/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_configuration.py +++ b/samples/openapi3/client/petstore/python-pydantic-v1/tests/test_configuration.py @@ -19,7 +19,7 @@ class TestConfiguration(unittest.TestCase): """Animal unit test stubs""" def setUp(self): - pass + self.config = petstore_api.Configuration() def tearDown(self): # reset Configuration @@ -57,6 +57,24 @@ def testApiClientDefaultConfiguration(self): def testAccessTokenWhenConstructingConfiguration(self): c1 = petstore_api.Configuration(access_token="12345") self.assertEqual(c1.access_token, "12345") + + def test_get_host_settings(self): + host_settings = self.config.get_host_settings() + + self.assertEqual('http://{server}.swagger.io:{port}/v2', host_settings[0]['url']) + self.assertEqual('petstore', host_settings[0]['variables']['server']['default_value']) + + self.assertEqual('https://localhost:8080/{version}', host_settings[1]['url']) + self.assertEqual('v2', host_settings[1]['variables']['version']['default_value']) + + def test_get_host_from_settings(self): + """ Test get_host_from_settings + + Test get URL from host settings + """ + self.assertEqual("http://petstore.swagger.io:80/v2", self.config.get_host_from_settings(0)) + self.assertEqual("http://petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'port': '8080'})) + self.assertEqual("http://dev-petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'server': 'dev-petstore', 'port': '8080'})) if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/FILES b/samples/openapi3/client/petstore/python/.openapi-generator/FILES index ff22e2855124..090c6c431e53 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/FILES +++ b/samples/openapi3/client/petstore/python/.openapi-generator/FILES @@ -12,7 +12,6 @@ docs/Animal.md docs/AnotherFakeApi.md docs/AnyOfColor.md docs/AnyOfPig.md -docs/ApiResponse.md docs/ArrayOfArrayOfModel.md docs/ArrayOfArrayOfNumberOnly.md docs/ArrayOfNumberOnly.md @@ -54,6 +53,7 @@ docs/MapOfArrayOfModel.md docs/MapTest.md docs/MixedPropertiesAndAdditionalPropertiesClass.md docs/Model200Response.md +docs/ModelApiResponse.md docs/ModelReturn.md docs/Name.md docs/NullableClass.md @@ -84,6 +84,8 @@ docs/SpecialModelName.md docs/SpecialName.md docs/StoreApi.md docs/Tag.md +docs/TestErrorResponsesWithModel400Response.md +docs/TestErrorResponsesWithModel404Response.md docs/TestInlineFreeformAdditionalPropertiesRequest.md docs/Tiger.md docs/UnnamedDictWithAdditionalModelListProperties.md @@ -114,7 +116,6 @@ petstore_api/models/all_of_with_single_ref.py petstore_api/models/animal.py petstore_api/models/any_of_color.py petstore_api/models/any_of_pig.py -petstore_api/models/api_response.py petstore_api/models/array_of_array_of_model.py petstore_api/models/array_of_array_of_number_only.py petstore_api/models/array_of_number_only.py @@ -153,6 +154,7 @@ petstore_api/models/map_of_array_of_model.py petstore_api/models/map_test.py petstore_api/models/mixed_properties_and_additional_properties_class.py petstore_api/models/model200_response.py +petstore_api/models/model_api_response.py petstore_api/models/model_return.py petstore_api/models/name.py petstore_api/models/nullable_class.py @@ -181,6 +183,8 @@ petstore_api/models/special_character_enum.py petstore_api/models/special_model_name.py petstore_api/models/special_name.py petstore_api/models/tag.py +petstore_api/models/test_error_responses_with_model400_response.py +petstore_api/models/test_error_responses_with_model404_response.py petstore_api/models/test_inline_freeform_additional_properties_request.py petstore_api/models/tiger.py petstore_api/models/unnamed_dict_with_additional_model_list_properties.py diff --git a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100755 --- a/samples/openapi3/client/petstore/python/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/python/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/python/README.md b/samples/openapi3/client/petstore/python/README.md index cf91d3ad0ce9..419d744d6ee9 100755 --- a/samples/openapi3/client/petstore/python/README.md +++ b/samples/openapi3/client/petstore/python/README.md @@ -50,7 +50,6 @@ Please follow the [installation procedure](#installation--usage) and then run th ```python import datetime -import time import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -96,14 +95,18 @@ Class | Method | HTTP request | Description *FakeApi* | [**fake_outer_number_serialize**](docs/FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | *FakeApi* | [**fake_outer_string_serialize**](docs/FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | *FakeApi* | [**fake_property_enum_integer_serialize**](docs/FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +*FakeApi* | [**fake_ref_enum_string**](docs/FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string *FakeApi* | [**fake_return_list_of_objects**](docs/FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects *FakeApi* | [**fake_uuid_example**](docs/FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +*FakeApi* | [**test_additional_properties_reference**](docs/FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties *FakeApi* | [**test_body_with_binary**](docs/FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | *FakeApi* | [**test_body_with_file_schema**](docs/FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | *FakeApi* | [**test_body_with_query_params**](docs/FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | *FakeApi* | [**test_client_model**](docs/FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model *FakeApi* | [**test_date_time_query_parameter**](docs/FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +*FakeApi* | [**test_empty_and_non_empty_responses**](docs/FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses *FakeApi* | [**test_endpoint_parameters**](docs/FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +*FakeApi* | [**test_error_responses_with_model**](docs/FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model *FakeApi* | [**test_group_parameters**](docs/FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) *FakeApi* | [**test_inline_additional_properties**](docs/FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties *FakeApi* | [**test_inline_freeform_additional_properties**](docs/FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -143,7 +146,6 @@ Class | Method | HTTP request | Description - [Animal](docs/Animal.md) - [AnyOfColor](docs/AnyOfColor.md) - [AnyOfPig](docs/AnyOfPig.md) - - [ApiResponse](docs/ApiResponse.md) - [ArrayOfArrayOfModel](docs/ArrayOfArrayOfModel.md) - [ArrayOfArrayOfNumberOnly](docs/ArrayOfArrayOfNumberOnly.md) - [ArrayOfNumberOnly](docs/ArrayOfNumberOnly.md) @@ -182,6 +184,7 @@ Class | Method | HTTP request | Description - [MapTest](docs/MapTest.md) - [MixedPropertiesAndAdditionalPropertiesClass](docs/MixedPropertiesAndAdditionalPropertiesClass.md) - [Model200Response](docs/Model200Response.md) + - [ModelApiResponse](docs/ModelApiResponse.md) - [ModelReturn](docs/ModelReturn.md) - [Name](docs/Name.md) - [NullableClass](docs/NullableClass.md) @@ -210,6 +213,8 @@ Class | Method | HTTP request | Description - [SpecialModelName](docs/SpecialModelName.md) - [SpecialName](docs/SpecialName.md) - [Tag](docs/Tag.md) + - [TestErrorResponsesWithModel400Response](docs/TestErrorResponsesWithModel400Response.md) + - [TestErrorResponsesWithModel404Response](docs/TestErrorResponsesWithModel404Response.md) - [TestInlineFreeformAdditionalPropertiesRequest](docs/TestInlineFreeformAdditionalPropertiesRequest.md) - [Tiger](docs/Tiger.md) - [UnnamedDictWithAdditionalModelListProperties](docs/UnnamedDictWithAdditionalModelListProperties.md) diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md index beedef76c051..f9556560ea43 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesAnyType.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md index 6abc3136b9ca..dd6a13fd8e90 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_property** | **Dict[str, str]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md index 8b9259c687f6..3e5dc0557c4f 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesObject.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md index d66094f18e57..540511bfdfa5 100644 --- a/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md +++ b/samples/openapi3/client/petstore/python/docs/AdditionalPropertiesWithDescriptionOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md b/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md index 1a8b4df7ecc5..64ec2aece749 100644 --- a/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md +++ b/samples/openapi3/client/petstore/python/docs/AllOfWithSingleRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **username** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Animal.md b/samples/openapi3/client/petstore/python/docs/Animal.md index b62f19690994..c052862c7b35 100644 --- a/samples/openapi3/client/petstore/python/docs/Animal.md +++ b/samples/openapi3/client/petstore/python/docs/Animal.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md b/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md index d3103c7d369f..3ec02d261eed 100644 --- a/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/AnotherFakeApi.md @@ -16,9 +16,8 @@ To test special tags and operation ID starting with number ### Example + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -50,6 +49,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -68,6 +68,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python/docs/AnyOfColor.md b/samples/openapi3/client/petstore/python/docs/AnyOfColor.md index 9b161ccba1c0..0b36e7623305 100644 --- a/samples/openapi3/client/petstore/python/docs/AnyOfColor.md +++ b/samples/openapi3/client/petstore/python/docs/AnyOfColor.md @@ -3,6 +3,7 @@ Any of RGB array, RGBA array, or hex string. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/AnyOfPig.md b/samples/openapi3/client/petstore/python/docs/AnyOfPig.md index 2da7ca6eefe7..a88832b1a221 100644 --- a/samples/openapi3/client/petstore/python/docs/AnyOfPig.md +++ b/samples/openapi3/client/petstore/python/docs/AnyOfPig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md index 094061592613..7928604f14c9 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **another_property** | **List[List[Tag]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md index 3f0c127d4fa3..5d9baca180b5 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfArrayOfNumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_array_number** | **List[List[float]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md index c10191915a70..efaf6adb623e 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayOfNumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_number** | **List[float]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ArrayTest.md b/samples/openapi3/client/petstore/python/docs/ArrayTest.md index 0a40fb36d26f..97e52ef5d6b3 100644 --- a/samples/openapi3/client/petstore/python/docs/ArrayTest.md +++ b/samples/openapi3/client/petstore/python/docs/ArrayTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **array_of_string** | **List[str]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/BasquePig.md b/samples/openapi3/client/petstore/python/docs/BasquePig.md index 552b9390c7e5..19a5ba6a0aac 100644 --- a/samples/openapi3/client/petstore/python/docs/BasquePig.md +++ b/samples/openapi3/client/petstore/python/docs/BasquePig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/Capitalization.md b/samples/openapi3/client/petstore/python/docs/Capitalization.md index 99e6fae88fde..26dcd554b18f 100644 --- a/samples/openapi3/client/petstore/python/docs/Capitalization.md +++ b/samples/openapi3/client/petstore/python/docs/Capitalization.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **small_camel** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Cat.md b/samples/openapi3/client/petstore/python/docs/Cat.md index 4b509dda7ea3..1a69ead05378 100644 --- a/samples/openapi3/client/petstore/python/docs/Cat.md +++ b/samples/openapi3/client/petstore/python/docs/Cat.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **declawed** | **bool** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Category.md b/samples/openapi3/client/petstore/python/docs/Category.md index c49514ef8023..42ac5ce00d61 100644 --- a/samples/openapi3/client/petstore/python/docs/Category.md +++ b/samples/openapi3/client/petstore/python/docs/Category.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md b/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md index d5e97934d2be..99e42d961c53 100644 --- a/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md +++ b/samples/openapi3/client/petstore/python/docs/CircularReferenceModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ClassModel.md b/samples/openapi3/client/petstore/python/docs/ClassModel.md index 1b6fb7cfc77d..196e4d77bace 100644 --- a/samples/openapi3/client/petstore/python/docs/ClassModel.md +++ b/samples/openapi3/client/petstore/python/docs/ClassModel.md @@ -3,6 +3,7 @@ Model for testing model with \"_class\" property ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_class** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Client.md b/samples/openapi3/client/petstore/python/docs/Client.md index b0ded10dd762..5eb04e6a5097 100644 --- a/samples/openapi3/client/petstore/python/docs/Client.md +++ b/samples/openapi3/client/petstore/python/docs/Client.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **client** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Color.md b/samples/openapi3/client/petstore/python/docs/Color.md index 07fcd01991ac..769f47b82a69 100644 --- a/samples/openapi3/client/petstore/python/docs/Color.md +++ b/samples/openapi3/client/petstore/python/docs/Color.md @@ -3,6 +3,7 @@ RGB array, RGBA array, or hex string. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/Creature.md b/samples/openapi3/client/petstore/python/docs/Creature.md index 54249d5871e0..1df27fe75a53 100644 --- a/samples/openapi3/client/petstore/python/docs/Creature.md +++ b/samples/openapi3/client/petstore/python/docs/Creature.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **info** | [**CreatureInfo**](CreatureInfo.md) | | diff --git a/samples/openapi3/client/petstore/python/docs/CreatureInfo.md b/samples/openapi3/client/petstore/python/docs/CreatureInfo.md index 5a600b9f3374..7211f27546d5 100644 --- a/samples/openapi3/client/petstore/python/docs/CreatureInfo.md +++ b/samples/openapi3/client/petstore/python/docs/CreatureInfo.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/DanishPig.md b/samples/openapi3/client/petstore/python/docs/DanishPig.md index 253616c2fc32..04b55ec828bc 100644 --- a/samples/openapi3/client/petstore/python/docs/DanishPig.md +++ b/samples/openapi3/client/petstore/python/docs/DanishPig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/DefaultApi.md b/samples/openapi3/client/petstore/python/docs/DefaultApi.md index a5c2b671f341..634dc9688427 100644 --- a/samples/openapi3/client/petstore/python/docs/DefaultApi.md +++ b/samples/openapi3/client/petstore/python/docs/DefaultApi.md @@ -14,9 +14,8 @@ Method | HTTP request | Description ### Example + ```python -import time -import os import petstore_api from petstore_api.models.foo_get_default_response import FooGetDefaultResponse from petstore_api.rest import ApiException @@ -45,6 +44,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -61,6 +61,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | response | - | diff --git a/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md b/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md index e6cf57189634..2a081e0710cf 100644 --- a/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md +++ b/samples/openapi3/client/petstore/python/docs/DeprecatedObject.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Dog.md b/samples/openapi3/client/petstore/python/docs/Dog.md index 3469be73a761..958fc3dae084 100644 --- a/samples/openapi3/client/petstore/python/docs/Dog.md +++ b/samples/openapi3/client/petstore/python/docs/Dog.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **breed** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/DummyModel.md b/samples/openapi3/client/petstore/python/docs/DummyModel.md index e690a8874f8c..8ecb4948523c 100644 --- a/samples/openapi3/client/petstore/python/docs/DummyModel.md +++ b/samples/openapi3/client/petstore/python/docs/DummyModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/EnumArrays.md b/samples/openapi3/client/petstore/python/docs/EnumArrays.md index d21f58a66087..19b048165d00 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumArrays.md +++ b/samples/openapi3/client/petstore/python/docs/EnumArrays.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_symbol** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/EnumClass.md b/samples/openapi3/client/petstore/python/docs/EnumClass.md index 64830e3d1dee..8097457bd55a 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumClass.md +++ b/samples/openapi3/client/petstore/python/docs/EnumClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/EnumString1.md b/samples/openapi3/client/petstore/python/docs/EnumString1.md index 194d65b48fa0..1e2b5eaa0390 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumString1.md +++ b/samples/openapi3/client/petstore/python/docs/EnumString1.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/EnumString2.md b/samples/openapi3/client/petstore/python/docs/EnumString2.md index 0d8568bfbeff..15a466f322d4 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumString2.md +++ b/samples/openapi3/client/petstore/python/docs/EnumString2.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/EnumTest.md b/samples/openapi3/client/petstore/python/docs/EnumTest.md index 5bcb8e7027e3..e5c6e6dee0b9 100644 --- a/samples/openapi3/client/petstore/python/docs/EnumTest.md +++ b/samples/openapi3/client/petstore/python/docs/EnumTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **enum_string** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/FakeApi.md b/samples/openapi3/client/petstore/python/docs/FakeApi.md index 4a998d2c0626..033744514748 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeApi.md +++ b/samples/openapi3/client/petstore/python/docs/FakeApi.md @@ -13,14 +13,18 @@ Method | HTTP request | Description [**fake_outer_number_serialize**](FakeApi.md#fake_outer_number_serialize) | **POST** /fake/outer/number | [**fake_outer_string_serialize**](FakeApi.md#fake_outer_string_serialize) | **POST** /fake/outer/string | [**fake_property_enum_integer_serialize**](FakeApi.md#fake_property_enum_integer_serialize) | **POST** /fake/property/enum-int | +[**fake_ref_enum_string**](FakeApi.md#fake_ref_enum_string) | **GET** /fake/ref_enum_string | test ref to enum string [**fake_return_list_of_objects**](FakeApi.md#fake_return_list_of_objects) | **GET** /fake/return_list_of_object | test returning list of objects [**fake_uuid_example**](FakeApi.md#fake_uuid_example) | **GET** /fake/uuid_example | test uuid example +[**test_additional_properties_reference**](FakeApi.md#test_additional_properties_reference) | **POST** /fake/additionalProperties-reference | test referenced additionalProperties [**test_body_with_binary**](FakeApi.md#test_body_with_binary) | **PUT** /fake/body-with-binary | [**test_body_with_file_schema**](FakeApi.md#test_body_with_file_schema) | **PUT** /fake/body-with-file-schema | [**test_body_with_query_params**](FakeApi.md#test_body_with_query_params) | **PUT** /fake/body-with-query-params | [**test_client_model**](FakeApi.md#test_client_model) | **PATCH** /fake | To test \"client\" model [**test_date_time_query_parameter**](FakeApi.md#test_date_time_query_parameter) | **PUT** /fake/date-time-query-params | +[**test_empty_and_non_empty_responses**](FakeApi.md#test_empty_and_non_empty_responses) | **POST** /fake/empty_and_non_empty_responses | test empty and non-empty responses [**test_endpoint_parameters**](FakeApi.md#test_endpoint_parameters) | **POST** /fake | Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 +[**test_error_responses_with_model**](FakeApi.md#test_error_responses_with_model) | **POST** /fake/error_responses_with_model | test error responses with model [**test_group_parameters**](FakeApi.md#test_group_parameters) | **DELETE** /fake | Fake endpoint to test group parameters (optional) [**test_inline_additional_properties**](FakeApi.md#test_inline_additional_properties) | **POST** /fake/inline-additionalProperties | test inline additionalProperties [**test_inline_freeform_additional_properties**](FakeApi.md#test_inline_freeform_additional_properties) | **POST** /fake/inline-freeform-additionalProperties | test inline free-form additionalProperties @@ -35,9 +39,8 @@ test any type request body ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -66,6 +69,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **object**| | [optional] @@ -84,6 +88,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | OK | - | @@ -97,9 +102,8 @@ test enum reference query parameter ### Example + ```python -import time -import os import petstore_api from petstore_api.models.enum_class import EnumClass from petstore_api.rest import ApiException @@ -129,6 +133,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **enum_ref** | [**EnumClass**](.md)| enum reference | [optional] @@ -147,6 +152,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Get successful | - | @@ -160,9 +166,8 @@ Health check endpoint ### Example + ```python -import time -import os import petstore_api from petstore_api.models.health_check_result import HealthCheckResult from petstore_api.rest import ApiException @@ -192,6 +197,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -208,6 +214,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | The instance started successfully | - | @@ -221,9 +228,8 @@ test http signature authentication ### Example + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -322,6 +328,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -342,6 +349,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | The instance started successfully | - | @@ -357,9 +365,8 @@ Test serialization of outer boolean types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -389,6 +396,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bool**| Input boolean as post body | [optional] @@ -407,6 +415,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output boolean | - | @@ -422,9 +431,8 @@ Test serialization of object with outer number type ### Example + ```python -import time -import os import petstore_api from petstore_api.models.outer_composite import OuterComposite from petstore_api.rest import ApiException @@ -455,6 +463,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **outer_composite** | [**OuterComposite**](OuterComposite.md)| Input composite as post body | [optional] @@ -473,6 +482,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output composite | - | @@ -488,9 +498,8 @@ Test serialization of outer number types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -520,6 +529,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **float**| Input number as post body | [optional] @@ -538,6 +548,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output number | - | @@ -553,9 +564,8 @@ Test serialization of outer string types ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -585,6 +595,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **str**| Input string as post body | [optional] @@ -603,6 +614,7 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output string | - | @@ -618,9 +630,8 @@ Test serialization of enum (int) properties with examples ### Example + ```python -import time -import os import petstore_api from petstore_api.models.outer_object_with_enum_property import OuterObjectWithEnumProperty from petstore_api.rest import ApiException @@ -651,6 +662,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **outer_object_with_enum_property** | [**OuterObjectWithEnumProperty**](OuterObjectWithEnumProperty.md)| Input enum (int) as post body | @@ -669,12 +681,75 @@ No authorization required - **Accept**: */* ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Output enum (int) | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **fake_ref_enum_string** +> EnumClass fake_ref_enum_string() + +test ref to enum string + +### Example + + +```python +import petstore_api +from petstore_api.models.enum_class import EnumClass +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test ref to enum string + api_response = api_instance.fake_ref_enum_string() + print("The response of FakeApi->fake_ref_enum_string:\n") + pprint(api_response) + except Exception as e: + print("Exception when calling FakeApi->fake_ref_enum_string: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +[**EnumClass**](EnumClass.md) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: plain/text + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | OK | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **fake_return_list_of_objects** > List[List[Tag]] fake_return_list_of_objects() @@ -682,9 +757,8 @@ test returning list of objects ### Example + ```python -import time -import os import petstore_api from petstore_api.models.tag import Tag from petstore_api.rest import ApiException @@ -714,6 +788,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -730,6 +805,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | OK | - | @@ -743,9 +819,8 @@ test uuid example ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -774,6 +849,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **uuid_example** | **str**| uuid example | @@ -792,12 +868,78 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Get successful | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_additional_properties_reference** +> test_additional_properties_reference(request_body) + +test referenced additionalProperties + + + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + request_body = None # Dict[str, object] | request body + + try: + # test referenced additionalProperties + api_instance.test_additional_properties_reference(request_body) + except Exception as e: + print("Exception when calling FakeApi->test_additional_properties_reference: %s\n" % e) +``` + + + +### Parameters + + +Name | Type | Description | Notes +------------- | ------------- | ------------- | ------------- + **request_body** | [**Dict[str, object]**](object.md)| request body | + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: application/json + - **Accept**: Not defined + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**200** | successful operation | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_body_with_binary** > test_body_with_binary(body) @@ -807,9 +949,8 @@ For this test, the body has to be a binary file. ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -837,6 +978,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **body** | **bytearray**| image to upload | @@ -855,6 +997,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -870,9 +1013,8 @@ For this test, the body for this request must reference a schema named `File`. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.file_schema_test_class import FileSchemaTestClass from petstore_api.rest import ApiException @@ -901,6 +1043,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **file_schema_test_class** | [**FileSchemaTestClass**](FileSchemaTestClass.md)| | @@ -919,6 +1062,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -932,9 +1076,8 @@ No authorization required ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -964,6 +1107,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **query** | **str**| | @@ -983,6 +1127,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | @@ -998,9 +1143,8 @@ To test \"client\" model ### Example + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -1032,6 +1176,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -1050,6 +1195,7 @@ No authorization required - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1063,9 +1209,8 @@ No authorization required ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1094,6 +1239,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **date_time_query** | **datetime**| | @@ -1113,12 +1259,75 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_empty_and_non_empty_responses** +> test_empty_and_non_empty_responses() + +test empty and non-empty responses + + + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test empty and non-empty responses + api_instance.test_empty_and_non_empty_responses() + except Exception as e: + print("Exception when calling FakeApi->test_empty_and_non_empty_responses: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: text/plain + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**206** | Partial response content | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_endpoint_parameters** > test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer=integer, int32=int32, int64=int64, var_float=var_float, string=string, binary=binary, byte_with_max_length=byte_with_max_length, var_date=var_date, date_time=date_time, password=password, param_callback=param_callback) @@ -1129,9 +1338,8 @@ Fake endpoint for testing various parameters 假端點 偽のエンドポイン ### Example * Basic Authentication (http_basic_test): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1184,6 +1392,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **number** | **float**| None | @@ -1216,6 +1425,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid username supplied | - | @@ -1223,6 +1433,67 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) +# **test_error_responses_with_model** +> test_error_responses_with_model() + +test error responses with model + +### Example + + +```python +import petstore_api +from petstore_api.rest import ApiException +from pprint import pprint + +# Defining the host is optional and defaults to http://petstore.swagger.io:80/v2 +# See configuration.py for a list of all supported configuration parameters. +configuration = petstore_api.Configuration( + host = "http://petstore.swagger.io:80/v2" +) + + +# Enter a context with an instance of the API client +with petstore_api.ApiClient(configuration) as api_client: + # Create an instance of the API class + api_instance = petstore_api.FakeApi(api_client) + + try: + # test error responses with model + api_instance.test_error_responses_with_model() + except Exception as e: + print("Exception when calling FakeApi->test_error_responses_with_model: %s\n" % e) +``` + + + +### Parameters + +This endpoint does not need any parameter. + +### Return type + +void (empty response body) + +### Authorization + +No authorization required + +### HTTP request headers + + - **Content-Type**: Not defined + - **Accept**: application/json + +### HTTP response details + +| Status code | Description | Response headers | +|-------------|-------------|------------------| +**204** | Success, but no response content | - | +**400** | | - | +**404** | | - | + +[[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) + # **test_group_parameters** > test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group=string_group, boolean_group=boolean_group, int64_group=int64_group) @@ -1233,9 +1504,8 @@ Fake endpoint to test group parameters (optional) ### Example * Bearer (JWT) Authentication (bearer_test): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1278,6 +1548,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **required_string_group** | **int**| Required String in group parameters | @@ -1301,6 +1572,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Someting wrong | - | @@ -1316,9 +1588,8 @@ test inline additionalProperties ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1347,6 +1618,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **request_body** | [**Dict[str, str]**](str.md)| request body | @@ -1365,6 +1637,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1380,9 +1653,8 @@ test inline free-form additionalProperties ### Example + ```python -import time -import os import petstore_api from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.rest import ApiException @@ -1412,6 +1684,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **test_inline_freeform_additional_properties_request** | [**TestInlineFreeformAdditionalPropertiesRequest**](TestInlineFreeformAdditionalPropertiesRequest.md)| request body | @@ -1430,6 +1703,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1445,9 +1719,8 @@ test json serialization of form data ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1477,6 +1750,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **param** | **str**| field1 | @@ -1496,6 +1770,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -1511,9 +1786,8 @@ To test the collection format in query parameters ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -1547,6 +1821,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pipe** | [**List[str]**](str.md)| | @@ -1571,6 +1846,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Success | - | diff --git a/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md b/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md index 0319aac41cfc..5194f5a2eefa 100644 --- a/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md +++ b/samples/openapi3/client/petstore/python/docs/FakeClassnameTags123Api.md @@ -17,9 +17,8 @@ To test class name in snake case ### Example * Api Key Authentication (api_key_query): + ```python -import time -import os import petstore_api from petstore_api.models.client import Client from petstore_api.rest import ApiException @@ -61,6 +60,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **client** | [**Client**](Client.md)| client model | @@ -79,6 +79,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python/docs/File.md b/samples/openapi3/client/petstore/python/docs/File.md index 586da8e32559..af7192f8d60c 100644 --- a/samples/openapi3/client/petstore/python/docs/File.md +++ b/samples/openapi3/client/petstore/python/docs/File.md @@ -3,6 +3,7 @@ Must be named `File` for test. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **source_uri** | **str** | Test capitalization | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md index fb967a8d9924..55abbcc14d7e 100644 --- a/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md +++ b/samples/openapi3/client/petstore/python/docs/FileSchemaTestClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **file** | [**File**](File.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/FirstRef.md b/samples/openapi3/client/petstore/python/docs/FirstRef.md index b5e7ab766b45..0d4d44cf5f42 100644 --- a/samples/openapi3/client/petstore/python/docs/FirstRef.md +++ b/samples/openapi3/client/petstore/python/docs/FirstRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Foo.md b/samples/openapi3/client/petstore/python/docs/Foo.md index 8062d08df1dd..9cd6e8f56c53 100644 --- a/samples/openapi3/client/petstore/python/docs/Foo.md +++ b/samples/openapi3/client/petstore/python/docs/Foo.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [default to 'bar'] diff --git a/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md b/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md index 550fbe78fa17..96211ac791f5 100644 --- a/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md +++ b/samples/openapi3/client/petstore/python/docs/FooGetDefaultResponse.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **string** | [**Foo**](Foo.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/FormatTest.md b/samples/openapi3/client/petstore/python/docs/FormatTest.md index 4f1950492c07..eec9904cef5c 100644 --- a/samples/openapi3/client/petstore/python/docs/FormatTest.md +++ b/samples/openapi3/client/petstore/python/docs/FormatTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **integer** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md index 99573bd28a2f..e960a679b2ad 100644 --- a/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md +++ b/samples/openapi3/client/petstore/python/docs/HasOnlyReadOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] diff --git a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md index b8723e018aa1..8c26c2a47c39 100644 --- a/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md +++ b/samples/openapi3/client/petstore/python/docs/HealthCheckResult.md @@ -3,6 +3,7 @@ Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **nullable_message** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md b/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md index 45d76ad458c4..5fc372302446 100644 --- a/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md +++ b/samples/openapi3/client/petstore/python/docs/InnerDictWithProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **a_property** | **object** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/IntOrString.md b/samples/openapi3/client/petstore/python/docs/IntOrString.md index 0a441f186dbc..f1dc942fa7ab 100644 --- a/samples/openapi3/client/petstore/python/docs/IntOrString.md +++ b/samples/openapi3/client/petstore/python/docs/IntOrString.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/List.md b/samples/openapi3/client/petstore/python/docs/List.md deleted file mode 100644 index 7643e4ea92dd..000000000000 --- a/samples/openapi3/client/petstore/python/docs/List.md +++ /dev/null @@ -1,28 +0,0 @@ -# List - - -## Properties -Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**var_123_list** | **str** | | [optional] - -## Example - -```python -from petstore_api.models.list import List - -# TODO update the JSON string below -json = "{}" -# create an instance of List from a JSON string -list_instance = List.from_json(json) -# print the JSON string representation of the object -print List.to_json() - -# convert the object into a dict -list_dict = list_instance.to_dict() -# create an instance of List from a dict -list_form_dict = list.from_dict(list_dict) -``` -[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) - - diff --git a/samples/openapi3/client/petstore/python/docs/ListClass.md b/samples/openapi3/client/petstore/python/docs/ListClass.md index ceb1f50705bd..7cf3da96c1d8 100644 --- a/samples/openapi3/client/petstore/python/docs/ListClass.md +++ b/samples/openapi3/client/petstore/python/docs/ListClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_123_list** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md b/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md index b97ace0f42c8..8380cbd6ffd1 100644 --- a/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md +++ b/samples/openapi3/client/petstore/python/docs/MapOfArrayOfModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **shop_id_to_org_online_lip_map** | **Dict[str, List[Tag]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/MapTest.md b/samples/openapi3/client/petstore/python/docs/MapTest.md index ba87758a5220..8c2f507e6964 100644 --- a/samples/openapi3/client/petstore/python/docs/MapTest.md +++ b/samples/openapi3/client/petstore/python/docs/MapTest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **map_map_of_string** | **Dict[str, Dict[str, str]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md index 8f628d133abf..c3a2ec9609aa 100644 --- a/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md +++ b/samples/openapi3/client/petstore/python/docs/MixedPropertiesAndAdditionalPropertiesClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Model200Response.md b/samples/openapi3/client/petstore/python/docs/Model200Response.md index 6a20cefe99cb..c4306a646ffb 100644 --- a/samples/openapi3/client/petstore/python/docs/Model200Response.md +++ b/samples/openapi3/client/petstore/python/docs/Model200Response.md @@ -3,6 +3,7 @@ Model for testing model name starting with number ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python-aiohttp/docs/ApiResponse.md b/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md similarity index 55% rename from samples/openapi3/client/petstore/python-aiohttp/docs/ApiResponse.md rename to samples/openapi3/client/petstore/python/docs/ModelApiResponse.md index ba35ea9e2f0e..659823b8051f 100644 --- a/samples/openapi3/client/petstore/python-aiohttp/docs/ApiResponse.md +++ b/samples/openapi3/client/petstore/python/docs/ModelApiResponse.md @@ -1,7 +1,8 @@ -# ApiResponse +# ModelApiResponse ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **code** | **int** | | [optional] @@ -11,19 +12,19 @@ Name | Type | Description | Notes ## Example ```python -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse # TODO update the JSON string below json = "{}" -# create an instance of ApiResponse from a JSON string -api_response_instance = ApiResponse.from_json(json) +# create an instance of ModelApiResponse from a JSON string +model_api_response_instance = ModelApiResponse.from_json(json) # print the JSON string representation of the object -print ApiResponse.to_json() +print ModelApiResponse.to_json() # convert the object into a dict -api_response_dict = api_response_instance.to_dict() -# create an instance of ApiResponse from a dict -api_response_form_dict = api_response.from_dict(api_response_dict) +model_api_response_dict = model_api_response_instance.to_dict() +# create an instance of ModelApiResponse from a dict +model_api_response_form_dict = model_api_response.from_dict(model_api_response_dict) ``` [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/openapi3/client/petstore/python/docs/ModelReturn.md b/samples/openapi3/client/petstore/python/docs/ModelReturn.md index a5b47f423c81..861de1b9324b 100644 --- a/samples/openapi3/client/petstore/python/docs/ModelReturn.md +++ b/samples/openapi3/client/petstore/python/docs/ModelReturn.md @@ -3,6 +3,7 @@ Model for testing reserved words ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_return** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Name.md b/samples/openapi3/client/petstore/python/docs/Name.md index 4ccd0ce09aa2..01284e603d04 100644 --- a/samples/openapi3/client/petstore/python/docs/Name.md +++ b/samples/openapi3/client/petstore/python/docs/Name.md @@ -3,6 +3,7 @@ Model for testing model name same as property name ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **name** | **int** | | diff --git a/samples/openapi3/client/petstore/python/docs/NullableClass.md b/samples/openapi3/client/petstore/python/docs/NullableClass.md index 1658756b50e4..93fa80af2eaf 100644 --- a/samples/openapi3/client/petstore/python/docs/NullableClass.md +++ b/samples/openapi3/client/petstore/python/docs/NullableClass.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **required_integer_prop** | **int** | | diff --git a/samples/openapi3/client/petstore/python/docs/NullableProperty.md b/samples/openapi3/client/petstore/python/docs/NullableProperty.md index fd9cbbc51aaa..0ca7715cc961 100644 --- a/samples/openapi3/client/petstore/python/docs/NullableProperty.md +++ b/samples/openapi3/client/petstore/python/docs/NullableProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | diff --git a/samples/openapi3/client/petstore/python/docs/NumberOnly.md b/samples/openapi3/client/petstore/python/docs/NumberOnly.md index f49216ddaa4e..5a80bd15c6da 100644 --- a/samples/openapi3/client/petstore/python/docs/NumberOnly.md +++ b/samples/openapi3/client/petstore/python/docs/NumberOnly.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **just_number** | **float** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md b/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md index c4ba9a958503..6711cbfc07d4 100644 --- a/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md +++ b/samples/openapi3/client/petstore/python/docs/ObjectToTestAdditionalProperties.md @@ -3,6 +3,7 @@ Minimal object ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_property** | **bool** | Property | [optional] [default to False] diff --git a/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md b/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md index 8daa55a39161..c73370addc81 100644 --- a/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md +++ b/samples/openapi3/client/petstore/python/docs/ObjectWithDeprecatedFields.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **uuid** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md b/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md index c7c28bc29440..63c06158223d 100644 --- a/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md +++ b/samples/openapi3/client/petstore/python/docs/OneOfEnumString.md @@ -3,6 +3,7 @@ oneOf enum strings ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/Order.md b/samples/openapi3/client/petstore/python/docs/Order.md index e71e955a11dd..bd4c124320c7 100644 --- a/samples/openapi3/client/petstore/python/docs/Order.md +++ b/samples/openapi3/client/petstore/python/docs/Order.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/OuterComposite.md b/samples/openapi3/client/petstore/python/docs/OuterComposite.md index 504e266f9a14..13f271f268db 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterComposite.md +++ b/samples/openapi3/client/petstore/python/docs/OuterComposite.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **my_number** | **float** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnum.md b/samples/openapi3/client/petstore/python/docs/OuterEnum.md index 4cb31437c7e2..948ce460ac39 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterEnum.md +++ b/samples/openapi3/client/petstore/python/docs/OuterEnum.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md b/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md index 4a5ba6428d83..bcb71d067649 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md +++ b/samples/openapi3/client/petstore/python/docs/OuterEnumDefaultValue.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md b/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md index fc84ec365851..c60cb25ddd65 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md +++ b/samples/openapi3/client/petstore/python/docs/OuterEnumInteger.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md b/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md index 0de4199a8401..0f982a2609b5 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md +++ b/samples/openapi3/client/petstore/python/docs/OuterEnumIntegerDefaultValue.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md b/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md index c6a1cdcbc193..b8001294de6d 100644 --- a/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md +++ b/samples/openapi3/client/petstore/python/docs/OuterObjectWithEnumProperty.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **str_value** | [**OuterEnum**](OuterEnum.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Parent.md b/samples/openapi3/client/petstore/python/docs/Parent.md index 9a963a6b722d..620ed9c2f4c1 100644 --- a/samples/openapi3/client/petstore/python/docs/Parent.md +++ b/samples/openapi3/client/petstore/python/docs/Parent.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md b/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md index 04bf94942019..0c530c421647 100644 --- a/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md +++ b/samples/openapi3/client/petstore/python/docs/ParentWithOptionalDict.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **optional_dict** | [**Dict[str, InnerDictWithProperty]**](InnerDictWithProperty.md) | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Pet.md b/samples/openapi3/client/petstore/python/docs/Pet.md index 05a466f880a3..cc8fa36537f7 100644 --- a/samples/openapi3/client/petstore/python/docs/Pet.md +++ b/samples/openapi3/client/petstore/python/docs/Pet.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/PetApi.md b/samples/openapi3/client/petstore/python/docs/PetApi.md index 8a0202f37531..05c547865afd 100644 --- a/samples/openapi3/client/petstore/python/docs/PetApi.md +++ b/samples/openapi3/client/petstore/python/docs/PetApi.md @@ -25,9 +25,8 @@ Add a new pet to the store ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -126,6 +125,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -144,6 +144,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -161,9 +162,8 @@ Deletes a pet ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -199,6 +199,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| Pet id to delete | @@ -218,6 +219,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -235,9 +237,8 @@ Multiple status values can be provided with comma separated strings ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -338,6 +339,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **status** | [**List[str]**](str.md)| Status values that need to be considered for filter | @@ -356,6 +358,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -373,9 +376,8 @@ Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -476,6 +478,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **tags** | [**List[str]**](str.md)| Tags to filter by | @@ -494,6 +497,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -511,9 +515,8 @@ Returns a single pet ### Example * Api Key Authentication (api_key): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -555,6 +558,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to return | @@ -573,6 +577,7 @@ Name | Type | Description | Notes - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -591,9 +596,8 @@ Update an existing pet ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.models.pet import Pet from petstore_api.rest import ApiException @@ -692,6 +696,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet** | [**Pet**](Pet.md)| Pet object that needs to be added to the store | @@ -710,6 +715,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -729,9 +735,8 @@ Updates a pet in the store with form data ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -768,6 +773,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet that needs to be updated | @@ -788,6 +794,7 @@ void (empty response body) - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | Successful operation | - | @@ -796,7 +803,7 @@ void (empty response body) [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **upload_file** -> ApiResponse upload_file(pet_id, additional_metadata=additional_metadata, file=file) +> ModelApiResponse upload_file(pet_id, additional_metadata=additional_metadata, file=file) uploads an image @@ -805,11 +812,10 @@ uploads an image ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.rest import ApiException from pprint import pprint @@ -847,6 +853,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | @@ -855,7 +862,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**ModelApiResponse**](ModelApiResponse.md) ### Authorization @@ -867,6 +874,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -874,7 +882,7 @@ Name | Type | Description | Notes [[Back to top]](#) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to Model list]](../README.md#documentation-for-models) [[Back to README]](../README.md) # **upload_file_with_required_file** -> ApiResponse upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) +> ModelApiResponse upload_file_with_required_file(pet_id, required_file, additional_metadata=additional_metadata) uploads an image (required) @@ -883,11 +891,10 @@ uploads an image (required) ### Example * OAuth Authentication (petstore_auth): + ```python -import time -import os import petstore_api -from petstore_api.models.api_response import ApiResponse +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.rest import ApiException from pprint import pprint @@ -925,6 +932,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **pet_id** | **int**| ID of pet to update | @@ -933,7 +941,7 @@ Name | Type | Description | Notes ### Return type -[**ApiResponse**](ApiResponse.md) +[**ModelApiResponse**](ModelApiResponse.md) ### Authorization @@ -945,6 +953,7 @@ Name | Type | Description | Notes - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python/docs/Pig.md b/samples/openapi3/client/petstore/python/docs/Pig.md index 398d6c6c6e38..241a54b33099 100644 --- a/samples/openapi3/client/petstore/python/docs/Pig.md +++ b/samples/openapi3/client/petstore/python/docs/Pig.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **class_name** | **str** | | diff --git a/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md b/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md index 1a9303701b0a..0893df6055d0 100644 --- a/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md +++ b/samples/openapi3/client/petstore/python/docs/PropertyNameCollision.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **underscore_type** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md index 22b5acca70c7..f42def3b2e9c 100644 --- a/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md +++ b/samples/openapi3/client/petstore/python/docs/ReadOnlyFirst.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **bar** | **str** | | [optional] [readonly] diff --git a/samples/openapi3/client/petstore/python/docs/SecondRef.md b/samples/openapi3/client/petstore/python/docs/SecondRef.md index e6fb1e2d4f7c..a1af8f281fa9 100644 --- a/samples/openapi3/client/petstore/python/docs/SecondRef.md +++ b/samples/openapi3/client/petstore/python/docs/SecondRef.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **category** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md b/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md index dbf9589d576b..50f9bf79663d 100644 --- a/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md +++ b/samples/openapi3/client/petstore/python/docs/SelfReferenceModel.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/SingleRefType.md b/samples/openapi3/client/petstore/python/docs/SingleRefType.md index 4178ac3b505e..728e7c214aa3 100644 --- a/samples/openapi3/client/petstore/python/docs/SingleRefType.md +++ b/samples/openapi3/client/petstore/python/docs/SingleRefType.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/SpecialCharacterEnum.md b/samples/openapi3/client/petstore/python/docs/SpecialCharacterEnum.md index 801c3b5c8459..b36a28316577 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialCharacterEnum.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialCharacterEnum.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- diff --git a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md index 3d27640abb04..c59bb655a0d8 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialModelName.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialModelName.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **special_property_name** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/SpecialName.md b/samples/openapi3/client/petstore/python/docs/SpecialName.md index 0b4129525978..2c3491adc6b0 100644 --- a/samples/openapi3/client/petstore/python/docs/SpecialName.md +++ b/samples/openapi3/client/petstore/python/docs/SpecialName.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **var_property** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/StoreApi.md b/samples/openapi3/client/petstore/python/docs/StoreApi.md index 9a4c0ec8c002..19d6a89e5b9f 100644 --- a/samples/openapi3/client/petstore/python/docs/StoreApi.md +++ b/samples/openapi3/client/petstore/python/docs/StoreApi.md @@ -19,9 +19,8 @@ For valid response try integer IDs with value < 1000. Anything above 1000 or non ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -50,6 +49,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order_id** | **str**| ID of the order that needs to be deleted | @@ -68,6 +68,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid ID supplied | - | @@ -85,9 +86,8 @@ Returns a map of status codes to quantities ### Example * Api Key Authentication (api_key): + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -126,6 +126,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -142,6 +143,7 @@ This endpoint does not need any parameter. - **Accept**: application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -157,9 +159,8 @@ For valid response try integer IDs with value <= 5 or > 10. Other values will ge ### Example + ```python -import time -import os import petstore_api from petstore_api.models.order import Order from petstore_api.rest import ApiException @@ -191,6 +192,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order_id** | **int**| ID of pet that needs to be fetched | @@ -209,6 +211,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -226,9 +229,8 @@ Place an order for a pet ### Example + ```python -import time -import os import petstore_api from petstore_api.models.order import Order from petstore_api.rest import ApiException @@ -260,6 +262,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **order** | [**Order**](Order.md)| order placed for purchasing the pet | @@ -278,6 +281,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | diff --git a/samples/openapi3/client/petstore/python/docs/Tag.md b/samples/openapi3/client/petstore/python/docs/Tag.md index e680c68bedd8..a09b1949ce80 100644 --- a/samples/openapi3/client/petstore/python/docs/Tag.md +++ b/samples/openapi3/client/petstore/python/docs/Tag.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md new file mode 100644 index 000000000000..902a9c7c3a74 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel400Response.md @@ -0,0 +1,29 @@ +# TestErrorResponsesWithModel400Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason400** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel400Response from a JSON string +test_error_responses_with_model400_response_instance = TestErrorResponsesWithModel400Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel400Response.to_json() + +# convert the object into a dict +test_error_responses_with_model400_response_dict = test_error_responses_with_model400_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel400Response from a dict +test_error_responses_with_model400_response_form_dict = test_error_responses_with_model400_response.from_dict(test_error_responses_with_model400_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md new file mode 100644 index 000000000000..bbcb7975db78 --- /dev/null +++ b/samples/openapi3/client/petstore/python/docs/TestErrorResponsesWithModel404Response.md @@ -0,0 +1,29 @@ +# TestErrorResponsesWithModel404Response + + +## Properties + +Name | Type | Description | Notes +------------ | ------------- | ------------- | ------------- +**reason404** | **str** | | [optional] + +## Example + +```python +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +# TODO update the JSON string below +json = "{}" +# create an instance of TestErrorResponsesWithModel404Response from a JSON string +test_error_responses_with_model404_response_instance = TestErrorResponsesWithModel404Response.from_json(json) +# print the JSON string representation of the object +print TestErrorResponsesWithModel404Response.to_json() + +# convert the object into a dict +test_error_responses_with_model404_response_dict = test_error_responses_with_model404_response_instance.to_dict() +# create an instance of TestErrorResponsesWithModel404Response from a dict +test_error_responses_with_model404_response_form_dict = test_error_responses_with_model404_response.from_dict(test_error_responses_with_model404_response_dict) +``` +[[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) + + diff --git a/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md b/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md index 7cf86c5244e3..fe79a4322c63 100644 --- a/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md +++ b/samples/openapi3/client/petstore/python/docs/TestInlineFreeformAdditionalPropertiesRequest.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **some_property** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/Tiger.md b/samples/openapi3/client/petstore/python/docs/Tiger.md index 6ce50a31f5ae..2d8b755e9670 100644 --- a/samples/openapi3/client/petstore/python/docs/Tiger.md +++ b/samples/openapi3/client/petstore/python/docs/Tiger.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **skill** | **str** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md index c102bb86bebf..2982c29e5d54 100644 --- a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md +++ b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalModelListProperties.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dict_property** | **Dict[str, List[CreatureInfo]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md index 926404ccd6ee..a06bd36d74cb 100644 --- a/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md +++ b/samples/openapi3/client/petstore/python/docs/UnnamedDictWithAdditionalStringListProperties.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **dict_property** | **Dict[str, List[str]]** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/User.md b/samples/openapi3/client/petstore/python/docs/User.md index 6d7c357ea865..721a9d4401e1 100644 --- a/samples/openapi3/client/petstore/python/docs/User.md +++ b/samples/openapi3/client/petstore/python/docs/User.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **id** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/docs/UserApi.md b/samples/openapi3/client/petstore/python/docs/UserApi.md index 810e75e12717..a1e152924c0c 100644 --- a/samples/openapi3/client/petstore/python/docs/UserApi.md +++ b/samples/openapi3/client/petstore/python/docs/UserApi.md @@ -23,9 +23,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -55,6 +54,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**User**](User.md)| Created user object | @@ -73,6 +73,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -88,9 +89,8 @@ Creates list of users with given input array ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -120,6 +120,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**List[User]**](User.md)| List of user object | @@ -138,6 +139,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -153,9 +155,8 @@ Creates list of users with given input array ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -185,6 +186,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **user** | [**List[User]**](User.md)| List of user object | @@ -203,6 +205,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -218,9 +221,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -249,6 +251,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The name that needs to be deleted | @@ -267,6 +270,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid username supplied | - | @@ -283,9 +287,8 @@ Get user by user name ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -317,6 +320,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The name that needs to be fetched. Use user1 for testing. | @@ -335,6 +339,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | - | @@ -352,9 +357,8 @@ Logs user into the system ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -386,6 +390,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| The user name for login | @@ -405,6 +410,7 @@ No authorization required - **Accept**: application/xml, application/json ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **200** | successful operation | * X-Rate-Limit - calls per hour allowed by the user
              * X-Expires-After - date in UTC when token expires
              | @@ -421,9 +427,8 @@ Logs out current logged in user session ### Example + ```python -import time -import os import petstore_api from petstore_api.rest import ApiException from pprint import pprint @@ -450,6 +455,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + This endpoint does not need any parameter. ### Return type @@ -466,6 +472,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **0** | successful operation | - | @@ -481,9 +488,8 @@ This can only be done by the logged in user. ### Example + ```python -import time -import os import petstore_api from petstore_api.models.user import User from petstore_api.rest import ApiException @@ -514,6 +520,7 @@ with petstore_api.ApiClient(configuration) as api_client: ### Parameters + Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- **username** | **str**| name that need to be deleted | @@ -533,6 +540,7 @@ No authorization required - **Accept**: Not defined ### HTTP response details + | Status code | Description | Response headers | |-------------|-------------|------------------| **400** | Invalid user supplied | - | diff --git a/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md b/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md index 247afcab99da..c46f89e66f1d 100644 --- a/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md +++ b/samples/openapi3/client/petstore/python/docs/WithNestedOneOf.md @@ -2,6 +2,7 @@ ## Properties + Name | Type | Description | Notes ------------ | ------------- | ------------- | ------------- **size** | **int** | | [optional] diff --git a/samples/openapi3/client/petstore/python/petstore_api/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/__init__.py index c1c56eb81159..f791bc531127 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/__init__.py @@ -46,7 +46,6 @@ from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor from petstore_api.models.any_of_pig import AnyOfPig -from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.models.array_of_number_only import ArrayOfNumberOnly @@ -85,6 +84,7 @@ from petstore_api.models.map_test import MapTest from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.models.model200_response import Model200Response +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.model_return import ModelReturn from petstore_api.models.name import Name from petstore_api.models.nullable_class import NullableClass @@ -113,6 +113,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py index 0ecf79068174..fbf76bad47a4 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/another_fake_api.py @@ -11,24 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import Field from typing_extensions import Annotated from petstore_api.models.client import Client -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class AnotherFakeApi: @@ -43,161 +37,272 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def call_123_test_special_tags( self, client: Annotated[Client, Field(description="client model")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Client: - """To test special tags # noqa: E501 + """To test special tags - To test special tags and operation ID starting with number # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.call_123_test_special_tags(client, async_req=True) - >>> result = thread.get() + To test special tags and operation ID starting with number :param client: client model (required) :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the call_123_test_special_tags_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.call_123_test_special_tags_with_http_info.raw_function( - client, - **kwargs, + """ # noqa: E501 + + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def call_123_test_special_tags_with_http_info( self, client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test special tags # noqa: E501 - - To test special tags and operation ID starting with number # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test special tags - >>> thread = api.call_123_test_special_tags_with_http_info(client, async_req=True) - >>> result = thread.get() + To test special tags and operation ID starting with number :param client: client model (required) :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def call_123_test_special_tags_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test special tags + + To test special tags and operation ID starting with number + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._call_123_test_special_tags_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method call_123_test_special_tags" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _call_123_test_special_tags_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + if client is not None: + _body_params = client + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/another-fake/dummy', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PATCH', + resource_path='/another-fake/dummy', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py index ee965a8422d8..a53204ffc755 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/default_api.py @@ -11,22 +11,16 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from petstore_api.models.foo_get_default_response import FooGetDefaultResponse -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class DefaultApi: @@ -41,140 +35,238 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def foo_get( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> FooGetDefaultResponse: - """foo_get # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """foo_get - >>> thread = api.foo_get(async_req=True) - >>> result = thread.get() - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: FooGetDefaultResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the foo_get_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.foo_get_with_http_info.raw_function( - **kwargs, + """ # noqa: E501 + + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def foo_get_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """foo_get # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.foo_get_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[FooGetDefaultResponse]: + """foo_get + + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(FooGetDefaultResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def foo_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """foo_get + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._foo_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method foo_get" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _foo_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/foo', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/foo', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py index 8e2dcdcb672a..8323fe6a0806 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_api.py @@ -11,22 +11,15 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from datetime import date, datetime - -from pydantic import StrictBool, StrictBytes, StrictFloat, StrictInt, StrictStr, field_validator +from datetime import date, datetime +from pydantic import Field, StrictBool, StrictBytes, StrictFloat, StrictInt, StrictStr, field_validator from typing import Any, Dict, List, Optional, Union - +from typing_extensions import Annotated from petstore_api.models.client import Client from petstore_api.models.enum_class import EnumClass from petstore_api.models.file_schema_test_class import FileSchemaTestClass @@ -38,12 +31,9 @@ from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.user import User -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class FakeApi: @@ -58,439 +48,756 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def fake_any_type_request_body( self, body: Optional[Dict[str, Any]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test any type request body # noqa: E501 + """test any type request body - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.fake_any_type_request_body(body, async_req=True) - >>> result = thread.get() :param body: :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_any_type_request_body_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_any_type_request_body_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_any_type_request_body_with_http_info( self, body: Optional[Dict[str, Any]] = None, - **kwargs, - ) -> ApiResponse: - """test any type request body # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test any type request body + + + :param body: + :type body: object + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def fake_any_type_request_body_without_preload_content( + self, + body: Optional[Dict[str, Any]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test any type request body - >>> thread = api.fake_any_type_request_body_with_http_info(body, async_req=True) - >>> result = thread.get() :param body: :type body: object - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_any_type_request_body_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_any_type_request_body" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _fake_any_type_request_body_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/any_type_body', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/any_type_body', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_enum_ref_query_parameter( self, enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test enum reference query parameter # noqa: E501 + """test enum reference query parameter - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.fake_enum_ref_query_parameter(enum_ref, async_req=True) - >>> result = thread.get() :param enum_ref: enum reference :type enum_ref: EnumClass - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_enum_ref_query_parameter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_enum_ref_query_parameter_with_http_info.raw_function( - enum_ref, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_enum_ref_query_parameter_with_http_info( self, enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, - **kwargs, - ) -> ApiResponse: - """test enum reference query parameter # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test enum reference query parameter + + + :param enum_ref: enum reference + :type enum_ref: EnumClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def fake_enum_ref_query_parameter_without_preload_content( + self, + enum_ref: Annotated[Optional[EnumClass], Field(description="enum reference")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test enum reference query parameter - >>> thread = api.fake_enum_ref_query_parameter_with_http_info(enum_ref, async_req=True) - >>> result = thread.get() :param enum_ref: enum reference :type enum_ref: EnumClass - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_enum_ref_query_parameter_serialize( + enum_ref=enum_ref, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'enum_ref' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_enum_ref_query_parameter" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _fake_enum_ref_query_parameter_serialize( + self, + enum_ref, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None - # process the path parameters - _path_params: Dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - # process the query parameters + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('enum_ref') is not None: # noqa: E501 - _query_params.append(('enum_ref', _params['enum_ref'].value)) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if enum_ref is not None: + + _query_params.append(('enum_ref', enum_ref.value)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake/enum_ref_query_parameter', 'GET', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/enum_ref_query_parameter', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_health_get( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> HealthCheckResult: - """Health check endpoint # noqa: E501 + """Health check endpoint - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.fake_health_get(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: HealthCheckResult - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_health_get_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_health_get_with_http_info.raw_function( - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_health_get_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Health check endpoint # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[HealthCheckResult]: + """Health check endpoint + - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fake_health_get_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Health check endpoint - >>> thread = api.fake_health_get_with_http_info(async_req=True) - >>> result = thread.get() - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(HealthCheckResult, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_health_get_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_health_get" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "HealthCheckResult", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_health_get_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "HealthCheckResult", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/health', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/health', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_http_signature_test( @@ -498,15 +805,21 @@ def fake_http_signature_test( pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test http signature authentication # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """test http signature authentication - >>> thread = api.fake_http_signature_test(pet, query_1, header_1, async_req=True) - >>> result = thread.get() :param pet: Pet object that needs to be added to the store (required) :type pet: Pet @@ -514,28 +827,51 @@ def fake_http_signature_test( :type query_1: str :param header_1: header parameter :type header_1: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_http_signature_test_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.fake_http_signature_test_with_http_info.raw_function( - pet, - query_1, - header_1, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_http_signature_test_with_http_info( @@ -543,15 +879,21 @@ def fake_http_signature_test_with_http_info( pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, - **kwargs, - ) -> ApiResponse: - """test http signature authentication # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test http signature authentication - >>> thread = api.fake_http_signature_test_with_http_info(pet, query_1, header_1, async_req=True) - >>> result = thread.get() :param pet: Pet object that needs to be added to the store (required) :type pet: Pet @@ -559,1982 +901,4269 @@ def fake_http_signature_test_with_http_info( :type query_1: str :param header_1: header parameter :type header_1: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'pet', - 'query_1', - 'header_1' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_http_signature_test" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def fake_http_signature_test_without_preload_content( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + query_1: Annotated[Optional[StrictStr], Field(description="query parameter")] = None, + header_1: Annotated[Optional[StrictStr], Field(description="header parameter")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test http signature authentication - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('query_1') is not None: # noqa: E501 - _query_params.append(('query_1', _params['query_1'])) - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['header_1'] is not None: - _header_params['header_1'] = _params['header_1'] + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param query_1: query parameter + :type query_1: str + :param header_1: header parameter + :type header_1: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_http_signature_test_serialize( + pet=pet, + query_1=query_1, + header_1=header_1, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - # process the form parameters + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fake_http_signature_test_serialize( + self, + pet, + query_1, + header_1, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if query_1 is not None: + + _query_params.append(('query_1', query_1)) + + # process the header parameters + if header_1 is not None: + _header_params['header_1'] = header_1 + # process the form parameters # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'http_signature_test' + ] - return self.api_client.call_api( - '/fake/http-signature-test', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/http-signature-test', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_outer_boolean_serialize( self, body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> bool: - """fake_outer_boolean_serialize # noqa: E501 - - Test serialization of outer boolean types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """fake_outer_boolean_serialize - >>> thread = api.fake_outer_boolean_serialize(body, async_req=True) - >>> result = thread.get() + Test serialization of outer boolean types :param body: Input boolean as post body :type body: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: bool - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_boolean_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_outer_boolean_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_outer_boolean_serialize_with_http_info( self, body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_boolean_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[bool]: + """fake_outer_boolean_serialize + + Test serialization of outer boolean types + + :param body: Input boolean as post body + :type body: bool + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - Test serialization of outer boolean types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.fake_outer_boolean_serialize_with_http_info(body, async_req=True) - >>> result = thread.get() + @validate_call + def fake_outer_boolean_serialize_without_preload_content( + self, + body: Annotated[Optional[StrictBool], Field(description="Input boolean as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_boolean_serialize + + Test serialization of outer boolean types :param body: Input boolean as post body :type body: bool - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(bool, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_boolean_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "bool", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_boolean_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _fake_outer_boolean_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "bool", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/outer/boolean', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/boolean', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_outer_composite_serialize( self, outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> OuterComposite: - """fake_outer_composite_serialize # noqa: E501 - - Test serialization of object with outer number type # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """fake_outer_composite_serialize - >>> thread = api.fake_outer_composite_serialize(outer_composite, async_req=True) - >>> result = thread.get() + Test serialization of object with outer number type :param outer_composite: Input composite as post body :type outer_composite: OuterComposite - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: OuterComposite - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_composite_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_outer_composite_serialize_with_http_info.raw_function( - outer_composite, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_outer_composite_serialize_with_http_info( self, outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_composite_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[OuterComposite]: + """fake_outer_composite_serialize + + Test serialization of object with outer number type + + :param outer_composite: Input composite as post body + :type outer_composite: OuterComposite + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - Test serialization of object with outer number type # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.fake_outer_composite_serialize_with_http_info(outer_composite, async_req=True) - >>> result = thread.get() + @validate_call + def fake_outer_composite_serialize_without_preload_content( + self, + outer_composite: Annotated[Optional[OuterComposite], Field(description="Input composite as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_composite_serialize + + Test serialization of object with outer number type :param outer_composite: Input composite as post body :type outer_composite: OuterComposite - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(OuterComposite, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_composite_serialize_serialize( + outer_composite=outer_composite, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterComposite", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _all_params = [ - 'outer_composite' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_composite_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _fake_outer_composite_serialize_serialize( + self, + outer_composite, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['outer_composite'] is not None: - _body_params = _params['outer_composite'] + if outer_composite is not None: + _body_params = outer_composite + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "OuterComposite", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/outer/composite', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/composite', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_outer_number_serialize( self, body: Annotated[Optional[StrictFloat], Field(description="Input number as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> float: - """fake_outer_number_serialize # noqa: E501 - - Test serialization of outer number types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """fake_outer_number_serialize - >>> thread = api.fake_outer_number_serialize(body, async_req=True) - >>> result = thread.get() + Test serialization of outer number types :param body: Input number as post body :type body: float - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: float - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_number_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_outer_number_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_outer_number_serialize_with_http_info( self, body: Annotated[Optional[StrictFloat], Field(description="Input number as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_number_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[float]: + """fake_outer_number_serialize + + Test serialization of outer number types + + :param body: Input number as post body + :type body: float + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - Test serialization of outer number types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.fake_outer_number_serialize_with_http_info(body, async_req=True) - >>> result = thread.get() + @validate_call + def fake_outer_number_serialize_without_preload_content( + self, + body: Annotated[Optional[StrictFloat], Field(description="Input number as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_number_serialize + + Test serialization of outer number types :param body: Input number as post body :type body: float - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(float, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_number_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "float", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_number_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _fake_outer_number_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 + _auth_settings: List[str] = [ + ] - _response_types_map: Dict[str, Optional[str]] = { - '200': "float", - } - - return self.api_client.call_api( - '/fake/outer/number', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/number', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_outer_string_serialize( self, body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """fake_outer_string_serialize # noqa: E501 - - Test serialization of outer string types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """fake_outer_string_serialize - >>> thread = api.fake_outer_string_serialize(body, async_req=True) - >>> result = thread.get() + Test serialization of outer string types :param body: Input string as post body :type body: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_outer_string_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_outer_string_serialize_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_outer_string_serialize_with_http_info( self, body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, - **kwargs, - ) -> ApiResponse: - """fake_outer_string_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """fake_outer_string_serialize + + Test serialization of outer string types + + :param body: Input string as post body + :type body: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - Test serialization of outer string types # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.fake_outer_string_serialize_with_http_info(body, async_req=True) - >>> result = thread.get() + @validate_call + def fake_outer_string_serialize_without_preload_content( + self, + body: Annotated[Optional[StrictStr], Field(description="Input string as post body")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_outer_string_serialize + + Test serialization of outer string types :param body: Input string as post body :type body: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_outer_string_serialize_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_outer_string_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _fake_outer_string_serialize_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] + if body is not None: + _body_params = body + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/outer/string', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/outer/string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def fake_property_enum_integer_serialize( self, outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> OuterObjectWithEnumProperty: - """fake_property_enum_integer_serialize # noqa: E501 - - Test serialization of enum (int) properties with examples # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """fake_property_enum_integer_serialize - >>> thread = api.fake_property_enum_integer_serialize(outer_object_with_enum_property, async_req=True) - >>> result = thread.get() + Test serialization of enum (int) properties with examples :param outer_object_with_enum_property: Input enum (int) as post body (required) :type outer_object_with_enum_property: OuterObjectWithEnumProperty - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: OuterObjectWithEnumProperty - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_property_enum_integer_serialize_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.fake_property_enum_integer_serialize_with_http_info.raw_function( - outer_object_with_enum_property, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def fake_property_enum_integer_serialize_with_http_info( self, outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], - **kwargs, - ) -> ApiResponse: - """fake_property_enum_integer_serialize # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[OuterObjectWithEnumProperty]: + """fake_property_enum_integer_serialize + + Test serialization of enum (int) properties with examples - Test serialization of enum (int) properties with examples # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + :param outer_object_with_enum_property: Input enum (int) as post body (required) + :type outer_object_with_enum_property: OuterObjectWithEnumProperty + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fake_property_enum_integer_serialize_without_preload_content( + self, + outer_object_with_enum_property: Annotated[OuterObjectWithEnumProperty, Field(description="Input enum (int) as post body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """fake_property_enum_integer_serialize - >>> thread = api.fake_property_enum_integer_serialize_with_http_info(outer_object_with_enum_property, async_req=True) - >>> result = thread.get() + Test serialization of enum (int) properties with examples :param outer_object_with_enum_property: Input enum (int) as post body (required) :type outer_object_with_enum_property: OuterObjectWithEnumProperty - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(OuterObjectWithEnumProperty, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._fake_property_enum_integer_serialize_serialize( + outer_object_with_enum_property=outer_object_with_enum_property, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "OuterObjectWithEnumProperty", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _all_params = [ - 'outer_object_with_enum_property' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_property_enum_integer_serialize" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _fake_property_enum_integer_serialize_serialize( + self, + outer_object_with_enum_property, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['outer_object_with_enum_property'] is not None: - _body_params = _params['outer_object_with_enum_property'] + if outer_object_with_enum_property is not None: + _body_params = outer_object_with_enum_property + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['*/*']) # noqa: E501 + [ + '*/*' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "OuterObjectWithEnumProperty", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/property/enum-int', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/property/enum-int', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - def fake_return_list_of_objects( + def fake_ref_enum_string( self, - **kwargs, - ) -> List[List[Tag]]: - """test returning list of objects # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> EnumClass: + """test ref to enum string - >>> thread = api.fake_return_list_of_objects(async_req=True) - >>> result = thread.get() - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[List[Tag]] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_return_list_of_objects_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return self.fake_return_list_of_objects_with_http_info.raw_function( - **kwargs, + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "EnumClass", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - def fake_return_list_of_objects_with_http_info( + def fake_ref_enum_string_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """test returning list of objects # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[EnumClass]: + """test ref to enum string + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "EnumClass", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def fake_ref_enum_string_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test ref to enum string - >>> thread = api.fake_return_list_of_objects_with_http_info(async_req=True) - >>> result = thread.get() - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[List[Tag]], status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_ref_enum_string_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_return_list_of_objects" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "EnumClass", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _fake_ref_enum_string_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'plain/text' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[List[Tag]]", - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/return_list_of_object', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/ref_enum_string', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - def fake_uuid_example( - self, - uuid_example: Annotated[StrictStr, Field(description="uuid example")], - **kwargs, - ) -> None: - """test uuid example # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _host=_host, + _request_auth=_request_auth + ) - >>> thread = api.fake_uuid_example(uuid_example, async_req=True) - >>> result = thread.get() - :param uuid_example: uuid example (required) - :type uuid_example: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the fake_uuid_example_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.fake_uuid_example_with_http_info.raw_function( - uuid_example, - **kwargs, - ) @validate_call - def fake_uuid_example_with_http_info( + def fake_return_list_of_objects( self, - uuid_example: Annotated[StrictStr, Field(description="uuid example")], - **kwargs, - ) -> ApiResponse: - """test uuid example # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> List[List[Tag]]: + """test returning list of objects - >>> thread = api.fake_uuid_example_with_http_info(uuid_example, async_req=True) - >>> result = thread.get() - :param uuid_example: uuid example (required) - :type uuid_example: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 - _params = locals() + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'uuid_example' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method fake_uuid_example" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + @validate_call + def fake_return_list_of_objects_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[List[Tag]]]: + """test returning list of objects - # process the query parameters + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fake_return_list_of_objects_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test returning list of objects + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_return_list_of_objects_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[List[Tag]]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _fake_return_list_of_objects_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('uuid_example') is not None: # noqa: E501 - _query_params.append(('uuid_example', _params['uuid_example'])) + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake/uuid_example', 'GET', - _path_params, - _query_params, - _header_params, + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/return_list_of_object', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - def test_body_with_binary( + def fake_uuid_example( self, - body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], - **kwargs, + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test_body_with_binary # noqa: E501 + """test uuid example - For this test, the body has to be a binary file. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_body_with_binary(body, async_req=True) - >>> result = thread.get() - - :param body: image to upload (required) - :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param uuid_example: uuid example (required) + :type uuid_example: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_binary_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_with_binary_with_http_info.raw_function( - body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call - def test_body_with_binary_with_http_info( + def fake_uuid_example_with_http_info( self, - body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], - **kwargs, - ) -> ApiResponse: - """test_body_with_binary # noqa: E501 + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test uuid example - For this test, the body has to be a binary file. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - >>> thread = api.test_body_with_binary_with_http_info(body, async_req=True) - >>> result = thread.get() + :param uuid_example: uuid example (required) + :type uuid_example: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - :param body: image to upload (required) - :type body: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def fake_uuid_example_without_preload_content( + self, + uuid_example: Annotated[StrictStr, Field(description="uuid example")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test uuid example + + + :param uuid_example: uuid example (required) + :type uuid_example: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._fake_uuid_example_serialize( + uuid_example=uuid_example, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_binary" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _fake_uuid_example_serialize( + self, + uuid_example, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] + if uuid_example is not None: + + _query_params.append(('uuid_example', uuid_example)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['body'] is not None: - _body_params = _params['body'] - # convert to byte array if the input is a file name (str) - if isinstance(_body_params, str): - with io.open(_body_params, "rb") as _fp: - _body_params_from_file = _fp.read() - _body_params = _body_params_from_file - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['image/png'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake/body-with-binary', 'PUT', - _path_params, - _query_params, - _header_params, + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/uuid_example', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call - def test_body_with_file_schema( + def test_additional_properties_reference( self, - file_schema_test_class: FileSchemaTestClass, - **kwargs, + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test_body_with_file_schema # noqa: E501 + """test referenced additionalProperties + + - For this test, the body for this request must reference a schema named `File`. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data - >>> thread = api.test_body_with_file_schema(file_schema_test_class, async_req=True) - >>> result = thread.get() - :param file_schema_test_class: (required) - :type file_schema_test_class: FileSchemaTestClass - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + @validate_call + def test_additional_properties_reference_with_http_info( + self, + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test referenced additionalProperties + + + + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_file_schema_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_body_with_file_schema_with_http_info.raw_function( - file_schema_test_class, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - def test_body_with_file_schema_with_http_info( + def test_additional_properties_reference_without_preload_content( self, - file_schema_test_class: FileSchemaTestClass, - **kwargs, - ) -> ApiResponse: - """test_body_with_file_schema # noqa: E501 + request_body: Annotated[Dict[str, Any], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test referenced additionalProperties - For this test, the body for this request must reference a schema named `File`. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + - >>> thread = api.test_body_with_file_schema_with_http_info(file_schema_test_class, async_req=True) - >>> result = thread.get() + :param request_body: request body (required) + :type request_body: Dict[str, object] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_additional_properties_reference_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - :param file_schema_test_class: (required) - :type file_schema_test_class: FileSchemaTestClass - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_additional_properties_reference_serialize( + self, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if request_body is not None: + _body_params = request_body + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/additionalProperties-reference', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_body_with_binary( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_body_with_binary_with_http_info( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_body_with_binary_without_preload_content( + self, + body: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="image to upload")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_binary + + For this test, the body has to be a binary file. + + :param body: image to upload (required) + :type body: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_binary_serialize( + body=body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_binary_serialize( + self, + body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if body is not None: + # convert to byte array if the input is a file name (str) + if isinstance(body, str): + with open(body, "rb") as _fp: + _body_params = _fp.read() + else: + _body_params = body + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'image/png' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-binary', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_body_with_file_schema( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_body_with_file_schema_with_http_info( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_body_with_file_schema_without_preload_content( + self, + file_schema_test_class: FileSchemaTestClass, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_file_schema + + For this test, the body for this request must reference a schema named `File`. + + :param file_schema_test_class: (required) + :type file_schema_test_class: FileSchemaTestClass + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_file_schema_serialize( + file_schema_test_class=file_schema_test_class, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_file_schema_serialize( + self, + file_schema_test_class, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if file_schema_test_class is not None: + _body_params = file_schema_test_class + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-file-schema', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_body_with_query_params( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_body_with_query_params_with_http_info( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_body_with_query_params_without_preload_content( + self, + query: StrictStr, + user: User, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_body_with_query_params + + + :param query: (required) + :type query: str + :param user: (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_body_with_query_params_serialize( + query=query, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_body_with_query_params_serialize( + self, + query, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if query is not None: + + _query_params.append(('query', query)) + + # process the header parameters + # process the form parameters + # process the body parameter + if user is not None: + _body_params = user + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/body-with-query-params', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_client_model( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> Client: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_client_model_with_http_info( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_client_model_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test \"client\" model + + To test \"client\" model + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_client_model_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _test_client_model_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + if client is not None: + _body_params = client + + + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PATCH', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_date_time_query_parameter( + self, + date_time_query: datetime, + str_query: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test_date_time_query_parameter + + + :param date_time_query: (required) + :type date_time_query: datetime + :param str_query: (required) + :type str_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_date_time_query_parameter_with_http_info( + self, + date_time_query: datetime, + str_query: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_date_time_query_parameter + + + :param date_time_query: (required) + :type date_time_query: datetime + :param str_query: (required) + :type str_query: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def test_date_time_query_parameter_without_preload_content( + self, + date_time_query: datetime, + str_query: StrictStr, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_date_time_query_parameter + + + :param date_time_query: (required) + :type date_time_query: datetime + :param str_query: (required) + :type str_query: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_date_time_query_parameter_serialize( + date_time_query=date_time_query, + str_query=str_query, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'file_schema_test_class' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_file_schema" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _test_date_time_query_parameter_serialize( + self, + date_time_query, + str_query, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] + if date_time_query is not None: + if isinstance(date_time_query, datetime): + _query_params.append( + ( + 'date_time_query', + date_time_query.strftime( + self.api_client.configuration.datetime_format + ) + ) + ) + else: + _query_params.append(('date_time_query', date_time_query)) + + if str_query is not None: + + _query_params.append(('str_query', str_query)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['file_schema_test_class'] is not None: - _body_params = _params['file_schema_test_class'] - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake/body-with-file-schema', 'PUT', - _path_params, - _query_params, - _header_params, + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/date-time-query-params', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - def test_body_with_query_params( - self, - query: StrictStr, - user: User, - **kwargs, - ) -> None: - """test_body_with_query_params # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _host=_host, + _request_auth=_request_auth + ) - >>> thread = api.test_body_with_query_params(query, user, async_req=True) - >>> result = thread.get() - :param query: (required) - :type query: str - :param user: (required) - :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_body_with_query_params_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.test_body_with_query_params_with_http_info.raw_function( - query, - user, - **kwargs, - ) @validate_call - def test_body_with_query_params_with_http_info( + def test_empty_and_non_empty_responses( self, - query: StrictStr, - user: User, - **kwargs, - ) -> ApiResponse: - """test_body_with_query_params # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test empty and non-empty responses - >>> thread = api.test_body_with_query_params_with_http_info(query, user, async_req=True) - >>> result = thread.get() + - :param query: (required) - :type query: str - :param user: (required) - :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'query', - 'user' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_body_with_query_params" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats: Dict[str, str] = {} - - # process the path parameters - _path_params: Dict[str, str] = {} - - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('query') is not None: # noqa: E501 - _query_params.append(('query', _params['query'])) + """ # noqa: E501 - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] - - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.api_client.call_api( - '/fake/body-with-query-params', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + ).data + @validate_call - def test_client_model( + def test_empty_and_non_empty_responses_with_http_info( self, - client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> Client: - """To test \"client\" model # noqa: E501 - - To test \"client\" model # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test empty and non-empty responses - >>> thread = api.test_client_model(client, async_req=True) - >>> result = thread.get() + - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_client_model_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_client_model_with_http_info.raw_function( - client, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - def test_client_model_with_http_info( + def test_empty_and_non_empty_responses_without_preload_content( self, - client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test \"client\" model # noqa: E501 - - To test \"client\" model # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test empty and non-empty responses - >>> thread = api.test_client_model_with_http_info(client, async_req=True) - >>> result = thread.get() + - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._test_empty_and_non_empty_responses_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_client_model" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '206': "str", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_empty_and_non_empty_responses_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'text/plain' + ] + ) - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/empty_and_non_empty_responses', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) - - @validate_call - def test_date_time_query_parameter( - self, - date_time_query: datetime, - str_query: StrictStr, - **kwargs, - ) -> None: - """test_date_time_query_parameter # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _host=_host, + _request_auth=_request_auth + ) - >>> thread = api.test_date_time_query_parameter(date_time_query, str_query, async_req=True) - >>> result = thread.get() - :param date_time_query: (required) - :type date_time_query: datetime - :param str_query: (required) - :type str_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_date_time_query_parameter_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - return self.test_date_time_query_parameter_with_http_info.raw_function( - date_time_query, - str_query, - **kwargs, - ) @validate_call - def test_date_time_query_parameter_with_http_info( + def test_endpoint_parameters( self, - date_time_query: datetime, - str_query: StrictStr, - **kwargs, - ) -> ApiResponse: - """test_date_time_query_parameter # noqa: E501 - - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + number: Annotated[float, Field(le=543.2, strict=True, ge=32.1, description="None")], + double: Annotated[float, Field(le=123.4, strict=True, ge=67.8, description="None")], + pattern_without_delimiter: Annotated[str, Field(strict=True, description="None")], + byte: Annotated[Union[StrictBytes, StrictStr], Field(description="None")], + integer: Annotated[Optional[Annotated[int, Field(le=100, strict=True, ge=10)]], Field(description="None")] = None, + int32: Annotated[Optional[Annotated[int, Field(le=200, strict=True, ge=20)]], Field(description="None")] = None, + int64: Annotated[Optional[StrictInt], Field(description="None")] = None, + var_float: Annotated[Optional[Annotated[float, Field(le=987.6, strict=True)]], Field(description="None")] = None, + string: Annotated[Optional[Annotated[str, Field(strict=True)]], Field(description="None")] = None, + binary: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="None")] = None, + byte_with_max_length: Annotated[Optional[Union[Annotated[bytes, Field(strict=True, max_length=64)], Annotated[str, Field(strict=True, max_length=64)]]], Field(description="None")] = None, + var_date: Annotated[Optional[date], Field(description="None")] = None, + date_time: Annotated[Optional[datetime], Field(description="None")] = None, + password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, + param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - >>> thread = api.test_date_time_query_parameter_with_http_info(date_time_query, str_query, async_req=True) - >>> result = thread.get() + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - :param date_time_query: (required) - :type date_time_query: datetime - :param str_query: (required) - :type str_query: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + :param number: None (required) + :type number: float + :param double: None (required) + :type double: float + :param pattern_without_delimiter: None (required) + :type pattern_without_delimiter: str + :param byte: None (required) + :type byte: bytearray + :param integer: None + :type integer: int + :param int32: None + :type int32: int + :param int64: None + :type int64: int + :param var_float: None + :type var_float: float + :param string: None + :type string: str + :param binary: None + :type binary: bytearray + :param byte_with_max_length: None + :type byte_with_max_length: bytearray + :param var_date: None + :type var_date: date + :param date_time: None + :type date_time: datetime + :param password: None + :type password: str + :param param_callback: None + :type param_callback: str :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'date_time_query', - 'str_query' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_date_time_query_parameter" % _key - ) - _params[_key] = _val - del _params['kwargs'] - - _collection_formats: Dict[str, str] = {} - - # process the path parameters - _path_params: Dict[str, str] = {} - - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('date_time_query') is not None: # noqa: E501 - if isinstance(_params['date_time_query'], datetime): - _query_params.append(('date_time_query', _params['date_time_query'].strftime(self.api_client.configuration.datetime_format))) - else: - _query_params.append(('date_time_query', _params['date_time_query'])) - - if _params.get('str_query') is not None: # noqa: E501 - _query_params.append(('str_query', _params['str_query'])) - - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.api_client.call_api( - '/fake/date-time-query-params', 'PUT', - _path_params, - _query_params, - _header_params, - body=_body_params, - post_params=_form_params, - files=_files, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, response_types_map=_response_types_map, - auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + ).data + @validate_call - def test_endpoint_parameters( + def test_endpoint_parameters_with_http_info( self, number: Annotated[float, Field(le=543.2, strict=True, ge=32.1, description="None")], double: Annotated[float, Field(le=123.4, strict=True, ge=67.8, description="None")], @@ -2551,16 +5180,22 @@ def test_endpoint_parameters( date_time: Annotated[Optional[datetime], Field(description="None")] = None, password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, - **kwargs, - ) -> None: - """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - >>> thread = api.test_endpoint_parameters(number, double, pattern_without_delimiter, byte, integer, int32, int64, var_float, string, binary, byte_with_max_length, var_date, date_time, password, param_callback, async_req=True) - >>> result = thread.get() + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 :param number: None (required) :type number: float @@ -2592,43 +5227,67 @@ def test_endpoint_parameters( :type password: str :param param_callback: None :type param_callback: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_endpoint_parameters_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_endpoint_parameters_with_http_info.raw_function( - number, - double, - pattern_without_delimiter, - byte, - integer, - int32, - int64, - var_float, - string, - binary, - byte_with_max_length, - var_date, - date_time, - password, - param_callback, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + @validate_call - def test_endpoint_parameters_with_http_info( + def test_endpoint_parameters_without_preload_content( self, number: Annotated[float, Field(le=543.2, strict=True, ge=32.1, description="None")], double: Annotated[float, Field(le=123.4, strict=True, ge=67.8, description="None")], @@ -2645,16 +5304,22 @@ def test_endpoint_parameters_with_http_info( date_time: Annotated[Optional[datetime], Field(description="None")] = None, password: Annotated[Optional[Annotated[str, Field(min_length=10, strict=True, max_length=64)]], Field(description="None")] = None, param_callback: Annotated[Optional[StrictStr], Field(description="None")] = None, - **kwargs, - ) -> ApiResponse: - """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - - Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 - >>> thread = api.test_endpoint_parameters_with_http_info(number, double, pattern_without_delimiter, byte, integer, int32, int64, var_float, string, binary, byte_with_max_length, var_date, date_time, password, param_callback, async_req=True) - >>> result = thread.get() + Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트 :param number: None (required) :type number: float @@ -2686,159 +5351,415 @@ def test_endpoint_parameters_with_http_info( :type password: str :param param_callback: None :type param_callback: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'number', - 'double', - 'pattern_without_delimiter', - 'byte', - 'integer', - 'int32', - 'int64', - 'var_float', - 'string', - 'binary', - 'byte_with_max_length', - 'var_date', - 'date_time', - 'password', - 'param_callback' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_endpoint_parameters" % _key - ) - _params[_key] = _val - del _params['kwargs'] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_endpoint_parameters_serialize( + number=number, + double=double, + pattern_without_delimiter=pattern_without_delimiter, + byte=byte, + integer=integer, + int32=int32, + int64=int64, + var_float=var_float, + string=string, + binary=binary, + byte_with_max_length=byte_with_max_length, + var_date=var_date, + date_time=date_time, + password=password, + param_callback=param_callback, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_endpoint_parameters_serialize( + self, + number, + double, + pattern_without_delimiter, + byte, + integer, + int32, + int64, + var_float, + string, + binary, + byte_with_max_length, + var_date, + date_time, + password, + param_callback, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['integer'] is not None: - _form_params.append(('integer', _params['integer'])) + if integer is not None: + _form_params.append(('integer', integer)) + if int32 is not None: + _form_params.append(('int32', int32)) + if int64 is not None: + _form_params.append(('int64', int64)) + if number is not None: + _form_params.append(('number', number)) + if var_float is not None: + _form_params.append(('float', var_float)) + if double is not None: + _form_params.append(('double', double)) + if string is not None: + _form_params.append(('string', string)) + if pattern_without_delimiter is not None: + _form_params.append(('pattern_without_delimiter', pattern_without_delimiter)) + if byte is not None: + _form_params.append(('byte', byte)) + if binary is not None: + _files['binary'] = binary + if byte_with_max_length is not None: + _form_params.append(('byte_with_max_length', byte_with_max_length)) + if var_date is not None: + _form_params.append(('date', var_date)) + if date_time is not None: + _form_params.append(('dateTime', date_time)) + if password is not None: + _form_params.append(('password', password)) + if param_callback is not None: + _form_params.append(('callback', param_callback)) + # process the body parameter + + + + # set the HTTP header `Content-Type` + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type + + # authentication setting + _auth_settings: List[str] = [ + 'http_basic_test' + ] + + return self.api_client.param_serialize( + method='POST', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, + body=_body_params, + post_params=_form_params, + files=_files, + auth_settings=_auth_settings, + collection_formats=_collection_formats, + _host=_host, + _request_auth=_request_auth + ) + + + + + @validate_call + def test_error_responses_with_model( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> None: + """test error responses with model + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + + @validate_call + def test_error_responses_with_model_with_http_info( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test error responses with model + - if _params['int32'] is not None: - _form_params.append(('int32', _params['int32'])) + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 - if _params['int64'] is not None: - _form_params.append(('int64', _params['int64'])) + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['number'] is not None: - _form_params.append(('number', _params['number'])) + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - if _params['var_float'] is not None: - _form_params.append(('float', _params['var_float'])) - if _params['double'] is not None: - _form_params.append(('double', _params['double'])) + @validate_call + def test_error_responses_with_model_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test error responses with model - if _params['string'] is not None: - _form_params.append(('string', _params['string'])) - if _params['pattern_without_delimiter'] is not None: - _form_params.append(('pattern_without_delimiter', _params['pattern_without_delimiter'])) + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 - if _params['byte'] is not None: - _form_params.append(('byte', _params['byte'])) + _param = self._test_error_responses_with_model_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params['binary'] is not None: - _files['binary'] = _params['binary'] + _response_types_map: Dict[str, Optional[str]] = { + '204': None, + '400': "TestErrorResponsesWithModel400Response", + '404': "TestErrorResponsesWithModel404Response", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params['byte_with_max_length'] is not None: - _form_params.append(('byte_with_max_length', _params['byte_with_max_length'])) - if _params['var_date'] is not None: - _form_params.append(('date', _params['var_date'])) + def _test_error_responses_with_model_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - if _params['date_time'] is not None: - _form_params.append(('dateTime', _params['date_time'])) + _host = None - if _params['password'] is not None: - _form_params.append(('password', _params['password'])) + _collection_formats: Dict[str, str] = { + } - if _params['param_callback'] is not None: - _form_params.append(('callback', _params['param_callback'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list - # authentication setting - _auth_settings: List[str] = ['http_basic_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} + # set the HTTP header `Accept` + _header_params['Accept'] = self.api_client.select_header_accept( + [ + 'application/json' + ] + ) + + + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/error_responses_with_model', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_group_parameters( @@ -2849,16 +5770,22 @@ def test_group_parameters( string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Fake endpoint to test group parameters (optional) # noqa: E501 + """Fake endpoint to test group parameters (optional) - Fake endpoint to test group parameters (optional) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_group_parameters(required_string_group, required_boolean_group, required_int64_group, string_group, boolean_group, int64_group, async_req=True) - >>> result = thread.get() + Fake endpoint to test group parameters (optional) :param required_string_group: Required String in group parameters (required) :type required_string_group: int @@ -2872,32 +5799,55 @@ def test_group_parameters( :type boolean_group: bool :param int64_group: Integer in group parameters :type int64_group: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_group_parameters_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_group_parameters_with_http_info.raw_function( - required_string_group, - required_boolean_group, - required_int64_group, - string_group, - boolean_group, - int64_group, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def test_group_parameters_with_http_info( self, @@ -2907,16 +5857,22 @@ def test_group_parameters_with_http_info( string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, - **kwargs, - ) -> ApiResponse: - """Fake endpoint to test group parameters (optional) # noqa: E501 - - Fake endpoint to test group parameters (optional) # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Fake endpoint to test group parameters (optional) - >>> thread = api.test_group_parameters_with_http_info(required_string_group, required_boolean_group, required_int64_group, string_group, boolean_group, int64_group, async_req=True) - >>> result = thread.get() + Fake endpoint to test group parameters (optional) :param required_string_group: Required String in group parameters (required) :type required_string_group: int @@ -2930,586 +5886,1022 @@ def test_group_parameters_with_http_info( :type boolean_group: bool :param int64_group: Integer in group parameters :type int64_group: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'required_string_group', - 'required_boolean_group', - 'required_int64_group', - 'string_group', - 'boolean_group', - 'int64_group' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_group_parameters" % _key - ) - _params[_key] = _val - del _params['kwargs'] + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _collection_formats: Dict[str, str] = {} + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - # process the path parameters - _path_params: Dict[str, str] = {} - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('required_string_group') is not None: # noqa: E501 - _query_params.append(('required_string_group', _params['required_string_group'])) + @validate_call + def test_group_parameters_without_preload_content( + self, + required_string_group: Annotated[StrictInt, Field(description="Required String in group parameters")], + required_boolean_group: Annotated[StrictBool, Field(description="Required Boolean in group parameters")], + required_int64_group: Annotated[StrictInt, Field(description="Required Integer in group parameters")], + string_group: Annotated[Optional[StrictInt], Field(description="String in group parameters")] = None, + boolean_group: Annotated[Optional[StrictBool], Field(description="Boolean in group parameters")] = None, + int64_group: Annotated[Optional[StrictInt], Field(description="Integer in group parameters")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Fake endpoint to test group parameters (optional) - if _params.get('required_int64_group') is not None: # noqa: E501 - _query_params.append(('required_int64_group', _params['required_int64_group'])) + Fake endpoint to test group parameters (optional) - if _params.get('string_group') is not None: # noqa: E501 - _query_params.append(('string_group', _params['string_group'])) + :param required_string_group: Required String in group parameters (required) + :type required_string_group: int + :param required_boolean_group: Required Boolean in group parameters (required) + :type required_boolean_group: bool + :param required_int64_group: Required Integer in group parameters (required) + :type required_int64_group: int + :param string_group: String in group parameters + :type string_group: int + :param boolean_group: Boolean in group parameters + :type boolean_group: bool + :param int64_group: Integer in group parameters + :type int64_group: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_group_parameters_serialize( + required_string_group=required_string_group, + required_boolean_group=required_boolean_group, + required_int64_group=required_int64_group, + string_group=string_group, + boolean_group=boolean_group, + int64_group=int64_group, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params.get('int64_group') is not None: # noqa: E501 - _query_params.append(('int64_group', _params['int64_group'])) + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['required_boolean_group'] is not None: - _header_params['required_boolean_group'] = _params['required_boolean_group'] - if _params['boolean_group'] is not None: - _header_params['boolean_group'] = _params['boolean_group'] + def _test_group_parameters_serialize( + self, + required_string_group, + required_boolean_group, + required_int64_group, + string_group, + boolean_group, + int64_group, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if required_string_group is not None: + + _query_params.append(('required_string_group', required_string_group)) + + if required_int64_group is not None: + + _query_params.append(('required_int64_group', required_int64_group)) + + if string_group is not None: + + _query_params.append(('string_group', string_group)) + + if int64_group is not None: + + _query_params.append(('int64_group', int64_group)) + + # process the header parameters + if required_boolean_group is not None: + _header_params['required_boolean_group'] = required_boolean_group + if boolean_group is not None: + _header_params['boolean_group'] = boolean_group + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = ['bearer_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + 'bearer_test' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/fake', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_inline_additional_properties( self, request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test inline additionalProperties # noqa: E501 + """test inline additionalProperties + + + + :param request_body: request body (required) + :type request_body: Dict[str, str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def test_inline_additional_properties_with_http_info( + self, + request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test inline additionalProperties - >>> thread = api.test_inline_additional_properties(request_body, async_req=True) - >>> result = thread.get() + :param request_body: request body (required) :type request_body: Dict[str, str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_inline_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_inline_additional_properties_with_http_info.raw_function( - request_body, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, ) + @validate_call - def test_inline_additional_properties_with_http_info( + def test_inline_additional_properties_without_preload_content( self, request_body: Annotated[Dict[str, StrictStr], Field(description="request body")], - **kwargs, - ) -> ApiResponse: - """test inline additionalProperties # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test inline additionalProperties - >>> thread = api.test_inline_additional_properties_with_http_info(request_body, async_req=True) - >>> result = thread.get() + :param request_body: request body (required) :type request_body: Dict[str, str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_inline_additional_properties_serialize( + request_body=request_body, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'request_body' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_inline_additional_properties" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _test_inline_additional_properties_serialize( + self, + request_body, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['request_body'] is not None: - _body_params = _params['request_body'] + if request_body is not None: + _body_params = request_body + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/inline-additionalProperties', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/inline-additionalProperties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_inline_freeform_additional_properties( self, test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test inline free-form additionalProperties # noqa: E501 + """test inline free-form additionalProperties - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_inline_freeform_additional_properties(test_inline_freeform_additional_properties_request, async_req=True) - >>> result = thread.get() + :param test_inline_freeform_additional_properties_request: request body (required) :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_inline_freeform_additional_properties_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_inline_freeform_additional_properties_with_http_info.raw_function( - test_inline_freeform_additional_properties_request, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_inline_freeform_additional_properties_with_http_info( self, test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], - **kwargs, - ) -> ApiResponse: - """test inline free-form additionalProperties # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test inline free-form additionalProperties + + + + :param test_inline_freeform_additional_properties_request: request body (required) + :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def test_inline_freeform_additional_properties_without_preload_content( + self, + test_inline_freeform_additional_properties_request: Annotated[TestInlineFreeformAdditionalPropertiesRequest, Field(description="request body")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test inline free-form additionalProperties - >>> thread = api.test_inline_freeform_additional_properties_with_http_info(test_inline_freeform_additional_properties_request, async_req=True) - >>> result = thread.get() + :param test_inline_freeform_additional_properties_request: request body (required) :type test_inline_freeform_additional_properties_request: TestInlineFreeformAdditionalPropertiesRequest - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_inline_freeform_additional_properties_serialize( + test_inline_freeform_additional_properties_request=test_inline_freeform_additional_properties_request, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _params = locals() - _all_params = [ - 'test_inline_freeform_additional_properties_request' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_inline_freeform_additional_properties" % _key - ) - _params[_key] = _val - del _params['kwargs'] + def _test_inline_freeform_additional_properties_serialize( + self, + test_inline_freeform_additional_properties_request, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - _collection_formats: Dict[str, str] = {} + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['test_inline_freeform_additional_properties_request'] is not None: - _body_params = _params['test_inline_freeform_additional_properties_request'] + if test_inline_freeform_additional_properties_request is not None: + _body_params = test_inline_freeform_additional_properties_request + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/inline-freeform-additionalProperties', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/inline-freeform-additionalProperties', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_json_form_data( self, param: Annotated[StrictStr, Field(description="field1")], param2: Annotated[StrictStr, Field(description="field2")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test json serialization of form data # noqa: E501 + """test json serialization of form data - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_json_form_data(param, param2, async_req=True) - >>> result = thread.get() + :param param: field1 (required) :type param: str :param param2: field2 (required) :type param2: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_json_form_data_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.test_json_form_data_with_http_info.raw_function( - param, - param2, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_json_form_data_with_http_info( self, param: Annotated[StrictStr, Field(description="field1")], param2: Annotated[StrictStr, Field(description="field2")], - **kwargs, - ) -> ApiResponse: - """test json serialization of form data # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test json serialization of form data + + + + :param param: field1 (required) + :type param: str + :param param2: field2 (required) + :type param2: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + @validate_call + def test_json_form_data_without_preload_content( + self, + param: Annotated[StrictStr, Field(description="field1")], + param2: Annotated[StrictStr, Field(description="field2")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test json serialization of form data - >>> thread = api.test_json_form_data_with_http_info(param, param2, async_req=True) - >>> result = thread.get() + :param param: field1 (required) :type param: str :param param2: field2 (required) :type param2: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._test_json_form_data_serialize( + param=param, + param2=param2, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _all_params = [ - 'param', - 'param2' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_json_form_data" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _test_json_form_data_serialize( + self, + param, + param2, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['param'] is not None: - _form_params.append(('param', _params['param'])) + if param is not None: + _form_params.append(('param', param)) + if param2 is not None: + _form_params.append(('param2', param2)) + # process the body parameter + - if _params['param2'] is not None: - _form_params.append(('param2', _params['param2'])) - # process the body parameter - _body_params = None # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/fake/jsonFormData', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/fake/jsonFormData', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def test_query_parameter_collection_format( @@ -3521,16 +6913,22 @@ def test_query_parameter_collection_format( context: List[StrictStr], allow_empty: StrictStr, language: Optional[Dict[str, StrictStr]] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """test_query_parameter_collection_format # noqa: E501 + """test_query_parameter_collection_format - To test the collection format in query parameters # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_query_parameter_collection_format(pipe, ioutil, http, url, context, allow_empty, language, async_req=True) - >>> result = thread.get() + To test the collection format in query parameters :param pipe: (required) :type pipe: List[str] @@ -3546,32 +6944,55 @@ def test_query_parameter_collection_format( :type allow_empty: str :param language: :type language: Dict[str, str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_query_parameter_collection_format_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_query_parameter_collection_format_with_http_info.raw_function( - pipe, - ioutil, - http, - url, - context, - allow_empty, - language, - **kwargs, + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_query_parameter_collection_format_with_http_info( @@ -3583,16 +7004,22 @@ def test_query_parameter_collection_format_with_http_info( context: List[StrictStr], allow_empty: StrictStr, language: Optional[Dict[str, StrictStr]] = None, - **kwargs, - ) -> ApiResponse: - """test_query_parameter_collection_format # noqa: E501 - - To test the collection format in query parameters # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """test_query_parameter_collection_format - >>> thread = api.test_query_parameter_collection_format_with_http_info(pipe, ioutil, http, url, context, allow_empty, language, async_req=True) - >>> result = thread.get() + To test the collection format in query parameters :param pipe: (required) :type pipe: List[str] @@ -3608,122 +7035,229 @@ def test_query_parameter_collection_format_with_http_info( :type allow_empty: str :param language: :type language: Dict[str, str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'pipe', - 'ioutil', - 'http', - 'url', - 'context', - 'allow_empty', - 'language' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_query_parameter_collection_format" % _key - ) - _params[_key] = _val - del _params['kwargs'] + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _collection_formats: Dict[str, str] = {} + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - # process the path parameters - _path_params: Dict[str, str] = {} - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('pipe') is not None: # noqa: E501 - _query_params.append(('pipe', _params['pipe'])) - _collection_formats['pipe'] = 'pipes' + @validate_call + def test_query_parameter_collection_format_without_preload_content( + self, + pipe: List[StrictStr], + ioutil: List[StrictStr], + http: List[StrictStr], + url: List[StrictStr], + context: List[StrictStr], + allow_empty: StrictStr, + language: Optional[Dict[str, StrictStr]] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """test_query_parameter_collection_format - if _params.get('ioutil') is not None: # noqa: E501 - _query_params.append(('ioutil', _params['ioutil'])) - _collection_formats['ioutil'] = 'csv' + To test the collection format in query parameters - if _params.get('http') is not None: # noqa: E501 - _query_params.append(('http', _params['http'])) - _collection_formats['http'] = 'ssv' + :param pipe: (required) + :type pipe: List[str] + :param ioutil: (required) + :type ioutil: List[str] + :param http: (required) + :type http: List[str] + :param url: (required) + :type url: List[str] + :param context: (required) + :type context: List[str] + :param allow_empty: (required) + :type allow_empty: str + :param language: + :type language: Dict[str, str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_query_parameter_collection_format_serialize( + pipe=pipe, + ioutil=ioutil, + http=http, + url=url, + context=context, + allow_empty=allow_empty, + language=language, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - if _params.get('url') is not None: # noqa: E501 - _query_params.append(('url', _params['url'])) - _collection_formats['url'] = 'csv' + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - if _params.get('context') is not None: # noqa: E501 - _query_params.append(('context', _params['context'])) - _collection_formats['context'] = 'multi' - if _params.get('language') is not None: # noqa: E501 - _query_params.append(('language', _params['language'])) + def _test_query_parameter_collection_format_serialize( + self, + pipe, + ioutil, + http, + url, + context, + allow_empty, + language, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'pipe': 'pipes', + 'ioutil': 'csv', + 'http': 'ssv', + 'url': 'csv', + 'context': 'multi', + } - if _params.get('allow_empty') is not None: # noqa: E501 - _query_params.append(('allowEmpty', _params['allow_empty'])) + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if pipe is not None: + + _query_params.append(('pipe', pipe)) + + if ioutil is not None: + + _query_params.append(('ioutil', ioutil)) + + if http is not None: + + _query_params.append(('http', http)) + + if url is not None: + + _query_params.append(('url', url)) + + if context is not None: + + _query_params.append(('context', context)) + + if language is not None: + + _query_params.append(('language', language)) + + if allow_empty is not None: + + _query_params.append(('allowEmpty', allow_empty)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/fake/test-query-parameters', 'PUT', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='PUT', + resource_path='/fake/test-query-parameters', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py index 5dfe702c19ea..ba6f2b31baed 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags123_api.py @@ -11,24 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union +from typing_extensions import Annotated from pydantic import Field from typing_extensions import Annotated from petstore_api.models.client import Client -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class FakeClassnameTags123Api: @@ -43,161 +37,273 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def test_classname( self, client: Annotated[Client, Field(description="client model")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Client: - """To test class name in snake case # noqa: E501 + """To test class name in snake case - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_classname(client, async_req=True) - >>> result = thread.get() + To test class name in snake case :param client: client model (required) :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the test_classname_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.test_classname_with_http_info.raw_function( - client, - **kwargs, + """ # noqa: E501 + + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def test_classname_with_http_info( self, client: Annotated[Client, Field(description="client model")], - **kwargs, - ) -> ApiResponse: - """To test class name in snake case # noqa: E501 - - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Client]: + """To test class name in snake case - >>> thread = api.test_classname_with_http_info(client, async_req=True) - >>> result = thread.get() + To test class name in snake case :param client: client model (required) :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'client' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def test_classname_without_preload_content( + self, + client: Annotated[Client, Field(description="client model")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """To test class name in snake case + + To test class name in snake case + + :param client: client model (required) + :type client: Client + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._test_classname_serialize( + client=client, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_classname" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Client", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _test_classname_serialize( + self, + client, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['client'] is not None: - _body_params = _params['client'] + if client is not None: + _body_params = client + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['api_key_query'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Client", - } + _auth_settings: List[str] = [ + 'api_key_query' + ] - return self.api_client.call_api( - '/fake_classname_test', 'PATCH', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PATCH', + resource_path='/fake_classname_test', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py deleted file mode 100755 index c4d582464d68..000000000000 --- a/samples/openapi3/client/petstore/python/petstore_api/api/fake_classname_tags_123_api.py +++ /dev/null @@ -1,178 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import re # noqa: F401 - -from petstore_api.api_client import ApiClient -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) - - -class FakeClassnameTags123Api(object): - """NOTE: This class is auto generated by OpenAPI Generator - Ref: https://openapi-generator.tech - - Do not edit the class manually. - """ - - def __init__(self, api_client=None): - if api_client is None: - api_client = ApiClient() - self.api_client = api_client - - def test_classname(self, client, **kwargs): # noqa: E501 - """To test class name in snake case # noqa: E501 - - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_classname(client, async_req=True) - >>> result = thread.get() - - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Client - """ - kwargs['_return_http_data_only'] = True - return self.test_classname_with_http_info(client, **kwargs) # noqa: E501 - - def test_classname_with_http_info(self, client, **kwargs): # noqa: E501 - """To test class name in snake case # noqa: E501 - - To test class name in snake case # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.test_classname_with_http_info(client, async_req=True) - >>> result = thread.get() - - :param client: client model (required) - :type client: Client - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _return_http_data_only: response data without head status code - and headers - :type _return_http_data_only: bool, optional - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. - :type _preload_content: bool, optional - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request - :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Client, status_code(int), headers(HTTPHeaderDict)) - """ - - local_var_params = locals() - - all_params = [ - 'client' - ] - all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - for key, val in local_var_params['kwargs'].items(): - if key not in all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method test_classname" % key - ) - local_var_params[key] = val - del local_var_params['kwargs'] - # verify the required parameter 'client' is set - if self.api_client.client_side_validation and ('client' not in local_var_params or # noqa: E501 - local_var_params['client'] is None): # noqa: E501 - raise ApiValueError("Missing the required parameter `client` when calling `test_classname`") # noqa: E501 - - collection_formats = {} - - path_params = {} - - query_params = [] - - header_params = dict(local_var_params.get('_headers', {})) - - form_params = [] - local_var_files = {} - - body_params = None - if 'client' in local_var_params: - body_params = local_var_params['client'] - # HTTP header `Accept` - header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 - - # HTTP header `Content-Type` - header_params['Content-Type'] = local_var_params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'], - 'PATCH', body_params)) # noqa: E501 - - # Authentication setting - auth_settings = ['api_key_query'] # noqa: E501 - - response_types_map = { - 200: "Client", - } - - return self.api_client.call_api( - '/fake_classname_test', 'PATCH', - path_params, - query_params, - header_params, - body=body_params, - post_params=form_params, - files=local_var_files, - response_types_map=response_types_map, - auth_settings=auth_settings, - async_req=local_var_params.get('async_req'), - _return_http_data_only=local_var_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=local_var_params.get('_preload_content', True), - _request_timeout=local_var_params.get('_request_timeout'), - collection_formats=collection_formats, - _request_auth=local_var_params.get('_request_auth')) diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py index c51f6ba6c05f..7918936e764d 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/pet_api.py @@ -11,29 +11,20 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictBytes, StrictInt, StrictStr, field_validator +from pydantic import Field, StrictBytes, StrictInt, StrictStr, field_validator from typing import List, Optional, Union - -from petstore_api.models.api_response import ApiResponse +from typing_extensions import Annotated +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.pet import Pet -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class PetApi: @@ -48,932 +39,1622 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def add_pet( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Add a new pet to the store # noqa: E501 + """Add a new pet to the store - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.add_pet(pet, async_req=True) - >>> result = thread.get() + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the add_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.add_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def add_pet_with_http_info( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, - ) -> ApiResponse: - """Add a new pet to the store # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Add a new pet to the store - >>> thread = api.add_pet_with_http_info(pet, async_req=True) - >>> result = thread.get() + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def add_pet_without_preload_content( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Add a new pet to the store + + + + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._add_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method add_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _add_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return self.api_client.call_api( - '/pet', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def delete_pet( self, pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], api_key: Optional[StrictStr] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Deletes a pet # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Deletes a pet - >>> thread = api.delete_pet(pet_id, api_key, async_req=True) - >>> result = thread.get() + :param pet_id: Pet id to delete (required) :type pet_id: int :param api_key: :type api_key: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.delete_pet_with_http_info.raw_function( - pet_id, - api_key, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def delete_pet_with_http_info( self, pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], api_key: Optional[StrictStr] = None, - **kwargs, - ) -> ApiResponse: - """Deletes a pet # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Deletes a pet - >>> thread = api.delete_pet_with_http_info(pet_id, api_key, async_req=True) - >>> result = thread.get() + :param pet_id: Pet id to delete (required) :type pet_id: int :param api_key: :type api_key: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet_id', - 'api_key' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def delete_pet_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="Pet id to delete")], + api_key: Optional[StrictStr] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Deletes a pet + + + + :param pet_id: Pet id to delete (required) + :type pet_id: int + :param api_key: + :type api_key: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_pet_serialize( + pet_id=pet_id, + api_key=api_key, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _delete_pet_serialize( + self, + pet_id, + api_key, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - if _params['api_key'] is not None: - _header_params['api_key'] = _params['api_key'] + _collection_formats: Dict[str, str] = { + } - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id + # process the query parameters + # process the header parameters + if api_key is not None: + _header_params['api_key'] = api_key + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/pet/{petId}', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth' + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def find_pets_by_status( self, status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> List[Pet]: - """Finds Pets by status # noqa: E501 + """Finds Pets by status - Multiple status values can be provided with comma separated strings # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.find_pets_by_status(status, async_req=True) - >>> result = thread.get() + Multiple status values can be provided with comma separated strings :param status: Status values that need to be considered for filter (required) :type status: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[Pet] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the find_pets_by_status_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.find_pets_by_status_with_http_info.raw_function( - status, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def find_pets_by_status_with_http_info( self, status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], - **kwargs, - ) -> ApiResponse: - """Finds Pets by status # noqa: E501 - - Multiple status values can be provided with comma separated strings # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Pet]]: + """Finds Pets by status - >>> thread = api.find_pets_by_status_with_http_info(status, async_req=True) - >>> result = thread.get() + Multiple status values can be provided with comma separated strings :param status: Status values that need to be considered for filter (required) :type status: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[Pet], status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'status' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def find_pets_by_status_without_preload_content( + self, + status: Annotated[List[StrictStr], Field(description="Status values that need to be considered for filter")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Finds Pets by status + + Multiple status values can be provided with comma separated strings + + :param status: Status values that need to be considered for filter (required) + :type status: List[str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._find_pets_by_status_serialize( + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method find_pets_by_status" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _find_pets_by_status_serialize( + self, + status, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + 'status': 'csv', + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('status') is not None: # noqa: E501 - _query_params.append(('status', _params['status'])) - _collection_formats['status'] = 'csv' + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if status is not None: + + _query_params.append(('status', status)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[Pet]", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return self.api_client.call_api( - '/pet/findByStatus', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/findByStatus', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def find_pets_by_tags( self, tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> List[Pet]: - """(Deprecated) Finds Pets by tags # noqa: E501 + """(Deprecated) Finds Pets by tags - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.find_pets_by_tags(tags, async_req=True) - >>> result = thread.get() + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. :param tags: Tags to filter by (required) :type tags: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: List[Pet] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the find_pets_by_tags_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) - return self.find_pets_by_tags_with_http_info.raw_function( - tags, - **kwargs, + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def find_pets_by_tags_with_http_info( self, tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], - **kwargs, - ) -> ApiResponse: - """(Deprecated) Finds Pets by tags # noqa: E501 - - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[List[Pet]]: + """(Deprecated) Finds Pets by tags - >>> thread = api.find_pets_by_tags_with_http_info(tags, async_req=True) - >>> result = thread.get() + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. :param tags: Tags to filter by (required) :type tags: List[str] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(List[Pet], status_code(int), headers(HTTPHeaderDict)) - """ - + """ # noqa: E501 warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) - _params = locals() + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'tags' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def find_pets_by_tags_without_preload_content( + self, + tags: Annotated[List[StrictStr], Field(description="Tags to filter by")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """(Deprecated) Finds Pets by tags + + Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. + + :param tags: Tags to filter by (required) + :type tags: List[str] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + warnings.warn("GET /pet/findByTags is deprecated.", DeprecationWarning) + + _param = self._find_pets_by_tags_serialize( + tags=tags, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method find_pets_by_tags" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "List[Pet]", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _find_pets_by_tags_serialize( + self, + tags, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters + _host = None + + _collection_formats: Dict[str, str] = { + 'tags': 'csv', + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - if _params.get('tags') is not None: # noqa: E501 - _query_params.append(('tags', _params['tags'])) - _collection_formats['tags'] = 'csv' + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + # process the query parameters + if tags is not None: + + _query_params.append(('tags', tags)) + # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "List[Pet]", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return self.api_client.call_api( - '/pet/findByTags', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/findByTags', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def get_pet_by_id( self, pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Pet: - """Find pet by ID # noqa: E501 - - Returns a single pet # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Find pet by ID - >>> thread = api.get_pet_by_id(pet_id, async_req=True) - >>> result = thread.get() + Returns a single pet :param pet_id: ID of pet to return (required) :type pet_id: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Pet - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_pet_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.get_pet_by_id_with_http_info.raw_function( - pet_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def get_pet_by_id_with_http_info( self, pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], - **kwargs, - ) -> ApiResponse: - """Find pet by ID # noqa: E501 - - Returns a single pet # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Pet]: + """Find pet by ID - >>> thread = api.get_pet_by_id_with_http_info(pet_id, async_req=True) - >>> result = thread.get() + Returns a single pet :param pet_id: ID of pet to return (required) :type pet_id: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Pet, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def get_pet_by_id_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to return")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Find pet by ID + + Returns a single pet + + :param pet_id: ID of pet to return (required) + :type pet_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_pet_by_id_serialize( + pet_id=pet_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_pet_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Pet", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _get_pet_by_id_serialize( + self, + pet_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['api_key'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Pet", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + 'api_key' + ] - return self.api_client.call_api( - '/pet/{petId}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def update_pet( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Update an existing pet # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Update an existing pet - >>> thread = api.update_pet(pet, async_req=True) - >>> result = thread.get() + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.update_pet_with_http_info.raw_function( - pet, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def update_pet_with_http_info( self, pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], - **kwargs, - ) -> ApiResponse: - """Update an existing pet # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Update an existing pet + + - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + :param pet: Pet object that needs to be added to the store (required) + :type pet: Pet + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def update_pet_without_preload_content( + self, + pet: Annotated[Pet, Field(description="Pet object that needs to be added to the store")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Update an existing pet - >>> thread = api.update_pet_with_http_info(pet, async_req=True) - >>> result = thread.get() + :param pet: Pet object that needs to be added to the store (required) :type pet: Pet - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() + """ # noqa: E501 + + _param = self._update_pet_serialize( + pet=pet, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - 'pet' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '400': None, + '404': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + return response_data.response - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet" % _key - ) - _params[_key] = _val - del _params['kwargs'] - _collection_formats: Dict[str, str] = {} + def _update_pet_serialize( + self, + pet, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['pet'] is not None: - _body_params = _params['pet'] + if pet is not None: + _body_params = pet + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json', 'application/xml'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json', + 'application/xml' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth', 'http_signature_test'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth', + 'http_signature_test' + ] - return self.api_client.call_api( - '/pet', 'PUT', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PUT', + resource_path='/pet', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def update_pet_with_form( @@ -981,16 +1662,22 @@ def update_pet_with_form( pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Updates a pet in the store with form data # noqa: E501 + """Updates a pet in the store with form data - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_pet_with_form(pet_id, name, status, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet that needs to be updated (required) :type pet_id: int @@ -998,28 +1685,52 @@ def update_pet_with_form( :type name: str :param status: Updated status of the pet :type status: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_pet_with_form_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.update_pet_with_form_with_http_info.raw_function( - pet_id, - name, - status, - **kwargs, + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def update_pet_with_form_with_http_info( @@ -1027,16 +1738,22 @@ def update_pet_with_form_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, - **kwargs, - ) -> ApiResponse: - """Updates a pet in the store with form data # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Updates a pet in the store with form data - >>> thread = api.update_pet_with_form_with_http_info(pet_id, name, status, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet that needs to be updated (required) :type pet_id: int @@ -1044,111 +1761,198 @@ def update_pet_with_form_with_http_info( :type name: str :param status: Updated status of the pet :type status: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet_id', - 'name', - 'status' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def update_pet_with_form_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet that needs to be updated")], + name: Annotated[Optional[StrictStr], Field(description="Updated name of the pet")] = None, + status: Annotated[Optional[StrictStr], Field(description="Updated status of the pet")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Updates a pet in the store with form data + + + + :param pet_id: ID of pet that needs to be updated (required) + :type pet_id: int + :param name: Updated name of the pet + :type name: str + :param status: Updated status of the pet + :type status: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_pet_with_form_serialize( + pet_id=pet_id, + name=name, + status=status, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_pet_with_form" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': None, + '405': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _update_pet_with_form_serialize( + self, + pet_id, + name, + status, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['name'] is not None: - _form_params.append(('name', _params['name'])) + if name is not None: + _form_params.append(('name', name)) + if status is not None: + _form_params.append(('status', status)) + # process the body parameter + - if _params['status'] is not None: - _form_params.append(('status', _params['status'])) - # process the body parameter - _body_params = None # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/x-www-form-urlencoded'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/x-www-form-urlencoded' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return self.api_client.call_api( - '/pet/{petId}', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet/{petId}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def upload_file( @@ -1156,16 +1960,22 @@ def upload_file( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads an image - >>> thread = api.upload_file(pet_id, additional_metadata, file, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1173,28 +1983,51 @@ def upload_file( :type additional_metadata: str :param file: file to upload :type file: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ApiResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the upload_file_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.upload_file_with_http_info.raw_function( - pet_id, - additional_metadata, - file, - **kwargs, + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def upload_file_with_http_info( @@ -1202,16 +2035,22 @@ def upload_file_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads an image - >>> thread = api.upload_file_with_http_info(pet_id, additional_metadata, file, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1219,117 +2058,202 @@ def upload_file_with_http_info( :type additional_metadata: str :param file: file to upload :type file: bytearray - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'pet_id', - 'additional_metadata', - 'file' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def upload_file_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], + additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, + file: Annotated[Optional[Union[StrictBytes, StrictStr]], Field(description="file to upload")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads an image + + + + :param pet_id: ID of pet to update (required) + :type pet_id: int + :param additional_metadata: Additional data to pass to server + :type additional_metadata: str + :param file: file to upload + :type file: bytearray + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_serialize( + pet_id=pet_id, + additional_metadata=additional_metadata, + file=file, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method upload_file" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _upload_file_serialize( + self, + pet_id, + additional_metadata, + file, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['additional_metadata'] is not None: - _form_params.append(('additionalMetadata', _params['additional_metadata'])) + if additional_metadata is not None: + _form_params.append(('additionalMetadata', additional_metadata)) + if file is not None: + _files['file'] = file + # process the body parameter - if _params['file'] is not None: - _files['file'] = _params['file'] - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ApiResponse", - } + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return self.api_client.call_api( - '/pet/{petId}/uploadImage', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/pet/{petId}/uploadImage', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def upload_file_with_required_file( @@ -1337,16 +2261,22 @@ def upload_file_with_required_file( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image (required) # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ModelApiResponse: + """uploads an image (required) - >>> thread = api.upload_file_with_required_file(pet_id, required_file, additional_metadata, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1354,28 +2284,51 @@ def upload_file_with_required_file( :type required_file: bytearray :param additional_metadata: Additional data to pass to server :type additional_metadata: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: ApiResponse - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the upload_file_with_required_file_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) - - return self.upload_file_with_required_file_with_http_info.raw_function( - pet_id, - required_file, - additional_metadata, - **kwargs, + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def upload_file_with_required_file_with_http_info( @@ -1383,16 +2336,22 @@ def upload_file_with_required_file_with_http_info( pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, - **kwargs, - ) -> ApiResponse: - """uploads an image (required) # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[ModelApiResponse]: + """uploads an image (required) - >>> thread = api.upload_file_with_required_file_with_http_info(pet_id, required_file, additional_metadata, async_req=True) - >>> result = thread.get() + :param pet_id: ID of pet to update (required) :type pet_id: int @@ -1400,114 +2359,198 @@ def upload_file_with_required_file_with_http_info( :type required_file: bytearray :param additional_metadata: Additional data to pass to server :type additional_metadata: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(ApiResponse, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'pet_id', - 'required_file', - 'additional_metadata' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def upload_file_with_required_file_without_preload_content( + self, + pet_id: Annotated[StrictInt, Field(description="ID of pet to update")], + required_file: Annotated[Union[StrictBytes, StrictStr], Field(description="file to upload")], + additional_metadata: Annotated[Optional[StrictStr], Field(description="Additional data to pass to server")] = None, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """uploads an image (required) + + + + :param pet_id: ID of pet to update (required) + :type pet_id: int + :param required_file: file to upload (required) + :type required_file: bytearray + :param additional_metadata: Additional data to pass to server + :type additional_metadata: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._upload_file_with_required_file_serialize( + pet_id=pet_id, + required_file=required_file, + additional_metadata=additional_metadata, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method upload_file_with_required_file" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "ModelApiResponse", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['pet_id'] is not None: - _path_params['petId'] = _params['pet_id'] + def _upload_file_with_required_file_serialize( + self, + pet_id, + required_file, + additional_metadata, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters + if pet_id is not None: + _path_params['petId'] = pet_id # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - if _params['additional_metadata'] is not None: - _form_params.append(('additionalMetadata', _params['additional_metadata'])) + if additional_metadata is not None: + _form_params.append(('additionalMetadata', additional_metadata)) + if required_file is not None: + _files['requiredFile'] = required_file + # process the body parameter - if _params['required_file'] is not None: - _files['requiredFile'] = _params['required_file'] - # process the body parameter - _body_params = None # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['multipart/form-data'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'multipart/form-data' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = ['petstore_auth'] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "ApiResponse", - } + _auth_settings: List[str] = [ + 'petstore_auth' + ] - return self.api_client.call_api( - '/fake/{petId}/uploadImageWithRequiredFile', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/fake/{petId}/uploadImageWithRequiredFile', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py index b9da73871464..b88e9c82a159 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/store_api.py @@ -11,28 +11,18 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictStr - -from typing import Dict +from pydantic import Field, StrictStr +from typing_extensions import Annotated from petstore_api.models.order import Order -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class StoreApi: @@ -47,603 +37,1037 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def delete_order( self, order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Delete purchase order by ID # noqa: E501 - - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Delete purchase order by ID - >>> thread = api.delete_order(order_id, async_req=True) - >>> result = thread.get() + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted (required) :type order_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_order_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.delete_order_with_http_info.raw_function( - order_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def delete_order_with_http_info( self, order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], - **kwargs, - ) -> ApiResponse: - """Delete purchase order by ID # noqa: E501 - - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete purchase order by ID - >>> thread = api.delete_order_with_http_info(order_id, async_req=True) - >>> result = thread.get() + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors :param order_id: ID of the order that needs to be deleted (required) :type order_id: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'order_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def delete_order_without_preload_content( + self, + order_id: Annotated[StrictStr, Field(description="ID of the order that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete purchase order by ID + + For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors + + :param order_id: ID of the order that needs to be deleted (required) + :type order_id: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_order_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_order" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['order_id'] is not None: - _path_params['order_id'] = _params['order_id'] + def _delete_order_serialize( + self, + order_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if order_id is not None: + _path_params['order_id'] = order_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/store/order/{order_id}', 'DELETE', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/store/order/{order_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def get_inventory( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Dict[str, int]: - """Returns pet inventories by status # noqa: E501 - - Returns a map of status codes to quantities # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Returns pet inventories by status - >>> thread = api.get_inventory(async_req=True) - >>> result = thread.get() + Returns a map of status codes to quantities - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Dict[str, int] - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_inventory_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.get_inventory_with_http_info.raw_function( - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def get_inventory_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Returns pet inventories by status # noqa: E501 - - Returns a map of status codes to quantities # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_inventory_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Dict[str, int]]: + """Returns pet inventories by status + + Returns a map of status codes to quantities + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Dict[str, int], status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 - _params = locals() + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def get_inventory_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Returns pet inventories by status + + Returns a map of status codes to quantities + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_inventory_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_inventory" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Dict[str, int]", + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _get_inventory_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/json']) # noqa: E501 + [ + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = ['api_key'] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Dict[str, int]", - } + # authentication setting + _auth_settings: List[str] = [ + 'api_key' + ] - return self.api_client.call_api( - '/store/inventory', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/store/inventory', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def get_order_by_id( self, order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Order: - """Find purchase order by ID # noqa: E501 + """Find purchase order by ID - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_order_by_id(order_id, async_req=True) - >>> result = thread.get() + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions :param order_id: ID of pet that needs to be fetched (required) :type order_id: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Order - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_order_by_id_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.get_order_by_id_with_http_info.raw_function( - order_id, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def get_order_by_id_with_http_info( self, order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], - **kwargs, - ) -> ApiResponse: - """Find purchase order by ID # noqa: E501 - - For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Order]: + """Find purchase order by ID - >>> thread = api.get_order_by_id_with_http_info(order_id, async_req=True) - >>> result = thread.get() + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions :param order_id: ID of pet that needs to be fetched (required) :type order_id: int - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Order, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'order_id' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def get_order_by_id_without_preload_content( + self, + order_id: Annotated[int, Field(le=5, strict=True, ge=1, description="ID of pet that needs to be fetched")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Find purchase order by ID + + For valid response try integer IDs with value <= 5 or > 10. Other values will generated exceptions + + :param order_id: ID of pet that needs to be fetched (required) + :type order_id: int + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_order_by_id_serialize( + order_id=order_id, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_order_by_id" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['order_id'] is not None: - _path_params['order_id'] = _params['order_id'] + def _get_order_by_id_serialize( + self, + order_id, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if order_id is not None: + _path_params['order_id'] = order_id + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "Order", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/store/order/{order_id}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/store/order/{order_id}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def place_order( self, order: Annotated[Order, Field(description="order placed for purchasing the pet")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> Order: - """Place an order for a pet # noqa: E501 + """Place an order for a pet - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.place_order(order, async_req=True) - >>> result = thread.get() + :param order: order placed for purchasing the pet (required) :type order: Order - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: Order - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the place_order_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.place_order_with_http_info.raw_function( - order, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def place_order_with_http_info( self, order: Annotated[Order, Field(description="order placed for purchasing the pet")], - **kwargs, - ) -> ApiResponse: - """Place an order for a pet # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[Order]: + """Place an order for a pet - >>> thread = api.place_order_with_http_info(order, async_req=True) - >>> result = thread.get() + :param order: order placed for purchasing the pet (required) :type order: Order - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(Order, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'order' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def place_order_without_preload_content( + self, + order: Annotated[Order, Field(description="order placed for purchasing the pet")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Place an order for a pet + + + + :param order: order placed for purchasing the pet (required) + :type order: Order + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._place_order_serialize( + order=order, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method place_order" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "Order", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _place_order_serialize( + self, + order, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['order'] is not None: - _body_params = _params['order'] + if order is not None: + _body_params = order + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = { - '200': "Order", - '400': None, - } + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/store/order', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/store/order', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py b/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py index 91ab25e8e0cb..2624e2e2dcbb 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api/user_api.py @@ -11,28 +11,19 @@ Do not edit the class manually. """ # noqa: E501 - -import re # noqa: F401 -import io import warnings - -from pydantic import validate_call, ValidationError -from typing import Dict, List, Optional, Tuple - -from pydantic import Field +from pydantic import validate_call, Field, StrictFloat, StrictStr, StrictInt +from typing import Any, Dict, List, Optional, Tuple, Union from typing_extensions import Annotated -from pydantic import StrictStr +from pydantic import Field, StrictStr from typing import List - +from typing_extensions import Annotated from petstore_api.models.user import User -from petstore_api.api_client import ApiClient +from petstore_api.api_client import ApiClient, RequestSerialized from petstore_api.api_response import ApiResponse -from petstore_api.exceptions import ( # noqa: F401 - ApiTypeError, - ApiValueError -) +from petstore_api.rest import RESTResponseType class UserApi: @@ -47,1239 +38,2105 @@ def __init__(self, api_client=None) -> None: api_client = ApiClient.get_default() self.api_client = api_client + @validate_call def create_user( self, user: Annotated[User, Field(description="Created user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, ) -> None: - """Create user # noqa: E501 - - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Create user - >>> thread = api.create_user(user, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param user: Created user object (required) :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.create_user_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def create_user_with_http_info( self, user: Annotated[User, Field(description="Created user object")], - **kwargs, - ) -> ApiResponse: - """Create user # noqa: E501 + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, + ) -> ApiResponse[None]: + """Create user + + This can only be done by the logged in user. + + :param user: Created user object (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def create_user_without_preload_content( + self, + user: Annotated[User, Field(description="Created user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=3)] = 0, + ) -> RESTResponseType: + """Create user - >>> thread = api.create_user_with_http_info(user, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param user: Created user object (required) :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_user_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _create_user_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: _hosts = [ 'http://petstore.swagger.io/v2', 'http://path-server-test.petstore.local/v2', 'http://{server}.swagger.io:{port}/v2' ] - _host = _hosts[0] - if kwargs.get('_host_index'): - _host_index = int(kwargs.get('_host_index')) - if _host_index < 0 or _host_index >= len(_hosts): - raise ApiValueError( - "Invalid host index. Must be 0 <= index < %s" - % len(_host) - ) - _host = _hosts[_host_index] - _params = locals() - - _all_params = [ - 'user' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] - ) - - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params and _key != "_host_index": - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _host = _hosts[_host_index] - _collection_formats: Dict[str, str] = {} + _collection_formats: Dict[str, str] = { + } - # process the path parameters _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), - _host=_host, collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def create_users_with_array_input( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Creates list of users with given input array # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Creates list of users with given input array - >>> thread = api.create_users_with_array_input(user, async_req=True) - >>> result = thread.get() + :param user: List of user object (required) :type user: List[User] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_users_with_array_input_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.create_users_with_array_input_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def create_users_with_array_input_with_http_info( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, - ) -> ApiResponse: - """Creates list of users with given input array # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates list of users with given input array - >>> thread = api.create_users_with_array_input_with_http_info(user, async_req=True) - >>> result = thread.get() + :param user: List of user object (required) :type user: List[User] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'user' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def create_users_with_array_input_without_preload_content( + self, + user: Annotated[List[User], Field(description="List of user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates list of users with given input array + + + + :param user: List of user object (required) + :type user: List[User] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_users_with_array_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_users_with_array_input" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _create_users_with_array_input_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'User': '', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user/createWithArray', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user/createWithArray', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def create_users_with_list_input( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Creates list of users with given input array # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Creates list of users with given input array - >>> thread = api.create_users_with_list_input(user, async_req=True) - >>> result = thread.get() + :param user: List of user object (required) :type user: List[User] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the create_users_with_list_input_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.create_users_with_list_input_with_http_info.raw_function( - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def create_users_with_list_input_with_http_info( self, user: Annotated[List[User], Field(description="List of user object")], - **kwargs, - ) -> ApiResponse: - """Creates list of users with given input array # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Creates list of users with given input array - >>> thread = api.create_users_with_list_input_with_http_info(user, async_req=True) - >>> result = thread.get() + :param user: List of user object (required) :type user: List[User] - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'user' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def create_users_with_list_input_without_preload_content( + self, + user: Annotated[List[User], Field(description="List of user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Creates list of users with given input array + + + + :param user: List of user object (required) + :type user: List[User] + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._create_users_with_list_input_serialize( + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method create_users_with_list_input" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _create_users_with_list_input_serialize( + self, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + 'User': '', + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user/createWithList', 'POST', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='POST', + resource_path='/user/createWithList', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def delete_user( self, username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Delete user # noqa: E501 - - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Delete user - >>> thread = api.delete_user(username, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param username: The name that needs to be deleted (required) :type username: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the delete_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.delete_user_with_http_info.raw_function( - username, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def delete_user_with_http_info( self, username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], - **kwargs, - ) -> ApiResponse: - """Delete user # noqa: E501 - - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Delete user - >>> thread = api.delete_user_with_http_info(username, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param username: The name that needs to be deleted (required) :type username: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - - _params = locals() - - _all_params = [ - 'username' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' - ] + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method delete_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + @validate_call + def delete_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The name that needs to be deleted")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Delete user + This can only be done by the logged in user. - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} - # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 + :param username: The name that needs to be deleted (required) + :type username: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._delete_user_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _response_types_map: Dict[str, Optional[str]] = {} + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response + + + def _delete_user_serialize( + self, + username, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - return self.api_client.call_api( - '/user/{username}', 'DELETE', - _path_params, - _query_params, - _header_params, + _host = None + + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters + # process the body parameter + + + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='DELETE', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def get_user_by_name( self, username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> User: - """Get user by user name # noqa: E501 + """Get user by user name - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.get_user_by_name(username, async_req=True) - >>> result = thread.get() + :param username: The name that needs to be fetched. Use user1 for testing. (required) :type username: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: User - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the get_user_by_name_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.get_user_by_name_with_http_info.raw_function( - username, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def get_user_by_name_with_http_info( self, username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], - **kwargs, - ) -> ApiResponse: - """Get user by user name # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[User]: + """Get user by user name - >>> thread = api.get_user_by_name_with_http_info(username, async_req=True) - >>> result = thread.get() + :param username: The name that needs to be fetched. Use user1 for testing. (required) :type username: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(User, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'username' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def get_user_by_name_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The name that needs to be fetched. Use user1 for testing.")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Get user by user name + + + + :param username: The name that needs to be fetched. Use user1 for testing. (required) + :type username: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._get_user_by_name_serialize( + username=username, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method get_user_by_name" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "User", + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + def _get_user_by_name_serialize( + self, + username, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "User", - '400': None, - '404': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user/{username}', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def login_user( self, username: Annotated[StrictStr, Field(description="The user name for login")], password: Annotated[StrictStr, Field(description="The password for login in clear text")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> str: - """Logs user into the system # noqa: E501 + """Logs user into the system - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.login_user(username, password, async_req=True) - >>> result = thread.get() + :param username: The user name for login (required) :type username: str :param password: The password for login in clear text (required) :type password: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: str - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the login_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.login_user_with_http_info.raw_function( - username, - password, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def login_user_with_http_info( self, username: Annotated[StrictStr, Field(description="The user name for login")], password: Annotated[StrictStr, Field(description="The password for login in clear text")], - **kwargs, - ) -> ApiResponse: - """Logs user into the system # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[str]: + """Logs user into the system - >>> thread = api.login_user_with_http_info(username, password, async_req=True) - >>> result = thread.get() + :param username: The user name for login (required) :type username: str :param password: The password for login in clear text (required) :type password: str - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: tuple(str, status_code(int), headers(HTTPHeaderDict)) - """ + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _params = locals() + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _all_params = [ - 'username', - 'password' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + + @validate_call + def login_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="The user name for login")], + password: Annotated[StrictStr, Field(description="The password for login in clear text")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Logs user into the system + + + + :param username: The user name for login (required) + :type username: str + :param password: The password for login in clear text (required) + :type password: str + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._login_user_serialize( + username=username, + password=password, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method login_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '200': "str", + '400': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} + def _login_user_serialize( + self, + username, + password, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: - # process the query parameters - _query_params: List[Tuple[str, str]] = [] - if _params.get('username') is not None: # noqa: E501 - _query_params.append(('username', _params['username'])) + _host = None - if _params.get('password') is not None: # noqa: E501 - _query_params.append(('password', _params['password'])) + _collection_formats: Dict[str, str] = { + } - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + # process the query parameters + if username is not None: + + _query_params.append(('username', username)) + + if password is not None: + + _query_params.append(('password', password)) + + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None + + # set the HTTP header `Accept` _header_params['Accept'] = self.api_client.select_header_accept( - ['application/xml', 'application/json']) # noqa: E501 + [ + 'application/xml', + 'application/json' + ] + ) - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = { - '200': "str", - '400': None, - } + # authentication setting + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user/login', 'GET', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='GET', + resource_path='/user/login', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def logout_user( self, - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Logs out current logged in user session # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + """Logs out current logged in user session - >>> thread = api.logout_user(async_req=True) - >>> result = thread.get() + - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the logout_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 - return self.logout_user_with_http_info.raw_function( - **kwargs, + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + + @validate_call def logout_user_with_http_info( self, - **kwargs, - ) -> ApiResponse: - """Logs out current logged in user session # noqa: E501 - - # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.logout_user_with_http_info(async_req=True) - >>> result = thread.get() - - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Logs out current logged in user session + + + :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 - _params = locals() + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - _all_params = [ - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) + + + @validate_call + def logout_user_without_preload_content( + self, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Logs out current logged in user session + + + + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._logout_user_serialize( + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method logout_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters + def _logout_user_serialize( + self, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + + _host = None + + _collection_formats: Dict[str, str] = { + } + _path_params: Dict[str, str] = {} + _query_params: List[Tuple[str, str]] = [] + _header_params: Dict[str, Optional[str]] = _headers or {} + _form_params: List[Tuple[str, str]] = [] + _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + # process the path parameters # process the query parameters - _query_params: List[Tuple[str, str]] = [] # process the header parameters - _header_params = dict(_params.get('_headers', {})) # process the form parameters - _form_params: List[Tuple[str, str]] = [] - _files: Dict[str, str] = {} # process the body parameter - _body_params = None - # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - _response_types_map: Dict[str, Optional[str]] = {} - return self.api_client.call_api( - '/user/logout', 'GET', - _path_params, - _query_params, - _header_params, + + + # authentication setting + _auth_settings: List[str] = [ + ] + + return self.api_client.param_serialize( + method='GET', + resource_path='/user/logout', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + + @validate_call def update_user( self, username: Annotated[StrictStr, Field(description="name that need to be deleted")], user: Annotated[User, Field(description="Updated user object")], - **kwargs, + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, ) -> None: - """Updated user # noqa: E501 + """Updated user - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True - - >>> thread = api.update_user(username, user, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param username: name that need to be deleted (required) :type username: str :param user: Updated user object (required) :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _request_timeout: timeout setting for this request. - If one number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ - kwargs['_return_http_data_only'] = True - if '_preload_content' in kwargs: - message = "Error! Please call the update_user_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data" # noqa: E501 - raise ValueError(message) + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) - return self.update_user_with_http_info.raw_function( - username, - user, - **kwargs, + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ).data + @validate_call def update_user_with_http_info( self, username: Annotated[StrictStr, Field(description="name that need to be deleted")], user: Annotated[User, Field(description="Updated user object")], - **kwargs, - ) -> ApiResponse: - """Updated user # noqa: E501 - - This can only be done by the logged in user. # noqa: E501 - This method makes a synchronous HTTP request by default. To make an - asynchronous HTTP request, please pass async_req=True + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] + ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> ApiResponse[None]: + """Updated user - >>> thread = api.update_user_with_http_info(username, user, async_req=True) - >>> result = thread.get() + This can only be done by the logged in user. :param username: name that need to be deleted (required) :type username: str :param user: Updated user object (required) :type user: User - :param async_req: Whether to execute the request asynchronously. - :type async_req: bool, optional - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :type _preload_content: bool, optional - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :type _return_http_data_only: bool, optional :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. + request; this effectively ignores the + authentication in the spec for a single request. :type _request_auth: dict, optional - :type _content_type: string, optional: force content-type for the request + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional :return: Returns the result object. - If the method is called asynchronously, - returns the request thread. - :rtype: None - """ + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index + ) + + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + response_data.read() + return self.api_client.response_deserialize( + response_data=response_data, + response_types_map=_response_types_map, + ) - _params = locals() - _all_params = [ - 'username', - 'user' - ] - _all_params.extend( - [ - 'async_req', - '_return_http_data_only', - '_preload_content', - '_request_timeout', - '_request_auth', - '_content_type', - '_headers' + @validate_call + def update_user_without_preload_content( + self, + username: Annotated[StrictStr, Field(description="name that need to be deleted")], + user: Annotated[User, Field(description="Updated user object")], + _request_timeout: Union[ + None, + Annotated[StrictFloat, Field(gt=0)], + Tuple[ + Annotated[StrictFloat, Field(gt=0)], + Annotated[StrictFloat, Field(gt=0)] ] + ] = None, + _request_auth: Optional[Dict[StrictStr, Any]] = None, + _content_type: Optional[StrictStr] = None, + _headers: Optional[Dict[StrictStr, Any]] = None, + _host_index: Annotated[StrictInt, Field(ge=0, le=0)] = 0, + ) -> RESTResponseType: + """Updated user + + This can only be done by the logged in user. + + :param username: name that need to be deleted (required) + :type username: str + :param user: Updated user object (required) + :type user: User + :param _request_timeout: timeout setting for this request. If one + number provided, it will be total request + timeout. It can also be a pair (tuple) of + (connection, read) timeouts. + :type _request_timeout: int, tuple(int, int), optional + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the + authentication in the spec for a single request. + :type _request_auth: dict, optional + :param _content_type: force content-type for the request. + :type _content_type: str, Optional + :param _headers: set to override the headers for a single + request; this effectively ignores the headers + in the spec for a single request. + :type _headers: dict, optional + :param _host_index: set to override the host_index for a single + request; this effectively ignores the host_index + in the spec for a single request. + :type _host_index: int, optional + :return: Returns the result object. + """ # noqa: E501 + + _param = self._update_user_serialize( + username=username, + user=user, + _request_auth=_request_auth, + _content_type=_content_type, + _headers=_headers, + _host_index=_host_index ) - # validate the arguments - for _key, _val in _params['kwargs'].items(): - if _key not in _all_params: - raise ApiTypeError( - "Got an unexpected keyword argument '%s'" - " to method update_user" % _key - ) - _params[_key] = _val - del _params['kwargs'] + _response_types_map: Dict[str, Optional[str]] = { + '400': None, + '404': None, + } + response_data = self.api_client.call_api( + *_param, + _request_timeout=_request_timeout + ) + return response_data.response - _collection_formats: Dict[str, str] = {} - # process the path parameters - _path_params: Dict[str, str] = {} - if _params['username'] is not None: - _path_params['username'] = _params['username'] + def _update_user_serialize( + self, + username, + user, + _request_auth, + _content_type, + _headers, + _host_index, + ) -> RequestSerialized: + _host = None - # process the query parameters + _collection_formats: Dict[str, str] = { + } + + _path_params: Dict[str, str] = {} _query_params: List[Tuple[str, str]] = [] - # process the header parameters - _header_params = dict(_params.get('_headers', {})) - # process the form parameters + _header_params: Dict[str, Optional[str]] = _headers or {} _form_params: List[Tuple[str, str]] = [] _files: Dict[str, str] = {} + _body_params: Optional[bytes] = None + + # process the path parameters + if username is not None: + _path_params['username'] = username + # process the query parameters + # process the header parameters + # process the form parameters # process the body parameter - _body_params = None - if _params['user'] is not None: - _body_params = _params['user'] + if user is not None: + _body_params = user + + # set the HTTP header `Content-Type` - _content_types_list = _params.get('_content_type', - self.api_client.select_header_content_type( - ['application/json'])) - if _content_types_list: - _header_params['Content-Type'] = _content_types_list + if _content_type: + _header_params['Content-Type'] = _content_type + else: + _default_content_type = ( + self.api_client.select_header_content_type( + [ + 'application/json' + ] + ) + ) + if _default_content_type is not None: + _header_params['Content-Type'] = _default_content_type # authentication setting - _auth_settings: List[str] = [] # noqa: E501 - - _response_types_map: Dict[str, Optional[str]] = {} + _auth_settings: List[str] = [ + ] - return self.api_client.call_api( - '/user/{username}', 'PUT', - _path_params, - _query_params, - _header_params, + return self.api_client.param_serialize( + method='PUT', + resource_path='/user/{username}', + path_params=_path_params, + query_params=_query_params, + header_params=_header_params, body=_body_params, post_params=_form_params, files=_files, - response_types_map=_response_types_map, auth_settings=_auth_settings, - async_req=_params.get('async_req'), - _return_http_data_only=_params.get('_return_http_data_only'), # noqa: E501 - _preload_content=_params.get('_preload_content', True), - _request_timeout=_params.get('_request_timeout'), collection_formats=_collection_formats, - _request_auth=_params.get('_request_auth')) + _host=_host, + _request_auth=_request_auth + ) + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/api_client.py b/samples/openapi3/client/petstore/python/petstore_api/api_client.py index 9579cce1349c..5aca14639f2a 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/api_client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api_client.py @@ -12,24 +12,32 @@ """ # noqa: E501 -import atexit import datetime from dateutil.parser import parse import json import mimetypes -from multiprocessing.pool import ThreadPool import os import re import tempfile from urllib.parse import quote +from typing import Tuple, Optional, List, Dict from petstore_api.configuration import Configuration -from petstore_api.api_response import ApiResponse +from petstore_api.api_response import ApiResponse, T as ApiResponseT import petstore_api.models from petstore_api import rest -from petstore_api.exceptions import ApiValueError, ApiException - +from petstore_api.exceptions import ( + ApiValueError, + ApiException, + BadRequestException, + UnauthorizedException, + ForbiddenException, + NotFoundException, + ServiceException +) + +RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]] class ApiClient: """Generic API client for OpenAPI client library builds. @@ -45,8 +53,6 @@ class ApiClient: the API. :param cookie: a cookie to include in the header when making calls to the API - :param pool_threads: The number of threads to use for async requests - to the API. More threads means more concurrent API requests. """ PRIMITIVE_TYPES = (float, bool, bytes, str, int) @@ -62,13 +68,17 @@ class ApiClient: } _pool = None - def __init__(self, configuration=None, header_name=None, header_value=None, - cookie=None, pool_threads=1) -> None: + def __init__( + self, + configuration=None, + header_name=None, + header_value=None, + cookie=None + ) -> None: # use default configuration if none is provided if configuration is None: configuration = Configuration.get_default() self.configuration = configuration - self.pool_threads = pool_threads self.rest_client = rest.RESTClientObject(configuration) self.default_headers = {} @@ -83,25 +93,7 @@ def __enter__(self): return self def __exit__(self, exc_type, exc_value, traceback): - self.close() - - def close(self): - if self._pool: - self._pool.close() - self._pool.join() - self._pool = None - if hasattr(atexit, 'unregister'): - atexit.unregister(self.close) - - @property - def pool(self): - """Create thread pool on first request - avoids instantiating unused threadpool for blocking clients. - """ - if self._pool is None: - atexit.register(self.close) - self._pool = ThreadPool(self.pool_threads) - return self._pool + pass @property def user_agent(self): @@ -142,13 +134,42 @@ def set_default(cls, default): """ cls._default = default - def __call_api( - self, resource_path, method, path_params=None, - query_params=None, header_params=None, body=None, post_params=None, - files=None, response_types_map=None, auth_settings=None, - _return_http_data_only=None, collection_formats=None, - _preload_content=True, _request_timeout=None, _host=None, - _request_auth=None): + def param_serialize( + self, + method, + resource_path, + path_params=None, + query_params=None, + header_params=None, + body=None, + post_params=None, + files=None, auth_settings=None, + collection_formats=None, + _host=None, + _request_auth=None + ) -> RequestSerialized: + + """Builds the HTTP request params needed by the request. + :param method: Method to call. + :param resource_path: Path to method endpoint. + :param path_params: Path parameters in the url. + :param query_params: Query parameters in the url. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param auth_settings list: Auth Settings names for the request. + :param files dict: key -> filename, value -> filepath, + for `multipart/form-data`. + :param collection_formats: dict of collection formats for path, query, + header, and post parameters. + :param _request_auth: set to override the auth_settings for an a single + request; this effectively ignores the authentication + in the spec for a single request. + :return: tuple of form (path, http_method, query_params, header_params, + body, post_params, files) + """ config = self.configuration @@ -159,14 +180,17 @@ def __call_api( header_params['Cookie'] = self.cookie if header_params: header_params = self.sanitize_for_serialization(header_params) - header_params = dict(self.parameters_to_tuples(header_params, - collection_formats)) + header_params = dict( + self.parameters_to_tuples(header_params,collection_formats) + ) # path parameters if path_params: path_params = self.sanitize_for_serialization(path_params) - path_params = self.parameters_to_tuples(path_params, - collection_formats) + path_params = self.parameters_to_tuples( + path_params, + collection_formats + ) for k, v in path_params: # specified safe chars, encode everything resource_path = resource_path.replace( @@ -178,15 +202,22 @@ def __call_api( if post_params or files: post_params = post_params if post_params else [] post_params = self.sanitize_for_serialization(post_params) - post_params = self.parameters_to_tuples(post_params, - collection_formats) + post_params = self.parameters_to_tuples( + post_params, + collection_formats + ) post_params.extend(self.files_parameters(files)) # auth setting self.update_params_for_auth( - header_params, query_params, auth_settings, - resource_path, method, body, - request_auth=_request_auth) + header_params, + query_params, + auth_settings, + resource_path, + method, + body, + request_auth=_request_auth + ) # body if body: @@ -202,59 +233,99 @@ def __call_api( # query parameters if query_params: query_params = self.sanitize_for_serialization(query_params) - url_query = self.parameters_to_url_query(query_params, - collection_formats) + url_query = self.parameters_to_url_query( + query_params, + collection_formats + ) url += "?" + url_query + return method, url, header_params, body, post_params + + + def call_api( + self, + method, + url, + header_params=None, + body=None, + post_params=None, + _request_timeout=None + ) -> rest.RESTResponse: + """Makes the HTTP request (synchronous) + :param method: Method to call. + :param url: Path to method endpoint. + :param header_params: Header parameters to be + placed in the request header. + :param body: Request body. + :param post_params dict: Request post form parameters, + for `application/x-www-form-urlencoded`, `multipart/form-data`. + :param _request_timeout: timeout setting for this request. + :return: RESTResponse + """ + try: # perform request and return response - response_data = self.request( + response_data = self.rest_client.request( method, url, - query_params=query_params, headers=header_params, - post_params=post_params, body=body, - _preload_content=_preload_content, - _request_timeout=_request_timeout) + body=body, post_params=post_params, + _request_timeout=_request_timeout + ) + except ApiException as e: - if e.body: - e.body = e.body.decode('utf-8') raise e - self.last_response = response_data - - return_data = None # assuming deserialization is not needed - # data needs deserialization or returns HTTP data (deserialized) only - if _preload_content or _return_http_data_only: - response_type = response_types_map.get(str(response_data.status), None) - if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: - # if not found, look for '1XX', '2XX', etc. - response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) - - if response_type == "bytearray": - response_data.data = response_data.data - else: - match = None - content_type = response_data.getheader('content-type') - if content_type is not None: - match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) - encoding = match.group(1) if match else "utf-8" - response_data.data = response_data.data.decode(encoding) - - # deserialize response data - if response_type == "bytearray": - return_data = response_data.data - elif response_type: - return_data = self.deserialize(response_data, response_type) - else: - return_data = None - - if _return_http_data_only: - return return_data - else: - return ApiResponse(status_code = response_data.status, - data = return_data, - headers = response_data.getheaders(), - raw_data = response_data.data) + return response_data + + def response_deserialize( + self, + response_data: rest.RESTResponse, + response_types_map: Optional[Dict[str, ApiResponseT]]=None + ) -> ApiResponse[ApiResponseT]: + """Deserializes response into an object. + :param response_data: RESTResponse object to be deserialized. + :param response_types_map: dict of response types. + :return: ApiResponse + """ + + msg = "RESTResponse.read() must be called before passing it to response_deserialize()" + assert response_data.data is not None, msg + + response_type = response_types_map.get(str(response_data.status), None) + if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599: + # if not found, look for '1XX', '2XX', etc. + response_type = response_types_map.get(str(response_data.status)[0] + "XX", None) + + # deserialize response data + response_text = None + return_data = None + try: + if response_type == "bytearray": + return_data = response_data.data + elif response_type == "file": + return_data = self.__deserialize_file(response_data) + elif response_type is not None: + match = None + content_type = response_data.getheader('content-type') + if content_type is not None: + match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type) + encoding = match.group(1) if match else "utf-8" + response_text = response_data.data.decode(encoding) + return_data = self.deserialize(response_text, response_type) + finally: + if not 200 <= response_data.status <= 299: + raise ApiException.from_response( + http_resp=response_data, + body=response_text, + data=return_data, + ) + + return ApiResponse( + status_code = response_data.status, + data = return_data, + headers = response_data.getheaders(), + raw_data = response_data.data + ) def sanitize_for_serialization(self, obj): """Builds a JSON POST object. @@ -275,15 +346,17 @@ def sanitize_for_serialization(self, obj): elif isinstance(obj, self.PRIMITIVE_TYPES): return obj elif isinstance(obj, list): - return [self.sanitize_for_serialization(sub_obj) - for sub_obj in obj] + return [ + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ] elif isinstance(obj, tuple): - return tuple(self.sanitize_for_serialization(sub_obj) - for sub_obj in obj) + return tuple( + self.sanitize_for_serialization(sub_obj) for sub_obj in obj + ) elif isinstance(obj, (datetime.datetime, datetime.date)): return obj.isoformat() - if isinstance(obj, dict): + elif isinstance(obj, dict): obj_dict = obj else: # Convert model obj to dict except @@ -293,10 +366,12 @@ def sanitize_for_serialization(self, obj): # model definition for request. obj_dict = obj.to_dict() - return {key: self.sanitize_for_serialization(val) - for key, val in obj_dict.items()} + return { + key: self.sanitize_for_serialization(val) + for key, val in obj_dict.items() + } - def deserialize(self, response, response_type): + def deserialize(self, response_text, response_type): """Deserializes response into an object. :param response: RESTResponse object to be deserialized. @@ -305,16 +380,12 @@ def deserialize(self, response, response_type): :return: deserialized object. """ - # handle file downloading - # save response body into a tmp file and return the instance - if response_type == "file": - return self.__deserialize_file(response) # fetch data from response object try: - data = json.loads(response.data) + data = json.loads(response_text) except ValueError: - data = response.data + data = response_text return self.__deserialize(data, response_type) @@ -331,12 +402,16 @@ def __deserialize(self, data, klass): if isinstance(klass, str): if klass.startswith('List['): - sub_kls = re.match(r'List\[(.*)]', klass).group(1) + m = re.match(r'List\[(.*)]', klass) + assert m is not None, "Malformed List type definition" + sub_kls = m.group(1) return [self.__deserialize(sub_data, sub_kls) for sub_data in data] if klass.startswith('Dict['): - sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2) + m = re.match(r'Dict\[([^,]*), (.*)]', klass) + assert m is not None, "Malformed Dict type definition" + sub_kls = m.group(2) return {k: self.__deserialize(v, sub_kls) for k, v in data.items()} @@ -357,136 +432,6 @@ def __deserialize(self, data, klass): else: return self.__deserialize_model(data, klass) - def call_api(self, resource_path, method, - path_params=None, query_params=None, header_params=None, - body=None, post_params=None, files=None, - response_types_map=None, auth_settings=None, - async_req=None, _return_http_data_only=None, - collection_formats=None, _preload_content=True, - _request_timeout=None, _host=None, _request_auth=None): - """Makes the HTTP request (synchronous) and returns deserialized data. - - To make an async_req request, set the async_req parameter. - - :param resource_path: Path to method endpoint. - :param method: Method to call. - :param path_params: Path parameters in the url. - :param query_params: Query parameters in the url. - :param header_params: Header parameters to be - placed in the request header. - :param body: Request body. - :param post_params dict: Request post form parameters, - for `application/x-www-form-urlencoded`, `multipart/form-data`. - :param auth_settings list: Auth Settings names for the request. - :param response: Response data type. - :param files dict: key -> filename, value -> filepath, - for `multipart/form-data`. - :param async_req bool: execute request asynchronously - :param _return_http_data_only: response data instead of ApiResponse - object with status code, headers, etc - :param _preload_content: if False, the ApiResponse.data will - be set to none and raw_data will store the - HTTP response body without reading/decoding. - Default is True. - :param collection_formats: dict of collection formats for path, query, - header, and post parameters. - :param _request_timeout: timeout setting for this request. If one - number provided, it will be total request - timeout. It can also be a pair (tuple) of - (connection, read) timeouts. - :param _request_auth: set to override the auth_settings for an a single - request; this effectively ignores the authentication - in the spec for a single request. - :type _request_token: dict, optional - :return: - If async_req parameter is True, - the request will be called asynchronously. - The method will return the request thread. - If parameter async_req is False or missing, - then the method will return the response directly. - """ - args = ( - resource_path, - method, - path_params, - query_params, - header_params, - body, - post_params, - files, - response_types_map, - auth_settings, - _return_http_data_only, - collection_formats, - _preload_content, - _request_timeout, - _host, - _request_auth, - ) - if not async_req: - return self.__call_api(*args) - - return self.pool.apply_async(self.__call_api, args) - - def request(self, method, url, query_params=None, headers=None, - post_params=None, body=None, _preload_content=True, - _request_timeout=None): - """Makes the HTTP request using RESTClient.""" - if method == "GET": - return self.rest_client.get_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "HEAD": - return self.rest_client.head_request(url, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - headers=headers) - elif method == "OPTIONS": - return self.rest_client.options_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout) - elif method == "POST": - return self.rest_client.post_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PUT": - return self.rest_client.put_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "PATCH": - return self.rest_client.patch_request(url, - query_params=query_params, - headers=headers, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - elif method == "DELETE": - return self.rest_client.delete_request(url, - query_params=query_params, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - else: - raise ApiValueError( - "http method must be `GET`, `HEAD`, `OPTIONS`," - " `POST`, `PATCH`, `PUT` or `DELETE`." - ) - def parameters_to_tuples(self, params, collection_formats): """Get parameters as list of tuples, formatting collections. @@ -494,10 +439,10 @@ def parameters_to_tuples(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: Parameters as list of tuples, collections formatted """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 + for k, v in params.items() if isinstance(params, dict) else params: if k in collection_formats: collection_format = collection_formats[k] if collection_format == 'multi': @@ -524,14 +469,14 @@ def parameters_to_url_query(self, params, collection_formats): :param dict collection_formats: Parameter collection formats :return: URL query string (e.g. a=Hello%20World&b=123) """ - new_params = [] + new_params: List[Tuple[str, str]] = [] if collection_formats is None: collection_formats = {} - for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501 - if isinstance(v, (int, float)): - v = str(v) + for k, v in params.items() if isinstance(params, dict) else params: if isinstance(v, bool): v = str(v).lower() + if isinstance(v, (int, float)): + v = str(v) if isinstance(v, dict): v = json.dumps(v) @@ -549,7 +494,8 @@ def parameters_to_url_query(self, params, collection_formats): else: # csv is the default delimiter = ',' new_params.append( - (k, delimiter.join(quote(str(value)) for value in v))) + (k, delimiter.join(quote(str(value)) for value in v)) + ) else: new_params.append((k, quote(str(v)))) @@ -572,21 +518,24 @@ def files_parameters(self, files=None): with open(n, 'rb') as f: filename = os.path.basename(f.name) filedata = f.read() - mimetype = (mimetypes.guess_type(filename)[0] or - 'application/octet-stream') + mimetype = ( + mimetypes.guess_type(filename)[0] + or 'application/octet-stream' + ) params.append( - tuple([k, tuple([filename, filedata, mimetype])])) + tuple([k, tuple([filename, filedata, mimetype])]) + ) return params - def select_header_accept(self, accepts): + def select_header_accept(self, accepts: List[str]) -> Optional[str]: """Returns `Accept` based on an array of accepts provided. :param accepts: List of headers. :return: Accept (e.g. application/json). """ if not accepts: - return + return None for accept in accepts: if re.search('json', accept, re.IGNORECASE): @@ -609,9 +558,16 @@ def select_header_content_type(self, content_types): return content_types[0] - def update_params_for_auth(self, headers, queries, auth_settings, - resource_path, method, body, - request_auth=None): + def update_params_for_auth( + self, + headers, + queries, + auth_settings, + resource_path, + method, + body, + request_auth=None + ) -> None: """Updates header and query params based on authentication setting. :param headers: Header parameters dict to be updated. @@ -628,21 +584,36 @@ def update_params_for_auth(self, headers, queries, auth_settings, return if request_auth: - self._apply_auth_params(headers, queries, - resource_path, method, body, - request_auth) - return - - for auth in auth_settings: - auth_setting = self.configuration.auth_settings().get(auth) - if auth_setting: - self._apply_auth_params(headers, queries, - resource_path, method, body, - auth_setting) - - def _apply_auth_params(self, headers, queries, - resource_path, method, body, - auth_setting): + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + request_auth + ) + else: + for auth in auth_settings: + auth_setting = self.configuration.auth_settings().get(auth) + if auth_setting: + self._apply_auth_params( + headers, + queries, + resource_path, + method, + body, + auth_setting + ) + + def _apply_auth_params( + self, + headers, + queries, + resource_path, + method, + body, + auth_setting + ) -> None: """Updates the request parameters based on a single auth_setting :param headers: Header parameters dict to be updated. @@ -678,6 +649,9 @@ def __deserialize_file(self, response): Saves response body into a file in a temporary folder, using the filename from the `Content-Disposition` header if provided. + handle file downloading + save response body into a tmp file and return the instance + :param response: RESTResponse. :return: file path. """ @@ -687,8 +661,12 @@ def __deserialize_file(self, response): content_disposition = response.getheader("Content-Disposition") if content_disposition: - filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', - content_disposition).group(1) + m = re.search( + r'filename=[\'"]?([^\'"\s]+)[\'"]?', + content_disposition + ) + assert m is not None, "Unexpected 'content-disposition' header value" + filename = m.group(1) path = os.path.join(os.path.dirname(path), filename) with open(path, "wb") as f: diff --git a/samples/openapi3/client/petstore/python/petstore_api/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/api_response.py index a0b62b95246c..9bc7c11f6b9f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/api_response.py @@ -1,25 +1,21 @@ """API response object.""" from __future__ import annotations -from typing import Any, Dict, Optional -from pydantic import Field, StrictInt, StrictStr +from typing import Optional, Generic, Mapping, TypeVar +from pydantic import Field, StrictInt, StrictBytes, BaseModel -class ApiResponse: +T = TypeVar("T") + +class ApiResponse(BaseModel, Generic[T]): """ API response object """ - status_code: Optional[StrictInt] = Field(None, description="HTTP status code") - headers: Optional[Dict[StrictStr, StrictStr]] = Field(None, description="HTTP headers") - data: Optional[Any] = Field(None, description="Deserialized data given the data type") - raw_data: Optional[Any] = Field(None, description="Raw data (HTTP response body)") + status_code: StrictInt = Field(description="HTTP status code") + headers: Optional[Mapping[str, str]] = Field(None, description="HTTP headers") + data: T = Field(description="Deserialized data given the data type") + raw_data: StrictBytes = Field(description="Raw data (HTTP response body)") - def __init__(self, - status_code=None, - headers=None, - data=None, - raw_data=None) -> None: - self.status_code = status_code - self.headers = headers - self.data = data - self.raw_data = raw_data + model_config = { + "arbitrary_types_allowed": True + } diff --git a/samples/openapi3/client/petstore/python/petstore_api/configuration.py b/samples/openapi3/client/petstore/python/petstore_api/configuration.py index 8bca6dc7ab0e..c6751d422b7f 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/configuration.py +++ b/samples/openapi3/client/petstore/python/petstore_api/configuration.py @@ -14,8 +14,10 @@ import copy import logging +from logging import FileHandler import multiprocessing import sys +from typing import Optional import urllib3 import http.client as httplib @@ -198,7 +200,7 @@ def __init__(self, host=None, self.logger_stream_handler = None """Log stream handler """ - self.logger_file_handler = None + self.logger_file_handler: Optional[FileHandler] = None """Log file handler """ self.logger_file = None @@ -238,7 +240,7 @@ def __init__(self, host=None, cpu_count * 5 is used as default value to increase performance. """ - self.proxy = None + self.proxy: Optional[str] = None """Proxy URL """ self.proxy_headers = None diff --git a/samples/openapi3/client/petstore/python/petstore_api/exceptions.py b/samples/openapi3/client/petstore/python/petstore_api/exceptions.py index 6c4ae9c4e02f..0cb484becbdb 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/exceptions.py +++ b/samples/openapi3/client/petstore/python/petstore_api/exceptions.py @@ -11,6 +11,8 @@ Do not edit the class manually. """ # noqa: E501 +from typing import Any, Optional +from typing_extensions import Self class OpenApiException(Exception): """The base exception class for all OpenAPIExceptions""" @@ -101,17 +103,56 @@ def __init__(self, msg, path_to_item=None) -> None: class ApiException(OpenApiException): - def __init__(self, status=None, reason=None, http_resp=None) -> None: + def __init__( + self, + status=None, + reason=None, + http_resp=None, + *, + body: Optional[str] = None, + data: Optional[Any] = None, + ) -> None: + self.status = status + self.reason = reason + self.body = body + self.data = data + self.headers = None + if http_resp: - self.status = http_resp.status - self.reason = http_resp.reason - self.body = http_resp.data + if self.status is None: + self.status = http_resp.status + if self.reason is None: + self.reason = http_resp.reason + if self.body is None: + try: + self.body = http_resp.data.decode('utf-8') + except Exception: + pass self.headers = http_resp.getheaders() - else: - self.status = status - self.reason = reason - self.body = None - self.headers = None + + @classmethod + def from_response( + cls, + *, + http_resp, + body: Optional[str], + data: Optional[Any], + ) -> Self: + if http_resp.status == 400: + raise BadRequestException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 401: + raise UnauthorizedException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 403: + raise ForbiddenException(http_resp=http_resp, body=body, data=data) + + if http_resp.status == 404: + raise NotFoundException(http_resp=http_resp, body=body, data=data) + + if 500 <= http_resp.status <= 599: + raise ServiceException(http_resp=http_resp, body=body, data=data) + raise ApiException(http_resp=http_resp, body=body, data=data) def __str__(self): """Custom error messages for exception""" @@ -121,38 +162,30 @@ def __str__(self): error_message += "HTTP response headers: {0}\n".format( self.headers) - if self.body: - error_message += "HTTP response body: {0}\n".format(self.body) + if self.data or self.body: + error_message += "HTTP response body: {0}\n".format(self.data or self.body) return error_message + class BadRequestException(ApiException): + pass - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(BadRequestException, self).__init__(status, reason, http_resp) class NotFoundException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(NotFoundException, self).__init__(status, reason, http_resp) + pass class UnauthorizedException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(UnauthorizedException, self).__init__(status, reason, http_resp) + pass class ForbiddenException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ForbiddenException, self).__init__(status, reason, http_resp) + pass class ServiceException(ApiException): - - def __init__(self, status=None, reason=None, http_resp=None) -> None: - super(ServiceException, self).__init__(status, reason, http_resp) + pass def render_path(path_to_item): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py index dd9388d355da..945dd198de1a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/__init__.py @@ -22,7 +22,6 @@ from petstore_api.models.animal import Animal from petstore_api.models.any_of_color import AnyOfColor from petstore_api.models.any_of_pig import AnyOfPig -from petstore_api.models.api_response import ApiResponse from petstore_api.models.array_of_array_of_model import ArrayOfArrayOfModel from petstore_api.models.array_of_array_of_number_only import ArrayOfArrayOfNumberOnly from petstore_api.models.array_of_number_only import ArrayOfNumberOnly @@ -61,6 +60,7 @@ from petstore_api.models.map_test import MapTest from petstore_api.models.mixed_properties_and_additional_properties_class import MixedPropertiesAndAdditionalPropertiesClass from petstore_api.models.model200_response import Model200Response +from petstore_api.models.model_api_response import ModelApiResponse from petstore_api.models.model_return import ModelReturn from petstore_api.models.name import Name from petstore_api.models.nullable_class import NullableClass @@ -89,6 +89,8 @@ from petstore_api.models.special_model_name import SpecialModelName from petstore_api.models.special_name import SpecialName from petstore_api.models.tag import Tag +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response from petstore_api.models.test_inline_freeform_additional_properties_request import TestInlineFreeformAdditionalPropertiesRequest from petstore_api.models.tiger import Tiger from petstore_api.models.unnamed_dict_with_additional_model_list_properties import UnnamedDictWithAdditionalModelListProperties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py index 0c7dbcc65571..43a139dc1749 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_any_type.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesAnyType(BaseModel): """ AdditionalPropertiesAnyType - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesAnyType from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesAnyType from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py index 396e7d12bccd..f12f7a84965d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_class.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesClass(BaseModel): """ AdditionalPropertiesClass - """ + """ # noqa: E501 map_property: Optional[Dict[str, StrictStr]] = None map_of_map_property: Optional[Dict[str, Dict[str, StrictStr]]] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class AdditionalPropertiesClass(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py index 3b562c4f8000..03735c7429c9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_object.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesObject(BaseModel): """ AdditionalPropertiesObject - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesObject from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesObject from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py index a626cd66730f..7e3f920ab3cb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/additional_properties_with_description_only.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class AdditionalPropertiesWithDescriptionOnly(BaseModel): """ AdditionalPropertiesWithDescriptionOnly - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AdditionalPropertiesWithDescriptionOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AdditionalPropertiesWithDescriptionOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py index c25ff6350690..2be839908d10 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/all_of_with_single_ref.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field from petstore_api.models.single_ref_type import SingleRefType -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class AllOfWithSingleRef(BaseModel): """ AllOfWithSingleRef - """ + """ # noqa: E501 username: Optional[StrictStr] = None single_ref_type: Optional[SingleRefType] = Field(default=None, alias="SingleRefType") additional_properties: Dict[str, Any] = {} @@ -39,7 +34,8 @@ class AllOfWithSingleRef(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of AllOfWithSingleRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -83,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of AllOfWithSingleRef from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/animal.py b/samples/openapi3/client/petstore/python/petstore_api/models/animal.py index 138891981e1d..4e14ccbfc780 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/animal.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/animal.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional, Union -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Animal(BaseModel): """ Animal - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") color: Optional[StrictStr] = 'red' additional_properties: Dict[str, Any] = {} @@ -38,12 +33,13 @@ class Animal(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } # JSON field name that stores the object type - __discriminator_property_name: ClassVar[List[str]] = 'className' + __discriminator_property_name: ClassVar[str] = 'className' # discriminator mappings __discriminator_value_class_map: ClassVar[Dict[str, str]] = { @@ -51,7 +47,7 @@ class Animal(BaseModel): } @classmethod - def get_discriminator_value(cls, obj: dict) -> str: + def get_discriminator_value(cls, obj: Dict[str, Any]) -> Optional[str]: """Returns the discriminator value (object type) of the data""" discriminator_value = obj[cls.__discriminator_property_name] if discriminator_value: @@ -69,7 +65,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Union[Self, Self]: + def from_json(cls, json_str: str) -> Optional[Union[Self, Self]]: """Create an instance of Animal from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -84,11 +80,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -99,7 +97,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Union[Self, Self]: + def from_dict(cls, obj: Dict[str, Any]) -> Optional[Union[Self, Self]]: """Create an instance of Animal from a dict""" # look up the object type based on discriminator mapping object_type = cls.get_discriminator_value(obj) @@ -113,9 +111,6 @@ def from_dict(cls, obj: dict) -> Union[Self, Self]: from petstore_api.models.cat import Cat from petstore_api.models.dog import Dog -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # Animal.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +Animal.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py index db4718b868b0..b952c65ffcce 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_color.py @@ -17,18 +17,12 @@ import json import pprint import re # noqa: F401 - -from typing import List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import List, Optional from typing_extensions import Annotated from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal -from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Literal, Self +from pydantic import Field ANYOFCOLOR_ANY_OF_SCHEMAS = ["List[int]", "str"] @@ -47,10 +41,11 @@ class AnyOfColor(BaseModel): actual_instance: Optional[Union[List[int], str]] = None else: actual_instance: Any = None - any_of_schemas: List[str] = Literal[ANYOFCOLOR_ANY_OF_SCHEMAS] + any_of_schemas: List[str] = Field(default=Literal["List[int]", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } def __init__(self, *args, **kwargs) -> None: @@ -92,7 +87,7 @@ def actual_instance_must_validate_anyof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -139,22 +134,20 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: - return "null" + return None - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py index 2a2a04932225..3dff97862165 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/any_of_pig.py @@ -17,18 +17,13 @@ import json import pprint import re # noqa: F401 - -from typing import Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal -from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Literal, Self +from pydantic import Field ANYOFPIG_ANY_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -45,10 +40,11 @@ class AnyOfPig(BaseModel): actual_instance: Optional[Union[BasquePig, DanishPig]] = None else: actual_instance: Any = None - any_of_schemas: List[str] = Literal[ANYOFPIG_ANY_OF_SCHEMAS] + any_of_schemas: List[str] = Field(default=Literal["BasquePig", "DanishPig"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } def __init__(self, *args, **kwargs) -> None: @@ -84,7 +80,7 @@ def actual_instance_must_validate_anyof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Dict[str, Any]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -116,22 +112,20 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: - return "null" + return None - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: - return json.dumps(self.actual_instance) + return self.actual_instance def to_str(self) -> str: """Returns the string representation of the actual instance""" diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py index 1a1517f63713..06b35e19668e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_model.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayOfArrayOfModel(BaseModel): """ ArrayOfArrayOfModel - """ + """ # noqa: E501 another_property: Optional[List[List[Tag]]] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["another_property"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfArrayOfModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each item in another_property (list of list) @@ -90,7 +89,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfArrayOfModel from a dict""" if obj is None: return None @@ -101,7 +100,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "another_property": [ [Tag.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("another_property") + for _item in obj["another_property"] ] if obj.get("another_property") is not None else None }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py index 22b78207654e..94aa0ac6539f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_array_of_number_only.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictFloat -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayOfArrayOfNumberOnly(BaseModel): """ ArrayOfArrayOfNumberOnly - """ + """ # noqa: E501 array_array_number: Optional[List[List[StrictFloat]]] = Field(default=None, alias="ArrayArrayNumber") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["ArrayArrayNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfArrayOfNumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfArrayOfNumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py index af483a7d7c77..c0da65e33234 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_of_number_only.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictFloat -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayOfNumberOnly(BaseModel): """ ArrayOfNumberOnly - """ + """ # noqa: E501 array_number: Optional[List[StrictFloat]] = Field(default=None, alias="ArrayNumber") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["ArrayNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayOfNumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayOfNumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py index 4a105ad03563..01639b8261a5 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/array_test.py @@ -17,22 +17,17 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field from typing_extensions import Annotated from petstore_api.models.read_only_first import ReadOnlyFirst -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ArrayTest(BaseModel): """ ArrayTest - """ + """ # noqa: E501 array_of_string: Optional[Annotated[List[StrictStr], Field(min_length=0, max_length=3)]] = None array_array_of_integer: Optional[List[List[StrictInt]]] = None array_array_of_model: Optional[List[List[ReadOnlyFirst]]] = None @@ -41,7 +36,8 @@ class ArrayTest(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -55,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ArrayTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -70,11 +66,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each item in array_array_of_model (list of list) @@ -94,7 +92,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ArrayTest from a dict""" if obj is None: return None @@ -107,7 +105,7 @@ def from_dict(cls, obj: dict) -> Self: "array_array_of_integer": obj.get("array_array_of_integer"), "array_array_of_model": [ [ReadOnlyFirst.from_dict(_inner_item) for _inner_item in _item] - for _item in obj.get("array_array_of_model") + for _item in obj["array_array_of_model"] ] if obj.get("array_array_of_model") is not None else None }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py index 7bf0494f1718..c1c5b702f33a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/basque_pig.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class BasquePig(BaseModel): """ BasquePig - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") color: StrictStr additional_properties: Dict[str, Any] = {} @@ -38,7 +33,8 @@ class BasquePig(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of BasquePig from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -82,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of BasquePig from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py b/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py index 6405f1383e72..117c5cebac02 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/capitalization.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Capitalization(BaseModel): """ Capitalization - """ + """ # noqa: E501 small_camel: Optional[StrictStr] = Field(default=None, alias="smallCamel") capital_camel: Optional[StrictStr] = Field(default=None, alias="CapitalCamel") small_snake: Optional[StrictStr] = Field(default=None, alias="small_Snake") @@ -42,7 +37,8 @@ class Capitalization(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -56,7 +52,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Capitalization from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -71,11 +67,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -86,7 +84,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Capitalization from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/cat.py b/samples/openapi3/client/petstore/python/petstore_api/models/cat.py index 3801d7c5e73c..a9c79649401d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/cat.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/cat.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import StrictBool +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Cat(Animal): """ Cat - """ + """ # noqa: E501 declawed: Optional[StrictBool] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["className", "color", "declawed"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Cat from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Cat from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/category.py b/samples/openapi3/client/petstore/python/petstore_api/models/category.py index 655d732f2743..d1808eb1a976 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/category.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/category.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Category(BaseModel): """ Category - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: StrictStr additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class Category(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Category from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Category from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py index 87c75c69894c..914e011e9106 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/circular_reference_model.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class CircularReferenceModel(BaseModel): """ CircularReferenceModel - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested: Optional[FirstRef] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class CircularReferenceModel(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CircularReferenceModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CircularReferenceModel from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested": FirstRef.from_dict(obj.get("nested")) if obj.get("nested") is not None else None + "nested": FirstRef.from_dict(obj["nested"]) if obj.get("nested") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): @@ -104,9 +103,6 @@ def from_dict(cls, obj: dict) -> Self: return _obj from petstore_api.models.first_ref import FirstRef -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # CircularReferenceModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +CircularReferenceModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py index 44c2a4c46d61..6148c24ceed1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/class_model.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ClassModel(BaseModel): """ - Model for testing model with \"_class\" property # noqa: E501 - """ + Model for testing model with \"_class\" property + """ # noqa: E501 var_class: Optional[StrictStr] = Field(default=None, alias="_class") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["_class"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ClassModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ClassModel from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/client.py b/samples/openapi3/client/petstore/python/petstore_api/models/client.py index 6699b5e70d60..72f57b6815d7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/client.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/client.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Client(BaseModel): """ Client - """ + """ # noqa: E501 client: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["client"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Client from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Client from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/color.py b/samples/openapi3/client/petstore/python/petstore_api/models/color.py index b5abaccbd0ba..bfcbcfc03f27 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/color.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/color.py @@ -13,22 +13,14 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import Any, List, Optional from typing_extensions import Annotated -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self COLOR_ONE_OF_SCHEMAS = ["List[int]", "str"] @@ -43,10 +35,11 @@ class Color(BaseModel): # data type: str oneof_schema_3_validator: Optional[Annotated[str, Field(min_length=7, strict=True, max_length=7)]] = Field(default=None, description="Hex color string, such as #00FF00.") actual_instance: Optional[Union[List[int], str]] = None - one_of_schemas: List[str] = Literal["List[int]", "str"] + one_of_schemas: List[str] = Field(default=Literal["List[int]", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -96,11 +89,11 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: Optional[str]) -> Self: """Returns the object represented by the json string""" instance = cls.model_construct() if json_str is None: @@ -151,19 +144,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], List[int], str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/creature.py b/samples/openapi3/client/petstore/python/petstore_api/models/creature.py index eb6ef06e7dc5..052e533ac378 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/creature.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/creature.py @@ -17,20 +17,16 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List from petstore_api.models.creature_info import CreatureInfo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Creature(BaseModel): """ Creature - """ + """ # noqa: E501 info: CreatureInfo type: StrictStr additional_properties: Dict[str, Any] = {} @@ -38,7 +34,8 @@ class Creature(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Creature from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of info @@ -85,7 +84,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Creature from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "info": CreatureInfo.from_dict(obj.get("info")) if obj.get("info") is not None else None, + "info": CreatureInfo.from_dict(obj["info"]) if obj.get("info") is not None else None, "type": obj.get("type") }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py b/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py index 4a8fc9bbf112..6096bbbb5c77 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/creature_info.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List +from typing import Optional, Set +from typing_extensions import Self class CreatureInfo(BaseModel): """ CreatureInfo - """ + """ # noqa: E501 name: StrictStr additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of CreatureInfo from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of CreatureInfo from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py index 42858fbaca6a..16b44763d28b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/danish_pig.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class DanishPig(BaseModel): """ DanishPig - """ + """ # noqa: E501 class_name: StrictStr = Field(alias="className") size: StrictInt additional_properties: Dict[str, Any] = {} @@ -38,7 +33,8 @@ class DanishPig(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DanishPig from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -82,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DanishPig from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py b/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py index a0eec30d42a7..ed9dc5912f12 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/deprecated_object.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class DeprecatedObject(BaseModel): """ DeprecatedObject - """ + """ # noqa: E501 name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["name"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DeprecatedObject from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DeprecatedObject from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/dog.py b/samples/openapi3/client/petstore/python/petstore_api/models/dog.py index ce75782ef430..c7dda299c935 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/dog.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/dog.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import StrictStr +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Dog(Animal): """ Dog - """ + """ # noqa: E501 breed: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["className", "color", "breed"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Dog from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Dog from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py index f36c7e906d7f..d1211acd8253 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/dummy_model.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class DummyModel(BaseModel): """ DummyModel - """ + """ # noqa: E501 category: Optional[StrictStr] = None self_ref: Optional[SelfReferenceModel] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class DummyModel(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of DummyModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of self_ref @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of DummyModel from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "self_ref": SelfReferenceModel.from_dict(obj.get("self_ref")) if obj.get("self_ref") is not None else None + "self_ref": SelfReferenceModel.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): @@ -104,9 +103,6 @@ def from_dict(cls, obj: dict) -> Self: return _obj from petstore_api.models.self_reference_model import SelfReferenceModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # DummyModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +DummyModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py index f0a8bcd34e17..378abbf93c6d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_arrays.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr, field_validator -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class EnumArrays(BaseModel): """ EnumArrays - """ + """ # noqa: E501 just_symbol: Optional[StrictStr] = None array_enum: Optional[List[StrictStr]] = None additional_properties: Dict[str, Any] = {} @@ -58,7 +54,8 @@ def array_enum_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -72,7 +69,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EnumArrays from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -87,11 +84,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -102,7 +101,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EnumArrays from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_class.py index 11255f418979..1ba5af8036df 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_class.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumClass(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_string1.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_string1.py index efe9a6056218..678b4e12661f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_string1.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_string1.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumString1(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_string2.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_string2.py index 222c5dc6b824..a959f554e0af 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_string2.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_string2.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class EnumString2(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py index 3072578a82c7..835d3da23303 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/enum_test.py @@ -17,24 +17,19 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictFloat, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictFloat, StrictInt, StrictStr, field_validator -from pydantic import Field from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_default_value import OuterEnumDefaultValue from petstore_api.models.outer_enum_integer import OuterEnumInteger from petstore_api.models.outer_enum_integer_default_value import OuterEnumIntegerDefaultValue -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class EnumTest(BaseModel): """ EnumTest - """ + """ # noqa: E501 enum_string: Optional[StrictStr] = None enum_string_required: StrictStr enum_integer_default: Optional[StrictInt] = 5 @@ -96,7 +91,8 @@ def enum_number_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -110,7 +106,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of EnumTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -125,11 +121,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -145,7 +143,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of EnumTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/file.py b/samples/openapi3/client/petstore/python/petstore_api/models/file.py index e3fa35e73d41..ce2688c5f0cb 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/file.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/file.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class File(BaseModel): """ - Must be named `File` for test. # noqa: E501 - """ + Must be named `File` for test. + """ # noqa: E501 source_uri: Optional[StrictStr] = Field(default=None, description="Test capitalization", alias="sourceURI") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["sourceURI"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of File from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of File from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py index a1dadbb4a2f1..f660e0161ca7 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/file_schema_test_class.py @@ -17,20 +17,16 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.file import File -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FileSchemaTestClass(BaseModel): """ FileSchemaTestClass - """ + """ # noqa: E501 file: Optional[File] = None files: Optional[List[File]] = None additional_properties: Dict[str, Any] = {} @@ -38,7 +34,8 @@ class FileSchemaTestClass(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FileSchemaTestClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of file @@ -92,7 +91,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FileSchemaTestClass from a dict""" if obj is None: return None @@ -101,8 +100,8 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "file": File.from_dict(obj.get("file")) if obj.get("file") is not None else None, - "files": [File.from_dict(_item) for _item in obj.get("files")] if obj.get("files") is not None else None + "file": File.from_dict(obj["file"]) if obj.get("file") is not None else None, + "files": [File.from_dict(_item) for _item in obj["files"]] if obj.get("files") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py index c74cacde3be7..a7c2af974d43 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/first_ref.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class FirstRef(BaseModel): """ FirstRef - """ + """ # noqa: E501 category: Optional[StrictStr] = None self_ref: Optional[SecondRef] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class FirstRef(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FirstRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of self_ref @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FirstRef from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "self_ref": SecondRef.from_dict(obj.get("self_ref")) if obj.get("self_ref") is not None else None + "self_ref": SecondRef.from_dict(obj["self_ref"]) if obj.get("self_ref") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): @@ -104,9 +103,6 @@ def from_dict(cls, obj: dict) -> Self: return _obj from petstore_api.models.second_ref import SecondRef -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # FirstRef.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +FirstRef.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/foo.py b/samples/openapi3/client/petstore/python/petstore_api/models/foo.py index 263cd0026ecc..24321df43c5b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/foo.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/foo.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Foo(BaseModel): """ Foo - """ + """ # noqa: E501 bar: Optional[StrictStr] = 'bar' additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["bar"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Foo from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Foo from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py index 8fdaee41b988..d602be27708d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/foo_get_default_response.py @@ -17,27 +17,24 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.foo import Foo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FooGetDefaultResponse(BaseModel): """ FooGetDefaultResponse - """ + """ # noqa: E501 string: Optional[Foo] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["string"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FooGetDefaultResponse from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of string @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FooGetDefaultResponse from a dict""" if obj is None: return None @@ -93,7 +92,7 @@ def from_dict(cls, obj: dict) -> Self: return cls.model_validate(obj) _obj = cls.model_validate({ - "string": Foo.from_dict(obj.get("string")) if obj.get("string") is not None else None + "string": Foo.from_dict(obj["string"]) if obj.get("string") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py index 685fb0250f66..c2787c1586a3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/format_test.py @@ -18,21 +18,17 @@ import json from datetime import date, datetime -from typing import Any, ClassVar, Dict, List, Optional, Union -from pydantic import BaseModel, StrictBytes, StrictInt, StrictStr, field_validator from decimal import Decimal -from pydantic import Field +from pydantic import BaseModel, Field, StrictBytes, StrictInt, StrictStr, field_validator +from typing import Any, ClassVar, Dict, List, Optional, Union from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class FormatTest(BaseModel): """ FormatTest - """ + """ # noqa: E501 integer: Optional[Annotated[int, Field(le=100, strict=True, ge=10)]] = None int32: Optional[Annotated[int, Field(le=200, strict=True, ge=20)]] = None int64: Optional[StrictInt] = None @@ -95,7 +91,8 @@ def pattern_with_digits_and_delimiter_validate_regular_expression(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -109,7 +106,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of FormatTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -124,11 +121,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -139,7 +138,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of FormatTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py index 68f2b2da1f44..6e80185d9b8d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/has_only_read_only.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class HasOnlyReadOnly(BaseModel): """ HasOnlyReadOnly - """ + """ # noqa: E501 bar: Optional[StrictStr] = None foo: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class HasOnlyReadOnly(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of HasOnlyReadOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,13 +65,15 @@ def to_dict(self) -> Dict[str, Any]: * OpenAPI `readOnly` fields are excluded. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "bar", + "foo", + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "bar", - "foo", - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -85,7 +84,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of HasOnlyReadOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py b/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py index 7665cc0df357..8f6e6565fd5b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/health_check_result.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class HealthCheckResult(BaseModel): """ - Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. # noqa: E501 - """ + Just a string to inform instance is up and running. Make it nullable in hope to get it as pointer in generated model. + """ # noqa: E501 nullable_message: Optional[StrictStr] = Field(default=None, alias="NullableMessage") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["NullableMessage"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of HealthCheckResult from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -86,7 +84,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of HealthCheckResult from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py index 73aba7cd2b0a..e71b74e0a7db 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/inner_dict_with_property.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional, Union -from pydantic import BaseModel -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from pydantic import BaseModel, Field +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class InnerDictWithProperty(BaseModel): """ InnerDictWithProperty - """ - a_property: Optional[Union[str, Any]] = Field(default=None, alias="aProperty") + """ # noqa: E501 + a_property: Optional[Dict[str, Any]] = Field(default=None, alias="aProperty") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["aProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of InnerDictWithProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of InnerDictWithProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py index cd6f56fdeba5..def00e1558c4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/int_or_string.py @@ -13,22 +13,14 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator -from pydantic import Field +from typing import Any, List, Optional from typing_extensions import Annotated -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self INTORSTRING_ONE_OF_SCHEMAS = ["int", "str"] @@ -41,10 +33,11 @@ class IntOrString(BaseModel): # data type: str oneof_schema_2_validator: Optional[StrictStr] = None actual_instance: Optional[Union[int, str]] = None - one_of_schemas: List[str] = Literal["int", "str"] + one_of_schemas: List[str] = Field(default=Literal["int", "str"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -85,7 +78,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -128,19 +121,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], int, str]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py index f0951e6ca3d4..568454db1e5b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/list_class.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ListClass(BaseModel): """ ListClass - """ + """ # noqa: E501 var_123_list: Optional[StrictStr] = Field(default=None, alias="123-list") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["123-list"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ListClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ListClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py index cbc1f669c86d..8ff27629f5a9 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/map_of_array_of_model.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class MapOfArrayOfModel(BaseModel): """ MapOfArrayOfModel - """ + """ # noqa: E501 shop_id_to_org_online_lip_map: Optional[Dict[str, List[Tag]]] = Field(default=None, alias="shopIdToOrgOnlineLipMap") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["shopIdToOrgOnlineLipMap"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MapOfArrayOfModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in shop_id_to_org_online_lip_map (dict of array) @@ -91,7 +89,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MapOfArrayOfModel from a dict""" if obj is None: return None @@ -106,7 +104,7 @@ def from_dict(cls, obj: dict) -> Self: if _v is not None else None ) - for _k, _v in obj.get("shopIdToOrgOnlineLipMap").items() + for _k, _v in obj.get("shopIdToOrgOnlineLipMap", {}).items() ) }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py index 504c11a9aeda..3912fd9d66ee 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/map_test.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictBool, StrictStr, field_validator -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class MapTest(BaseModel): """ MapTest - """ + """ # noqa: E501 map_map_of_string: Optional[Dict[str, Dict[str, StrictStr]]] = None map_of_enum_string: Optional[Dict[str, StrictStr]] = None direct_map: Optional[Dict[str, StrictBool]] = None @@ -49,7 +45,8 @@ def map_of_enum_string_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -63,7 +60,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MapTest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -78,11 +75,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -93,7 +92,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MapTest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py index a9dbe95b3dac..7b7506264a8e 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/mixed_properties_and_additional_properties_class.py @@ -18,20 +18,16 @@ import json from datetime import datetime +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field from petstore_api.models.animal import Animal -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): """ MixedPropertiesAndAdditionalPropertiesClass - """ + """ # noqa: E501 uuid: Optional[StrictStr] = None date_time: Optional[datetime] = Field(default=None, alias="dateTime") map: Optional[Dict[str, Animal]] = None @@ -40,7 +36,8 @@ class MixedPropertiesAndAdditionalPropertiesClass(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -69,11 +66,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in map (dict) @@ -91,7 +90,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of MixedPropertiesAndAdditionalPropertiesClass from a dict""" if obj is None: return None @@ -104,7 +103,7 @@ def from_dict(cls, obj: dict) -> Self: "dateTime": obj.get("dateTime"), "map": dict( (_k, Animal.from_dict(_v)) - for _k, _v in obj.get("map").items() + for _k, _v in obj["map"].items() ) if obj.get("map") is not None else None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py index 1f190eb4a08f..08010aa12199 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model200_response.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Model200Response(BaseModel): """ - Model for testing model name starting with number # noqa: E501 - """ + Model for testing model name starting with number + """ # noqa: E501 name: Optional[StrictInt] = None var_class: Optional[StrictStr] = Field(default=None, alias="class") additional_properties: Dict[str, Any] = {} @@ -38,7 +33,8 @@ class Model200Response(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Model200Response from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -82,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Model200Response from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/api_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py similarity index 81% rename from samples/openapi3/client/petstore/python/petstore_api/models/api_response.py rename to samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py index 91af78b6d654..75b120b87984 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/api_response.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model_api_response.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self -class ApiResponse(BaseModel): - """ - ApiResponse +class ModelApiResponse(BaseModel): """ + ModelApiResponse + """ # noqa: E501 code: Optional[StrictInt] = None type: Optional[StrictStr] = None message: Optional[StrictStr] = None @@ -38,7 +34,8 @@ class ApiResponse(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,8 +49,8 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: - """Create an instance of ApiResponse from a JSON string""" + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of ModelApiResponse from a JSON string""" return cls.from_dict(json.loads(json_str)) def to_dict(self) -> Dict[str, Any]: @@ -67,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -82,8 +81,8 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: - """Create an instance of ApiResponse from a dict""" + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of ModelApiResponse from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py b/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py index 38d635780f1c..4648542ef073 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/model_return.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ModelReturn(BaseModel): """ - Model for testing reserved words # noqa: E501 - """ + Model for testing reserved words + """ # noqa: E501 var_return: Optional[StrictInt] = Field(default=None, alias="return") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["return"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ModelReturn from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ModelReturn from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/name.py b/samples/openapi3/client/petstore/python/petstore_api/models/name.py index 00575c968913..acb8c1a60efe 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/name.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Name(BaseModel): """ - Model for testing model name same as property name # noqa: E501 - """ + Model for testing model name same as property name + """ # noqa: E501 name: StrictInt snake_case: Optional[StrictInt] = None var_property: Optional[StrictStr] = Field(default=None, alias="property") @@ -40,7 +35,8 @@ class Name(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Name from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -71,13 +67,15 @@ def to_dict(self) -> Dict[str, Any]: * OpenAPI `readOnly` fields are excluded. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "snake_case", + "var_123_number", + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "snake_case", - "var_123_number", - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -88,7 +86,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Name from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py index 4b76865b0d31..903fa5d037b8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_class.py @@ -18,18 +18,15 @@ import json from datetime import date, datetime -from typing import Any, ClassVar, Dict, List, Optional, Union from pydantic import BaseModel, StrictBool, StrictFloat, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class NullableClass(BaseModel): """ NullableClass - """ + """ # noqa: E501 required_integer_prop: Optional[StrictInt] integer_prop: Optional[StrictInt] = None number_prop: Optional[StrictFloat] = None @@ -37,18 +34,19 @@ class NullableClass(BaseModel): string_prop: Optional[StrictStr] = None date_prop: Optional[date] = None datetime_prop: Optional[datetime] = None - array_nullable_prop: Optional[List[Union[str, Any]]] = None - array_and_items_nullable_prop: Optional[List[Union[str, Any]]] = None - array_items_nullable: Optional[List[Union[str, Any]]] = None - object_nullable_prop: Optional[Dict[str, Union[str, Any]]] = None - object_and_items_nullable_prop: Optional[Dict[str, Union[str, Any]]] = None - object_items_nullable: Optional[Dict[str, Union[str, Any]]] = None + array_nullable_prop: Optional[List[Dict[str, Any]]] = None + array_and_items_nullable_prop: Optional[List[Dict[str, Any]]] = None + array_items_nullable: Optional[List[Dict[str, Any]]] = None + object_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None + object_and_items_nullable_prop: Optional[Dict[str, Dict[str, Any]]] = None + object_items_nullable: Optional[Dict[str, Dict[str, Any]]] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["required_integer_prop", "integer_prop", "number_prop", "boolean_prop", "string_prop", "date_prop", "datetime_prop", "array_nullable_prop", "array_and_items_nullable_prop", "array_items_nullable", "object_nullable_prop", "object_and_items_nullable_prop", "object_items_nullable"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -62,7 +60,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NullableClass from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -77,11 +75,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -147,7 +147,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NullableClass from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py index da7b79fcb40b..b6c314ecbef8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/nullable_property.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, field_validator from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, field_validator -from pydantic import Field from typing_extensions import Annotated -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class NullableProperty(BaseModel): """ NullableProperty - """ + """ # noqa: E501 id: StrictInt name: Optional[Annotated[str, Field(strict=True)]] additional_properties: Dict[str, Any] = {} @@ -49,7 +44,8 @@ def name_validate_regular_expression(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -63,7 +59,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NullableProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -78,11 +74,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -98,7 +96,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NullableProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py b/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py index 2b8d76dab0d9..5674323d5aae 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/number_only.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictFloat from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictFloat -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class NumberOnly(BaseModel): """ NumberOnly - """ + """ # noqa: E501 just_number: Optional[StrictFloat] = Field(default=None, alias="JustNumber") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["JustNumber"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of NumberOnly from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of NumberOnly from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py index b09bcedac46d..8923eb7e2c33 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/object_to_test_additional_properties.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictBool from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictBool -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ObjectToTestAdditionalProperties(BaseModel): """ - Minimal object # noqa: E501 - """ + Minimal object + """ # noqa: E501 var_property: Optional[StrictBool] = Field(default=False, description="Property", alias="property") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["property"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ObjectToTestAdditionalProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ObjectToTestAdditionalProperties from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py b/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py index b1113b9a817e..592a5e177f2a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/object_with_deprecated_fields.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictFloat, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictFloat, StrictStr -from pydantic import Field from petstore_api.models.deprecated_object import DeprecatedObject -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ObjectWithDeprecatedFields(BaseModel): """ ObjectWithDeprecatedFields - """ + """ # noqa: E501 uuid: Optional[StrictStr] = None id: Optional[StrictFloat] = None deprecated_ref: Optional[DeprecatedObject] = Field(default=None, alias="deprecatedRef") @@ -41,7 +36,8 @@ class ObjectWithDeprecatedFields(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -55,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ObjectWithDeprecatedFields from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -70,11 +66,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of deprecated_ref @@ -88,7 +86,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ObjectWithDeprecatedFields from a dict""" if obj is None: return None @@ -99,7 +97,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "uuid": obj.get("uuid"), "id": obj.get("id"), - "deprecatedRef": DeprecatedObject.from_dict(obj.get("deprecatedRef")) if obj.get("deprecatedRef") is not None else None, + "deprecatedRef": DeprecatedObject.from_dict(obj["deprecatedRef"]) if obj.get("deprecatedRef") is not None else None, "bars": obj.get("bars") }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py index 3e9c111a4a73..181582f8830d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/one_of_enum_string.py @@ -13,22 +13,15 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from petstore_api.models.enum_string1 import EnumString1 from petstore_api.models.enum_string2 import EnumString2 -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self ONEOFENUMSTRING_ONE_OF_SCHEMAS = ["EnumString1", "EnumString2"] @@ -41,10 +34,11 @@ class OneOfEnumString(BaseModel): # data type: EnumString2 oneof_schema_2_validator: Optional[EnumString2] = None actual_instance: Optional[Union[EnumString1, EnumString2]] = None - one_of_schemas: List[str] = Literal["EnumString1", "EnumString2"] + one_of_schemas: List[str] = Field(default=Literal["EnumString1", "EnumString2"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -83,7 +77,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -120,19 +114,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], EnumString1, EnumString2]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/order.py b/samples/openapi3/client/petstore/python/petstore_api/models/order.py index 5d58dc22d2eb..d9fa3d4e2f34 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/order.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/order.py @@ -18,19 +18,15 @@ import json from datetime import datetime +from pydantic import BaseModel, Field, StrictBool, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictBool, StrictInt, StrictStr, field_validator -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Order(BaseModel): """ Order - """ + """ # noqa: E501 id: Optional[StrictInt] = None pet_id: Optional[StrictInt] = Field(default=None, alias="petId") quantity: Optional[StrictInt] = None @@ -52,7 +48,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -66,7 +63,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Order from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -81,11 +78,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -96,7 +95,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Order from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py index ca58500b2350..727440deb47f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_composite.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictBool, StrictFloat, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class OuterComposite(BaseModel): """ OuterComposite - """ + """ # noqa: E501 my_number: Optional[StrictFloat] = None my_string: Optional[StrictStr] = None my_boolean: Optional[StrictBool] = None @@ -38,7 +34,8 @@ class OuterComposite(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of OuterComposite from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -82,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of OuterComposite from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum.py index 89b19cbcf664..ac48cc0dc4d8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnum(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_default_value.py index 51ca91443e27..99d6fd5fc042 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_default_value.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumDefaultValue(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer.py index 8947df650469..b771b7a61f55 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumInteger(int, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer_default_value.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer_default_value.py index 970487bb0c4d..8df41b2bd320 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer_default_value.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_enum_integer_default_value.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class OuterEnumIntegerDefaultValue(int, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py b/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py index 4ee7ca1a0918..155b41cef8ef 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/outer_object_with_enum_property.py @@ -17,21 +17,17 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.outer_enum import OuterEnum from petstore_api.models.outer_enum_integer import OuterEnumInteger -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class OuterObjectWithEnumProperty(BaseModel): """ OuterObjectWithEnumProperty - """ + """ # noqa: E501 str_value: Optional[OuterEnum] = None value: OuterEnumInteger additional_properties: Dict[str, Any] = {} @@ -39,7 +35,8 @@ class OuterObjectWithEnumProperty(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +50,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of OuterObjectWithEnumProperty from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,11 +65,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -88,7 +87,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of OuterObjectWithEnumProperty from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/parent.py b/samples/openapi3/client/petstore/python/petstore_api/models/parent.py index 727a54a2523c..5c9515aef8a1 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/parent.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/parent.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field from petstore_api.models.inner_dict_with_property import InnerDictWithProperty -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Parent(BaseModel): """ Parent - """ + """ # noqa: E501 optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(default=None, alias="optionalDict") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["optionalDict"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Parent from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) @@ -89,7 +87,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Parent from a dict""" if obj is None: return None @@ -100,7 +98,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "optionalDict": dict( (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj.get("optionalDict").items() + for _k, _v in obj["optionalDict"].items() ) if obj.get("optionalDict") is not None else None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py b/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py index c0192fdcba47..1bff7f8a4ec4 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/parent_with_optional_dict.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field from petstore_api.models.inner_dict_with_property import InnerDictWithProperty -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class ParentWithOptionalDict(BaseModel): """ ParentWithOptionalDict - """ + """ # noqa: E501 optional_dict: Optional[Dict[str, InnerDictWithProperty]] = Field(default=None, alias="optionalDict") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["optionalDict"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ParentWithOptionalDict from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in optional_dict (dict) @@ -89,7 +87,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ParentWithOptionalDict from a dict""" if obj is None: return None @@ -100,7 +98,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "optionalDict": dict( (_k, InnerDictWithProperty.from_dict(_v)) - for _k, _v in obj.get("optionalDict").items() + for _k, _v in obj["optionalDict"].items() ) if obj.get("optionalDict") is not None else None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py index 50ee73984a30..fe2bf02c789f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pet.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pet.py @@ -17,23 +17,18 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field from typing_extensions import Annotated from petstore_api.models.category import Category from petstore_api.models.tag import Tag -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class Pet(BaseModel): """ Pet - """ + """ # noqa: E501 id: Optional[StrictInt] = None category: Optional[Category] = None name: StrictStr @@ -55,7 +50,8 @@ def status_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -69,7 +65,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Pet from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -84,11 +80,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of category @@ -109,7 +107,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Pet from a dict""" if obj is None: return None @@ -119,10 +117,10 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "id": obj.get("id"), - "category": Category.from_dict(obj.get("category")) if obj.get("category") is not None else None, + "category": Category.from_dict(obj["category"]) if obj.get("category") is not None else None, "name": obj.get("name"), "photoUrls": obj.get("photoUrls"), - "tags": [Tag.from_dict(_item) for _item in obj.get("tags")] if obj.get("tags") is not None else None, + "tags": [Tag.from_dict(_item) for _item in obj["tags"]] if obj.get("tags") is not None else None, "status": obj.get("status") }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py index a7912f71a227..e87c402504d0 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/pig.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/pig.py @@ -13,22 +13,15 @@ from __future__ import annotations -from inspect import getfullargspec import json import pprint -import re # noqa: F401 - -from typing import Any, List, Optional from pydantic import BaseModel, Field, StrictStr, ValidationError, field_validator +from typing import Any, List, Optional from petstore_api.models.basque_pig import BasquePig from petstore_api.models.danish_pig import DanishPig -from typing import Union, Any, List, TYPE_CHECKING, Optional, Dict -from typing_extensions import Literal from pydantic import StrictStr, Field -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Union, List, Optional, Dict +from typing_extensions import Literal, Self PIG_ONE_OF_SCHEMAS = ["BasquePig", "DanishPig"] @@ -41,10 +34,11 @@ class Pig(BaseModel): # data type: DanishPig oneof_schema_2_validator: Optional[DanishPig] = None actual_instance: Optional[Union[BasquePig, DanishPig]] = None - one_of_schemas: List[str] = Literal["BasquePig", "DanishPig"] + one_of_schemas: List[str] = Field(default=Literal["BasquePig", "DanishPig"]) model_config = { - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -86,7 +80,7 @@ def actual_instance_must_validate_oneof(cls, v): return v @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Union[str, Dict[str, Any]]) -> Self: return cls.from_json(json.dumps(obj)) @classmethod @@ -138,19 +132,17 @@ def to_json(self) -> str: if self.actual_instance is None: return "null" - to_json = getattr(self.actual_instance, "to_json", None) - if callable(to_json): + if hasattr(self.actual_instance, "to_json") and callable(self.actual_instance.to_json): return self.actual_instance.to_json() else: return json.dumps(self.actual_instance) - def to_dict(self) -> dict: + def to_dict(self) -> Optional[Union[Dict[str, Any], BasquePig, DanishPig]]: """Returns the dict representation of the actual instance""" if self.actual_instance is None: return None - to_dict = getattr(self.actual_instance, "to_dict", None) - if callable(to_dict): + if hasattr(self.actual_instance, "to_dict") and callable(self.actual_instance.to_dict): return self.actual_instance.to_dict() else: # primitive type diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py b/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py index 40e492c3d8ce..65058950f28d 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/property_name_collision.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class PropertyNameCollision(BaseModel): """ PropertyNameCollision - """ + """ # noqa: E501 underscore_type: Optional[StrictStr] = Field(default=None, alias="_type") type: Optional[StrictStr] = None type_with_underscore: Optional[StrictStr] = Field(default=None, alias="type_") @@ -39,7 +34,8 @@ class PropertyNameCollision(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -53,7 +49,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of PropertyNameCollision from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -68,11 +64,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -83,7 +81,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of PropertyNameCollision from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py b/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py index c513afd99eae..565612986362 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/read_only_first.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class ReadOnlyFirst(BaseModel): """ ReadOnlyFirst - """ + """ # noqa: E501 bar: Optional[StrictStr] = None baz: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class ReadOnlyFirst(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of ReadOnlyFirst from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,12 +64,14 @@ def to_dict(self) -> Dict[str, Any]: * OpenAPI `readOnly` fields are excluded. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "bar", + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "bar", - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -83,7 +82,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of ReadOnlyFirst from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py b/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py index 440a92d69ff8..2e181890002f 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/second_ref.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class SecondRef(BaseModel): """ SecondRef - """ + """ # noqa: E501 category: Optional[StrictStr] = None circular_ref: Optional[CircularReferenceModel] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class SecondRef(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SecondRef from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of circular_ref @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SecondRef from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "category": obj.get("category"), - "circular_ref": CircularReferenceModel.from_dict(obj.get("circular_ref")) if obj.get("circular_ref") is not None else None + "circular_ref": CircularReferenceModel.from_dict(obj["circular_ref"]) if obj.get("circular_ref") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): @@ -104,9 +103,6 @@ def from_dict(cls, obj: dict) -> Self: return _obj from petstore_api.models.circular_reference_model import CircularReferenceModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # SecondRef.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +SecondRef.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py b/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py index dea2c090fa28..8f161da4a200 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/self_reference_model.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class SelfReferenceModel(BaseModel): """ SelfReferenceModel - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested: Optional[DummyModel] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class SelfReferenceModel(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SelfReferenceModel from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested @@ -84,7 +83,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SelfReferenceModel from a dict""" if obj is None: return None @@ -94,7 +93,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested": DummyModel.from_dict(obj.get("nested")) if obj.get("nested") is not None else None + "nested": DummyModel.from_dict(obj["nested"]) if obj.get("nested") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): @@ -104,9 +103,6 @@ def from_dict(cls, obj: dict) -> Self: return _obj from petstore_api.models.dummy_model import DummyModel -from typing import TYPE_CHECKING -if TYPE_CHECKING: - # TODO: pydantic v2 - # SelfReferenceModel.model_rebuild() - pass +# TODO: Rewrite to not use raise_errors +SelfReferenceModel.model_rebuild(raise_errors=False) diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/single_ref_type.py b/samples/openapi3/client/petstore/python/petstore_api/models/single_ref_type.py index 3c41c4118654..91ab07e2535c 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/single_ref_type.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/single_ref_type.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class SingleRefType(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/special_character_enum.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_character_enum.py index 77ed288a94b4..1d85fd148d4b 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_character_enum.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_character_enum.py @@ -14,16 +14,8 @@ from __future__ import annotations import json -import pprint -import re # noqa: F401 from enum import Enum - - - -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing_extensions import Self class SpecialCharacterEnum(str, Enum): diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py index 1ebdc712468a..e9d7dbb92aa3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_model_name.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class SpecialModelName(BaseModel): """ SpecialModelName - """ + """ # noqa: E501 special_property_name: Optional[StrictInt] = Field(default=None, alias="$special[property.name]") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["$special[property.name]"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SpecialModelName from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SpecialModelName from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py index cb6d63fbfa93..1322827d7ebf 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/special_name.py @@ -17,21 +17,16 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr, field_validator from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr, field_validator -from pydantic import Field from petstore_api.models.category import Category -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class SpecialName(BaseModel): """ SpecialName - """ + """ # noqa: E501 var_property: Optional[StrictInt] = Field(default=None, alias="property") var_async: Optional[Category] = Field(default=None, alias="async") var_schema: Optional[StrictStr] = Field(default=None, description="pet status in the store", alias="schema") @@ -50,7 +45,8 @@ def var_schema_validate_enum(cls, value): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -64,7 +60,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of SpecialName from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -79,11 +75,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of var_async @@ -97,7 +95,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of SpecialName from a dict""" if obj is None: return None @@ -107,7 +105,7 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "property": obj.get("property"), - "async": Category.from_dict(obj.get("async")) if obj.get("async") is not None else None, + "async": Category.from_dict(obj["async"]) if obj.get("async") is not None else None, "schema": obj.get("schema") }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/tag.py b/samples/openapi3/client/petstore/python/petstore_api/models/tag.py index 64fbd720e3cb..b7dde8077f27 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/tag.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/tag.py @@ -17,19 +17,15 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tag(BaseModel): """ Tag - """ + """ # noqa: E501 id: Optional[StrictInt] = None name: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} @@ -37,7 +33,8 @@ class Tag(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tag from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +80,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tag from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..f6d0e496e495 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model400_response.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class TestErrorResponsesWithModel400Response(BaseModel): + """ + TestErrorResponsesWithModel400Response + """ # noqa: E501 + reason400: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["reason400"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True, + "protected_namespaces": (), + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel400Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel400Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reason400": obj.get("reason400") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..d9993a5c63c4 --- /dev/null +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_error_responses_with_model404_response.py @@ -0,0 +1,100 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +from __future__ import annotations +import pprint +import re # noqa: F401 +import json + +from pydantic import BaseModel, StrictStr +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self + +class TestErrorResponsesWithModel404Response(BaseModel): + """ + TestErrorResponsesWithModel404Response + """ # noqa: E501 + reason404: Optional[StrictStr] = None + additional_properties: Dict[str, Any] = {} + __properties: ClassVar[List[str]] = ["reason404"] + + model_config = { + "populate_by_name": True, + "validate_assignment": True, + "protected_namespaces": (), + } + + + def to_str(self) -> str: + """Returns the string representation of the model using alias""" + return pprint.pformat(self.model_dump(by_alias=True)) + + def to_json(self) -> str: + """Returns the JSON representation of the model using alias""" + # TODO: pydantic v2: use .model_dump_json(by_alias=True, exclude_unset=True) instead + return json.dumps(self.to_dict()) + + @classmethod + def from_json(cls, json_str: str) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel404Response from a JSON string""" + return cls.from_dict(json.loads(json_str)) + + def to_dict(self) -> Dict[str, Any]: + """Return the dictionary representation of the model using alias. + + This has the following differences from calling pydantic's + `self.model_dump(by_alias=True)`: + + * `None` is only added to the output dict for nullable fields that + were set at model initialization. Other fields with value `None` + are ignored. + * Fields in `self.additional_properties` are added to the output dict. + """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + + _dict = self.model_dump( + by_alias=True, + exclude=excluded_fields, + exclude_none=True, + ) + # puts key-value pairs in additional_properties in the top level + if self.additional_properties is not None: + for _key, _value in self.additional_properties.items(): + _dict[_key] = _value + + return _dict + + @classmethod + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: + """Create an instance of TestErrorResponsesWithModel404Response from a dict""" + if obj is None: + return None + + if not isinstance(obj, dict): + return cls.model_validate(obj) + + _obj = cls.model_validate({ + "reason404": obj.get("reason404") + }) + # store additional fields in additional_properties + for _key in obj.keys(): + if _key not in cls.__properties: + _obj.additional_properties[_key] = obj.get(_key) + + return _obj + + diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py b/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py index ffd24d69c23c..2fb96a50dd78 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/test_inline_freeform_additional_properties_request.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class TestInlineFreeformAdditionalPropertiesRequest(BaseModel): """ TestInlineFreeformAdditionalPropertiesRequest - """ + """ # noqa: E501 some_property: Optional[StrictStr] = Field(default=None, alias="someProperty") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["someProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of TestInlineFreeformAdditionalPropertiesRequest from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py b/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py index d2d1f61b440c..56f0f8c04ab8 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/tiger.py @@ -17,26 +17,23 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictStr -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Any, ClassVar, Dict, List, Optional +from typing import Optional, Set +from typing_extensions import Self class Tiger(BaseModel): """ Tiger - """ + """ # noqa: E501 skill: Optional[StrictStr] = None additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["skill"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -50,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of Tiger from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -65,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -80,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of Tiger from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py index 4aa1fcbac582..6be5a7eb89c3 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_model_list_properties.py @@ -17,28 +17,24 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel -from pydantic import Field from petstore_api.models.creature_info import CreatureInfo -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class UnnamedDictWithAdditionalModelListProperties(BaseModel): """ UnnamedDictWithAdditionalModelListProperties - """ + """ # noqa: E501 dict_property: Optional[Dict[str, List[CreatureInfo]]] = Field(default=None, alias="dictProperty") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["dictProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -52,7 +48,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalModelListProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -67,11 +63,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of each value in dict_property (dict of array) @@ -91,7 +89,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalModelListProperties from a dict""" if obj is None: return None @@ -106,7 +104,7 @@ def from_dict(cls, obj: dict) -> Self: if _v is not None else None ) - for _k, _v in obj.get("dictProperty").items() + for _k, _v in obj.get("dictProperty", {}).items() ) }) # store additional fields in additional_properties diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py index bee320032a90..2fcd15c86f4a 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/unnamed_dict_with_additional_string_list_properties.py @@ -17,27 +17,23 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class UnnamedDictWithAdditionalStringListProperties(BaseModel): """ UnnamedDictWithAdditionalStringListProperties - """ + """ # noqa: E501 dict_property: Optional[Dict[str, List[StrictStr]]] = Field(default=None, alias="dictProperty") additional_properties: Dict[str, Any] = {} __properties: ClassVar[List[str]] = ["dictProperty"] model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -51,7 +47,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalStringListProperties from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -66,11 +62,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -81,7 +79,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of UnnamedDictWithAdditionalStringListProperties from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/user.py b/samples/openapi3/client/petstore/python/petstore_api/models/user.py index 250c3aac6397..6be27943f015 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/user.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/user.py @@ -17,20 +17,15 @@ import re # noqa: F401 import json - +from pydantic import BaseModel, Field, StrictInt, StrictStr from typing import Any, ClassVar, Dict, List, Optional -from pydantic import BaseModel, StrictInt, StrictStr -from pydantic import Field -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class User(BaseModel): """ User - """ + """ # noqa: E501 id: Optional[StrictInt] = None username: Optional[StrictStr] = None first_name: Optional[StrictStr] = Field(default=None, alias="firstName") @@ -44,7 +39,8 @@ class User(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -58,7 +54,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of User from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -73,11 +69,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # puts key-value pairs in additional_properties in the top level @@ -88,7 +86,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of User from a dict""" if obj is None: return None diff --git a/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py b/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py index 75fc92ba2865..95c2da7f6295 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py +++ b/samples/openapi3/client/petstore/python/petstore_api/models/with_nested_one_of.py @@ -17,21 +17,17 @@ import re # noqa: F401 import json - -from typing import Any, ClassVar, Dict, List, Optional from pydantic import BaseModel, StrictInt +from typing import Any, ClassVar, Dict, List, Optional from petstore_api.models.one_of_enum_string import OneOfEnumString from petstore_api.models.pig import Pig -from typing import Dict, Any -try: - from typing import Self -except ImportError: - from typing_extensions import Self +from typing import Optional, Set +from typing_extensions import Self class WithNestedOneOf(BaseModel): """ WithNestedOneOf - """ + """ # noqa: E501 size: Optional[StrictInt] = None nested_pig: Optional[Pig] = None nested_oneof_enum_string: Optional[OneOfEnumString] = None @@ -40,7 +36,8 @@ class WithNestedOneOf(BaseModel): model_config = { "populate_by_name": True, - "validate_assignment": True + "validate_assignment": True, + "protected_namespaces": (), } @@ -54,7 +51,7 @@ def to_json(self) -> str: return json.dumps(self.to_dict()) @classmethod - def from_json(cls, json_str: str) -> Self: + def from_json(cls, json_str: str) -> Optional[Self]: """Create an instance of WithNestedOneOf from a JSON string""" return cls.from_dict(json.loads(json_str)) @@ -69,11 +66,13 @@ def to_dict(self) -> Dict[str, Any]: are ignored. * Fields in `self.additional_properties` are added to the output dict. """ + excluded_fields: Set[str] = set([ + "additional_properties", + ]) + _dict = self.model_dump( by_alias=True, - exclude={ - "additional_properties", - }, + exclude=excluded_fields, exclude_none=True, ) # override the default output from pydantic by calling `to_dict()` of nested_pig @@ -90,7 +89,7 @@ def to_dict(self) -> Dict[str, Any]: return _dict @classmethod - def from_dict(cls, obj: dict) -> Self: + def from_dict(cls, obj: Optional[Dict[str, Any]]) -> Optional[Self]: """Create an instance of WithNestedOneOf from a dict""" if obj is None: return None @@ -100,8 +99,8 @@ def from_dict(cls, obj: dict) -> Self: _obj = cls.model_validate({ "size": obj.get("size"), - "nested_pig": Pig.from_dict(obj.get("nested_pig")) if obj.get("nested_pig") is not None else None, - "nested_oneof_enum_string": OneOfEnumString.from_dict(obj.get("nested_oneof_enum_string")) if obj.get("nested_oneof_enum_string") is not None else None + "nested_pig": Pig.from_dict(obj["nested_pig"]) if obj.get("nested_pig") is not None else None, + "nested_oneof_enum_string": OneOfEnumString.from_dict(obj["nested_oneof_enum_string"]) if obj.get("nested_oneof_enum_string") is not None else None }) # store additional fields in additional_properties for _key in obj.keys(): diff --git a/samples/openapi3/client/petstore/python/petstore_api/rest.py b/samples/openapi3/client/petstore/python/petstore_api/rest.py index df9aca008048..a4dd7716349f 100755 --- a/samples/openapi3/client/petstore/python/petstore_api/rest.py +++ b/samples/openapi3/client/petstore/python/petstore_api/rest.py @@ -14,43 +14,55 @@ import io import json -import logging import re import ssl -from urllib.parse import urlencode, quote_plus import urllib3 -from petstore_api.exceptions import ApiException, UnauthorizedException, ForbiddenException, NotFoundException, ServiceException, ApiValueError, BadRequestException +from petstore_api.exceptions import ApiException, ApiValueError +SUPPORTED_SOCKS_PROXIES = {"socks5", "socks5h", "socks4", "socks4a"} +RESTResponseType = urllib3.HTTPResponse -logger = logging.getLogger(__name__) + +def is_socks_proxy_url(url): + if url is None: + return False + split_section = url.split("://") + if len(split_section) < 2: + return False + else: + return split_section[0].lower() in SUPPORTED_SOCKS_PROXIES class RESTResponse(io.IOBase): def __init__(self, resp) -> None: - self.urllib3_response = resp + self.response = resp self.status = resp.status self.reason = resp.reason - self.data = resp.data + self.data = None + + def read(self): + if self.data is None: + self.data = self.response.data + return self.data def getheaders(self): """Returns a dictionary of the response headers.""" - return self.urllib3_response.headers + return self.response.headers def getheader(self, name, default=None): """Returns a given response header.""" - return self.urllib3_response.headers.get(name, default) + return self.response.headers.get(name, default) class RESTClientObject: - def __init__(self, configuration, pools_size=4, maxsize=None) -> None: + def __init__(self, configuration) -> None: # urllib3.PoolManager will pass all kw parameters to connectionpool # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/poolmanager.py#L75 # noqa: E501 # https://github.com/shazow/urllib3/blob/f9409436f83aeb79fbaf090181cd81b784f1b8ce/urllib3/connectionpool.py#L680 # noqa: E501 - # maxsize is the number of requests to host that are allowed in parallel # noqa: E501 # Custom SSL certificates and client certificates: http://urllib3.readthedocs.io/en/latest/advanced-usage.html # noqa: E501 # cert_reqs @@ -59,74 +71,79 @@ def __init__(self, configuration, pools_size=4, maxsize=None) -> None: else: cert_reqs = ssl.CERT_NONE - addition_pool_args = {} + pool_args = { + "cert_reqs": cert_reqs, + "ca_certs": configuration.ssl_ca_cert, + "cert_file": configuration.cert_file, + "key_file": configuration.key_file, + } if configuration.assert_hostname is not None: - addition_pool_args['assert_hostname'] = configuration.assert_hostname # noqa: E501 + pool_args['assert_hostname'] = ( + configuration.assert_hostname + ) if configuration.retries is not None: - addition_pool_args['retries'] = configuration.retries + pool_args['retries'] = configuration.retries if configuration.tls_server_name: - addition_pool_args['server_hostname'] = configuration.tls_server_name + pool_args['server_hostname'] = configuration.tls_server_name if configuration.socket_options is not None: - addition_pool_args['socket_options'] = configuration.socket_options + pool_args['socket_options'] = configuration.socket_options - if maxsize is None: - if configuration.connection_pool_maxsize is not None: - maxsize = configuration.connection_pool_maxsize - else: - maxsize = 4 + if configuration.connection_pool_maxsize is not None: + pool_args['maxsize'] = configuration.connection_pool_maxsize # https pool manager + self.pool_manager: urllib3.PoolManager + if configuration.proxy: - self.pool_manager = urllib3.ProxyManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - proxy_url=configuration.proxy, - proxy_headers=configuration.proxy_headers, - **addition_pool_args - ) + if is_socks_proxy_url(configuration.proxy): + from urllib3.contrib.socks import SOCKSProxyManager + pool_args["proxy_url"] = configuration.proxy + pool_args["headers"] = configuration.proxy_headers + self.pool_manager = SOCKSProxyManager(**pool_args) + else: + pool_args["proxy_url"] = configuration.proxy + pool_args["proxy_headers"] = configuration.proxy_headers + self.pool_manager = urllib3.ProxyManager(**pool_args) else: - self.pool_manager = urllib3.PoolManager( - num_pools=pools_size, - maxsize=maxsize, - cert_reqs=cert_reqs, - ca_certs=configuration.ssl_ca_cert, - cert_file=configuration.cert_file, - key_file=configuration.key_file, - **addition_pool_args - ) - - def request(self, method, url, query_params=None, headers=None, - body=None, post_params=None, _preload_content=True, - _request_timeout=None): + self.pool_manager = urllib3.PoolManager(**pool_args) + + def request( + self, + method, + url, + headers=None, + body=None, + post_params=None, + _request_timeout=None + ): """Perform requests. :param method: http request method :param url: http request url - :param query_params: query parameters in the url :param headers: http request headers :param body: request json body, for `application/json` :param post_params: request post parameters, `application/x-www-form-urlencoded` and `multipart/form-data` - :param _preload_content: if False, the urllib3.HTTPResponse object will - be returned without reading/decoding response - data. Default is True. :param _request_timeout: timeout setting for this request. If one number provided, it will be total request timeout. It can also be a pair (tuple) of (connection, read) timeouts. """ method = method.upper() - assert method in ['GET', 'HEAD', 'DELETE', 'POST', 'PUT', - 'PATCH', 'OPTIONS'] + assert method in [ + 'GET', + 'HEAD', + 'DELETE', + 'POST', + 'PUT', + 'PATCH', + 'OPTIONS' + ] if post_params and body: raise ApiValueError( @@ -135,63 +152,84 @@ def request(self, method, url, query_params=None, headers=None, post_params = post_params or {} headers = headers or {} - # url already contains the URL query string - # so reset query_params to empty dict - query_params = {} timeout = None if _request_timeout: - if isinstance(_request_timeout, (int,float)): # noqa: E501,F821 + if isinstance(_request_timeout, (int, float)): timeout = urllib3.Timeout(total=_request_timeout) - elif (isinstance(_request_timeout, tuple) and - len(_request_timeout) == 2): + elif ( + isinstance(_request_timeout, tuple) + and len(_request_timeout) == 2 + ): timeout = urllib3.Timeout( - connect=_request_timeout[0], read=_request_timeout[1]) + connect=_request_timeout[0], + read=_request_timeout[1] + ) try: # For `POST`, `PUT`, `PATCH`, `OPTIONS`, `DELETE` if method in ['POST', 'PUT', 'PATCH', 'OPTIONS', 'DELETE']: # no content type provided or payload is json - if not headers.get('Content-Type') or re.search('json', headers['Content-Type'], re.IGNORECASE): + content_type = headers.get('Content-Type') + if ( + not content_type + or re.search('json', content_type, re.IGNORECASE) + ): request_body = None if body is not None: request_body = json.dumps(body) r = self.pool_manager.request( - method, url, + method, + url, body=request_body, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'application/x-www-form-urlencoded': # noqa: E501 + headers=headers, + preload_content=False + ) + elif content_type == 'application/x-www-form-urlencoded': r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=False, - preload_content=_preload_content, timeout=timeout, - headers=headers) - elif headers['Content-Type'] == 'multipart/form-data': + headers=headers, + preload_content=False + ) + elif content_type == 'multipart/form-data': # must del headers['Content-Type'], or the correct # Content-Type which generated by urllib3 will be # overwritten. del headers['Content-Type'] r = self.pool_manager.request( - method, url, + method, + url, fields=post_params, encode_multipart=True, - preload_content=_preload_content, timeout=timeout, - headers=headers) + headers=headers, + preload_content=False + ) # Pass a `string` parameter directly in the body to support - # other content types than Json when `body` argument is - # provided in serialized form + # other content types than JSON when `body` argument is + # provided in serialized form. elif isinstance(body, str) or isinstance(body, bytes): - request_body = body r = self.pool_manager.request( - method, url, + method, + url, + body=body, + timeout=timeout, + headers=headers, + preload_content=False + ) + elif headers['Content-Type'] == 'text/plain' and isinstance(body, bool): + request_body = "true" if body else "false" + r = self.pool_manager.request( + method, + url, body=request_body, - preload_content=_preload_content, + preload_content=False, timeout=timeout, headers=headers) else: @@ -202,102 +240,16 @@ def request(self, method, url, query_params=None, headers=None, raise ApiException(status=0, reason=msg) # For `GET`, `HEAD` else: - r = self.pool_manager.request(method, url, - fields={}, - preload_content=_preload_content, - timeout=timeout, - headers=headers) + r = self.pool_manager.request( + method, + url, + fields={}, + timeout=timeout, + headers=headers, + preload_content=False + ) except urllib3.exceptions.SSLError as e: - msg = "{0}\n{1}".format(type(e).__name__, str(e)) + msg = "\n".join([type(e).__name__, str(e)]) raise ApiException(status=0, reason=msg) - if _preload_content: - r = RESTResponse(r) - - # log response body - logger.debug("response body: %s", r.data) - - if not 200 <= r.status <= 299: - if r.status == 400: - raise BadRequestException(http_resp=r) - - if r.status == 401: - raise UnauthorizedException(http_resp=r) - - if r.status == 403: - raise ForbiddenException(http_resp=r) - - if r.status == 404: - raise NotFoundException(http_resp=r) - - if 500 <= r.status <= 599: - raise ServiceException(http_resp=r) - - raise ApiException(http_resp=r) - - return r - - def get_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("GET", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def head_request(self, url, headers=None, query_params=None, _preload_content=True, - _request_timeout=None): - return self.request("HEAD", url, - headers=headers, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - query_params=query_params) - - def options_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("OPTIONS", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def delete_request(self, url, headers=None, query_params=None, body=None, - _preload_content=True, _request_timeout=None): - return self.request("DELETE", url, - headers=headers, - query_params=query_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def post_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("POST", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def put_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PUT", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) - - def patch_request(self, url, headers=None, query_params=None, post_params=None, - body=None, _preload_content=True, _request_timeout=None): - return self.request("PATCH", url, - headers=headers, - query_params=query_params, - post_params=post_params, - _preload_content=_preload_content, - _request_timeout=_request_timeout, - body=body) + return RESTResponse(r) diff --git a/samples/openapi3/client/petstore/python/petstore_api/signing.py b/samples/openapi3/client/petstore/python/petstore_api/signing.py index ec4d7d2a67fd..e0ef058f4677 100644 --- a/samples/openapi3/client/petstore/python/petstore_api/signing.py +++ b/samples/openapi3/client/petstore/python/petstore_api/signing.py @@ -13,13 +13,16 @@ from base64 import b64encode from Crypto.IO import PEM, PKCS8 from Crypto.Hash import SHA256, SHA512 +from Crypto.Hash.SHA512 import SHA512Hash +from Crypto.Hash.SHA256 import SHA256Hash from Crypto.PublicKey import RSA, ECC from Crypto.Signature import PKCS1_v1_5, pss, DSS +from datetime import timedelta from email.utils import formatdate -import json import os import re from time import time +from typing import List, Optional, Union from urllib.parse import urlencode, urlparse # The constants below define a subset of HTTP headers that can be included in the @@ -68,18 +71,20 @@ class HttpSigningConfiguration: """The configuration parameters for the HTTP signature security scheme. + The HTTP signature security scheme is used to sign HTTP requests with a private key which is in possession of the API client. - An 'Authorization' header is calculated by creating a hash of select headers, + + An ``Authorization`` header is calculated by creating a hash of select headers, and optionally the body of the HTTP request, then signing the hash value using - a private key. The 'Authorization' header is added to outbound HTTP requests. + a private key. The ``Authorization`` header is added to outbound HTTP requests. :param key_id: A string value specifying the identifier of the cryptographic key, when signing HTTP requests. :param signing_scheme: A string value specifying the signature scheme, when signing HTTP requests. - Supported value are hs2019, rsa-sha256, rsa-sha512. - Avoid using rsa-sha256, rsa-sha512 as they are deprecated. These values are + Supported value are: ``hs2019``, ``rsa-sha256``, ``rsa-sha512``. + Avoid using ``rsa-sha256``, ``rsa-sha512`` as they are deprecated. These values are available for server-side applications that only support the older HTTP signature algorithms. :param private_key_path: A string value specifying the path of the file containing @@ -88,18 +93,19 @@ class HttpSigningConfiguration: the private key. :param signed_headers: A list of strings. Each value is the name of a HTTP header that must be included in the HTTP signature calculation. - The two special signature headers '(request-target)' and '(created)' SHOULD be + The two special signature headers ``(request-target)`` and ``(created)`` SHOULD be included in SignedHeaders. - The '(created)' header expresses when the signature was created. - The '(request-target)' header is a concatenation of the lowercased :method, an + The ``(created)`` header expresses when the signature was created. + The ``(request-target)`` header is a concatenation of the lowercased :method, an ASCII space, and the :path pseudo-headers. When signed_headers is not specified, the client defaults to a single value, - '(created)', in the list of HTTP headers. + ``(created)``, in the list of HTTP headers. When SignedHeaders contains the 'Digest' value, the client performs the following operations: - 1. Calculate a digest of request body, as specified in RFC3230, section 4.3.2. - 2. Set the 'Digest' header in the request body. - 3. Include the 'Digest' header and value in the HTTP signature. + 1. Calculate a digest of request body, as specified in `RFC3230, + section 4.3.2`_. + 2. Set the ``Digest`` header in the request body. + 3. Include the ``Digest`` header and value in the HTTP signature. :param signing_algorithm: A string value specifying the signature algorithm, when signing HTTP requests. Supported values are: @@ -117,12 +123,16 @@ class HttpSigningConfiguration: :param signature_max_validity: The signature max validity, expressed as a datetime.timedelta value. It must be a positive value. """ - def __init__(self, key_id, signing_scheme, private_key_path, - private_key_passphrase=None, - signed_headers=None, - signing_algorithm=None, - hash_algorithm=None, - signature_max_validity=None) -> None: + def __init__(self, + key_id: str, + signing_scheme: str, + private_key_path: str, + private_key_passphrase: Union[None, str]=None, + signed_headers: Optional[List[str]]=None, + signing_algorithm: Optional[str]=None, + hash_algorithm: Optional[str]=None, + signature_max_validity: Optional[timedelta]=None, + ) -> None: self.key_id = key_id if signing_scheme not in {SCHEME_HS2019, SCHEME_RSA_SHA256, SCHEME_RSA_SHA512}: raise Exception("Unsupported security scheme: {0}".format(signing_scheme)) @@ -166,11 +176,11 @@ def __init__(self, key_id, signing_scheme, private_key_path, if HEADER_AUTHORIZATION in signed_headers: raise Exception("'Authorization' header cannot be included in signed headers") self.signed_headers = signed_headers - self.private_key = None + self.private_key: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None """The private key used to sign HTTP requests. Initialized when the PEM-encoded private key is loaded from a file. """ - self.host = None + self.host: Optional[str] = None """The host name, optionally followed by a colon and TCP port number. """ self._load_private_key() @@ -208,7 +218,7 @@ def get_http_signature_headers(self, resource_path, method, headers, body, query def get_public_key(self): """Returns the public key object associated with the private key. """ - pubkey = None + pubkey: Optional[Union[ECC.EccKey, RSA.RsaKey]] = None if isinstance(self.private_key, RSA.RsaKey): pubkey = self.private_key.publickey() elif isinstance(self.private_key, ECC.EccKey): @@ -237,8 +247,11 @@ def _load_private_key(self): elif pem_header in {'PRIVATE KEY', 'ENCRYPTED PRIVATE KEY'}: # Key is in PKCS8 format, which is capable of holding many different # types of private keys, not just EC keys. - (key_binary, pem_header, is_encrypted) = \ - PEM.decode(pem_data, self.private_key_passphrase) + if self.private_key_passphrase is not None: + passphrase = self.private_key_passphrase.encode("utf-8") + else: + passphrase = None + (key_binary, pem_header, is_encrypted) = PEM.decode(pem_data, passphrase) (oid, privkey, params) = \ PKCS8.unwrap(key_binary, passphrase=self.private_key_passphrase) if oid == '1.2.840.10045.2.1': @@ -319,8 +332,11 @@ def _get_signed_header_info(self, resource_path, method, headers, body, query_pa request_headers_dict[HEADER_DIGEST] = '{0}{1}'.format( digest_prefix, b64_body_digest.decode('ascii')) elif hdr_key == HEADER_HOST.lower(): - value = target_host - request_headers_dict[HEADER_HOST] = '{0}'.format(target_host) + if isinstance(target_host, bytes): + value = target_host.decode('ascii') + else: + value = target_host + request_headers_dict[HEADER_HOST] = value else: value = next((v for k, v in headers.items() if k.lower() == hdr_key), None) if value is None: @@ -341,6 +357,9 @@ def _get_message_digest(self, data): The prefix is a string that identifies the cryptographic hash. It is used to generate the 'Digest' header as specified in RFC 3230. """ + + digest: Union[SHA256Hash, SHA512Hash] + if self.hash_algorithm == HASH_SHA512: digest = SHA512.new() prefix = 'SHA-512=' diff --git a/samples/openapi3/client/petstore/python/poetry.lock b/samples/openapi3/client/petstore/python/poetry.lock new file mode 100644 index 000000000000..2e5a00ee1120 --- /dev/null +++ b/samples/openapi3/client/petstore/python/poetry.lock @@ -0,0 +1,671 @@ +# This file is automatically @generated by Poetry 1.7.1 and should not be changed by hand. + +[[package]] +name = "annotated-types" +version = "0.5.0" +description = "Reusable constraint types to use with typing.Annotated" +optional = false +python-versions = ">=3.7" +files = [ + {file = "annotated_types-0.5.0-py3-none-any.whl", hash = "sha256:58da39888f92c276ad970249761ebea80ba544b77acddaa1a4d6cf78287d45fd"}, + {file = "annotated_types-0.5.0.tar.gz", hash = "sha256:47cdc3490d9ac1506ce92c7aaa76c579dc3509ff11e098fc867e5130ab7be802"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.0.0", markers = "python_version < \"3.9\""} + +[[package]] +name = "colorama" +version = "0.4.6" +description = "Cross-platform colored terminal text." +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,!=3.5.*,!=3.6.*,>=2.7" +files = [ + {file = "colorama-0.4.6-py2.py3-none-any.whl", hash = "sha256:4f1d9991f5acc0ca119f9d443620b77f9d6b33703e51011c16baf57afb285fc6"}, + {file = "colorama-0.4.6.tar.gz", hash = "sha256:08695f5cb7ed6e0531a20572697297273c47b8cae5a63ffc6d6ed5c201be6e44"}, +] + +[[package]] +name = "distlib" +version = "0.3.8" +description = "Distribution utilities" +optional = false +python-versions = "*" +files = [ + {file = "distlib-0.3.8-py2.py3-none-any.whl", hash = "sha256:034db59a0b96f8ca18035f36290806a9a6e6bd9d1ff91e45a7f172eb17e51784"}, + {file = "distlib-0.3.8.tar.gz", hash = "sha256:1530ea13e350031b6312d8580ddb6b27a104275a31106523b8f123787f494f64"}, +] + +[[package]] +name = "exceptiongroup" +version = "1.2.0" +description = "Backport of PEP 654 (exception groups)" +optional = false +python-versions = ">=3.7" +files = [ + {file = "exceptiongroup-1.2.0-py3-none-any.whl", hash = "sha256:4bfd3996ac73b41e9b9628b04e079f193850720ea5945fc96a08633c66912f14"}, + {file = "exceptiongroup-1.2.0.tar.gz", hash = "sha256:91f5c769735f051a4290d52edd0858999b57e5876e9f85937691bd4c9fa3ed68"}, +] + +[package.extras] +test = ["pytest (>=6)"] + +[[package]] +name = "filelock" +version = "3.12.2" +description = "A platform independent file lock." +optional = false +python-versions = ">=3.7" +files = [ + {file = "filelock-3.12.2-py3-none-any.whl", hash = "sha256:cbb791cdea2a72f23da6ac5b5269ab0a0d161e9ef0100e653b69049a7706d1ec"}, + {file = "filelock-3.12.2.tar.gz", hash = "sha256:002740518d8aa59a26b0c76e10fb8c6e15eae825d34b6fdf670333fd7b938d81"}, +] + +[package.extras] +docs = ["furo (>=2023.5.20)", "sphinx (>=7.0.1)", "sphinx-autodoc-typehints (>=1.23,!=1.23.4)"] +testing = ["covdefaults (>=2.3)", "coverage (>=7.2.7)", "diff-cover (>=7.5)", "pytest (>=7.3.1)", "pytest-cov (>=4.1)", "pytest-mock (>=3.10)", "pytest-timeout (>=2.1)"] + +[[package]] +name = "flake8" +version = "5.0.4" +description = "the modular source code checker: pep8 pyflakes and co" +optional = false +python-versions = ">=3.6.1" +files = [ + {file = "flake8-5.0.4-py2.py3-none-any.whl", hash = "sha256:7a1cf6b73744f5806ab95e526f6f0d8c01c66d7bbe349562d22dfca20610b248"}, + {file = "flake8-5.0.4.tar.gz", hash = "sha256:6fbe320aad8d6b95cec8b8e47bc933004678dc63095be98528b7bdd2a9f510db"}, +] + +[package.dependencies] +importlib-metadata = {version = ">=1.1.0,<4.3", markers = "python_version < \"3.8\""} +mccabe = ">=0.7.0,<0.8.0" +pycodestyle = ">=2.9.0,<2.10.0" +pyflakes = ">=2.5.0,<2.6.0" + +[[package]] +name = "importlib-metadata" +version = "4.2.0" +description = "Read metadata from Python packages" +optional = false +python-versions = ">=3.6" +files = [ + {file = "importlib_metadata-4.2.0-py3-none-any.whl", hash = "sha256:057e92c15bc8d9e8109738a48db0ccb31b4d9d5cfbee5a8670879a30be66304b"}, + {file = "importlib_metadata-4.2.0.tar.gz", hash = "sha256:b7e52a1f8dec14a75ea73e0891f3060099ca1d8e6a462a4dff11c3e119ea1b31"}, +] + +[package.dependencies] +typing-extensions = {version = ">=3.6.4", markers = "python_version < \"3.8\""} +zipp = ">=0.5" + +[package.extras] +docs = ["jaraco.packaging (>=8.2)", "rst.linker (>=1.9)", "sphinx"] +testing = ["flufl.flake8", "importlib-resources (>=1.3)", "packaging", "pep517", "pyfakefs", "pytest (>=4.6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.0.1)", "pytest-flake8", "pytest-mypy"] + +[[package]] +name = "iniconfig" +version = "2.0.0" +description = "brain-dead simple config-ini parsing" +optional = false +python-versions = ">=3.7" +files = [ + {file = "iniconfig-2.0.0-py3-none-any.whl", hash = "sha256:b6a85871a79d2e3b22d2d1b94ac2824226a63c6b741c88f7ae975f18b6778374"}, + {file = "iniconfig-2.0.0.tar.gz", hash = "sha256:2d91e135bf72d31a410b17c16da610a82cb55f6b0477d1a902134b24a455b8b3"}, +] + +[[package]] +name = "mccabe" +version = "0.7.0" +description = "McCabe checker, plugin for flake8" +optional = false +python-versions = ">=3.6" +files = [ + {file = "mccabe-0.7.0-py2.py3-none-any.whl", hash = "sha256:6c2d30ab6be0e4a46919781807b4f0d834ebdd6c6e3dca0bda5a15f863427b6e"}, + {file = "mccabe-0.7.0.tar.gz", hash = "sha256:348e0240c33b60bbdf4e523192ef919f28cb2c3d7d5c7794f74009290f236325"}, +] + +[[package]] +name = "mypy" +version = "1.4.1" +description = "Optional static typing for Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "mypy-1.4.1-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:566e72b0cd6598503e48ea610e0052d1b8168e60a46e0bfd34b3acf2d57f96a8"}, + {file = "mypy-1.4.1-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:ca637024ca67ab24a7fd6f65d280572c3794665eaf5edcc7e90a866544076878"}, + {file = "mypy-1.4.1-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:0dde1d180cd84f0624c5dcaaa89c89775550a675aff96b5848de78fb11adabcd"}, + {file = "mypy-1.4.1-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:8c4d8e89aa7de683e2056a581ce63c46a0c41e31bd2b6d34144e2c80f5ea53dc"}, + {file = "mypy-1.4.1-cp310-cp310-win_amd64.whl", hash = "sha256:bfdca17c36ae01a21274a3c387a63aa1aafe72bff976522886869ef131b937f1"}, + {file = "mypy-1.4.1-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:7549fbf655e5825d787bbc9ecf6028731973f78088fbca3a1f4145c39ef09462"}, + {file = "mypy-1.4.1-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:98324ec3ecf12296e6422939e54763faedbfcc502ea4a4c38502082711867258"}, + {file = "mypy-1.4.1-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:141dedfdbfe8a04142881ff30ce6e6653c9685b354876b12e4fe6c78598b45e2"}, + {file = "mypy-1.4.1-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:8207b7105829eca6f3d774f64a904190bb2231de91b8b186d21ffd98005f14a7"}, + {file = "mypy-1.4.1-cp311-cp311-win_amd64.whl", hash = "sha256:16f0db5b641ba159eff72cff08edc3875f2b62b2fa2bc24f68c1e7a4e8232d01"}, + {file = "mypy-1.4.1-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:470c969bb3f9a9efcedbadcd19a74ffb34a25f8e6b0e02dae7c0e71f8372f97b"}, + {file = "mypy-1.4.1-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e5952d2d18b79f7dc25e62e014fe5a23eb1a3d2bc66318df8988a01b1a037c5b"}, + {file = "mypy-1.4.1-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:190b6bab0302cec4e9e6767d3eb66085aef2a1cc98fe04936d8a42ed2ba77bb7"}, + {file = "mypy-1.4.1-cp37-cp37m-win_amd64.whl", hash = "sha256:9d40652cc4fe33871ad3338581dca3297ff5f2213d0df345bcfbde5162abf0c9"}, + {file = "mypy-1.4.1-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:01fd2e9f85622d981fd9063bfaef1aed6e336eaacca00892cd2d82801ab7c042"}, + {file = "mypy-1.4.1-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:2460a58faeea905aeb1b9b36f5065f2dc9a9c6e4c992a6499a2360c6c74ceca3"}, + {file = "mypy-1.4.1-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a2746d69a8196698146a3dbe29104f9eb6a2a4d8a27878d92169a6c0b74435b6"}, + {file = "mypy-1.4.1-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:ae704dcfaa180ff7c4cfbad23e74321a2b774f92ca77fd94ce1049175a21c97f"}, + {file = "mypy-1.4.1-cp38-cp38-win_amd64.whl", hash = "sha256:43d24f6437925ce50139a310a64b2ab048cb2d3694c84c71c3f2a1626d8101dc"}, + {file = "mypy-1.4.1-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:c482e1246726616088532b5e964e39765b6d1520791348e6c9dc3af25b233828"}, + {file = "mypy-1.4.1-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:43b592511672017f5b1a483527fd2684347fdffc041c9ef53428c8dc530f79a3"}, + {file = "mypy-1.4.1-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:34a9239d5b3502c17f07fd7c0b2ae6b7dd7d7f6af35fbb5072c6208e76295816"}, + {file = "mypy-1.4.1-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:5703097c4936bbb9e9bce41478c8d08edd2865e177dc4c52be759f81ee4dd26c"}, + {file = "mypy-1.4.1-cp39-cp39-win_amd64.whl", hash = "sha256:e02d700ec8d9b1859790c0475df4e4092c7bf3272a4fd2c9f33d87fac4427b8f"}, + {file = "mypy-1.4.1-py3-none-any.whl", hash = "sha256:45d32cec14e7b97af848bddd97d85ea4f0db4d5a149ed9676caa4eb2f7402bb4"}, + {file = "mypy-1.4.1.tar.gz", hash = "sha256:9bbcd9ab8ea1f2e1c8031c21445b511442cc45c89951e49bbf852cbb70755b1b"}, +] + +[package.dependencies] +mypy-extensions = ">=1.0.0" +tomli = {version = ">=1.1.0", markers = "python_version < \"3.11\""} +typed-ast = {version = ">=1.4.0,<2", markers = "python_version < \"3.8\""} +typing-extensions = ">=4.1.0" + +[package.extras] +dmypy = ["psutil (>=4.0)"] +install-types = ["pip"] +python2 = ["typed-ast (>=1.4.0,<2)"] +reports = ["lxml"] + +[[package]] +name = "mypy-extensions" +version = "1.0.0" +description = "Type system extensions for programs checked with the mypy type checker." +optional = false +python-versions = ">=3.5" +files = [ + {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, + {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, +] + +[[package]] +name = "packaging" +version = "23.2" +description = "Core utilities for Python packages" +optional = false +python-versions = ">=3.7" +files = [ + {file = "packaging-23.2-py3-none-any.whl", hash = "sha256:8c491190033a9af7e1d931d0b5dacc2ef47509b34dd0de67ed209b5203fc88c7"}, + {file = "packaging-23.2.tar.gz", hash = "sha256:048fb0e9405036518eaaf48a55953c750c11e1a1b68e0dd1a9d62ed0c092cfc5"}, +] + +[[package]] +name = "pem" +version = "21.2.0" +description = "Easy PEM file parsing in Python." +optional = false +python-versions = "*" +files = [ + {file = "pem-21.2.0-py2.py3-none-any.whl", hash = "sha256:64afb669f05502c071d0706ee66e51471718ae248ba39624919da7b4ea73506e"}, + {file = "pem-21.2.0.tar.gz", hash = "sha256:c491833b092662626fd58a87375d450637d4ee94996ad9bbbd42593428e93e5a"}, +] + +[package.extras] +dev = ["certifi", "coverage[toml] (>=5.0.2)", "furo", "pre-commit", "pretend", "pyopenssl", "pytest", "sphinx", "twisted[tls]"] +docs = ["furo", "sphinx"] +tests = ["certifi", "coverage[toml] (>=5.0.2)", "pretend", "pyopenssl", "pytest"] + +[[package]] +name = "platformdirs" +version = "2.6.2" +description = "A small Python package for determining appropriate platform-specific dirs, e.g. a \"user data dir\"." +optional = false +python-versions = ">=3.7" +files = [ + {file = "platformdirs-2.6.2-py3-none-any.whl", hash = "sha256:83c8f6d04389165de7c9b6f0c682439697887bca0aa2f1c87ef1826be3584490"}, + {file = "platformdirs-2.6.2.tar.gz", hash = "sha256:e1fea1fe471b9ff8332e229df3cb7de4f53eeea4998d3b6bfff542115e998bd2"}, +] + +[package.dependencies] +typing-extensions = {version = ">=4.4", markers = "python_version < \"3.8\""} + +[package.extras] +docs = ["furo (>=2022.12.7)", "proselint (>=0.13)", "sphinx (>=5.3)", "sphinx-autodoc-typehints (>=1.19.5)"] +test = ["appdirs (==1.4.4)", "covdefaults (>=2.2.2)", "pytest (>=7.2)", "pytest-cov (>=4)", "pytest-mock (>=3.10)"] + +[[package]] +name = "pluggy" +version = "1.2.0" +description = "plugin and hook calling mechanisms for python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pluggy-1.2.0-py3-none-any.whl", hash = "sha256:c2fd55a7d7a3863cba1a013e4e2414658b1d07b6bc57b3919e0c63c9abb99849"}, + {file = "pluggy-1.2.0.tar.gz", hash = "sha256:d12f0c4b579b15f5e054301bb226ee85eeeba08ffec228092f8defbaa3a4c4b3"}, +] + +[package.dependencies] +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} + +[package.extras] +dev = ["pre-commit", "tox"] +testing = ["pytest", "pytest-benchmark"] + +[[package]] +name = "py" +version = "1.11.0" +description = "library with cross-python path, ini-parsing, io, code, log facilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +files = [ + {file = "py-1.11.0-py2.py3-none-any.whl", hash = "sha256:607c53218732647dff4acdfcd50cb62615cedf612e72d1724fb1a0cc6405b378"}, + {file = "py-1.11.0.tar.gz", hash = "sha256:51c75c4126074b472f746a24399ad32f6053d1b34b68d2fa41e558e6f4a98719"}, +] + +[[package]] +name = "pycodestyle" +version = "2.9.1" +description = "Python style guide checker" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pycodestyle-2.9.1-py2.py3-none-any.whl", hash = "sha256:d1735fc58b418fd7c5f658d28d943854f8a849b01a5d0a1e6f3f3fdd0166804b"}, + {file = "pycodestyle-2.9.1.tar.gz", hash = "sha256:2c9607871d58c76354b697b42f5d57e1ada7d261c261efac224b664affdc5785"}, +] + +[[package]] +name = "pycryptodome" +version = "3.19.1" +description = "Cryptographic library for Python" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*" +files = [ + {file = "pycryptodome-3.19.1-cp27-cp27m-macosx_10_9_x86_64.whl", hash = "sha256:694020d2ff985cd714381b9da949a21028c24b86f562526186f6af7c7547e986"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-manylinux2010_i686.whl", hash = "sha256:4464b0e8fd5508bff9baf18e6fd4c6548b1ac2ce9862d6965ff6a84ec9cb302a"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-manylinux2010_x86_64.whl", hash = "sha256:420972f9c62978e852c74055d81c354079ce3c3a2213a92c9d7e37bbc63a26e2"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:c1bc0c49d986a1491d66d2a56570f12e960b12508b7e71f2423f532e28857f36"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-musllinux_1_1_aarch64.whl", hash = "sha256:e038ab77fec0956d7aa989a3c647652937fc142ef41c9382c2ebd13c127d5b4a"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-win32.whl", hash = "sha256:a991f8ffe8dfe708f86690948ae46442eebdd0fff07dc1b605987939a34ec979"}, + {file = "pycryptodome-3.19.1-cp27-cp27m-win_amd64.whl", hash = "sha256:2c16426ef49d9cba018be2340ea986837e1dfa25c2ea181787971654dd49aadd"}, + {file = "pycryptodome-3.19.1-cp27-cp27mu-manylinux2010_i686.whl", hash = "sha256:6d0d2b97758ebf2f36c39060520447c26455acb3bcff309c28b1c816173a6ff5"}, + {file = "pycryptodome-3.19.1-cp27-cp27mu-manylinux2010_x86_64.whl", hash = "sha256:b8b80ff92049fd042177282917d994d344365ab7e8ec2bc03e853d93d2401786"}, + {file = "pycryptodome-3.19.1-cp27-cp27mu-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cd4e7e8bf0fc1ada854688b9b309ee607e2aa85a8b44180f91021a4dd330a928"}, + {file = "pycryptodome-3.19.1-cp27-cp27mu-musllinux_1_1_aarch64.whl", hash = "sha256:8cf5d3d6cf921fa81acd1f632f6cedcc03f5f68fc50c364cd39490ba01d17c49"}, + {file = "pycryptodome-3.19.1-cp35-abi3-macosx_10_9_universal2.whl", hash = "sha256:67939a3adbe637281c611596e44500ff309d547e932c449337649921b17b6297"}, + {file = "pycryptodome-3.19.1-cp35-abi3-macosx_10_9_x86_64.whl", hash = "sha256:11ddf6c9b52116b62223b6a9f4741bc4f62bb265392a4463282f7f34bb287180"}, + {file = "pycryptodome-3.19.1-cp35-abi3-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e3e6f89480616781d2a7f981472d0cdb09b9da9e8196f43c1234eff45c915766"}, + {file = "pycryptodome-3.19.1-cp35-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27e1efcb68993b7ce5d1d047a46a601d41281bba9f1971e6be4aa27c69ab8065"}, + {file = "pycryptodome-3.19.1-cp35-abi3-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:1c6273ca5a03b672e504995529b8bae56da0ebb691d8ef141c4aa68f60765700"}, + {file = "pycryptodome-3.19.1-cp35-abi3-musllinux_1_1_aarch64.whl", hash = "sha256:b0bfe61506795877ff974f994397f0c862d037f6f1c0bfc3572195fc00833b96"}, + {file = "pycryptodome-3.19.1-cp35-abi3-musllinux_1_1_i686.whl", hash = "sha256:f34976c5c8eb79e14c7d970fb097482835be8d410a4220f86260695ede4c3e17"}, + {file = "pycryptodome-3.19.1-cp35-abi3-musllinux_1_1_x86_64.whl", hash = "sha256:7c9e222d0976f68d0cf6409cfea896676ddc1d98485d601e9508f90f60e2b0a2"}, + {file = "pycryptodome-3.19.1-cp35-abi3-win32.whl", hash = "sha256:4805e053571140cb37cf153b5c72cd324bb1e3e837cbe590a19f69b6cf85fd03"}, + {file = "pycryptodome-3.19.1-cp35-abi3-win_amd64.whl", hash = "sha256:a470237ee71a1efd63f9becebc0ad84b88ec28e6784a2047684b693f458f41b7"}, + {file = "pycryptodome-3.19.1-pp27-pypy_73-manylinux2010_x86_64.whl", hash = "sha256:ed932eb6c2b1c4391e166e1a562c9d2f020bfff44a0e1b108f67af38b390ea89"}, + {file = "pycryptodome-3.19.1-pp27-pypy_73-win32.whl", hash = "sha256:81e9d23c0316fc1b45d984a44881b220062336bbdc340aa9218e8d0656587934"}, + {file = "pycryptodome-3.19.1-pp310-pypy310_pp73-macosx_10_9_x86_64.whl", hash = "sha256:37e531bf896b70fe302f003d3be5a0a8697737a8d177967da7e23eff60d6483c"}, + {file = "pycryptodome-3.19.1-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:cd4e95b0eb4b28251c825fe7aa941fe077f993e5ca9b855665935b86fbb1cc08"}, + {file = "pycryptodome-3.19.1-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:c22c80246c3c880c6950d2a8addf156cee74ec0dc5757d01e8e7067a3c7da015"}, + {file = "pycryptodome-3.19.1-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:e70f5c839c7798743a948efa2a65d1fe96bb397fe6d7f2bde93d869fe4f0ad69"}, + {file = "pycryptodome-3.19.1-pp39-pypy39_pp73-macosx_10_9_x86_64.whl", hash = "sha256:6c3df3613592ea6afaec900fd7189d23c8c28b75b550254f4bd33fe94acb84b9"}, + {file = "pycryptodome-3.19.1-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:08b445799d571041765e7d5c9ca09c5d3866c2f22eeb0dd4394a4169285184f4"}, + {file = "pycryptodome-3.19.1-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.manylinux_2_17_i686.manylinux2014_i686.whl", hash = "sha256:954d156cd50130afd53f8d77f830fe6d5801bd23e97a69d358fed068f433fbfe"}, + {file = "pycryptodome-3.19.1-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:b7efd46b0b4ac869046e814d83244aeab14ef787f4850644119b1c8b0ec2d637"}, + {file = "pycryptodome-3.19.1.tar.gz", hash = "sha256:8ae0dd1bcfada451c35f9e29a3e5db385caabc190f98e4a80ad02a61098fb776"}, +] + +[[package]] +name = "pydantic" +version = "2.5.3" +description = "Data validation using Python type hints" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic-2.5.3-py3-none-any.whl", hash = "sha256:d0caf5954bee831b6bfe7e338c32b9e30c85dfe080c843680783ac2b631673b4"}, + {file = "pydantic-2.5.3.tar.gz", hash = "sha256:b3ef57c62535b0941697cce638c08900d87fcb67e29cfa99e8a68f747f393f7a"}, +] + +[package.dependencies] +annotated-types = ">=0.4.0" +importlib-metadata = {version = "*", markers = "python_version == \"3.7\""} +pydantic-core = "2.14.6" +typing-extensions = ">=4.6.1" + +[package.extras] +email = ["email-validator (>=2.0.0)"] + +[[package]] +name = "pydantic-core" +version = "2.14.6" +description = "" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pydantic_core-2.14.6-cp310-cp310-macosx_10_7_x86_64.whl", hash = "sha256:72f9a942d739f09cd42fffe5dc759928217649f070056f03c70df14f5770acf9"}, + {file = "pydantic_core-2.14.6-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:6a31d98c0d69776c2576dda4b77b8e0c69ad08e8b539c25c7d0ca0dc19a50d6c"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:5aa90562bc079c6c290f0512b21768967f9968e4cfea84ea4ff5af5d917016e4"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:370ffecb5316ed23b667d99ce4debe53ea664b99cc37bfa2af47bc769056d534"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:f85f3843bdb1fe80e8c206fe6eed7a1caeae897e496542cee499c374a85c6e08"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:9862bf828112e19685b76ca499b379338fd4c5c269d897e218b2ae8fcb80139d"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:036137b5ad0cb0004c75b579445a1efccd072387a36c7f217bb8efd1afbe5245"}, + {file = "pydantic_core-2.14.6-cp310-cp310-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:92879bce89f91f4b2416eba4429c7b5ca22c45ef4a499c39f0c5c69257522c7c"}, + {file = "pydantic_core-2.14.6-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:0c08de15d50fa190d577e8591f0329a643eeaed696d7771760295998aca6bc66"}, + {file = "pydantic_core-2.14.6-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:36099c69f6b14fc2c49d7996cbf4f87ec4f0e66d1c74aa05228583225a07b590"}, + {file = "pydantic_core-2.14.6-cp310-none-win32.whl", hash = "sha256:7be719e4d2ae6c314f72844ba9d69e38dff342bc360379f7c8537c48e23034b7"}, + {file = "pydantic_core-2.14.6-cp310-none-win_amd64.whl", hash = "sha256:36fa402dcdc8ea7f1b0ddcf0df4254cc6b2e08f8cd80e7010d4c4ae6e86b2a87"}, + {file = "pydantic_core-2.14.6-cp311-cp311-macosx_10_7_x86_64.whl", hash = "sha256:dea7fcd62915fb150cdc373212141a30037e11b761fbced340e9db3379b892d4"}, + {file = "pydantic_core-2.14.6-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:ffff855100bc066ff2cd3aa4a60bc9534661816b110f0243e59503ec2df38421"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1b027c86c66b8627eb90e57aee1f526df77dc6d8b354ec498be9a757d513b92b"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:00b1087dabcee0b0ffd104f9f53d7d3eaddfaa314cdd6726143af6bc713aa27e"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:75ec284328b60a4e91010c1acade0c30584f28a1f345bc8f72fe8b9e46ec6a96"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:7e1f4744eea1501404b20b0ac059ff7e3f96a97d3e3f48ce27a139e053bb370b"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:b2602177668f89b38b9f84b7b3435d0a72511ddef45dc14446811759b82235a1"}, + {file = "pydantic_core-2.14.6-cp311-cp311-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:6c8edaea3089bf908dd27da8f5d9e395c5b4dc092dbcce9b65e7156099b4b937"}, + {file = "pydantic_core-2.14.6-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:478e9e7b360dfec451daafe286998d4a1eeaecf6d69c427b834ae771cad4b622"}, + {file = "pydantic_core-2.14.6-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:b6ca36c12a5120bad343eef193cc0122928c5c7466121da7c20f41160ba00ba2"}, + {file = "pydantic_core-2.14.6-cp311-none-win32.whl", hash = "sha256:2b8719037e570639e6b665a4050add43134d80b687288ba3ade18b22bbb29dd2"}, + {file = "pydantic_core-2.14.6-cp311-none-win_amd64.whl", hash = "sha256:78ee52ecc088c61cce32b2d30a826f929e1708f7b9247dc3b921aec367dc1b23"}, + {file = "pydantic_core-2.14.6-cp311-none-win_arm64.whl", hash = "sha256:a19b794f8fe6569472ff77602437ec4430f9b2b9ec7a1105cfd2232f9ba355e6"}, + {file = "pydantic_core-2.14.6-cp312-cp312-macosx_10_7_x86_64.whl", hash = "sha256:667aa2eac9cd0700af1ddb38b7b1ef246d8cf94c85637cbb03d7757ca4c3fdec"}, + {file = "pydantic_core-2.14.6-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:cdee837710ef6b56ebd20245b83799fce40b265b3b406e51e8ccc5b85b9099b7"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:2c5bcf3414367e29f83fd66f7de64509a8fd2368b1edf4351e862910727d3e51"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:26a92ae76f75d1915806b77cf459811e772d8f71fd1e4339c99750f0e7f6324f"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:a983cca5ed1dd9a35e9e42ebf9f278d344603bfcb174ff99a5815f953925140a"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:cb92f9061657287eded380d7dc455bbf115430b3aa4741bdc662d02977e7d0af"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:e4ace1e220b078c8e48e82c081e35002038657e4b37d403ce940fa679e57113b"}, + {file = "pydantic_core-2.14.6-cp312-cp312-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:ef633add81832f4b56d3b4c9408b43d530dfca29e68fb1b797dcb861a2c734cd"}, + {file = "pydantic_core-2.14.6-cp312-cp312-musllinux_1_1_aarch64.whl", hash = "sha256:7e90d6cc4aad2cc1f5e16ed56e46cebf4877c62403a311af20459c15da76fd91"}, + {file = "pydantic_core-2.14.6-cp312-cp312-musllinux_1_1_x86_64.whl", hash = "sha256:e8a5ac97ea521d7bde7621d86c30e86b798cdecd985723c4ed737a2aa9e77d0c"}, + {file = "pydantic_core-2.14.6-cp312-none-win32.whl", hash = "sha256:f27207e8ca3e5e021e2402ba942e5b4c629718e665c81b8b306f3c8b1ddbb786"}, + {file = "pydantic_core-2.14.6-cp312-none-win_amd64.whl", hash = "sha256:b3e5fe4538001bb82e2295b8d2a39356a84694c97cb73a566dc36328b9f83b40"}, + {file = "pydantic_core-2.14.6-cp312-none-win_arm64.whl", hash = "sha256:64634ccf9d671c6be242a664a33c4acf12882670b09b3f163cd00a24cffbd74e"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-macosx_10_7_x86_64.whl", hash = "sha256:24368e31be2c88bd69340fbfe741b405302993242ccb476c5c3ff48aeee1afe0"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-macosx_11_0_arm64.whl", hash = "sha256:e33b0834f1cf779aa839975f9d8755a7c2420510c0fa1e9fa0497de77cd35d2c"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:6af4b3f52cc65f8a0bc8b1cd9676f8c21ef3e9132f21fed250f6958bd7223bed"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:d15687d7d7f40333bd8266f3814c591c2e2cd263fa2116e314f60d82086e353a"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:095b707bb287bfd534044166ab767bec70a9bba3175dcdc3371782175c14e43c"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:94fc0e6621e07d1e91c44e016cc0b189b48db053061cc22d6298a611de8071bb"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1ce830e480f6774608dedfd4a90c42aac4a7af0a711f1b52f807130c2e434c06"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a306cdd2ad3a7d795d8e617a58c3a2ed0f76c8496fb7621b6cd514eb1532cae8"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:2f5fa187bde8524b1e37ba894db13aadd64faa884657473b03a019f625cee9a8"}, + {file = "pydantic_core-2.14.6-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:438027a975cc213a47c5d70672e0d29776082155cfae540c4e225716586be75e"}, + {file = "pydantic_core-2.14.6-cp37-none-win32.whl", hash = "sha256:f96ae96a060a8072ceff4cfde89d261837b4294a4f28b84a28765470d502ccc6"}, + {file = "pydantic_core-2.14.6-cp37-none-win_amd64.whl", hash = "sha256:e646c0e282e960345314f42f2cea5e0b5f56938c093541ea6dbf11aec2862391"}, + {file = "pydantic_core-2.14.6-cp38-cp38-macosx_10_7_x86_64.whl", hash = "sha256:db453f2da3f59a348f514cfbfeb042393b68720787bbef2b4c6068ea362c8149"}, + {file = "pydantic_core-2.14.6-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:3860c62057acd95cc84044e758e47b18dcd8871a328ebc8ccdefd18b0d26a21b"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:36026d8f99c58d7044413e1b819a67ca0e0b8ebe0f25e775e6c3d1fabb3c38fb"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:8ed1af8692bd8d2a29d702f1a2e6065416d76897d726e45a1775b1444f5928a7"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:314ccc4264ce7d854941231cf71b592e30d8d368a71e50197c905874feacc8a8"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:982487f8931067a32e72d40ab6b47b1628a9c5d344be7f1a4e668fb462d2da42"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:2dbe357bc4ddda078f79d2a36fc1dd0494a7f2fad83a0a684465b6f24b46fe80"}, + {file = "pydantic_core-2.14.6-cp38-cp38-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:2f6ffc6701a0eb28648c845f4945a194dc7ab3c651f535b81793251e1185ac3d"}, + {file = "pydantic_core-2.14.6-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:7f5025db12fc6de7bc1104d826d5aee1d172f9ba6ca936bf6474c2148ac336c1"}, + {file = "pydantic_core-2.14.6-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:dab03ed811ed1c71d700ed08bde8431cf429bbe59e423394f0f4055f1ca0ea60"}, + {file = "pydantic_core-2.14.6-cp38-none-win32.whl", hash = "sha256:dfcbebdb3c4b6f739a91769aea5ed615023f3c88cb70df812849aef634c25fbe"}, + {file = "pydantic_core-2.14.6-cp38-none-win_amd64.whl", hash = "sha256:99b14dbea2fdb563d8b5a57c9badfcd72083f6006caf8e126b491519c7d64ca8"}, + {file = "pydantic_core-2.14.6-cp39-cp39-macosx_10_7_x86_64.whl", hash = "sha256:4ce8299b481bcb68e5c82002b96e411796b844d72b3e92a3fbedfe8e19813eab"}, + {file = "pydantic_core-2.14.6-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:b9a9d92f10772d2a181b5ca339dee066ab7d1c9a34ae2421b2a52556e719756f"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:fd9e98b408384989ea4ab60206b8e100d8687da18b5c813c11e92fd8212a98e0"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_armv7l.manylinux2014_armv7l.whl", hash = "sha256:4f86f1f318e56f5cbb282fe61eb84767aee743ebe32c7c0834690ebea50c0a6b"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_ppc64le.manylinux2014_ppc64le.whl", hash = "sha256:86ce5fcfc3accf3a07a729779d0b86c5d0309a4764c897d86c11089be61da160"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_s390x.manylinux2014_s390x.whl", hash = "sha256:3dcf1978be02153c6a31692d4fbcc2a3f1db9da36039ead23173bc256ee3b91b"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:eedf97be7bc3dbc8addcef4142f4b4164066df0c6f36397ae4aaed3eb187d8ab"}, + {file = "pydantic_core-2.14.6-cp39-cp39-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:d5f916acf8afbcab6bacbb376ba7dc61f845367901ecd5e328fc4d4aef2fcab0"}, + {file = "pydantic_core-2.14.6-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:8a14c192c1d724c3acbfb3f10a958c55a2638391319ce8078cb36c02283959b9"}, + {file = "pydantic_core-2.14.6-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:0348b1dc6b76041516e8a854ff95b21c55f5a411c3297d2ca52f5528e49d8411"}, + {file = "pydantic_core-2.14.6-cp39-none-win32.whl", hash = "sha256:de2a0645a923ba57c5527497daf8ec5df69c6eadf869e9cd46e86349146e5975"}, + {file = "pydantic_core-2.14.6-cp39-none-win_amd64.whl", hash = "sha256:aca48506a9c20f68ee61c87f2008f81f8ee99f8d7f0104bff3c47e2d148f89d9"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-macosx_10_7_x86_64.whl", hash = "sha256:d5c28525c19f5bb1e09511669bb57353d22b94cf8b65f3a8d141c389a55dec95"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-macosx_11_0_arm64.whl", hash = "sha256:78d0768ee59baa3de0f4adac9e3748b4b1fffc52143caebddfd5ea2961595277"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:8b93785eadaef932e4fe9c6e12ba67beb1b3f1e5495631419c784ab87e975670"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:a874f21f87c485310944b2b2734cd6d318765bcbb7515eead33af9641816506e"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:b89f4477d915ea43b4ceea6756f63f0288941b6443a2b28c69004fe07fde0d0d"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:172de779e2a153d36ee690dbc49c6db568d7b33b18dc56b69a7514aecbcf380d"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:dfcebb950aa7e667ec226a442722134539e77c575f6cfaa423f24371bb8d2e94"}, + {file = "pydantic_core-2.14.6-pp310-pypy310_pp73-win_amd64.whl", hash = "sha256:55a23dcd98c858c0db44fc5c04fc7ed81c4b4d33c653a7c45ddaebf6563a2f66"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-macosx_10_7_x86_64.whl", hash = "sha256:4241204e4b36ab5ae466ecec5c4c16527a054c69f99bba20f6f75232a6a534e2"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:e574de99d735b3fc8364cba9912c2bec2da78775eba95cbb225ef7dda6acea24"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:1302a54f87b5cd8528e4d6d1bf2133b6aa7c6122ff8e9dc5220fbc1e07bffebd"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:f8e81e4b55930e5ffab4a68db1af431629cf2e4066dbdbfef65348b8ab804ea8"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:c99462ffc538717b3e60151dfaf91125f637e801f5ab008f81c402f1dff0cd0f"}, + {file = "pydantic_core-2.14.6-pp37-pypy37_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:e4cf2d5829f6963a5483ec01578ee76d329eb5caf330ecd05b3edd697e7d768a"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-macosx_10_7_x86_64.whl", hash = "sha256:cf10b7d58ae4a1f07fccbf4a0a956d705356fea05fb4c70608bb6fa81d103cda"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-macosx_11_0_arm64.whl", hash = "sha256:399ac0891c284fa8eb998bcfa323f2234858f5d2efca3950ae58c8f88830f145"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:9c6a5c79b28003543db3ba67d1df336f253a87d3112dac3a51b94f7d48e4c0e1"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:599c87d79cab2a6a2a9df4aefe0455e61e7d2aeede2f8577c1b7c0aec643ee8e"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:43e166ad47ba900f2542a80d83f9fc65fe99eb63ceec4debec160ae729824052"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:3a0b5db001b98e1c649dd55afa928e75aa4087e587b9524a4992316fa23c9fba"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:747265448cb57a9f37572a488a57d873fd96bf51e5bb7edb52cfb37124516da4"}, + {file = "pydantic_core-2.14.6-pp38-pypy38_pp73-win_amd64.whl", hash = "sha256:7ebe3416785f65c28f4f9441e916bfc8a54179c8dea73c23023f7086fa601c5d"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-macosx_10_7_x86_64.whl", hash = "sha256:86c963186ca5e50d5c8287b1d1c9d3f8f024cbe343d048c5bd282aec2d8641f2"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-macosx_11_0_arm64.whl", hash = "sha256:e0641b506486f0b4cd1500a2a65740243e8670a2549bb02bc4556a83af84ae03"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:71d72ca5eaaa8d38c8df16b7deb1a2da4f650c41b58bb142f3fb75d5ad4a611f"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:27e524624eace5c59af499cd97dc18bb201dc6a7a2da24bfc66ef151c69a5f2a"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-manylinux_2_5_i686.manylinux1_i686.whl", hash = "sha256:a3dde6cac75e0b0902778978d3b1646ca9f438654395a362cb21d9ad34b24acf"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-musllinux_1_1_aarch64.whl", hash = "sha256:00646784f6cd993b1e1c0e7b0fdcbccc375d539db95555477771c27555e3c556"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-musllinux_1_1_x86_64.whl", hash = "sha256:23598acb8ccaa3d1d875ef3b35cb6376535095e9405d91a3d57a8c7db5d29341"}, + {file = "pydantic_core-2.14.6-pp39-pypy39_pp73-win_amd64.whl", hash = "sha256:7f41533d7e3cf9520065f610b41ac1c76bc2161415955fbcead4981b22c7611e"}, + {file = "pydantic_core-2.14.6.tar.gz", hash = "sha256:1fd0c1d395372843fba13a51c28e3bb9d59bd7aebfeb17358ffaaa1e4dbbe948"}, +] + +[package.dependencies] +typing-extensions = ">=4.6.0,<4.7.0 || >4.7.0" + +[[package]] +name = "pyflakes" +version = "2.5.0" +description = "passive checker of Python programs" +optional = false +python-versions = ">=3.6" +files = [ + {file = "pyflakes-2.5.0-py2.py3-none-any.whl", hash = "sha256:4579f67d887f804e67edb544428f264b7b24f435b263c4614f384135cea553d2"}, + {file = "pyflakes-2.5.0.tar.gz", hash = "sha256:491feb020dca48ccc562a8c0cbe8df07ee13078df59813b83959cbdada312ea3"}, +] + +[[package]] +name = "pytest" +version = "7.4.4" +description = "pytest: simple powerful testing with Python" +optional = false +python-versions = ">=3.7" +files = [ + {file = "pytest-7.4.4-py3-none-any.whl", hash = "sha256:b090cdf5ed60bf4c45261be03239c2c1c22df034fbffe691abe93cd80cea01d8"}, + {file = "pytest-7.4.4.tar.gz", hash = "sha256:2cf0005922c6ace4a3e2ec8b4080eb0d9753fdc93107415332f50ce9e7994280"}, +] + +[package.dependencies] +colorama = {version = "*", markers = "sys_platform == \"win32\""} +exceptiongroup = {version = ">=1.0.0rc8", markers = "python_version < \"3.11\""} +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +iniconfig = "*" +packaging = "*" +pluggy = ">=0.12,<2.0" +tomli = {version = ">=1.0.0", markers = "python_version < \"3.11\""} + +[package.extras] +testing = ["argcomplete", "attrs (>=19.2.0)", "hypothesis (>=3.56)", "mock", "nose", "pygments (>=2.7.2)", "requests", "setuptools", "xmlschema"] + +[[package]] +name = "python-dateutil" +version = "2.8.2" +description = "Extensions to the standard Python datetime module" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,>=2.7" +files = [ + {file = "python-dateutil-2.8.2.tar.gz", hash = "sha256:0123cacc1627ae19ddf3c27a5de5bd67ee4586fbdd6440d9748f8abb483d3e86"}, + {file = "python_dateutil-2.8.2-py2.py3-none-any.whl", hash = "sha256:961d03dc3453ebbc59dbdea9e4e11c5651520a876d0f4db161e8674aae935da9"}, +] + +[package.dependencies] +six = ">=1.5" + +[[package]] +name = "six" +version = "1.16.0" +description = "Python 2 and 3 compatibility utilities" +optional = false +python-versions = ">=2.7, !=3.0.*, !=3.1.*, !=3.2.*" +files = [ + {file = "six-1.16.0-py2.py3-none-any.whl", hash = "sha256:8abb2f1d86890a2dfb989f9a77cfcfd3e47c2a354b01111771326f8aa26e0254"}, + {file = "six-1.16.0.tar.gz", hash = "sha256:1e61c37477a1626458e36f7b1d82aa5c9b094fa4802892072e49de9c60c4c926"}, +] + +[[package]] +name = "tomli" +version = "2.0.1" +description = "A lil' TOML parser" +optional = false +python-versions = ">=3.7" +files = [ + {file = "tomli-2.0.1-py3-none-any.whl", hash = "sha256:939de3e7a6161af0c887ef91b7d41a53e7c5a1ca976325f429cb46ea9bc30ecc"}, + {file = "tomli-2.0.1.tar.gz", hash = "sha256:de526c12914f0c550d15924c62d72abc48d6fe7364aa87328337a31007fe8a4f"}, +] + +[[package]] +name = "tox" +version = "3.28.0" +description = "tox is a generic virtualenv management and test command line tool" +optional = false +python-versions = "!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.*,!=3.4.*,>=2.7" +files = [ + {file = "tox-3.28.0-py2.py3-none-any.whl", hash = "sha256:57b5ab7e8bb3074edc3c0c0b4b192a4f3799d3723b2c5b76f1fa9f2d40316eea"}, + {file = "tox-3.28.0.tar.gz", hash = "sha256:d0d28f3fe6d6d7195c27f8b054c3e99d5451952b54abdae673b71609a581f640"}, +] + +[package.dependencies] +colorama = {version = ">=0.4.1", markers = "platform_system == \"Windows\""} +filelock = ">=3.0.0" +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +packaging = ">=14" +pluggy = ">=0.12.0" +py = ">=1.4.17" +six = ">=1.14.0" +tomli = {version = ">=2.0.1", markers = "python_version >= \"3.7\" and python_version < \"3.11\""} +virtualenv = ">=16.0.0,<20.0.0 || >20.0.0,<20.0.1 || >20.0.1,<20.0.2 || >20.0.2,<20.0.3 || >20.0.3,<20.0.4 || >20.0.4,<20.0.5 || >20.0.5,<20.0.6 || >20.0.6,<20.0.7 || >20.0.7" + +[package.extras] +docs = ["pygments-github-lexers (>=0.0.5)", "sphinx (>=2.0.0)", "sphinxcontrib-autoprogram (>=0.1.5)", "towncrier (>=18.5.0)"] +testing = ["flaky (>=3.4.0)", "freezegun (>=0.3.11)", "pathlib2 (>=2.3.3)", "psutil (>=5.6.1)", "pytest (>=4.0.0)", "pytest-cov (>=2.5.1)", "pytest-mock (>=1.10.0)", "pytest-randomly (>=1.0.0)"] + +[[package]] +name = "typed-ast" +version = "1.5.5" +description = "a fork of Python 2 and 3 ast modules with type comment support" +optional = false +python-versions = ">=3.6" +files = [ + {file = "typed_ast-1.5.5-cp310-cp310-macosx_10_9_x86_64.whl", hash = "sha256:4bc1efe0ce3ffb74784e06460f01a223ac1f6ab31c6bc0376a21184bf5aabe3b"}, + {file = "typed_ast-1.5.5-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:5f7a8c46a8b333f71abd61d7ab9255440d4a588f34a21f126bbfc95f6049e686"}, + {file = "typed_ast-1.5.5-cp310-cp310-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:597fc66b4162f959ee6a96b978c0435bd63791e31e4f410622d19f1686d5e769"}, + {file = "typed_ast-1.5.5-cp310-cp310-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:d41b7a686ce653e06c2609075d397ebd5b969d821b9797d029fccd71fdec8e04"}, + {file = "typed_ast-1.5.5-cp310-cp310-musllinux_1_1_aarch64.whl", hash = "sha256:5fe83a9a44c4ce67c796a1b466c270c1272e176603d5e06f6afbc101a572859d"}, + {file = "typed_ast-1.5.5-cp310-cp310-musllinux_1_1_x86_64.whl", hash = "sha256:d5c0c112a74c0e5db2c75882a0adf3133adedcdbfd8cf7c9d6ed77365ab90a1d"}, + {file = "typed_ast-1.5.5-cp310-cp310-win_amd64.whl", hash = "sha256:e1a976ed4cc2d71bb073e1b2a250892a6e968ff02aa14c1f40eba4f365ffec02"}, + {file = "typed_ast-1.5.5-cp311-cp311-macosx_10_9_x86_64.whl", hash = "sha256:c631da9710271cb67b08bd3f3813b7af7f4c69c319b75475436fcab8c3d21bee"}, + {file = "typed_ast-1.5.5-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:b445c2abfecab89a932b20bd8261488d574591173d07827c1eda32c457358b18"}, + {file = "typed_ast-1.5.5-cp311-cp311-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:cc95ffaaab2be3b25eb938779e43f513e0e538a84dd14a5d844b8f2932593d88"}, + {file = "typed_ast-1.5.5-cp311-cp311-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:61443214d9b4c660dcf4b5307f15c12cb30bdfe9588ce6158f4a005baeb167b2"}, + {file = "typed_ast-1.5.5-cp311-cp311-musllinux_1_1_aarch64.whl", hash = "sha256:6eb936d107e4d474940469e8ec5b380c9b329b5f08b78282d46baeebd3692dc9"}, + {file = "typed_ast-1.5.5-cp311-cp311-musllinux_1_1_x86_64.whl", hash = "sha256:e48bf27022897577d8479eaed64701ecaf0467182448bd95759883300ca818c8"}, + {file = "typed_ast-1.5.5-cp311-cp311-win_amd64.whl", hash = "sha256:83509f9324011c9a39faaef0922c6f720f9623afe3fe220b6d0b15638247206b"}, + {file = "typed_ast-1.5.5-cp36-cp36m-macosx_10_9_x86_64.whl", hash = "sha256:44f214394fc1af23ca6d4e9e744804d890045d1643dd7e8229951e0ef39429b5"}, + {file = "typed_ast-1.5.5-cp36-cp36m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:118c1ce46ce58fda78503eae14b7664163aa735b620b64b5b725453696f2a35c"}, + {file = "typed_ast-1.5.5-cp36-cp36m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:be4919b808efa61101456e87f2d4c75b228f4e52618621c77f1ddcaae15904fa"}, + {file = "typed_ast-1.5.5-cp36-cp36m-musllinux_1_1_aarch64.whl", hash = "sha256:fc2b8c4e1bc5cd96c1a823a885e6b158f8451cf6f5530e1829390b4d27d0807f"}, + {file = "typed_ast-1.5.5-cp36-cp36m-musllinux_1_1_x86_64.whl", hash = "sha256:16f7313e0a08c7de57f2998c85e2a69a642e97cb32f87eb65fbfe88381a5e44d"}, + {file = "typed_ast-1.5.5-cp36-cp36m-win_amd64.whl", hash = "sha256:2b946ef8c04f77230489f75b4b5a4a6f24c078be4aed241cfabe9cbf4156e7e5"}, + {file = "typed_ast-1.5.5-cp37-cp37m-macosx_10_9_x86_64.whl", hash = "sha256:2188bc33d85951ea4ddad55d2b35598b2709d122c11c75cffd529fbc9965508e"}, + {file = "typed_ast-1.5.5-cp37-cp37m-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:0635900d16ae133cab3b26c607586131269f88266954eb04ec31535c9a12ef1e"}, + {file = "typed_ast-1.5.5-cp37-cp37m-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:57bfc3cf35a0f2fdf0a88a3044aafaec1d2f24d8ae8cd87c4f58d615fb5b6311"}, + {file = "typed_ast-1.5.5-cp37-cp37m-musllinux_1_1_aarch64.whl", hash = "sha256:fe58ef6a764de7b4b36edfc8592641f56e69b7163bba9f9c8089838ee596bfb2"}, + {file = "typed_ast-1.5.5-cp37-cp37m-musllinux_1_1_x86_64.whl", hash = "sha256:d09d930c2d1d621f717bb217bf1fe2584616febb5138d9b3e8cdd26506c3f6d4"}, + {file = "typed_ast-1.5.5-cp37-cp37m-win_amd64.whl", hash = "sha256:d40c10326893ecab8a80a53039164a224984339b2c32a6baf55ecbd5b1df6431"}, + {file = "typed_ast-1.5.5-cp38-cp38-macosx_10_9_x86_64.whl", hash = "sha256:fd946abf3c31fb50eee07451a6aedbfff912fcd13cf357363f5b4e834cc5e71a"}, + {file = "typed_ast-1.5.5-cp38-cp38-macosx_11_0_arm64.whl", hash = "sha256:ed4a1a42df8a3dfb6b40c3d2de109e935949f2f66b19703eafade03173f8f437"}, + {file = "typed_ast-1.5.5-cp38-cp38-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:045f9930a1550d9352464e5149710d56a2aed23a2ffe78946478f7b5416f1ede"}, + {file = "typed_ast-1.5.5-cp38-cp38-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:381eed9c95484ceef5ced626355fdc0765ab51d8553fec08661dce654a935db4"}, + {file = "typed_ast-1.5.5-cp38-cp38-musllinux_1_1_aarch64.whl", hash = "sha256:bfd39a41c0ef6f31684daff53befddae608f9daf6957140228a08e51f312d7e6"}, + {file = "typed_ast-1.5.5-cp38-cp38-musllinux_1_1_x86_64.whl", hash = "sha256:8c524eb3024edcc04e288db9541fe1f438f82d281e591c548903d5b77ad1ddd4"}, + {file = "typed_ast-1.5.5-cp38-cp38-win_amd64.whl", hash = "sha256:7f58fabdde8dcbe764cef5e1a7fcb440f2463c1bbbec1cf2a86ca7bc1f95184b"}, + {file = "typed_ast-1.5.5-cp39-cp39-macosx_10_9_x86_64.whl", hash = "sha256:042eb665ff6bf020dd2243307d11ed626306b82812aba21836096d229fdc6a10"}, + {file = "typed_ast-1.5.5-cp39-cp39-macosx_11_0_arm64.whl", hash = "sha256:622e4a006472b05cf6ef7f9f2636edc51bda670b7bbffa18d26b255269d3d814"}, + {file = "typed_ast-1.5.5-cp39-cp39-manylinux_2_17_aarch64.manylinux2014_aarch64.whl", hash = "sha256:1efebbbf4604ad1283e963e8915daa240cb4bf5067053cf2f0baadc4d4fb51b8"}, + {file = "typed_ast-1.5.5-cp39-cp39-manylinux_2_17_x86_64.manylinux2014_x86_64.whl", hash = "sha256:f0aefdd66f1784c58f65b502b6cf8b121544680456d1cebbd300c2c813899274"}, + {file = "typed_ast-1.5.5-cp39-cp39-musllinux_1_1_aarch64.whl", hash = "sha256:48074261a842acf825af1968cd912f6f21357316080ebaca5f19abbb11690c8a"}, + {file = "typed_ast-1.5.5-cp39-cp39-musllinux_1_1_x86_64.whl", hash = "sha256:429ae404f69dc94b9361bb62291885894b7c6fb4640d561179548c849f8492ba"}, + {file = "typed_ast-1.5.5-cp39-cp39-win_amd64.whl", hash = "sha256:335f22ccb244da2b5c296e6f96b06ee9bed46526db0de38d2f0e5a6597b81155"}, + {file = "typed_ast-1.5.5.tar.gz", hash = "sha256:94282f7a354f36ef5dbce0ef3467ebf6a258e370ab33d5b40c249fa996e590dd"}, +] + +[[package]] +name = "types-python-dateutil" +version = "2.8.19.14" +description = "Typing stubs for python-dateutil" +optional = false +python-versions = "*" +files = [ + {file = "types-python-dateutil-2.8.19.14.tar.gz", hash = "sha256:1f4f10ac98bb8b16ade9dbee3518d9ace017821d94b057a425b069f834737f4b"}, + {file = "types_python_dateutil-2.8.19.14-py3-none-any.whl", hash = "sha256:f977b8de27787639986b4e28963263fd0e5158942b3ecef91b9335c130cb1ce9"}, +] + +[[package]] +name = "typing-extensions" +version = "4.7.1" +description = "Backported and Experimental Type Hints for Python 3.7+" +optional = false +python-versions = ">=3.7" +files = [ + {file = "typing_extensions-4.7.1-py3-none-any.whl", hash = "sha256:440d5dd3af93b060174bf433bccd69b0babc3b15b1a8dca43789fd7f61514b36"}, + {file = "typing_extensions-4.7.1.tar.gz", hash = "sha256:b75ddc264f0ba5615db7ba217daeb99701ad295353c45f9e95963337ceeeffb2"}, +] + +[[package]] +name = "urllib3" +version = "2.0.7" +description = "HTTP library with thread-safe connection pooling, file post, and more." +optional = false +python-versions = ">=3.7" +files = [ + {file = "urllib3-2.0.7-py3-none-any.whl", hash = "sha256:fdb6d215c776278489906c2f8916e6e7d4f5a9b602ccbcfdf7f016fc8da0596e"}, + {file = "urllib3-2.0.7.tar.gz", hash = "sha256:c97dfde1f7bd43a71c8d2a58e369e9b2bf692d1334ea9f9cae55add7d0dd0f84"}, +] + +[package.extras] +brotli = ["brotli (>=1.0.9)", "brotlicffi (>=0.8.0)"] +secure = ["certifi", "cryptography (>=1.9)", "idna (>=2.0.0)", "pyopenssl (>=17.1.0)", "urllib3-secure-extra"] +socks = ["pysocks (>=1.5.6,!=1.5.7,<2.0)"] +zstd = ["zstandard (>=0.18.0)"] + +[[package]] +name = "virtualenv" +version = "20.16.2" +description = "Virtual Python Environment builder" +optional = false +python-versions = ">=3.6" +files = [ + {file = "virtualenv-20.16.2-py2.py3-none-any.whl", hash = "sha256:635b272a8e2f77cb051946f46c60a54ace3cb5e25568228bd6b57fc70eca9ff3"}, + {file = "virtualenv-20.16.2.tar.gz", hash = "sha256:0ef5be6d07181946891f5abc8047fda8bc2f0b4b9bf222c64e6e8963baee76db"}, +] + +[package.dependencies] +distlib = ">=0.3.1,<1" +filelock = ">=3.2,<4" +importlib-metadata = {version = ">=0.12", markers = "python_version < \"3.8\""} +platformdirs = ">=2,<3" + +[package.extras] +docs = ["proselint (>=0.10.2)", "sphinx (>=3)", "sphinx-argparse (>=0.2.5)", "sphinx-rtd-theme (>=0.4.3)", "towncrier (>=21.3)"] +testing = ["coverage (>=4)", "coverage-enable-subprocess (>=1)", "flaky (>=3)", "packaging (>=20.0)", "pytest (>=4)", "pytest-env (>=0.6.2)", "pytest-freezegun (>=0.4.1)", "pytest-mock (>=2)", "pytest-randomly (>=1)", "pytest-timeout (>=1)"] + +[[package]] +name = "zipp" +version = "3.15.0" +description = "Backport of pathlib-compatible object wrapper for zip files" +optional = false +python-versions = ">=3.7" +files = [ + {file = "zipp-3.15.0-py3-none-any.whl", hash = "sha256:48904fc76a60e542af151aded95726c1a5c34ed43ab4134b597665c86d7ad556"}, + {file = "zipp-3.15.0.tar.gz", hash = "sha256:112929ad649da941c23de50f356a2b5570c954b65150642bccdd66bf194d224b"}, +] + +[package.extras] +docs = ["furo", "jaraco.packaging (>=9)", "jaraco.tidelift (>=1.4)", "rst.linker (>=1.9)", "sphinx (>=3.5)", "sphinx-lint"] +testing = ["big-O", "flake8 (<5)", "jaraco.functools", "jaraco.itertools", "more-itertools", "pytest (>=6)", "pytest-black (>=0.3.7)", "pytest-checkdocs (>=2.4)", "pytest-cov", "pytest-enabler (>=1.3)", "pytest-flake8", "pytest-mypy (>=0.9.1)"] + +[metadata] +lock-version = "2.0" +python-versions = "^3.7" +content-hash = "96d25a1701fc4c71e041dd068430d11b575227644b810a999176e8f98aa070e4" diff --git a/samples/openapi3/client/petstore/python/pyproject.toml b/samples/openapi3/client/petstore/python/pyproject.toml index 0d153fcb0c3d..e416a2dcbdab 100644 --- a/samples/openapi3/client/petstore/python/pyproject.toml +++ b/samples/openapi3/client/petstore/python/pyproject.toml @@ -23,6 +23,9 @@ typing-extensions = ">=4.7.1" pytest = ">=7.2.1" tox = ">=3.9.0" flake8 = ">=4.0.0" +types-python-dateutil = ">=2.8.19.14" +mypy = "1.4.1" + [build-system] requires = ["setuptools"] @@ -30,3 +33,41 @@ build-backend = "setuptools.build_meta" [tool.pylint.'MESSAGES CONTROL'] extension-pkg-whitelist = "pydantic" + +[tool.mypy] +files = [ + "petstore_api", + #"test", # auto-generated tests + "tests", # hand-written tests +] +# TODO: enable "strict" once all these individual checks are passing +# strict = true + +# List from: https://mypy.readthedocs.io/en/stable/existing_code.html#introduce-stricter-options +warn_unused_configs = true +warn_redundant_casts = true +warn_unused_ignores = true + +## Getting these passing should be easy +strict_equality = true +strict_concatenate = true + +## Strongly recommend enabling this one as soon as you can +check_untyped_defs = true + +## These shouldn't be too much additional work, but may be tricky to +## get passing if you use a lot of untyped libraries +disallow_subclassing_any = true +disallow_untyped_decorators = true +disallow_any_generics = true + +### These next few are various gradations of forcing use of type annotations +#disallow_untyped_calls = true +#disallow_incomplete_defs = true +#disallow_untyped_defs = true +# +### This one isn't too hard to get passing, but return on investment is lower +#no_implicit_reexport = true +# +### This one can be tricky to get passing if you use a lot of untyped libraries +#warn_return_any = true diff --git a/samples/openapi3/client/petstore/python/test-requirements.txt b/samples/openapi3/client/petstore/python/test-requirements.txt index 3a0d0b939a1e..8e6d8cb13749 100755 --- a/samples/openapi3/client/petstore/python/test-requirements.txt +++ b/samples/openapi3/client/petstore/python/test-requirements.txt @@ -1,3 +1,5 @@ pytest~=7.1.3 pytest-cov>=2.8.1 pytest-randomly>=3.12.0 +mypy>=1.4.1 +types-python-dateutil>=2.8.19 diff --git a/samples/openapi3/client/petstore/python/test/test_api_response.py b/samples/openapi3/client/petstore/python/test/test_api_response.py deleted file mode 100644 index 95efd33bce57..000000000000 --- a/samples/openapi3/client/petstore/python/test/test_api_response.py +++ /dev/null @@ -1,53 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.api_response import ApiResponse # noqa: E501 -from petstore_api.rest import ApiException - -class TestApiResponse(unittest.TestCase): - """ApiResponse unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test ApiResponse - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.api_response.ApiResponse() # noqa: E501 - if include_optional : - return ApiResponse( - code = 56, - type = '', - message = '' - ) - else : - return ApiResponse( - ) - - def testApiResponse(self): - """Test ApiResponse""" - inst_req_only = self.make_instance(include_optional=False) - inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_configuration.py b/samples/openapi3/client/petstore/python/test/test_configuration.py deleted file mode 100755 index d41ffa63ba8a..000000000000 --- a/samples/openapi3/client/petstore/python/test/test_configuration.py +++ /dev/null @@ -1,54 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - OpenAPI spec version: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest - -import petstore_api -from petstore_api import Configuration # noqa: E501 -from petstore_api.rest import ApiException - - -class TestConfiguration(unittest.TestCase): - """Configuration unit test stubs""" - - def setUp(self): - self.config= Configuration() - - def tearDown(self): - pass - - def test_configuration(self): - """Test configuration - - Test host settings # noqa: E501 - """ - host_settings = self.config.get_host_settings() - - self.assertEqual('http://{server}.swagger.io:{port}/v2', host_settings[0]['url']) - self.assertEqual('petstore', host_settings[0]['variables']['server']['default_value']) - - self.assertEqual('https://localhost:8080/{version}', host_settings[1]['url']) - self.assertEqual('v2', host_settings[1]['variables']['version']['default_value']) - - def test_get_host_from_settings(self): - """ Test get_host_from_settings - - Test get URL from host settings - """ - self.assertEqual("http://petstore.swagger.io:80/v2", self.config.get_host_from_settings(0)) - self.assertEqual("http://petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'port': '8080'})) - self.assertEqual("http://dev-petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'server': 'dev-petstore', 'port': '8080'})) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_fake_api.py b/samples/openapi3/client/petstore/python/test/test_fake_api.py index cf074093f90d..9a7dfbb96439 100644 --- a/samples/openapi3/client/petstore/python/test/test_fake_api.py +++ b/samples/openapi3/client/petstore/python/test/test_fake_api.py @@ -129,6 +129,7 @@ def test_test_query_parameter_collection_format(self): """ pass + @unittest.skip("TODO: MagicMock error") def test_headers_parameter(self): """Test case for the _headers are passed by the user @@ -139,7 +140,7 @@ def test_headers_parameter(self): value_headers = {"Header1": "value1"} api.find_pets_by_status(["available"], _headers=value_headers) args, _ = mock_method.call_args - self.assertEqual(args, ('/pet/findByStatus', 'GET', {}, [('status', ['available'])], {'Accept': 'application/json', 'Header1': 'value1'}) + self.assertEqual(args, ('GET', '/pet/findByStatus', {}, [('status', ['available'])], {'Accept': 'application/json', 'Header1': 'value1'}) ) if __name__ == '__main__': diff --git a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py b/samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py index f54e0d06644f..881dcba0d25a 100644 --- a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py +++ b/samples/openapi3/client/petstore/python/test/test_fake_classname_tags123_api.py @@ -2,9 +2,7 @@ """ OpenAPI Petstore - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - The version of the OpenAPI document: 1.0.0 Generated by: https://openapi-generator.tech """ @@ -15,7 +13,7 @@ import unittest import petstore_api -from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 +from petstore_api.api.fake_classname_tags123_api import FakeClassnameTags123Api # noqa: E501 from petstore_api.rest import ApiException @@ -23,14 +21,13 @@ class TestFakeClassnameTags123Api(unittest.TestCase): """FakeClassnameTags123Api unit test stubs""" def setUp(self): - self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 + self.api = petstore_api.api.fake_classname_tags123_api.FakeClassnameTags123Api() # noqa: E501 def tearDown(self): pass def test_test_classname(self): """Test case for test_classname - To test class name in snake case # noqa: E501 """ pass diff --git a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags_123_api.py b/samples/openapi3/client/petstore/python/test/test_fake_classname_tags_123_api.py deleted file mode 100644 index f54e0d06644f..000000000000 --- a/samples/openapi3/client/petstore/python/test/test_fake_classname_tags_123_api.py +++ /dev/null @@ -1,40 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest - -import petstore_api -from petstore_api.api.fake_classname_tags_123_api import FakeClassnameTags123Api # noqa: E501 -from petstore_api.rest import ApiException - - -class TestFakeClassnameTags123Api(unittest.TestCase): - """FakeClassnameTags123Api unit test stubs""" - - def setUp(self): - self.api = petstore_api.api.fake_classname_tags_123_api.FakeClassnameTags123Api() # noqa: E501 - - def tearDown(self): - pass - - def test_test_classname(self): - """Test case for test_classname - - To test class name in snake case # noqa: E501 - """ - pass - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_list.py b/samples/openapi3/client/petstore/python/test/test_list.py deleted file mode 100644 index 94806473a93c..000000000000 --- a/samples/openapi3/client/petstore/python/test/test_list.py +++ /dev/null @@ -1,51 +0,0 @@ -# coding: utf-8 - -""" - OpenAPI Petstore - - This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ # noqa: E501 - - The version of the OpenAPI document: 1.0.0 - Generated by: https://openapi-generator.tech -""" - - -from __future__ import absolute_import - -import unittest -import datetime - -import petstore_api -from petstore_api.models.list_class import ListClass # noqa: E501 -from petstore_api.rest import ApiException - -class TestList(unittest.TestCase): - """List unit test stubs""" - - def setUp(self): - pass - - def tearDown(self): - pass - - def make_instance(self, include_optional): - """Test List - include_option is a boolean, when False only required - params are included, when True both required and - optional params are included """ - # model = petstore_api.models.list.List() # noqa: E501 - if include_optional : - return ListClass( - _123_list = '' - ) - else : - return ListClass( - ) - - def testList(self): - """Test List""" - inst_req_only = self.make_instance(include_optional=False) - inst_req_and_optional = self.make_instance(include_optional=True) - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_model_api_response.py b/samples/openapi3/client/petstore/python/test/test_model_api_response.py new file mode 100644 index 000000000000..f37f34084401 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_model_api_response.py @@ -0,0 +1,54 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.model_api_response import ModelApiResponse + +class TestModelApiResponse(unittest.TestCase): + """ModelApiResponse unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> ModelApiResponse: + """Test ModelApiResponse + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `ModelApiResponse` + """ + model = ModelApiResponse() + if include_optional: + return ModelApiResponse( + code = 56, + type = '', + message = '' + ) + else: + return ModelApiResponse( + ) + """ + + def testModelApiResponse(self): + """Test ModelApiResponse""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model400_response.py b/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model400_response.py new file mode 100644 index 000000000000..35db7ba74fb7 --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model400_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model400_response import TestErrorResponsesWithModel400Response + +class TestTestErrorResponsesWithModel400Response(unittest.TestCase): + """TestErrorResponsesWithModel400Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel400Response: + """Test TestErrorResponsesWithModel400Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel400Response` + """ + model = TestErrorResponsesWithModel400Response() + if include_optional: + return TestErrorResponsesWithModel400Response( + reason400 = '' + ) + else: + return TestErrorResponsesWithModel400Response( + ) + """ + + def testTestErrorResponsesWithModel400Response(self): + """Test TestErrorResponsesWithModel400Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model404_response.py b/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model404_response.py new file mode 100644 index 000000000000..e9c97c0f484b --- /dev/null +++ b/samples/openapi3/client/petstore/python/test/test_test_error_responses_with_model404_response.py @@ -0,0 +1,52 @@ +# coding: utf-8 + +""" + OpenAPI Petstore + + This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + + The version of the OpenAPI document: 1.0.0 + Generated by OpenAPI Generator (https://openapi-generator.tech) + + Do not edit the class manually. +""" # noqa: E501 + + +import unittest +import datetime + +from petstore_api.models.test_error_responses_with_model404_response import TestErrorResponsesWithModel404Response + +class TestTestErrorResponsesWithModel404Response(unittest.TestCase): + """TestErrorResponsesWithModel404Response unit test stubs""" + + def setUp(self): + pass + + def tearDown(self): + pass + + def make_instance(self, include_optional) -> TestErrorResponsesWithModel404Response: + """Test TestErrorResponsesWithModel404Response + include_option is a boolean, when False only required + params are included, when True both required and + optional params are included """ + # uncomment below to create an instance of `TestErrorResponsesWithModel404Response` + """ + model = TestErrorResponsesWithModel404Response() + if include_optional: + return TestErrorResponsesWithModel404Response( + reason404 = '' + ) + else: + return TestErrorResponsesWithModel404Response( + ) + """ + + def testTestErrorResponsesWithModel404Response(self): + """Test TestErrorResponsesWithModel404Response""" + # inst_req_only = self.make_instance(include_optional=False) + # inst_req_and_optional = self.make_instance(include_optional=True) + +if __name__ == '__main__': + unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests/test_api.py b/samples/openapi3/client/petstore/python/tests/test_api.py new file mode 100644 index 000000000000..8237969c4943 --- /dev/null +++ b/samples/openapi3/client/petstore/python/tests/test_api.py @@ -0,0 +1,84 @@ +import json +import unittest +from unittest.mock import patch, Mock + +import pytest + +import petstore_api + + +class TestMultipleResponseTypes(unittest.TestCase): + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.fake_api = petstore_api.FakeApi(self.api_client) + + def test_204(self): + mock_resp = Mock() + mock_resp.status = 204 + mock_resp.data = b"" + mock_resp.getheaders.return_value = {} + + with patch( + "petstore_api.api_client.ApiClient.call_api", return_value=mock_resp + ): + returned = self.fake_api.test_empty_and_non_empty_responses() + + assert returned is None + + def test_206(self): + mock_resp = Mock() + mock_resp.status = 206 + mock_resp.data = b"some text" + mock_resp.getheaders.return_value = {} + mock_resp.getheader = ( + lambda name: "text/plain" if name == "content-type" else Mock() + ) + + with patch( + "petstore_api.api_client.ApiClient.call_api", return_value=mock_resp + ): + returned = self.fake_api.test_empty_and_non_empty_responses() + + assert returned == "some text" + + +class TestErrorResponsesWithModels(unittest.TestCase): + def setUp(self): + self.api_client = petstore_api.ApiClient() + self.fake_api = petstore_api.FakeApi(self.api_client) + + def test_400(self): + mock_resp = Mock() + mock_resp.status = 400 + mock_resp.data = json.dumps({"reason400": "400 reason"}).encode("utf-8") + mock_resp.getheaders.return_value = {} + mock_resp.getheader.return_value = "" + + with patch( + "petstore_api.api_client.ApiClient.call_api", return_value=mock_resp + ): + with pytest.raises(petstore_api.exceptions.BadRequestException) as exc_info: + self.fake_api.test_error_responses_with_model() + + expected_resp = petstore_api.TestErrorResponsesWithModel400Response( + reason400="400 reason" + ) + assert exc_info.value.data == expected_resp + + def test_404(self): + mock_resp = Mock() + mock_resp.status = 404 + mock_resp.data = json.dumps({"reason404": "404 reason"}).encode("utf-8") + mock_resp.getheaders.return_value = {} + mock_resp.getheader.return_value = "" + + with patch( + "petstore_api.api_client.ApiClient.call_api", return_value=mock_resp + ): + with pytest.raises(petstore_api.exceptions.NotFoundException) as exc_info: + self.fake_api.test_error_responses_with_model() + + expected_resp = petstore_api.TestErrorResponsesWithModel404Response( + reason404="404 reason" + ) + assert exc_info.value.data == expected_resp diff --git a/samples/openapi3/client/petstore/python/tests/test_api_client.py b/samples/openapi3/client/petstore/python/tests/test_api_client.py index 81a5da38fde4..972b705872df 100644 --- a/samples/openapi3/client/petstore/python/tests/test_api_client.py +++ b/samples/openapi3/client/petstore/python/tests/test_api_client.py @@ -125,48 +125,47 @@ def test_select_header_content_type(self): content_type = self.api_client.select_header_content_type(content_types) self.assertEqual(content_type, None) - def test_sanitize_for_serialization(self): - # None + def test_sanitize_for_serialization_none(self): data = None result = self.api_client.sanitize_for_serialization(None) self.assertEqual(result, data) - # str + def test_sanitize_for_serialization_str(self): data = "test string" result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, data) - # int + def test_sanitize_for_serialization_int(self): data = 1 result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, data) - # bool + def test_sanitize_for_serialization_bool(self): data = True result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, data) - # date + def test_sanitize_for_serialization_date(self): data = parse("1997-07-16").date() # date result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, "1997-07-16") - # datetime + def test_sanitize_for_serialization_datetime(self): data = parse("1997-07-16T19:20:30.45+01:00") # datetime result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, "1997-07-16T19:20:30.450000+01:00") - # list + def test_sanitize_for_serialization_list(self): data = [1] result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, data) - # dict + def test_sanitize_for_serialization_dict(self): data = {"test key": "test value"} result = self.api_client.sanitize_for_serialization(data) self.assertEqual(result, data) - # model + def test_sanitize_for_serialization_model(self): pet_dict = {"id": 1, "name": "monkey", "category": {"id": 1, "name": "test category"}, "tags": [{"id": 1, "name": "test tag1"}, @@ -174,20 +173,19 @@ def test_sanitize_for_serialization(self): "status": "available", "photoUrls": ["http://foo.bar.com/3", "http://foo.bar.com/4"]} - pet = petstore_api.Pet(name=pet_dict["name"], photoUrls=pet_dict["photoUrls"]) - pet.id = pet_dict["id"] - cate = petstore_api.Category(name="something") - cate.id = pet_dict["category"]["id"] - cate.name = pet_dict["category"]["name"] + pet = petstore_api.Pet(name="monkey", photoUrls=["http://foo.bar.com/3", "http://foo.bar.com/4"]) + pet.id = 1 + cate = petstore_api.Category(name="test category") + cate.id = 1 pet.category = cate tag1 = petstore_api.Tag() - tag1.id = pet_dict["tags"][0]["id"] - tag1.name = pet_dict["tags"][0]["name"] + tag1.id = 1 + tag1.name = "test tag1" tag2 = petstore_api.Tag() - tag2.id = pet_dict["tags"][1]["id"] - tag2.name = pet_dict["tags"][1]["name"] + tag2.id = 2 + tag2.name = "test tag2" pet.tags = [tag1, tag2] - pet.status = pet_dict["status"] + pet.status = "available" data = pet result = self.api_client.sanitize_for_serialization(data) @@ -195,25 +193,10 @@ def test_sanitize_for_serialization(self): # list of models list_of_pet_dict = [pet_dict] - data = [pet] - result = self.api_client.sanitize_for_serialization(data) + result = self.api_client.sanitize_for_serialization([pet]) self.assertEqual(result, list_of_pet_dict) - def test_context_manager_closes_threadpool(self): - with petstore_api.ApiClient() as client: - self.assertIsNotNone(client.pool) - pool_ref = weakref.ref(client._pool) - self.assertIsNotNone(pool_ref()) - self.assertIsNone(pool_ref()) - - def test_atexit_closes_threadpool(self): - client = petstore_api.ApiClient() - self.assertIsNotNone(client.pool) - self.assertIsNotNone(client._pool) - atexit._run_exitfuncs() - self.assertIsNone(client._pool) - - def test_parameters_to_url_query(self): + def test_parameters_to_url_query_simple_values(self): data = 'value={"category": "example", "category2": "example2"}' dictionary = { "category": "example", @@ -222,6 +205,7 @@ def test_parameters_to_url_query(self): result = self.api_client.parameters_to_url_query([('value', dictionary)], {}) self.assertEqual(result, "value=%7B%22category%22%3A%20%22example%22%2C%20%22category2%22%3A%20%22example2%22%7D") + def test_parameters_to_url_query_complex_values(self): data='value={"number": 1, "string": "str", "bool": true, "dict": {"number": 1, "string": "str", "bool": true}}' dictionary = { "number": 1, @@ -236,6 +220,7 @@ def test_parameters_to_url_query(self): result = self.api_client.parameters_to_url_query([('value', dictionary)], {}) self.assertEqual(result, 'value=%7B%22number%22%3A%201%2C%20%22string%22%3A%20%22str%22%2C%20%22bool%22%3A%20true%2C%20%22dict%22%3A%20%7B%22number%22%3A%201%2C%20%22string%22%3A%20%22str%22%2C%20%22bool%22%3A%20true%7D%7D') + def test_parameters_to_url_query_dict_values(self): data='value={"strValues": ["one", "two", "three"], "dictValues": [{"name": "value1", "age": 14}, {"name": "value2", "age": 12}]}' dictionary = { "strValues": [ @@ -257,5 +242,6 @@ def test_parameters_to_url_query(self): result = self.api_client.parameters_to_url_query([('value', dictionary)], {}) self.assertEqual(result, 'value=%7B%22strValues%22%3A%20%5B%22one%22%2C%20%22two%22%2C%20%22three%22%5D%2C%20%22dictValues%22%3A%20%5B%7B%22name%22%3A%20%22value1%22%2C%20%22age%22%3A%2014%7D%2C%20%7B%22name%22%3A%20%22value2%22%2C%20%22age%22%3A%2012%7D%5D%7D') - - + def test_parameters_to_url_query_boolean_value(self): + result = self.api_client.parameters_to_url_query([('boolean', True)], {}) + self.assertEqual(result, "boolean=true") diff --git a/samples/openapi3/client/petstore/python/tests/test_api_exception.py b/samples/openapi3/client/petstore/python/tests/test_api_exception.py index bb8c5a1eac99..130f3aa65e37 100644 --- a/samples/openapi3/client/petstore/python/tests/test_api_exception.py +++ b/samples/openapi3/client/petstore/python/tests/test_api_exception.py @@ -41,6 +41,7 @@ def setUpModels(self): def test_404_error(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None self.pet_api.delete_pet(pet_id=self.pet.id) with self.checkRaiseRegex(ApiException, "Pet not found"): @@ -55,6 +56,7 @@ def test_404_error(self): def test_500_error(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None with self.checkRaiseRegex(ApiException, "Internal Server Error"): self.pet_api.upload_file( diff --git a/samples/openapi3/client/petstore/python/tests/test_api_validation.py b/samples/openapi3/client/petstore/python/tests/test_api_validation.py index 035d618ce050..679a3bb67b59 100644 --- a/samples/openapi3/client/petstore/python/tests/test_api_validation.py +++ b/samples/openapi3/client/petstore/python/tests/test_api_validation.py @@ -48,14 +48,14 @@ def test_set_param_validation(self): def test_required_param_validation(self): try: - self.pet_api.get_pet_by_id() + self.pet_api.get_pet_by_id() # type: ignore except ValidationError as e: self.assertIn("1 validation error for get_pet_by_id", str(e)) self.assertIn("Missing required argument", str(e)) def test_integer_validation(self): try: - self.pet_api.get_pet_by_id("123") + self.pet_api.get_pet_by_id("123") # type: ignore except ValidationError as e: # 1 validation error for get_pet_by_id # pet_id @@ -74,6 +74,48 @@ def test_string_enum_validation(self): self.assertIn("1 validation error for FindPetsByStatus", str(e)) self.assertIn("unexpected value; permitted: 'available', 'pending', 'sold'", str(e)) + def test_request_timeout_validation(self): + assert self.pet.id is not None + try: + # should be a number + self.pet_api.get_pet_by_id(self.pet.id, _request_timeout="1.0") # type: ignore + self.assertTrue(False) + except ValidationError as e: + pass + try: + # should be a number or a pair + self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=()) # type: ignore + self.assertTrue(False) + except ValidationError as e: + pass + try: + # should be a a pair + self.pet_api.get_pet_by_id(self.pet.id, _request_timeout=(1.0, 1.0, 1.0)) # type: ignore + self.assertTrue(False) + except ValidationError as e: + pass + + + def test_host_index_validation(self): + assert self.pet.id is not None + try: + # should be a number + self.pet_api.get_pet_by_id(self.pet.id, _host_index="1") # type: ignore + self.assertTrue(False) + except ValidationError as e: + pass + try: + self.pet_api.get_pet_by_id(self.pet.id, _host_index=1) + self.assertTrue(False) + except ValidationError as e: + pass + try: + self.pet_api.get_pet_by_id(self.pet.id, _host_index=-1) + self.assertTrue(False) + except ValidationError as e: + pass + + def checkRaiseRegex(self, expected_exception, expected_regex): return self.assertRaisesRegex(expected_exception, expected_regex) diff --git a/samples/openapi3/client/petstore/python/tests/test_configuration.py b/samples/openapi3/client/petstore/python/tests/test_configuration.py index 04c2781f5e29..d8084adafd24 100644 --- a/samples/openapi3/client/petstore/python/tests/test_configuration.py +++ b/samples/openapi3/client/petstore/python/tests/test_configuration.py @@ -19,7 +19,7 @@ class TestConfiguration(unittest.TestCase): """Animal unit test stubs""" def setUp(self): - pass + self.config = petstore_api.Configuration() def tearDown(self): # reset Configuration @@ -58,5 +58,23 @@ def testAccessTokenWhenConstructingConfiguration(self): c1 = petstore_api.Configuration(access_token="12345") self.assertEqual(c1.access_token, "12345") + def test_get_host_settings(self): + host_settings = self.config.get_host_settings() + + self.assertEqual('http://{server}.swagger.io:{port}/v2', host_settings[0]['url']) + self.assertEqual('petstore', host_settings[0]['variables']['server']['default_value']) + + self.assertEqual('https://localhost:8080/{version}', host_settings[1]['url']) + self.assertEqual('v2', host_settings[1]['variables']['version']['default_value']) + + def test_get_host_from_settings(self): + """ Test get_host_from_settings + + Test get URL from host settings + """ + self.assertEqual("http://petstore.swagger.io:80/v2", self.config.get_host_from_settings(0)) + self.assertEqual("http://petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'port': '8080'})) + self.assertEqual("http://dev-petstore.swagger.io:8080/v2", self.config.get_host_from_settings(0, {'server': 'dev-petstore', 'port': '8080'})) + if __name__ == '__main__': unittest.main() diff --git a/samples/openapi3/client/petstore/python/tests/test_deserialization.py b/samples/openapi3/client/petstore/python/tests/test_deserialization.py index 7d0c737191e3..08e09edea265 100644 --- a/samples/openapi3/client/petstore/python/tests/test_deserialization.py +++ b/samples/openapi3/client/petstore/python/tests/test_deserialization.py @@ -19,8 +19,6 @@ import petstore_api -MockResponse = namedtuple('MockResponse', 'data') - class DeserializationTests(unittest.TestCase): @@ -39,7 +37,7 @@ def test_enum_test(self): "outerEnum": "placed" } } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, 'Dict[str, EnumTest]') self.assertTrue(isinstance(deserialized, dict)) @@ -73,7 +71,7 @@ def test_deserialize_dict_str_pet(self): "status": "available" } } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, 'Dict[str, Pet]') self.assertTrue(isinstance(deserialized, dict)) @@ -90,7 +88,7 @@ def test_deserialize_dict_str_dog(self): "bread": "Jack Russel Terrier" } } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, 'Dict[str, Animal]') self.assertTrue(isinstance(deserialized, dict)) @@ -102,7 +100,7 @@ def test_deserialize_dict_str_int(self): data = { 'integer': 1 } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, 'Dict[str, int]') self.assertTrue(isinstance(deserialized, dict)) @@ -111,7 +109,7 @@ def test_deserialize_dict_str_int(self): def test_deserialize_str(self): """ deserialize str """ data = "test str" - response = MockResponse(data=json.dumps(data)) + response = data=json.dumps(data) deserialized = self.deserialize(response, "str") self.assertTrue(isinstance(deserialized, str)) @@ -119,7 +117,7 @@ def test_deserialize_str(self): def test_deserialize_date(self): """ deserialize date """ data = "1997-07-16" - response = MockResponse(data=json.dumps(data)) + response = data=json.dumps(data) deserialized = self.deserialize(response, "date") self.assertTrue(isinstance(deserialized, datetime.date)) @@ -127,7 +125,7 @@ def test_deserialize_date(self): def test_deserialize_datetime(self): """ deserialize datetime """ data = "1997-07-16T19:20:30.45+01:00" - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "datetime") self.assertTrue(isinstance(deserialized, datetime.datetime)) @@ -152,7 +150,7 @@ def test_deserialize_pet(self): ], "status": "available" } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "Pet") self.assertTrue(isinstance(deserialized, petstore_api.Pet)) @@ -202,7 +200,7 @@ def test_deserialize_list_of_pet(self): ], "status": "available" }] - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "List[Pet]") self.assertTrue(isinstance(deserialized, list)) @@ -219,7 +217,7 @@ def test_deserialize_nested_dict(self): "bar": 1 } } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "Dict[str, Dict[str, int]]") self.assertTrue(isinstance(deserialized, dict)) @@ -229,7 +227,7 @@ def test_deserialize_nested_dict(self): def test_deserialize_nested_list(self): """ deserialize list[list[str]] """ data = [["foo"]] - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "List[List[str]]") self.assertTrue(isinstance(deserialized, list)) @@ -238,7 +236,7 @@ def test_deserialize_nested_list(self): def test_deserialize_none(self): """ deserialize None """ - response = MockResponse(data=json.dumps(None)) + response = json.dumps(None) deserialized = self.deserialize(response, "datetime") self.assertIsNone(deserialized) @@ -250,7 +248,7 @@ def test_deserialize_pig(self): "color": "white" } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "Pig") self.assertTrue(isinstance(deserialized.actual_instance, petstore_api.BasquePig)) @@ -264,7 +262,7 @@ def test_deserialize_animal(self): "className": "Cat2222" # incorrect class name } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) with pytest.raises(ValueError) as ex: deserialized = self.deserialize(response, "Animal") @@ -277,7 +275,7 @@ def test_deserialize_animal(self): "className": "Cat" # correct class name } - response = MockResponse(data=json.dumps(data)) + response = json.dumps(data) deserialized = self.deserialize(response, "Animal") self.assertTrue(isinstance(deserialized, petstore_api.Cat)) diff --git a/samples/openapi3/client/petstore/python/tests/test_http_signature.py b/samples/openapi3/client/petstore/python/tests/test_http_signature.py index db7460a7a9ab..1d5f05abb462 100644 --- a/samples/openapi3/client/petstore/python/tests/test_http_signature.py +++ b/samples/openapi3/client/petstore/python/tests/test_http_signature.py @@ -17,11 +17,14 @@ import os import re import shutil +from typing import Union import unittest from urllib.parse import urlencode, urlparse from Crypto.Hash import SHA256, SHA512 from Crypto.PublicKey import ECC, RSA +from Crypto.Hash.SHA512 import SHA512Hash +from Crypto.Hash.SHA256 import SHA256Hash from Crypto.Signature import pkcs1_15, pss, DSS import petstore_api @@ -73,7 +76,7 @@ def __init__(self, *arg, **kwargs): def __eq__(self, other): return self._read == other._read and self._connect == other._connect and self.total == other.total -class MockPoolManager(object): +class MockPoolManager(urllib3.PoolManager): def __init__(self, tc): self._tc = tc self._reqs = [] @@ -83,9 +86,9 @@ def expect_request(self, *args, **kwargs): def set_signing_config(self, signing_cfg): self.signing_cfg = signing_cfg - self._tc.assertIsNotNone(self.signing_cfg) + assert self.signing_cfg is not None self.pubkey = self.signing_cfg.get_public_key() - self._tc.assertIsNotNone(self.pubkey) + assert self.pubkey is not None def request(self, *actual_request_target, **actual_request_headers_and_body): self._tc.assertTrue(len(self._reqs) > 0) @@ -124,13 +127,13 @@ def _validate_authorization_header(self, request_target, actual_headers, authori # Extract (created) r1 = re.compile(r'created=([0-9]+)') m1 = r1.search(authorization_header) - self._tc.assertIsNotNone(m1) + assert m1 is not None created = m1.group(1) # Extract list of signed headers r1 = re.compile(r'headers="([^"]+)"') m1 = r1.search(authorization_header) - self._tc.assertIsNotNone(m1) + assert m1 is not None headers = m1.group(1).split(' ') signed_headers_list = [] for h in headers: @@ -142,25 +145,26 @@ def _validate_authorization_header(self, request_target, actual_headers, authori signed_headers_list.append((h, "{0} {1}".format(request_target[0].lower(), target_path))) else: value = next((v for k, v in actual_headers.items() if k.lower() == h), None) - self._tc.assertIsNotNone(value) + assert value is not None signed_headers_list.append((h, value)) header_items = [ "{0}: {1}".format(key.lower(), value) for key, value in signed_headers_list] string_to_sign = "\n".join(header_items) - digest = None + digest: Union[SHA512Hash, SHA256Hash] if self.signing_cfg.hash_algorithm == signing.HASH_SHA512: digest = SHA512.new() elif self.signing_cfg.hash_algorithm == signing.HASH_SHA256: digest = SHA256.new() else: self._tc.fail("Unsupported hash algorithm: {0}".format(self.signing_cfg.hash_algorithm)) + digest.update(string_to_sign.encode()) b64_body_digest = base64.b64encode(digest.digest()).decode() # Extract the signature r2 = re.compile(r'signature="([^"]+)"') m2 = r2.search(authorization_header) - self._tc.assertIsNotNone(m2) + assert m2 is not None b64_signature = m2.group(1) signature = base64.b64decode(b64_signature) # Build the message @@ -190,6 +194,12 @@ def _validate_authorization_header(self, request_target, actual_headers, authori self._tc.fail("Unsupported signing algorithm: {0}".format(signing_alg)) class PetApiTests(unittest.TestCase): + rsa_key_path: str + rsa4096_key_path: str + ec_p521_key_path: str + pet: petstore_api.Pet + test_file_dir: str + private_key_passphrase: str @classmethod def setUpClass(cls): @@ -208,19 +218,19 @@ def tearDownClass(cls): @classmethod def setUpModels(cls): - cls.category = petstore_api.Category(name="dog") - cls.category.id = id_gen() - cls.tag = petstore_api.Tag() - cls.tag.id = id_gen() - cls.tag.name = "python-pet-tag" + category = petstore_api.Category(name="dog") + category.id = id_gen() + tag = petstore_api.Tag() + tag.id = id_gen() + tag.name = "python-pet-tag" cls.pet = petstore_api.Pet( name="hello kity", photoUrls=["http://foo.bar.com/1", "http://foo.bar.com/2"] ) cls.pet.id = id_gen() cls.pet.status = "sold" - cls.pet.category = cls.category - cls.pet.tags = [cls.tag] + cls.pet.category = category + cls.pet.tags = [tag] @classmethod def setUpFiles(cls): @@ -239,6 +249,8 @@ def setUpFiles(cls): with open(cls.rsa_key_path, 'w') as f: f.write(RSA_TEST_PRIVATE_KEY) + key: Union[RSA.RsaKey, ECC.EccKey] + if not os.path.exists(cls.rsa4096_key_path): key = RSA.generate(4096) private_key = key.export_key( @@ -250,13 +262,17 @@ def setUpFiles(cls): if not os.path.exists(cls.ec_p521_key_path): key = ECC.generate(curve='P-521') - private_key = key.export_key( + pkey = key.export_key( format='PEM', passphrase=cls.private_key_passphrase, use_pkcs8=True, protection='PBKDF2WithHMAC-SHA1AndAES128-CBC' ) - with open(cls.ec_p521_key_path, "wt") as f: + if isinstance(pkey, str): + private_key = pkey.encode("ascii") + else: + private_key = pkey + with open(cls.ec_p521_key_path, "wb") as f: f.write(private_key) def test_valid_http_signature(self): @@ -459,7 +475,7 @@ def test_invalid_configuration(self): signing_cfg = signing.HttpSigningConfiguration( key_id="my-key-id", private_key_path=self.ec_p521_key_path, - signing_scheme=None + signing_scheme=None # type: ignore ) self.assertTrue(re.match('Unsupported security scheme', str(cm.exception)), 'Exception message: {0}'.format(str(cm.exception))) diff --git a/samples/openapi3/client/petstore/python/tests/test_model.py b/samples/openapi3/client/petstore/python/tests/test_model.py index c41bfe8e7538..e67ae8fb6538 100644 --- a/samples/openapi3/client/petstore/python/tests/test_model.py +++ b/samples/openapi3/client/petstore/python/tests/test_model.py @@ -2,14 +2,17 @@ # flake8: noqa +from datetime import date import json import os import time import unittest from pydantic import ValidationError +import pytest import petstore_api +from petstore_api import InnerDictWithProperty class ModelTests(unittest.TestCase): @@ -132,28 +135,36 @@ def test_oneOf_array_of_integers(self): p = petstore_api.Color.from_json(None) self.assertEqual(p.actual_instance, None) - def test_oneof_enum_string(self): - enum_string1 = petstore_api.EnumString1('a') + def test_oneof_enum_string_from_json(self): # test from_json oneof_enum = petstore_api.OneOfEnumString.from_json('"a"') + + def test_oneof_nested_from_enum_string(self): # test from_dict oneof_enum = petstore_api.OneOfEnumString.from_dict("a") + assert oneof_enum is not None nested = petstore_api.WithNestedOneOf(size = 1, nested_oneof_enum_string = oneof_enum) # test to_json self.assertEqual(nested.to_json(), '{"size": 1, "nested_oneof_enum_string": "a"}') - # test from_json + + def test_oneof_nested_from_json(self): nested = petstore_api.WithNestedOneOf.from_json('{"size": 1, "nested_oneof_enum_string": "c"}') + assert nested is not None self.assertEqual(nested.to_json(), '{"size": 1, "nested_oneof_enum_string": "c"}') - # test from_dict + + def test_oneof_nested_from_dict(self): nested = petstore_api.WithNestedOneOf.from_dict({"size": 1, "nested_oneof_enum_string": "c"}) + assert nested is not None # test to_dict self.assertEqual(nested.to_dict(), {"size": 1, "nested_oneof_enum_string": "c"}) - # invalid enum value + + def test_oneof_nested_from_json_invalid(self): try: nested2 = petstore_api.WithNestedOneOf.from_json('{"size": 1, "nested_oneof_enum_string": "e"}') except ValueError as e: self.assertTrue("'e' is not a valid EnumString1, 'e' is not a valid EnumString" in str(e)) + def test_oneof_enum_string(self): # test the constructor enum_string1 = petstore_api.EnumString1('a') constructor1 = petstore_api.OneOfEnumString(actual_instance=enum_string1) @@ -274,6 +285,7 @@ def test_oneOf(self): nested_json = nested.to_json() nested2 = petstore_api.WithNestedOneOf.from_json(nested_json) + assert nested2 is not None self.assertEqual(nested2.to_json(), nested_json) def test_anyOf(self): @@ -326,30 +338,30 @@ def test_inheritance(self): self.assertEqual(dog.to_dict(), {'breed': 'bulldog', 'className': 'dog', 'color': 'white'}) dog2 = petstore_api.Dog.from_json(dog.to_json()) + assert dog2 is not None self.assertEqual(dog2.breed, 'bulldog') self.assertEqual(dog2.class_name, "dog") self.assertEqual(dog2.color, 'white') def test_list(self): # should throw exception as var_123_list should be string - kw = {"123-list": 123} try: - l3 = petstore_api.ListClass(**kw) + # Don't check the typing, because we are actually testing a typing error. + l3 = petstore_api.ListClass(**{"123-list": 123}) # type: ignore self.assertTrue(False) # this line shouldn't execute - breakpoint() except ValueError as e: # var_123_list # Input should be a valid string [type=string_type, input_value=123, input_type=int] # For further information visit https://errors.pydantic.dev/2.3/v/string_type self.assertTrue("Input should be a valid string" in str(e)) - kw = {"123-list": "bulldog"} - l = petstore_api.ListClass(**kw) + l = petstore_api.ListClass(**{"123-list": "bulldog"}) # type: ignore self.assertEqual(l.to_json(), '{"123-list": "bulldog"}') self.assertEqual(l.to_dict(), {'123-list': 'bulldog'}) + l2 = petstore_api.ListClass.from_json(l.to_json()) + assert l2 is not None self.assertEqual(l2.var_123_list, 'bulldog') - self.assertTrue(isinstance(l2, petstore_api.ListClass)) def test_enum_ref_property(self): @@ -361,6 +373,7 @@ def test_enum_ref_property(self): self.assertEqual(d2.to_json(), '{"str_value": "delivered", "value": 1}') # test from_json (round trip) d3 = petstore_api.OuterObjectWithEnumProperty.from_json(d2.to_json()) + assert d3 is not None self.assertEqual(d3.str_value, petstore_api.OuterEnum.DELIVERED) self.assertEqual(d3.value, petstore_api.OuterEnumInteger.NUMBER_1) self.assertEqual(d3.to_json(), '{"str_value": "delivered", "value": 1}') @@ -374,7 +387,7 @@ def test_enum_ref_property(self): def test_valdiator(self): # test regular expression - a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876") + a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876") try: a.pattern_with_digits_and_delimiter = "123" self.assertTrue(False) # this line shouldn't execute @@ -382,7 +395,7 @@ def test_valdiator(self): self.assertTrue(r"must validate the regular expression /^image_\d{1,3}$/i" in str(e)) # test None with optional string (with regualr expression) - a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date="2013-09-17", password="testing09876") + a = petstore_api.FormatTest(number=123.45, byte=bytes("string", 'utf-8'), date=date(2013, 9, 17), password="testing09876") a.string = None # shouldn't throw an exception a.pattern_with_digits_and_delimiter = "IMAGE_123" @@ -390,6 +403,9 @@ def test_valdiator(self): a.pattern_with_digits_and_delimiter = "image_123" self.assertEqual(a.pattern_with_digits_and_delimiter, "image_123") + # test sanitize for serializaation with SecretStr (format: password) + self.assertEquals(petstore_api.ApiClient().sanitize_for_serialization(a), {'byte': b'string', 'date': '2013-09-17', 'number': 123.45, 'password': 'testing09876', 'pattern_with_digits_and_delimiter': 'image_123'}) + def test_inline_enum_validator(self): self.pet = petstore_api.Pet(name="test name", photoUrls=["string"]) self.pet.id = 1 @@ -454,7 +470,7 @@ def test_additional_properties(self): self.assertNotEqual(id(pet_ap.additional_properties), id(pet_ap2.additional_properties)) pet_ap.additional_properties["something-new"] = "haha" - self.assertEqual(pet_ap.to_json(), '{"id":1,"name":"test name","photoUrls":["string"],"status":"available","something-new":"haha"}') + self.assertEqual(pet_ap.to_json(), '{"id": 1, "name": "test name", "photoUrls": ["string"], "status": "available", "something-new": "haha"}') self.assertEqual(type(pet_ap2.additional_properties), dict) self.assertNotEqual(id(pet_ap.additional_properties), id(pet_ap2.additional_properties)) self.assertEqual(pet_ap.additional_properties["something-new"], "haha") @@ -470,11 +486,12 @@ def test_additional_properties(self): pet_ap_dict["array"] = ["a", "b"] pet_ap_dict["dict"] = {"key999": "value999"} - pet_ap2 = petstore_api.Pet.from_dict(pet_ap_dict) + pet_ap3 = petstore_api.Pet.from_dict(pet_ap_dict) + assert pet_ap3 is not None - self.assertEqual(pet_ap2.additional_properties["array"], ["a", "b"]) - self.assertEqual(pet_ap2.additional_properties["something-new"], 123) - self.assertEqual(pet_ap2.additional_properties["dict"], {"key999": "value999"}) + self.assertEqual(pet_ap3.additional_properties["array"], ["a", "b"]) + self.assertEqual(pet_ap3.additional_properties["something-new"], 123) + self.assertEqual(pet_ap3.additional_properties["dict"], {"key999": "value999"}) def test_nullable(self): h = petstore_api.HealthCheckResult(NullableMessage="Not none") @@ -502,16 +519,31 @@ def test_object_with_optional_dict(self): # for https://github.com/OpenAPITools/openapi-generator/issues/14913 # shouldn't throw exception by the optional dict property a = petstore_api.ParentWithOptionalDict.from_dict({}) - self.assertFalse(a is None) b = petstore_api.ParentWithOptionalDict.from_dict({"optionalDict": {"key": {"aProperty": {"a": "b"}}}}) - self.assertFalse(b is None) + assert b is not None + assert b.optional_dict is not None + assert b.optional_dict["key"].a_property is not None self.assertEqual(b.optional_dict["key"].a_property["a"], "b") + def test_freeform_object(self): + # Allows dict[str, Any] and is nullable + a = InnerDictWithProperty.from_dict({"aProperty": {"a": 12}}) + a = InnerDictWithProperty.from_dict({"aProperty": None}) + + # Allows no other values + with pytest.raises(ValidationError): + a = InnerDictWithProperty.from_dict({"aProperty": {123: 45}}) + with pytest.raises(ValidationError): + a = InnerDictWithProperty.from_dict({"aProperty": "abc"}) + with pytest.raises(ValidationError): + a = InnerDictWithProperty.from_dict({"aProperty": 12}) + def test_object_with_dict_of_dict_of_object(self): # for https://github.com/OpenAPITools/openapi-generator/issues/15135 d = {"optionalDict": {"a": {"b": {"aProperty": "value"}}}} a = petstore_api.Parent.from_dict(d) + assert a is not None self.assertEqual(a.to_dict(), d) def test_eum_class(self): @@ -543,6 +575,7 @@ def test_map_of_array_of_model(self): self.assertEqual(a.to_dict(), {'shopIdToOrgOnlineLipMap': {'somekey': [{'id': 123, 'name': 'tag name'}]}}) self.assertEqual(a.to_json(), '{"shopIdToOrgOnlineLipMap": {"somekey": [{"id": 123, "name": "tag name"}]}}') a2 = petstore_api.MapOfArrayOfModel.from_dict(a.to_dict()) + assert a2 is not None self.assertEqual(a.to_dict(), a2.to_dict()) def test_array_of_array_of_model(self): @@ -552,6 +585,7 @@ def test_array_of_array_of_model(self): self.assertEqual(a.to_dict(), {'another_property': [[ {'id': 123, 'name': 'tag name'} ]]}) self.assertEqual(a.to_json(), '{"another_property": [[{"id": 123, "name": "tag name"}]]}') a2 = petstore_api.ArrayOfArrayOfModel.from_dict(a.to_dict()) + assert a2 is not None self.assertEqual(a.to_dict(), a2.to_dict()) def test_object_with_additional_properties(self): @@ -560,18 +594,21 @@ def test_object_with_additional_properties(self): # should not throw the following errors: # pydantic.errors.ConfigError: field "additional_properties" not yet prepared so type is still a ForwardRef, you might need to call ObjectToTestAdditionalProperties.update_forward_refs(). - @unittest.skip("TODO: pydantic v2: fix circular dependencies between CircularReferenceModel, FirstRef, SecondRef") def test_first_ref(self): # shouldn't throw "still a ForwardRef" error a = petstore_api.FirstRef.from_dict({}) + assert a is not None self.assertEqual(a.to_json(), "{}") def test_allof(self): # for issue 16104 model = petstore_api.Tiger.from_json('{"skill": "none", "type": "tiger", "info": {"name": "creature info"}}') # shouldn't throw NameError + assert model is not None self.assertEqual(model.to_json(), '{"skill": "none", "type": "tiger", "info": {"name": "creature info"}}') + +class TestdditionalPropertiesAnyType(unittest.TestCase): def test_additional_properties(self): a1 = petstore_api.AdditionalPropertiesAnyType() a1.additional_properties = { "abc": 123 } @@ -590,27 +627,29 @@ def test_additional_properties(self): class TestUnnamedDictWithAdditionalStringListProperties: def test_empty_dict(self): - a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={}) + a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={}) + assert a is not None assert a.to_dict() == {"dictProperty": {}} def test_empty_list(self): - a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={"b": []}) + a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={"b": []}) + assert a is not None assert a.to_dict() == {"dictProperty": {"b": []}} def test_single_string_item(self): - a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dict_property={"b": ["c"]}) + a = petstore_api.UnnamedDictWithAdditionalStringListProperties(dictProperty={"b": ["c"]}) assert a.to_dict() == {"dictProperty": {"b": ["c"]}} class TestUnnamedDictWithAdditionalModelListProperties: def test_empty_dict(self): - a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property={}) + a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty={}) assert a.to_dict() == {"dictProperty": {}} def test_empty_list(self): - a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property={"b": []}) + a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty={"b": []}) assert a.to_dict() == {"dictProperty": {"b": []}} def test_single_string_item(self): value = {"b": [petstore_api.CreatureInfo(name="creature_name")]} - a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dict_property=value) + a = petstore_api.UnnamedDictWithAdditionalModelListProperties(dictProperty=value) assert a.to_dict() == {"dictProperty": {"b": [{"name": "creature_name"}]}} diff --git a/samples/openapi3/client/petstore/python/tests/test_pet_api.py b/samples/openapi3/client/petstore/python/tests/test_pet_api.py index 0adf72c897bc..15e748ddea2e 100644 --- a/samples/openapi3/client/petstore/python/tests/test_pet_api.py +++ b/samples/openapi3/client/petstore/python/tests/test_pet_api.py @@ -35,7 +35,7 @@ def __eq__(self, other): return self._read == other._read and self._connect == other._connect and self.total == other.total -class MockPoolManager(object): +class MockPoolManager(urllib3.PoolManager): def __init__(self, tc): self._tc = tc self._reqs = [] @@ -96,16 +96,16 @@ def test_timeout(self): headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ACCESS_TOKEN', 'User-Agent': 'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=TimeoutWithEqual(total=5)) + preload_content=False, timeout=TimeoutWithEqual(total=5.0)) mock_pool.expect_request('POST', HOST + '/pet', body=json.dumps(self.api_client.sanitize_for_serialization(self.pet)), headers={'Content-Type': 'application/json', 'Authorization': 'Bearer ACCESS_TOKEN', 'User-Agent': 'OpenAPI-Generator/1.0.0/python'}, - preload_content=True, timeout=TimeoutWithEqual(connect=1, read=2)) + preload_content=False, timeout=TimeoutWithEqual(connect=1.0, read=2.0)) - self.pet_api.add_pet(self.pet, _request_timeout=5) - self.pet_api.add_pet(self.pet, _request_timeout=(1, 2)) + self.pet_api.add_pet(self.pet, _request_timeout=5.0) + self.pet_api.add_pet(self.pet, _request_timeout=(1.0, 2.0)) def test_separate_default_config_instances(self): # ensure the default api client is used @@ -115,94 +115,64 @@ def test_separate_default_config_instances(self): # ensure the default configuration is used self.assertEqual(id(pet_api.api_client.configuration), id(pet_api2.api_client.configuration)) - def test_async_request(self): - thread = self.pet_api.add_pet(self.pet, async_req=True) - response = thread.get() - self.assertIsNone(response) - - thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) - result = thread.get() - self.assertIsInstance(result, petstore_api.Pet) - - def test_async_with_result(self): - self.pet_api.add_pet(self.pet, async_req=False) - - thread = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) - thread2 = self.pet_api.get_pet_by_id(self.pet.id, async_req=True) - - response = thread.get() - response2 = thread2.get() - - self.assertEqual(response.id, self.pet.id) - self.assertIsNotNone(response2.id, self.pet.id) - - def test_async_with_http_info(self): - self.pet_api.add_pet(self.pet) - - thread = self.pet_api.get_pet_by_id_with_http_info(self.pet.id, async_req=True) - api_response_object = thread.get() - - self.assertIsInstance(api_response_object.data, petstore_api.Pet) - self.assertEqual(api_response_object.status_code, 200) - self.assertEqual(api_response_object.headers['Content-Type'], "application/json") - self.assertIsInstance(api_response_object.raw_data, str) # it's a str, not Pet - self.assertTrue(api_response_object.raw_data.startswith('{"id":')) - - def test_async_exception(self): - self.pet_api.add_pet(self.pet) - - thread = self.pet_api.get_pet_by_id(9999999999999, async_req=True) - - exception = None - try: - thread.get() - except ApiException as e: - exception = e - - self.assertIsInstance(exception, ApiException) - self.assertEqual(exception.status, 404) - def test_add_pet_and_get_pet_by_id(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) - self.assertIsNotNone(fetched) + assert fetched is not None self.assertEqual(self.pet.id, fetched.id) - self.assertIsNotNone(fetched.category) + assert fetched.category is not None + assert self.pet.category is not None self.assertEqual(self.pet.category.name, fetched.category.name) - def test_add_pet_and_get_pet_by_id_with_preload_content_flag(self): - try: - self.pet_api.add_pet(self.pet, _preload_content=False) - except ValueError as e: - self.assertEqual("Error! Please call the add_pet_with_http_info method with `_preload_content` instead and obtain raw data from ApiResponse.raw_data", str(e)) - + def test_add_pet_and_get_pet_by_id_without_preload_content_flag(self): self.pet_api.add_pet(self.pet) - fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id, - _preload_content=False) - self.assertIsNone(fetched.data) - self.assertIsInstance(fetched.raw_data, bytes) # it's a str, not Pet - self.assertTrue(fetched.raw_data.decode("utf-8").startswith('{"id":')) + assert self.pet.id is not None + + fetched = self.pet_api.get_pet_by_id_without_preload_content(pet_id=self.pet.id) + + self.assertIsInstance(fetched, urllib3.HTTPResponse) + self.assertFalse(fetched.closed) + read = fetched.read() + self.assertTrue(fetched.closed) + self.assertIsInstance(read, bytes) + self.assertEqual(fetched.data, b'') + self.assertEqual(fetched.read(), b'') + self.assertEqual(fetched.read(10), b'') + self.assertTrue(read.decode("utf-8").startswith('{"id":')) def test_add_pet_and_get_pet_by_id_with_http_info(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None # fetched is an ApiResponse object fetched = self.pet_api.get_pet_by_id_with_http_info(pet_id=self.pet.id) - self.assertIsNotNone(fetched.data) + assert fetched.data is not None self.assertEqual(self.pet.id, fetched.data.id) - self.assertIsNotNone(fetched.data.category) + assert fetched.data.category is not None + assert self.pet.category is not None self.assertEqual(self.pet.category.name, fetched.data.category.name) + def test_get_pet_by_id_serialize(self): + self.pet_api.add_pet(self.pet) + assert self.pet.id is not None + + fetched = self.pet_api._get_pet_by_id_serialize(self.pet.id, None, None, None, None) + assert fetched is not None + self.assertIsInstance(fetched, tuple) + def test_update_pet(self): self.pet.name = "hello kity with updated" self.pet_api.update_pet(self.pet) + assert self.pet.id is not None fetched = self.pet_api.get_pet_by_id(pet_id=self.pet.id) - self.assertIsNotNone(fetched) + assert fetched is not None self.assertEqual(self.pet.id, fetched.id) self.assertEqual(self.pet.name, fetched.name) - self.assertIsNotNone(fetched.category) + assert fetched.category is not None + assert self.pet.category is not None self.assertEqual(fetched.category.name, self.pet.category.name) def test_find_pets_by_status(self): @@ -218,6 +188,8 @@ def test_find_pets_by_status(self): def test_find_pets_by_tags(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None + assert self.tag.name is not None self.assertIn( self.pet.id, @@ -226,6 +198,7 @@ def test_find_pets_by_tags(self): def test_update_pet_with_form(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None name = "hello kity with form updated abc" status = "pending" @@ -237,6 +210,7 @@ def test_update_pet_with_form(self): self.assertEqual(status, fetched.status) def test_upload_file(self): + assert self.pet.id is not None # upload file with form parameter try: additional_metadata = "special data 123" @@ -256,6 +230,7 @@ def test_upload_file(self): def test_delete_pet(self): self.pet_api.add_pet(self.pet) + assert self.pet.id is not None self.pet_api.delete_pet(pet_id=self.pet.id, api_key="special-key") try: diff --git a/samples/openapi3/client/petstore/python/tests/test_pet_model.py b/samples/openapi3/client/petstore/python/tests/test_pet_model.py index f652431f5cda..4412255969e8 100644 --- a/samples/openapi3/client/petstore/python/tests/test_pet_model.py +++ b/samples/openapi3/client/petstore/python/tests/test_pet_model.py @@ -73,11 +73,14 @@ def test_from_to_methods(self): " \"status\": \"available\",\n" " \"tags\": [{\"id\": 1, \"name\": \"None\"}]}") pet = petstore_api.Pet.from_json(json_str) + assert pet is not None self.assertEqual(pet.id, 1) self.assertEqual(pet.status, "available") self.assertEqual(pet.photo_urls, ["string"]) + assert pet.tags is not None self.assertEqual(pet.tags[0].id, 1) self.assertEqual(pet.tags[0].name, "None") + assert pet.category is not None self.assertEqual(pet.category.id, 1) # test to_json self.assertEqual(pet.to_json(), @@ -91,16 +94,18 @@ def test_from_to_methods(self): # test from_dict pet2 = petstore_api.Pet.from_dict(pet.to_dict()) + assert pet2 is not None self.assertEqual(pet2.id, 1) self.assertEqual(pet2.status, "available") self.assertEqual(pet2.photo_urls, ["string"]) + assert pet2.tags is not None self.assertEqual(pet2.tags[0].id, 1) self.assertEqual(pet2.tags[0].name, "None") + assert pet2.category is not None self.assertEqual(pet2.category.id, 1) def test_unpack_operator(self): - d = {"name": "required name", "id": 123, "photoUrls": ["https://a.com", "https://b.com"]} - pet = petstore_api.Pet(**d) + pet = petstore_api.Pet(name="required name", id=123, photoUrls=["https://a.com", "https://b.com"]) self.assertEqual(pet.to_json(), '{"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]}') self.assertEqual(pet.to_dict(), {"id": 123, "name": "required name", "photoUrls": ["https://a.com", "https://b.com"]}) diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/PetApi.java index 9a547c6c1123..25a5a7682158 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/StoreApi.java index 27cb2c872e1a..e700d399ff1e 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/UserApi.java index 45f234ef52d8..fdd336454dae 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -58,7 +58,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ); @@ -76,7 +76,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Category.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Category.java index b24ec01be79c..58d36477cf71 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Category.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Category.java @@ -20,12 +20,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Category { - private Long id; + private Optional id = Optional.empty(); - private String name; + private Optional<@Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") String> name = Optional.empty(); public Category id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -35,16 +35,16 @@ public Category id(Long id) { */ @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Category name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -52,13 +52,13 @@ public Category name(String name) { * Get name * @return name */ - @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") + @JsonProperty("name") - public String getName() { + public Optional<@Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") String> getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/ModelApiResponse.java index 0bf61b71b160..922c22a484ff 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -22,14 +22,14 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ModelApiResponse { - private Integer code; + private Optional code = Optional.empty(); - private String type; + private Optional type = Optional.empty(); - private String message; + private Optional message = Optional.empty(); public ModelApiResponse code(Integer code) { - this.code = code; + this.code = Optional.of(code); return this; } @@ -39,16 +39,16 @@ public ModelApiResponse code(Integer code) { */ @JsonProperty("code") - public Integer getCode() { + public Optional getCode() { return code; } - public void setCode(Integer code) { + public void setCode(Optional code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; + this.type = Optional.of(type); return this; } @@ -58,16 +58,16 @@ public ModelApiResponse type(String type) { */ @JsonProperty("type") - public String getType() { + public Optional getType() { return type; } - public void setType(String type) { + public void setType(Optional type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; + this.message = Optional.of(message); return this; } @@ -77,11 +77,11 @@ public ModelApiResponse message(String message) { */ @JsonProperty("message") - public String getMessage() { + public Optional getMessage() { return message; } - public void setMessage(String message) { + public void setMessage(Optional message) { this.message = message; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Order.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Order.java index 16f368d9fe47..53096900e253 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Order.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Order.java @@ -23,14 +23,14 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Order { - private Long id; + private Optional id = Optional.empty(); - private Long petId; + private Optional petId = Optional.empty(); - private Integer quantity; + private Optional quantity = Optional.empty(); @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private OffsetDateTime shipDate; + private Optional shipDate = Optional.empty(); /** * Order Status @@ -69,12 +69,12 @@ public static StatusEnum fromValue(String value) { } } - private StatusEnum status; + private Optional status = Optional.empty(); - private Boolean complete = false; + private Optional complete = Optional.of(false); public Order id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -84,16 +84,16 @@ public Order id(Long id) { */ @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; + this.petId = Optional.of(petId); return this; } @@ -103,16 +103,16 @@ public Order petId(Long petId) { */ @JsonProperty("petId") - public Long getPetId() { + public Optional getPetId() { return petId; } - public void setPetId(Long petId) { + public void setPetId(Optional petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; + this.quantity = Optional.of(quantity); return this; } @@ -122,16 +122,16 @@ public Order quantity(Integer quantity) { */ @JsonProperty("quantity") - public Integer getQuantity() { + public Optional getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { + public void setQuantity(Optional quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; + this.shipDate = Optional.of(shipDate); return this; } @@ -141,16 +141,16 @@ public Order shipDate(OffsetDateTime shipDate) { */ @Valid @JsonProperty("shipDate") - public OffsetDateTime getShipDate() { + public Optional getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { + public void setShipDate(Optional shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; + this.status = Optional.of(status); return this; } @@ -160,16 +160,16 @@ public Order status(StatusEnum status) { */ @JsonProperty("status") - public StatusEnum getStatus() { + public Optional getStatus() { return status; } - public void setStatus(StatusEnum status) { + public void setStatus(Optional status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; + this.complete = Optional.of(complete); return this; } @@ -179,11 +179,11 @@ public Order complete(Boolean complete) { */ @JsonProperty("complete") - public Boolean getComplete() { + public Optional getComplete() { return complete; } - public void setComplete(Boolean complete) { + public void setComplete(Optional complete) { this.complete = complete; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Pet.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Pet.java index b80b957cba16..8d7bb11fc161 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Pet.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Pet.java @@ -26,9 +26,9 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Pet { - private Long id; + private Optional id = Optional.empty(); - private Category category; + private Optional category = Optional.empty(); private String name; @@ -76,7 +76,7 @@ public static StatusEnum fromValue(String value) { } @Deprecated - private StatusEnum status; + private Optional status = Optional.empty(); public Pet() { super(); @@ -91,7 +91,7 @@ public Pet(String name, List photoUrls) { } public Pet id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -101,16 +101,16 @@ public Pet id(Long id) { */ @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Pet category(Category category) { - this.category = category; + this.category = Optional.of(category); return this; } @@ -120,11 +120,11 @@ public Pet category(Category category) { */ @Valid @JsonProperty("category") - public Category getCategory() { + public Optional getCategory() { return category; } - public void setCategory(Category category) { + public void setCategory(Optional category) { this.category = category; } @@ -202,7 +202,7 @@ public void setTags(List<@Valid Tag> tags) { } public Pet status(StatusEnum status) { - this.status = status; + this.status = Optional.of(status); return this; } @@ -214,7 +214,7 @@ public Pet status(StatusEnum status) { @JsonProperty("status") @Deprecated - public StatusEnum getStatus() { + public Optional getStatus() { return status; } @@ -222,7 +222,7 @@ public StatusEnum getStatus() { * @deprecated */ @Deprecated - public void setStatus(StatusEnum status) { + public void setStatus(Optional status) { this.status = status; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Tag.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Tag.java index 1fe5ae4afdc8..f5ea2f8743a6 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Tag.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/Tag.java @@ -20,12 +20,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Tag { - private Long id; + private Optional id = Optional.empty(); - private String name; + private Optional name = Optional.empty(); public Tag id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -35,16 +35,16 @@ public Tag id(Long id) { */ @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Tag name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -54,11 +54,11 @@ public Tag name(String name) { */ @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/User.java b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/User.java index 8145125bfede..6deefb0b8f42 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/User.java +++ b/samples/openapi3/client/petstore/spring-cloud-3-with-optional/src/main/java/org/openapitools/model/User.java @@ -20,24 +20,24 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class User { - private Long id; + private Optional id = Optional.empty(); - private String username; + private Optional username = Optional.empty(); - private String firstName; + private Optional firstName = Optional.empty(); - private String lastName; + private Optional lastName = Optional.empty(); - private String email; + private Optional email = Optional.empty(); - private String password; + private Optional password = Optional.empty(); - private String phone; + private Optional phone = Optional.empty(); - private Integer userStatus; + private Optional userStatus = Optional.empty(); public User id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -47,16 +47,16 @@ public User id(Long id) { */ @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public User username(String username) { - this.username = username; + this.username = Optional.of(username); return this; } @@ -66,16 +66,16 @@ public User username(String username) { */ @JsonProperty("username") - public String getUsername() { + public Optional getUsername() { return username; } - public void setUsername(String username) { + public void setUsername(Optional username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; + this.firstName = Optional.of(firstName); return this; } @@ -85,16 +85,16 @@ public User firstName(String firstName) { */ @JsonProperty("firstName") - public String getFirstName() { + public Optional getFirstName() { return firstName; } - public void setFirstName(String firstName) { + public void setFirstName(Optional firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; + this.lastName = Optional.of(lastName); return this; } @@ -104,16 +104,16 @@ public User lastName(String lastName) { */ @JsonProperty("lastName") - public String getLastName() { + public Optional getLastName() { return lastName; } - public void setLastName(String lastName) { + public void setLastName(Optional lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; + this.email = Optional.of(email); return this; } @@ -123,16 +123,16 @@ public User email(String email) { */ @JsonProperty("email") - public String getEmail() { + public Optional getEmail() { return email; } - public void setEmail(String email) { + public void setEmail(Optional email) { this.email = email; } public User password(String password) { - this.password = password; + this.password = Optional.of(password); return this; } @@ -142,16 +142,16 @@ public User password(String password) { */ @JsonProperty("password") - public String getPassword() { + public Optional getPassword() { return password; } - public void setPassword(String password) { + public void setPassword(Optional password) { this.password = password; } public User phone(String phone) { - this.phone = phone; + this.phone = Optional.of(phone); return this; } @@ -161,16 +161,16 @@ public User phone(String phone) { */ @JsonProperty("phone") - public String getPhone() { + public Optional getPhone() { return phone; } - public void setPhone(String phone) { + public void setPhone(Optional phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; + this.userStatus = Optional.of(userStatus); return this; } @@ -180,11 +180,11 @@ public User userStatus(Integer userStatus) { */ @JsonProperty("userStatus") - public Integer getUserStatus() { + public Optional getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { + public void setUserStatus(Optional userStatus) { this.userStatus = userStatus; } diff --git a/samples/openapi3/client/petstore/spring-cloud-3/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java index aa4f9cda66e8..d2f955ce8bc1 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java index d2a4c03c7da9..185c6fa0d69c 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java index 028b64ff4f3f..9f0be612ed4a 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -94,7 +94,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -124,7 +124,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/openapi3/client/petstore/spring-cloud-3/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/openapi3/client/petstore/spring-cloud-async/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-async/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-async/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-async/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java index fa52f39ccee0..d92e57702179 100644 --- a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java index f07582d5ce82..6c05fe5f9353 100644 --- a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java index a669adc9f2ee..d9d38f90e9a5 100644 --- a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -95,7 +95,7 @@ CompletableFuture> createUser( ) CompletableFuture> createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -125,7 +125,7 @@ CompletableFuture> createUsersWithArrayInput( ) CompletableFuture> createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/openapi3/client/petstore/spring-cloud-async/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/openapi3/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-date-time/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java b/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java index ab1bfe6992fc..84749201da7f 100644 --- a/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-date-time/src/main/java/org/openapitools/api/DefaultApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator-ignore b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/FILES b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/FILES new file mode 100644 index 000000000000..e1cf3864f816 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/FILES @@ -0,0 +1,6 @@ +README.md +pom.xml +src/main/java/org/openapitools/api/PetApi.java +src/main/java/org/openapitools/model/Category.java +src/main/java/org/openapitools/model/Pet.java +src/main/java/org/openapitools/model/Tag.java diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/README.md b/samples/openapi3/client/petstore/spring-cloud-http-basic/README.md new file mode 100644 index 000000000000..a462be951ace --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/README.md @@ -0,0 +1,26 @@ +# OpenAPI generated API stub + +Spring Framework stub + + +## Overview +This code was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. +By using the [OpenAPI-Spec](https://openapis.org), you can easily generate an API stub. +This is an example of building API stub interfaces in Java using the Spring framework. + +The stubs generated can be used in your existing Spring-MVC or Spring-Boot application to create controller endpoints +by adding ```@Controller``` classes that implement the interface. Eg: +```java +@Controller +public class PetController implements PetApi { +// implement all PetApi methods +} +``` + +You can also use the interface to create [Spring-Cloud Feign clients](http://projects.spring.io/spring-cloud/spring-cloud.html#spring-cloud-feign-inheritance).Eg: +```java +@FeignClient(name="pet", url="http://petstore.swagger.io/v2") +public interface PetClient extends PetApi { + +} +``` diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/pom.xml b/samples/openapi3/client/petstore/spring-cloud-http-basic/pom.xml new file mode 100644 index 000000000000..6c63ac794490 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/pom.xml @@ -0,0 +1,82 @@ + + 4.0.0 + org.openapitools.openapi3 + spring-cloud-http-basic + jar + spring-cloud-http-basic + 1.0.0 + + 1.8 + ${java.version} + ${java.version} + UTF-8 + 1.6.14 + + + org.springframework.boot + spring-boot-starter-parent + 2.7.15 + + + + src/main/java + + + + + + org.springframework.cloud + spring-cloud-starter-parent + 2021.0.5 + pom + import + + + + + + + + org.springdoc + springdoc-openapi-ui + ${springdoc.version} + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + org.springframework.cloud + spring-cloud-starter-openfeign + + + org.springframework.security + spring-security-oauth2-client + 5.7.8 + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + org.openapitools + jackson-databind-nullable + 0.2.6 + + + org.springframework.boot + spring-boot-starter-validation + + + org.springframework.data + spring-data-commons + + + org.springframework.boot + spring-boot-starter-test + test + + + diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/api/PetApi.java new file mode 100644 index 000000000000..ecdc7b0835db --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/api/PetApi.java @@ -0,0 +1,75 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. + */ +package org.openapitools.api; + +import org.openapitools.model.Pet; +import io.swagger.v3.oas.annotations.ExternalDocumentation; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.Parameters; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; +import io.swagger.v3.oas.annotations.security.SecurityRequirement; +import io.swagger.v3.oas.annotations.tags.Tag; +import io.swagger.v3.oas.annotations.enums.ParameterIn; +import org.springframework.http.HttpStatus; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.validation.annotation.Validated; +import org.springframework.web.bind.annotation.*; +import org.springframework.web.context.request.NativeWebRequest; +import org.springframework.web.multipart.MultipartFile; + +import javax.validation.Valid; +import javax.validation.constraints.*; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import javax.annotation.Generated; + +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +@Validated +@Tag(name = "pet", description = "Everything about your Pets") +public interface PetApi { + + /** + * POST /pet : Add a new pet to the store + * + * + * @param pet Pet object that needs to be added to the store (required) + * @return successful operation (status code 200) + * or Invalid input (status code 405) + */ + @Operation( + operationId = "addPet", + summary = "Add a new pet to the store", + description = "", + tags = { "pet" }, + responses = { + @ApiResponse(responseCode = "200", description = "successful operation", content = { + @Content(mediaType = "application/xml", schema = @Schema(implementation = Pet.class)), + @Content(mediaType = "application/json", schema = @Schema(implementation = Pet.class)) + }), + @ApiResponse(responseCode = "405", description = "Invalid input") + }, + security = { + @SecurityRequirement(name = "http_basic") + } + ) + @RequestMapping( + method = RequestMethod.POST, + value = "/pet", + produces = "application/json", + consumes = "application/json" + ) + + ResponseEntity addPet( + @Parameter(name = "Pet", description = "Pet object that needs to be added to the store", required = true) @Valid @RequestBody Pet pet + ); + +} diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Category.java b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Category.java new file mode 100644 index 000000000000..0c0e8e8e72a4 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Category.java @@ -0,0 +1,108 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A category for a pet + */ + +@Schema(name = "Category", description = "A category for a pet") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Category { + + private Long id; + + private String name; + + public Category id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("id") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Category name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") + @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Category {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Pet.java b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Pet.java new file mode 100644 index 000000000000..6db8165203c1 --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Pet.java @@ -0,0 +1,284 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonValue; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import org.openapitools.model.Category; +import org.openapitools.model.Tag; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A pet for sale in the pet store + */ + +@Schema(name = "Pet", description = "A pet for sale in the pet store") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Pet { + + private Long id; + + private Category category; + + private String name; + + @Valid + private List photoUrls = new ArrayList<>(); + + @Valid + private List<@Valid Tag> tags; + + /** + * pet status in the store + */ + public enum StatusEnum { + AVAILABLE("available"), + + PENDING("pending"), + + SOLD("sold"); + + private String value; + + StatusEnum(String value) { + this.value = value; + } + + @JsonValue + public String getValue() { + return value; + } + + @Override + public String toString() { + return String.valueOf(value); + } + + @JsonCreator + public static StatusEnum fromValue(String value) { + for (StatusEnum b : StatusEnum.values()) { + if (b.value.equals(value)) { + return b; + } + } + throw new IllegalArgumentException("Unexpected value '" + value + "'"); + } + } + + @Deprecated + private StatusEnum status; + + public Pet() { + super(); + } + + /** + * Constructor with only required parameters + */ + public Pet(String name, List photoUrls) { + this.name = name; + this.photoUrls = photoUrls; + } + + public Pet id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("id") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Pet category(Category category) { + this.category = category; + return this; + } + + /** + * Get category + * @return category + */ + @Valid + @Schema(name = "category", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("category") + public Category getCategory() { + return category; + } + + public void setCategory(Category category) { + this.category = category; + } + + public Pet name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + @NotNull + @Schema(name = "name", example = "doggie", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + public Pet photoUrls(List photoUrls) { + this.photoUrls = photoUrls; + return this; + } + + public Pet addPhotoUrlsItem(String photoUrlsItem) { + if (this.photoUrls == null) { + this.photoUrls = new ArrayList<>(); + } + this.photoUrls.add(photoUrlsItem); + return this; + } + + /** + * Get photoUrls + * @return photoUrls + */ + @NotNull + @Schema(name = "photoUrls", requiredMode = Schema.RequiredMode.REQUIRED) + @JsonProperty("photoUrls") + public List getPhotoUrls() { + return photoUrls; + } + + public void setPhotoUrls(List photoUrls) { + this.photoUrls = photoUrls; + } + + public Pet tags(List<@Valid Tag> tags) { + this.tags = tags; + return this; + } + + public Pet addTagsItem(Tag tagsItem) { + if (this.tags == null) { + this.tags = new ArrayList<>(); + } + this.tags.add(tagsItem); + return this; + } + + /** + * Get tags + * @return tags + */ + @Valid + @Schema(name = "tags", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("tags") + public List<@Valid Tag> getTags() { + return tags; + } + + public void setTags(List<@Valid Tag> tags) { + this.tags = tags; + } + + public Pet status(StatusEnum status) { + this.status = status; + return this; + } + + /** + * pet status in the store + * @return status + * @deprecated + */ + + @Schema(name = "status", description = "pet status in the store", deprecated = true, requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("status") + @Deprecated + public StatusEnum getStatus() { + return status; + } + + /** + * @deprecated + */ + @Deprecated + public void setStatus(StatusEnum status) { + this.status = status; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Pet {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" category: ").append(toIndentedString(category)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append(" photoUrls: ").append(toIndentedString(photoUrls)).append("\n"); + sb.append(" tags: ").append(toIndentedString(tags)).append("\n"); + sb.append(" status: ").append(toIndentedString(status)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Tag.java b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Tag.java new file mode 100644 index 000000000000..adea27d0193c --- /dev/null +++ b/samples/openapi3/client/petstore/spring-cloud-http-basic/src/main/java/org/openapitools/model/Tag.java @@ -0,0 +1,108 @@ +package org.openapitools.model; + +import java.net.URI; +import java.util.Objects; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.fasterxml.jackson.annotation.JsonCreator; +import org.openapitools.jackson.nullable.JsonNullable; +import java.time.OffsetDateTime; +import javax.validation.Valid; +import javax.validation.constraints.*; +import io.swagger.v3.oas.annotations.media.Schema; + + +import java.util.*; +import javax.annotation.Generated; + +/** + * A tag for a pet + */ + +@Schema(name = "Tag", description = "A tag for a pet") +@Generated(value = "org.openapitools.codegen.languages.SpringCodegen") +public class Tag { + + private Long id; + + private String name; + + public Tag id(Long id) { + this.id = id; + return this; + } + + /** + * Get id + * @return id + */ + + @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("id") + public Long getId() { + return id; + } + + public void setId(Long id) { + this.id = id; + } + + public Tag name(String name) { + this.name = name; + return this; + } + + /** + * Get name + * @return name + */ + + @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @JsonProperty("name") + public String getName() { + return name; + } + + public void setName(String name) { + this.name = name; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + + @Override + public String toString() { + StringBuilder sb = new StringBuilder(); + sb.append("class Tag {\n"); + sb.append(" id: ").append(toIndentedString(id)).append("\n"); + sb.append(" name: ").append(toIndentedString(name)).append("\n"); + sb.append("}"); + return sb.toString(); + } + + /** + * Convert the given object to string with each line indented by 4 spaces + * (except the first line). + */ + private String toIndentedString(Object o) { + if (o == null) { + return "null"; + } + return o.toString().replace("\n", "\n "); + } +} + diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java index 93210401a0f2..f9e6abfb94dd 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java index b322430fbd49..260526842899 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java index f0dbbbc90594..dcc39ebde828 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/FakeClassnameTags123Api.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java index 13e702ba2676..8ba591940e1d 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java index 17b7cadd843d..e173f62079b9 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java index 0f9ae5b4a73b..e3a3f1ae76d2 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -88,7 +88,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -115,7 +115,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/ArrayTest.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/ArrayTest.java index 9f1e50085dac..32a273fe3286 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @Schema(name = "array_array_of_model", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/FormatTest.java b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/FormatTest.java index 81c7dcc4e286..c448bb04d5b3 100644 --- a/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/openapi3/client/petstore/spring-cloud-oas3-fakeapi/src/main/java/org/openapitools/model/FormatTest.java @@ -395,7 +395,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index a0418ffa9c8f..5672c99ea9e9 100644 --- a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index 68f537ff5f4f..6aa2035c3f5e 100644 --- a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index c57b90951d4e..148761ba0a66 100644 --- a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -84,7 +84,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "body", description = "List of user object", required = true) @Valid @RequestBody List body + @Parameter(name = "body", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ); @@ -108,7 +108,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "body", description = "List of user object", required = true) @Valid @RequestBody List body + @Parameter(name = "body", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ); diff --git a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/configuration/ClientConfiguration.java b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/configuration/ClientConfiguration.java index 0dc419b64b4f..e702587eb9d3 100644 --- a/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/configuration/ClientConfiguration.java +++ b/samples/openapi3/client/petstore/spring-cloud-spring-pageable/src/main/java/org/openapitools/configuration/ClientConfiguration.java @@ -1,6 +1,7 @@ package org.openapitools.configuration; import org.springframework.context.annotation.Bean; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.beans.factory.annotation.Value; import org.springframework.security.authentication.AnonymousAuthenticationToken; import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager; @@ -13,7 +14,6 @@ import org.springframework.security.oauth2.core.OAuth2AccessToken; import org.springframework.security.core.authority.AuthorityUtils; import org.springframework.http.HttpHeaders; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import feign.RequestInterceptor; import feign.RequestTemplate; diff --git a/samples/openapi3/client/petstore/spring-cloud/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-cloud/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-cloud/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-cloud/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java index 7aa471d2aebe..ee0b277d6f75 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java index cd1427025e5c..6b4cf8fc5360 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java index 0fc4481492e4..d52615ffe540 100644 --- a/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-cloud/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -94,7 +94,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); @@ -124,7 +124,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ); diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java index 6d723adc63dc..860eb02e844f 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java index 978b72fd207b..18d2654f5d69 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java index ff9e0ccbf5b5..faca2b95000c 100644 --- a/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-stubs-skip-default-interface/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -94,7 +94,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) throws Exception; @@ -124,7 +124,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) throws Exception; diff --git a/samples/openapi3/client/petstore/spring-stubs/.openapi-generator/VERSION b/samples/openapi3/client/petstore/spring-stubs/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/spring-stubs/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/spring-stubs/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java index 134deee1f859..5623b3b72f35 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java index 4ef08632a413..dbe8b98d9829 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java index f1547b4b6cc0..89190e827cc1 100644 --- a/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/client/petstore/spring-stubs/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -101,7 +101,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -134,7 +134,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/browser/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/browser/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts index d93655eca068..97a82f53c206 100644 --- a/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/browser/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts index b1beacef71f0..c98b183b5b66 100644 --- a/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/composed-schemas/models/ObjectSerializer.ts @@ -26,16 +26,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "DogBreedEnum", "PetByTypePetTypeEnum", @@ -53,6 +43,58 @@ let typeMap: {[index: string]: any} = { "PetsPatchRequest": PetsPatchRequest, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -198,31 +240,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -237,18 +275,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts index d93655eca068..97a82f53c206 100644 --- a/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/default/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/deno/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts index 1fff95395cd9..bea859c615bc 100644 --- a/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/deno/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts index d93655eca068..97a82f53c206 100644 --- a/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/inversify/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts index d93655eca068..97a82f53c206 100644 --- a/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/jquery/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION b/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts b/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts index d93655eca068..97a82f53c206 100644 --- a/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts +++ b/samples/openapi3/client/petstore/typescript/builds/object_params/models/ObjectSerializer.ts @@ -24,16 +24,6 @@ let primitives = [ "any" ]; -const supportedMediaTypes: { [mediaType: string]: number } = { - "application/json": Infinity, - "application/json-patch+json": 1, - "application/merge-patch+json": 1, - "application/strategic-merge-patch+json": 1, - "application/octet-stream": 0, - "application/x-www-form-urlencoded": 0 -} - - let enumsMap: Set = new Set([ "OrderStatusEnum", "PetStatusEnum", @@ -48,6 +38,58 @@ let typeMap: {[index: string]: any} = { "User": User, } +type MimeTypeDescriptor = { + type: string; + subtype: string; + subtypeTokens: string[]; +}; + +/** + * Every mime-type consists of a type, subtype, and optional parameters. + * The subtype can be composite, including information about the content format. + * For example: `application/json-patch+json`, `application/merge-patch+json`. + * + * This helper transforms a string mime-type into an internal representation. + * This simplifies the implementation of predicates that in turn define common rules for parsing or stringifying + * the payload. + */ +const parseMimeType = (mimeType: string): MimeTypeDescriptor => { + const [type, subtype] = mimeType.split('/'); + return { + type, + subtype, + subtypeTokens: subtype.split('+'), + }; +}; + +type MimeTypePredicate = (mimeType: string) => boolean; + +// This factory creates a predicate function that checks a string mime-type against defined rules. +const mimeTypePredicateFactory = (predicate: (descriptor: MimeTypeDescriptor) => boolean): MimeTypePredicate => (mimeType) => predicate(parseMimeType(mimeType)); + +// Use this factory when you need to define a simple predicate based only on type and, if applicable, subtype. +const mimeTypeSimplePredicateFactory = (type: string, subtype?: string): MimeTypePredicate => mimeTypePredicateFactory((descriptor) => { + if (descriptor.type !== type) return false; + if (subtype != null && descriptor.subtype !== subtype) return false; + return true; +}); + +// Creating a set of named predicates that will help us determine how to handle different mime-types +const isTextLikeMimeType = mimeTypeSimplePredicateFactory('text'); +const isJsonMimeType = mimeTypeSimplePredicateFactory('application', 'json'); +const isJsonLikeMimeType = mimeTypePredicateFactory((descriptor) => descriptor.type === 'application' && descriptor.subtypeTokens.some((item) => item === 'json')); +const isOctetStreamMimeType = mimeTypeSimplePredicateFactory('application', 'octet-stream'); +const isFormUrlencodedMimeType = mimeTypeSimplePredicateFactory('application', 'x-www-form-urlencoded'); + +// Defining a list of mime-types in the order of prioritization for handling. +const supportedMimeTypePredicatesWithPriority: MimeTypePredicate[] = [ + isJsonMimeType, + isJsonLikeMimeType, + isTextLikeMimeType, + isOctetStreamMimeType, + isFormUrlencodedMimeType, +]; + export class ObjectSerializer { public static findCorrectType(data: any, expectedType: string) { if (data == undefined) { @@ -193,31 +235,27 @@ export class ObjectSerializer { } const normalMediaTypes = mediaTypes.map(this.normalizeMediaType); - let selectedMediaType: string | undefined = undefined; - let selectedRank: number = -Infinity; - for (const mediaType of normalMediaTypes) { - if (supportedMediaTypes[mediaType!] > selectedRank) { - selectedMediaType = mediaType; - selectedRank = supportedMediaTypes[mediaType!]; - } - } - if (selectedMediaType === undefined) { - throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); + for (const predicate of supportedMimeTypePredicatesWithPriority) { + for (const mediaType of normalMediaTypes) { + if (mediaType != null && predicate(mediaType)) { + return mediaType; + } + } } - return selectedMediaType!; + throw new Error("None of the given media types are supported: " + mediaTypes.join(", ")); } /** * Convert data to a string according the given media type */ public static stringify(data: any, mediaType: string): string { - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return String(data); } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.stringify(data); } @@ -232,18 +270,14 @@ export class ObjectSerializer { throw new Error("Cannot parse content. No Content-Type defined."); } - if (mediaType === "text/plain") { + if (isTextLikeMimeType(mediaType)) { return rawData; } - if (mediaType === "application/json" || mediaType === "application/json-patch+json" || mediaType === "application/merge-patch+json" || mediaType === "application/strategic-merge-patch+json") { + if (isJsonLikeMimeType(mediaType)) { return JSON.parse(rawData); } - if (mediaType === "text/html") { - return rawData; - } - throw new Error("The mediaType " + mediaType + " is not supported by ObjectSerializer.parse."); } } diff --git a/samples/openapi3/client/petstore/typescript/tests/default/test/models/ObjectSerializer.test.ts b/samples/openapi3/client/petstore/typescript/tests/default/test/models/ObjectSerializer.test.ts index 4d546d9429de..c0a2be85466f 100644 --- a/samples/openapi3/client/petstore/typescript/tests/default/test/models/ObjectSerializer.test.ts +++ b/samples/openapi3/client/petstore/typescript/tests/default/test/models/ObjectSerializer.test.ts @@ -7,6 +7,18 @@ const objectSerializerFile = rewire(__dirname + "/../../node_modules/ts-petstore const ObjectSerializer = objectSerializerFile.__get__("ObjectSerializer") +const htmlContent = ` + + + + Error 404 Not Found + + +

              HTTP ERROR 404

              +

              Resource not found

              + + +`; describe("ObjectSerializer", () => { describe("Serialize", () => { @@ -229,12 +241,54 @@ describe("ObjectSerializer", () => { expect(deserialized[i].constructor.name).to.equal("Category") } expect(deserialized).to.deep.equal(categories) - }) + }) }) + describe("Parse", () => { - it("text/html", () => { - const input = "\n\n\nError 404 Not Found\n\n

              HTTP ERROR 404

              \n

              Resource not found

              \n\n\n" - expect(ObjectSerializer.parse(input, "text/html")).to.equal(input) + it("Text", () => { + expect(ObjectSerializer.parse("test", "text/plain")).to.equal("test") + expect(ObjectSerializer.parse(htmlContent, "text/html")).to.equal(htmlContent) + }); + + it("JSON", () => { + const jsonContent = { foo: "bar"}; + + expect(ObjectSerializer.parse(JSON.stringify(jsonContent), "application/json")).to.deep.equal(jsonContent) + expect(ObjectSerializer.parse(JSON.stringify(jsonContent), "application/json-patch+json")).to.deep.equal(jsonContent) + expect(ObjectSerializer.parse(JSON.stringify(jsonContent), "application/merge-patch+json")).to.deep.equal(jsonContent) + }); + }) + + describe("Stringify", () => { + it("Text", () => { + expect(ObjectSerializer.stringify("test", "text/plain")).to.equal("test") + expect(ObjectSerializer.stringify(htmlContent, "text/html")).to.equal(htmlContent) + }); + + it("JSON", () => { + const jsonContent = { foo: "bar"}; + + expect(ObjectSerializer.stringify(jsonContent, "application/json")).to.equal(JSON.stringify(jsonContent)) + expect(ObjectSerializer.stringify(jsonContent, "application/json-patch+json")).to.equal(JSON.stringify(jsonContent)) + expect(ObjectSerializer.stringify(jsonContent, "application/merge-patch+json")).to.equal(JSON.stringify(jsonContent)) + }); + }) + + describe("GetPreferredMediaType", () => { + it("Empty media-type", () => { + expect(ObjectSerializer.getPreferredMediaType([])).to.equal("application/json") + }); + + it("JSON media-type", () => { + expect(ObjectSerializer.getPreferredMediaType(["application/json"])).to.equal("application/json") + }); + + it("Multiple media-types", () => { + expect(ObjectSerializer.getPreferredMediaType(["text/plain", "application/x-www-form-urlencoded", "application/json"])).to.equal("application/json") + }); + + it("Unsupported media-type", () => { + expect(() => ObjectSerializer.getPreferredMediaType(["foo/bar"])).to.throw('None of the given media types are supported: foo/bar') }); }) }) diff --git a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION +++ b/samples/openapi3/schema/petstore/avro-schema/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/go/go-petstore/.openapi-generator/VERSION b/samples/openapi3/server/petstore/go/go-petstore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/go/go-petstore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go index 0efd81a77e9f..6b7c61f9ca42 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_pet.go @@ -13,6 +13,7 @@ import ( "encoding/json" "net/http" "strings" + "os" "github.com/go-chi/chi/v5" ) @@ -144,7 +145,10 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { // FindPetsByStatus - Finds Pets by status func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - statusParam := strings.Split(query.Get("status"), ",") + var statusParam []string + if query.Has("status") { + statusParam = strings.Split(query.Get("status"), ",") + } result, err := c.service.FindPetsByStatus(r.Context(), statusParam) // If an error occurred, encode the error with the status code if err != nil { @@ -159,7 +163,10 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque // Deprecated func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - tagsParam := strings.Split(query.Get("tags"), ",") + var tagsParam []string + if query.Has("tags") { + tagsParam = strings.Split(query.Get("tags"), ",") + } result, err := c.service.FindPetsByTags(r.Context(), tagsParam) // If an error occurred, encode the error with the status code if err != nil { @@ -231,10 +238,10 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - + nameParam := r.FormValue("name") - + statusParam := r.FormValue("status") result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) @@ -261,14 +268,18 @@ func (c *PetAPIController) UploadFile(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - - additionalMetadataParam := r.FormValue("additionalMetadata") - fileParam, err := ReadFormFileToTempFile(r, "file") - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return + additionalMetadataParam := r.FormValue("additionalMetadata") + var fileParam *os.File + { + param, err := ReadFormFileToTempFile(r, "file") + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + fileParam = param } diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go index 7b131249078c..3a2d0a3032b9 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_store.go @@ -76,6 +76,10 @@ func (c *StoreAPIController) Routes() Routes { // DeleteOrder - Delete purchase order by ID func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { orderIdParam := chi.URLParam(r, "orderId") + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) + return + } result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go b/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go index 45b17d50303c..998327702a27 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/api_user.go @@ -174,14 +174,24 @@ func (c *UserAPIController) CreateUsersWithListInput(w http.ResponseWriter, r *h func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() usernameParam := chi.URLParam(r, "username") - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) return } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } result, err := c.service.DeleteUser(r.Context(), usernameParam, booleanTestParam) // If an error occurred, encode the error with the status code if err != nil { @@ -195,6 +205,10 @@ func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { // GetUserByName - Get user by user name func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } result, err := c.service.GetUserByName(r.Context(), usernameParam) // If an error occurred, encode the error with the status code if err != nil { @@ -208,47 +222,93 @@ func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - usernameParam := query.Get("username") - passwordParam := query.Get("password") - int32TestParam, err := parseNumericParameter[int32]( - query.Get("int32_test"), - WithParse[int32](parseInt32), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var usernameParam string + if query.Has("username") { + param := query.Get("username") + + usernameParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "username"}, nil) return } - int64TestParam, err := parseNumericParameter[int64]( - query.Get("int64_test"), - WithParse[int64](parseInt64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) + var passwordParam string + if query.Has("password") { + param := query.Get("password") + + passwordParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "password"}, nil) return } - float32TestParam, err := parseNumericParameter[float32]( - query.Get("float32_test"), - WithParse[float32](parseFloat32), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return + var int32TestParam int32 + if query.Has("int32_test") { + param, err := parseNumericParameter[int32]( + query.Get("int32_test"), + WithParse[int32](parseInt32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + int32TestParam = param + } else { } - float64TestParam, err := parseNumericParameter[float64]( - query.Get("float64_test"), - WithParse[float64](parseFloat64), - ) - if err != nil { - c.errorHandler(w, r, &ParsingError{Err: err}, nil) - return + var int64TestParam int64 + if query.Has("int64_test") { + param, err := parseNumericParameter[int64]( + query.Get("int64_test"), + WithParse[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + int64TestParam = param + } else { } - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) - return + var float32TestParam float32 + if query.Has("float32_test") { + param, err := parseNumericParameter[float32]( + query.Get("float32_test"), + WithParse[float32](parseFloat32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + float32TestParam = param + } else { + } + var float64TestParam float64 + if query.Has("float64_test") { + param, err := parseNumericParameter[float64]( + query.Get("float64_test"), + WithParse[float64](parseFloat64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + float64TestParam = param + } else { + } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { } result, err := c.service.LoginUser(r.Context(), usernameParam, passwordParam, int32TestParam, int64TestParam, float32TestParam, float64TestParam, booleanTestParam) // If an error occurred, encode the error with the status code @@ -275,6 +335,10 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { // UpdateUser - Updated user func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } userParam := User{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() diff --git a/samples/openapi3/server/petstore/go/go-petstore/go/routers.go b/samples/openapi3/server/petstore/go/go-petstore/go/routers.go index af326677bf45..07d148352e28 100644 --- a/samples/openapi3/server/petstore/go/go-petstore/go/routers.go +++ b/samples/openapi3/server/petstore/go/go-petstore/go/routers.go @@ -12,9 +12,10 @@ package petstoreserver import ( "encoding/json" "errors" + "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" - "io/ioutil" + "io" "mime/multipart" "net/http" "os" @@ -64,7 +65,25 @@ func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, wHeader.Add(key, value) } } + + f, ok := i.(*os.File) + if ok { + data, err := io.ReadAll(f) + if err != nil { + return err + } + wHeader.Set("Content-Type", http.DetectContentType(data)) + wHeader.Set("Content-Disposition", "attachment; filename="+f.Name()) + if status != nil { + w.WriteHeader(*status) + } else { + w.WriteHeader(http.StatusOK) + } + _, err = w.Write(data) + return err + } wHeader.Set("Content-Type", "application/json; charset=UTF-8") + if status != nil { w.WriteHeader(*status) } else { @@ -117,21 +136,42 @@ func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error defer formFile.Close() - fileBytes, err := ioutil.ReadAll(formFile) + // Use .* as suffix, because the asterisk is a placeholder for the random value, + // and the period allows consumers of this file to remove the suffix to obtain the original file name + file, err := os.CreateTemp("", fileHeader.Filename+".*") if err != nil { return nil, err } - file, err := ioutil.TempFile("", fileHeader.Filename) + defer file.Close() + + _, err = io.Copy(file, formFile) if err != nil { return nil, err } + + return file, nil +} - defer file.Close() - - file.Write(fileBytes) +func parseTimes(param string) ([]time.Time, error) { + splits := strings.Split(param, ",") + times := make([]time.Time, 0, len(splits)) + for _, v := range splits { + t, err := parseTime(v) + if err != nil { + return nil, err + } + times = append(times, t) + } + return times, nil +} - return file, nil +// parseTime will parses a string parameter into a time.Time using the RFC3339 format +func parseTime(param string) (time.Time, error) { + if param == "" { + return time.Time{}, nil + } + return time.Parse(time.RFC3339, param) } type Number interface { diff --git a/samples/openapi3/server/petstore/python-flask/.dockerignore b/samples/openapi3/server/petstore/python-flask/.dockerignore deleted file mode 100644 index f9619601908b..000000000000 --- a/samples/openapi3/server/petstore/python-flask/.dockerignore +++ /dev/null @@ -1,72 +0,0 @@ -.travis.yaml -.openapi-generator-ignore -README.md -tox.ini -git_push.sh -test-requirements.txt -setup.py - -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ -venv/ -.python-version - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -#Ipython Notebook -.ipynb_checkpoints diff --git a/samples/openapi3/server/petstore/python-flask/.gitignore b/samples/openapi3/server/petstore/python-flask/.gitignore deleted file mode 100644 index 43995bd42fa2..000000000000 --- a/samples/openapi3/server/petstore/python-flask/.gitignore +++ /dev/null @@ -1,66 +0,0 @@ -# Byte-compiled / optimized / DLL files -__pycache__/ -*.py[cod] -*$py.class - -# C extensions -*.so - -# Distribution / packaging -.Python -env/ -build/ -develop-eggs/ -dist/ -downloads/ -eggs/ -.eggs/ -lib/ -lib64/ -parts/ -sdist/ -var/ -*.egg-info/ -.installed.cfg -*.egg - -# PyInstaller -# Usually these files are written by a python script from a template -# before PyInstaller builds the exe, so as to inject date/other infos into it. -*.manifest -*.spec - -# Installer logs -pip-log.txt -pip-delete-this-directory.txt - -# Unit test / coverage reports -htmlcov/ -.tox/ -.coverage -.coverage.* -.cache -nosetests.xml -coverage.xml -*,cover -.hypothesis/ -venv/ -.venv/ -.python-version -.pytest_cache - -# Translations -*.mo -*.pot - -# Django stuff: -*.log - -# Sphinx documentation -docs/_build/ - -# PyBuilder -target/ - -#Ipython Notebook -.ipynb_checkpoints diff --git a/samples/openapi3/server/petstore/python-flask/.openapi-generator/FILES b/samples/openapi3/server/petstore/python-flask/.openapi-generator/FILES deleted file mode 100644 index 79bc02917f5a..000000000000 --- a/samples/openapi3/server/petstore/python-flask/.openapi-generator/FILES +++ /dev/null @@ -1,31 +0,0 @@ -.dockerignore -.gitignore -.travis.yml -Dockerfile -README.md -git_push.sh -openapi_server/__init__.py -openapi_server/__main__.py -openapi_server/controllers/__init__.py -openapi_server/controllers/pet_controller.py -openapi_server/controllers/security_controller.py -openapi_server/controllers/store_controller.py -openapi_server/controllers/user_controller.py -openapi_server/encoder.py -openapi_server/models/__init__.py -openapi_server/models/api_response.py -openapi_server/models/base_model.py -openapi_server/models/category.py -openapi_server/models/order.py -openapi_server/models/pet.py -openapi_server/models/status_enum.py -openapi_server/models/tag.py -openapi_server/models/user.py -openapi_server/openapi/openapi.yaml -openapi_server/test/__init__.py -openapi_server/typing_utils.py -openapi_server/util.py -requirements.txt -setup.py -test-requirements.txt -tox.ini diff --git a/samples/openapi3/server/petstore/python-flask/.openapi-generator/VERSION b/samples/openapi3/server/petstore/python-flask/.openapi-generator/VERSION deleted file mode 100644 index 757e67400401..000000000000 --- a/samples/openapi3/server/petstore/python-flask/.openapi-generator/VERSION +++ /dev/null @@ -1 +0,0 @@ -7.0.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/python-flask/.travis.yml b/samples/openapi3/server/petstore/python-flask/.travis.yml deleted file mode 100644 index ad71ee5ca083..000000000000 --- a/samples/openapi3/server/petstore/python-flask/.travis.yml +++ /dev/null @@ -1,14 +0,0 @@ -# ref: https://docs.travis-ci.com/user/languages/python -language: python -python: - - "3.2" - - "3.3" - - "3.4" - - "3.5" - - "3.6" - - "3.7" - - "3.8" -# command to install dependencies -install: "pip install -r requirements.txt" -# command to run tests -script: nosetests diff --git a/samples/openapi3/server/petstore/python-flask/Dockerfile b/samples/openapi3/server/petstore/python-flask/Dockerfile deleted file mode 100644 index 4857637c3799..000000000000 --- a/samples/openapi3/server/petstore/python-flask/Dockerfile +++ /dev/null @@ -1,16 +0,0 @@ -FROM python:3-alpine - -RUN mkdir -p /usr/src/app -WORKDIR /usr/src/app - -COPY requirements.txt /usr/src/app/ - -RUN pip3 install --no-cache-dir -r requirements.txt - -COPY . /usr/src/app - -EXPOSE 8080 - -ENTRYPOINT ["python3"] - -CMD ["-m", "openapi_server"] \ No newline at end of file diff --git a/samples/openapi3/server/petstore/python-flask/README.md b/samples/openapi3/server/petstore/python-flask/README.md deleted file mode 100644 index 673c8b3b5a01..000000000000 --- a/samples/openapi3/server/petstore/python-flask/README.md +++ /dev/null @@ -1,49 +0,0 @@ -# OpenAPI generated server - -## Overview -This server was generated by the [OpenAPI Generator](https://openapi-generator.tech) project. By using the -[OpenAPI-Spec](https://openapis.org) from a remote server, you can easily generate a server stub. This -is an example of building a OpenAPI-enabled Flask server. - -This example uses the [Connexion](https://github.com/zalando/connexion) library on top of Flask. - -## Requirements -Python 3.5.2+ - -## Usage -To run the server, please execute the following from the root directory: - -``` -pip3 install -r requirements.txt -python3 -m openapi_server -``` - -and open your browser to here: - -``` -http://localhost:8080/v2/ui/ -``` - -Your OpenAPI definition lives here: - -``` -http://localhost:8080/v2/openapi.json -``` - -To launch the integration tests, use tox: -``` -sudo pip install tox -tox -``` - -## Running with Docker - -To run the server on a Docker container, please execute the following from the root directory: - -```bash -# building the image -docker build -t openapi_server . - -# starting up a container -docker run -p 8080:8080 openapi_server -``` \ No newline at end of file diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/__main__.py b/samples/openapi3/server/petstore/python-flask/openapi_server/__main__.py deleted file mode 100644 index 6045d0156f05..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/__main__.py +++ /dev/null @@ -1,19 +0,0 @@ -#!/usr/bin/env python3 - -import connexion - -from openapi_server import encoder - - -def main(): - app = connexion.App(__name__, specification_dir='./openapi/') - app.app.json_encoder = encoder.JSONEncoder - app.add_api('openapi.yaml', - arguments={'title': 'OpenAPI Petstore'}, - pythonic_params=True) - - app.run(port=8080) - - -if __name__ == '__main__': - main() diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py deleted file mode 100644 index 099f6fcadb9a..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/pet_controller.py +++ /dev/null @@ -1,146 +0,0 @@ -import connexion -from typing import Dict -from typing import Tuple -from typing import Union - -from openapi_server.models.api_response import ApiResponse # noqa: E501 -from openapi_server.models.pet import Pet # noqa: E501 -from openapi_server.models.pet_form import PetForm # noqa: E501 -from openapi_server.models.status_enum import StatusEnum # noqa: E501 -from openapi_server.models.upload_form import UploadForm # noqa: E501 -from openapi_server import util - - -def add_pet(pet): # noqa: E501 - """Add a new pet to the store - - # noqa: E501 - - :param pet: Pet object that needs to be added to the store - :type pet: dict | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - pet = Pet.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' - - -def delete_pet(pet_id, api_key=None): # noqa: E501 - """Deletes a pet - - # noqa: E501 - - :param pet_id: Pet id to delete - :type pet_id: int - :param api_key: - :type api_key: str - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - return 'do some magic!' - - -def find_pets_by_status(status): # noqa: E501 - """Finds Pets by status - - Multiple status values can be provided with comma separated strings # noqa: E501 - - :param status: Status values that need to be considered for filter - :type status: List[str] - - :rtype: Union[List[Pet], Tuple[List[Pet], int], Tuple[List[Pet], int, Dict[str, str]] - """ - return 'do some magic!' - - -def find_pets_by_tags(tags): # noqa: E501 - """Finds Pets by tags - - Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing. # noqa: E501 - - :param tags: Tags to filter by - :type tags: List[str] - - :rtype: Union[List[Pet], Tuple[List[Pet], int], Tuple[List[Pet], int, Dict[str, str]] - """ - return 'do some magic!' - - -def get_pet_by_id(pet_id): # noqa: E501 - """Find pet by ID - - Returns a single pet # noqa: E501 - - :param pet_id: ID of pet to return - :type pet_id: int - - :rtype: Union[Pet, Tuple[Pet, int], Tuple[Pet, int, Dict[str, str]] - """ - return 'do some magic!' - - -def update_pet(pet): # noqa: E501 - """Update an existing pet - - # noqa: E501 - - :param pet: Pet object that needs to be added to the store - :type pet: dict | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - pet = Pet.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' - - -def update_pet_status_with_enum(pet_id, status): # noqa: E501 - """Set the status of a pet in the store using an enum - - # noqa: E501 - - :param pet_id: ID of pet to return - :type pet_id: int - :param status: The required status - :type status: dict | bytes - - :rtype: Union[Pet, Tuple[Pet, int], Tuple[Pet, int, Dict[str, str]] - """ - if connexion.request.is_json: - status = StatusEnum.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' - - -def update_pet_with_form(pet_id, pet_form=None): # noqa: E501 - """Updates a pet in the store with form data - - # noqa: E501 - - :param pet_id: ID of pet that needs to be updated - :type pet_id: int - :param pet_form: - :type pet_form: dict | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - pet_form = PetForm.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' - - -def upload_file(pet_id, upload_form=None): # noqa: E501 - """uploads an image - - # noqa: E501 - - :param pet_id: ID of pet to update - :type pet_id: int - :param upload_form: - :type upload_form: dict | bytes - - :rtype: Union[ApiResponse, Tuple[ApiResponse, int], Tuple[ApiResponse, int, Dict[str, str]] - """ - if connexion.request.is_json: - upload_form = UploadForm.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/security_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/security_controller.py deleted file mode 100644 index 7a37d8e0b657..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/security_controller.py +++ /dev/null @@ -1,63 +0,0 @@ -from typing import List - - -def info_from_petstore_auth(token): - """ - Validate and decode token. - Returned value will be passed in 'token_info' parameter of your operation function, if there is one. - 'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one. - 'scope' or 'scopes' will be passed to scope validation function. - - :param token Token provided by Authorization header - :type token: str - :return: Decoded token information or None if token is invalid - :rtype: dict | None - """ - return {'scopes': ['read:pets', 'write:pets'], 'uid': 'user_id'} - - -def validate_scope_petstore_auth(required_scopes, token_scopes): - """ - Validate required scopes are included in token scope - - :param required_scopes Required scope to access called API - :type required_scopes: List[str] - :param token_scopes Scope present in token - :type token_scopes: List[str] - :return: True if access to called API is allowed - :rtype: bool - """ - return set(required_scopes).issubset(set(token_scopes)) - - -def info_from_api_key(api_key, required_scopes): - """ - Check and retrieve authentication information from api_key. - Returned value will be passed in 'token_info' parameter of your operation function, if there is one. - 'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one. - - :param api_key API key provided by Authorization header - :type api_key: str - :param required_scopes Always None. Used for other authentication method - :type required_scopes: None - :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API - :rtype: dict | None - """ - return {'uid': 'user_id'} - - -def info_from_auth_cookie(api_key, required_scopes): - """ - Check and retrieve authentication information from api_key. - Returned value will be passed in 'token_info' parameter of your operation function, if there is one. - 'sub' or 'uid' will be set in 'user' parameter of your operation function, if there is one. - - :param api_key API key provided by Authorization header - :type api_key: str - :param required_scopes Always None. Used for other authentication method - :type required_scopes: None - :return: Information attached to provided api_key or None if api_key is invalid or does not allow access to called API - :rtype: dict | None - """ - return {'uid': 'user_id'} - diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/store_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/store_controller.py deleted file mode 100644 index 1782980a90a1..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/store_controller.py +++ /dev/null @@ -1,59 +0,0 @@ -import connexion -from typing import Dict -from typing import Tuple -from typing import Union - -from openapi_server.models.order import Order # noqa: E501 -from openapi_server import util - - -def delete_order(order_id): # noqa: E501 - """Delete purchase order by ID - - For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors # noqa: E501 - - :param order_id: ID of the order that needs to be deleted - :type order_id: str - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - return 'do some magic!' - - -def get_inventory(): # noqa: E501 - """Returns pet inventories by status - - Returns a map of status codes to quantities # noqa: E501 - - - :rtype: Union[Dict[str, int], Tuple[Dict[str, int], int], Tuple[Dict[str, int], int, Dict[str, str]] - """ - return 'do some magic!' - - -def get_order_by_id(order_id): # noqa: E501 - """Find purchase order by ID - - For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions # noqa: E501 - - :param order_id: ID of pet that needs to be fetched - :type order_id: int - - :rtype: Union[Order, Tuple[Order, int], Tuple[Order, int, Dict[str, str]] - """ - return 'do some magic!' - - -def place_order(order): # noqa: E501 - """Place an order for a pet - - # noqa: E501 - - :param order: order placed for purchasing the pet - :type order: dict | bytes - - :rtype: Union[Order, Tuple[Order, int], Tuple[Order, int, Dict[str, str]] - """ - if connexion.request.is_json: - order = Order.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py deleted file mode 100644 index 67646174789d..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/controllers/user_controller.py +++ /dev/null @@ -1,121 +0,0 @@ -import connexion -from typing import Dict -from typing import Tuple -from typing import Union - -from openapi_server.models.user import User # noqa: E501 -from openapi_server import util - - -def create_user(user): # noqa: E501 - """Create user - - This can only be done by the logged in user. # noqa: E501 - - :param user: Created user object - :type user: dict | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - user = User.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' - - -def create_users_with_array_input(user): # noqa: E501 - """Creates list of users with given input array - - # noqa: E501 - - :param user: List of user objects - :type user: list | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - user = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 - return 'do some magic!' - - -def create_users_with_list_input(user): # noqa: E501 - """Creates list of users with given input array - - # noqa: E501 - - :param user: List of user objects - :type user: list | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - user = [User.from_dict(d) for d in connexion.request.get_json()] # noqa: E501 - return 'do some magic!' - - -def delete_user(username): # noqa: E501 - """Delete user - - This can only be done by the logged in user. # noqa: E501 - - :param username: The name that needs to be deleted - :type username: str - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - return 'do some magic!' - - -def get_user_by_name(username): # noqa: E501 - """Get user by user name - - # noqa: E501 - - :param username: The name that needs to be fetched. Use user1 for testing. - :type username: str - - :rtype: Union[User, Tuple[User, int], Tuple[User, int, Dict[str, str]] - """ - return 'do some magic!' - - -def login_user(username, password): # noqa: E501 - """Logs user into the system - - # noqa: E501 - - :param username: The user name for login - :type username: str - :param password: The password for login in clear text - :type password: str - - :rtype: Union[str, Tuple[str, int], Tuple[str, int, Dict[str, str]] - """ - return 'do some magic!' - - -def logout_user(): # noqa: E501 - """Logs out current logged in user session - - # noqa: E501 - - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - return 'do some magic!' - - -def update_user(username, user): # noqa: E501 - """Updated user - - This can only be done by the logged in user. # noqa: E501 - - :param username: name that need to be deleted - :type username: str - :param user: Updated user object - :type user: dict | bytes - - :rtype: Union[None, Tuple[None, int], Tuple[None, int, Dict[str, str]] - """ - if connexion.request.is_json: - user = User.from_dict(connexion.request.get_json()) # noqa: E501 - return 'do some magic!' diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/encoder.py b/samples/openapi3/server/petstore/python-flask/openapi_server/encoder.py deleted file mode 100644 index 60f4fa67e7dc..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/encoder.py +++ /dev/null @@ -1,19 +0,0 @@ -from connexion.apps.flask_app import FlaskJSONEncoder - -from openapi_server.models.base_model import Model - - -class JSONEncoder(FlaskJSONEncoder): - include_nulls = False - - def default(self, o): - if isinstance(o, Model): - dikt = {} - for attr in o.openapi_types: - value = getattr(o, attr) - if value is None and not self.include_nulls: - continue - attr = o.attribute_map[attr] - dikt[attr] = value - return dikt - return FlaskJSONEncoder.default(self, o) diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py deleted file mode 100644 index d96a91ec6464..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/__init__.py +++ /dev/null @@ -1,12 +0,0 @@ -# coding: utf-8 - -# flake8: noqa -from __future__ import absolute_import -# import models into model package -from openapi_server.models.api_response import ApiResponse -from openapi_server.models.category import Category -from openapi_server.models.order import Order -from openapi_server.models.pet import Pet -from openapi_server.models.status_enum import StatusEnum -from openapi_server.models.tag import Tag -from openapi_server.models.user import User diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/api_response.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/api_response.py deleted file mode 100644 index a795a0a22246..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/api_response.py +++ /dev/null @@ -1,116 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server import util - - -class ApiResponse(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, code=None, type=None, message=None): # noqa: E501 - """ApiResponse - a model defined in OpenAPI - - :param code: The code of this ApiResponse. # noqa: E501 - :type code: int - :param type: The type of this ApiResponse. # noqa: E501 - :type type: str - :param message: The message of this ApiResponse. # noqa: E501 - :type message: str - """ - self.openapi_types = { - 'code': int, - 'type': str, - 'message': str - } - - self.attribute_map = { - 'code': 'code', - 'type': 'type', - 'message': 'message' - } - - self._code = code - self._type = type - self._message = message - - @classmethod - def from_dict(cls, dikt) -> 'ApiResponse': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The ApiResponse of this ApiResponse. # noqa: E501 - :rtype: ApiResponse - """ - return util.deserialize_model(dikt, cls) - - @property - def code(self): - """Gets the code of this ApiResponse. - - - :return: The code of this ApiResponse. - :rtype: int - """ - return self._code - - @code.setter - def code(self, code): - """Sets the code of this ApiResponse. - - - :param code: The code of this ApiResponse. - :type code: int - """ - - self._code = code - - @property - def type(self): - """Gets the type of this ApiResponse. - - - :return: The type of this ApiResponse. - :rtype: str - """ - return self._type - - @type.setter - def type(self, type): - """Sets the type of this ApiResponse. - - - :param type: The type of this ApiResponse. - :type type: str - """ - - self._type = type - - @property - def message(self): - """Gets the message of this ApiResponse. - - - :return: The message of this ApiResponse. - :rtype: str - """ - return self._message - - @message.setter - def message(self, message): - """Sets the message of this ApiResponse. - - - :param message: The message of this ApiResponse. - :type message: str - """ - - self._message = message diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/base_model.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/base_model.py deleted file mode 100644 index 2f04ec6ff713..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/base_model.py +++ /dev/null @@ -1,68 +0,0 @@ -import pprint - -import typing - -from openapi_server import util - -T = typing.TypeVar('T') - - -class Model(object): - # openapiTypes: The key is attribute name and the - # value is attribute type. - openapi_types: typing.Dict[str, type] = {} - - # attributeMap: The key is attribute name and the - # value is json key in definition. - attribute_map: typing.Dict[str, str] = {} - - @classmethod - def from_dict(cls: typing.Type[T], dikt) -> T: - """Returns the dict as a model""" - return util.deserialize_model(dikt, cls) - - def to_dict(self): - """Returns the model properties as a dict - - :rtype: dict - """ - result = {} - - for attr in self.openapi_types: - value = getattr(self, attr) - if isinstance(value, list): - result[attr] = list(map( - lambda x: x.to_dict() if hasattr(x, "to_dict") else x, - value - )) - elif hasattr(value, "to_dict"): - result[attr] = value.to_dict() - elif isinstance(value, dict): - result[attr] = dict(map( - lambda item: (item[0], item[1].to_dict()) - if hasattr(item[1], "to_dict") else item, - value.items() - )) - else: - result[attr] = value - - return result - - def to_str(self): - """Returns the string representation of the model - - :rtype: str - """ - return pprint.pformat(self.to_dict()) - - def __repr__(self): - """For `print` and `pprint`""" - return self.to_str() - - def __eq__(self, other): - """Returns true if both objects are equal""" - return self.__dict__ == other.__dict__ - - def __ne__(self, other): - """Returns true if both objects are not equal""" - return not self == other diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/category.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/category.py deleted file mode 100644 index 16cde95a0563..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/category.py +++ /dev/null @@ -1,94 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -import re -from openapi_server import util - -import re # noqa: E501 - -class Category(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, id=None, name=None): # noqa: E501 - """Category - a model defined in OpenAPI - - :param id: The id of this Category. # noqa: E501 - :type id: int - :param name: The name of this Category. # noqa: E501 - :type name: str - """ - self.openapi_types = { - 'id': int, - 'name': str - } - - self.attribute_map = { - 'id': 'id', - 'name': 'name' - } - - self._id = id - self._name = name - - @classmethod - def from_dict(cls, dikt) -> 'Category': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The Category of this Category. # noqa: E501 - :rtype: Category - """ - return util.deserialize_model(dikt, cls) - - @property - def id(self): - """Gets the id of this Category. - - - :return: The id of this Category. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Category. - - - :param id: The id of this Category. - :type id: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this Category. - - - :return: The name of this Category. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Category. - - - :param name: The name of this Category. - :type name: str - """ - if name is not None and not re.search(r'^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$', name): # noqa: E501 - raise ValueError("Invalid value for `name`, must be a follow pattern or equal to `/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/`") # noqa: E501 - - self._name = name diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/order.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/order.py deleted file mode 100644 index b9b11b2b35a5..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/order.py +++ /dev/null @@ -1,202 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server import util - - -class Order(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, id=None, pet_id=None, quantity=None, ship_date=None, status=None, complete=False): # noqa: E501 - """Order - a model defined in OpenAPI - - :param id: The id of this Order. # noqa: E501 - :type id: int - :param pet_id: The pet_id of this Order. # noqa: E501 - :type pet_id: int - :param quantity: The quantity of this Order. # noqa: E501 - :type quantity: int - :param ship_date: The ship_date of this Order. # noqa: E501 - :type ship_date: datetime - :param status: The status of this Order. # noqa: E501 - :type status: str - :param complete: The complete of this Order. # noqa: E501 - :type complete: bool - """ - self.openapi_types = { - 'id': int, - 'pet_id': int, - 'quantity': int, - 'ship_date': datetime, - 'status': str, - 'complete': bool - } - - self.attribute_map = { - 'id': 'id', - 'pet_id': 'petId', - 'quantity': 'quantity', - 'ship_date': 'shipDate', - 'status': 'status', - 'complete': 'complete' - } - - self._id = id - self._pet_id = pet_id - self._quantity = quantity - self._ship_date = ship_date - self._status = status - self._complete = complete - - @classmethod - def from_dict(cls, dikt) -> 'Order': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The Order of this Order. # noqa: E501 - :rtype: Order - """ - return util.deserialize_model(dikt, cls) - - @property - def id(self): - """Gets the id of this Order. - - - :return: The id of this Order. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Order. - - - :param id: The id of this Order. - :type id: int - """ - - self._id = id - - @property - def pet_id(self): - """Gets the pet_id of this Order. - - - :return: The pet_id of this Order. - :rtype: int - """ - return self._pet_id - - @pet_id.setter - def pet_id(self, pet_id): - """Sets the pet_id of this Order. - - - :param pet_id: The pet_id of this Order. - :type pet_id: int - """ - - self._pet_id = pet_id - - @property - def quantity(self): - """Gets the quantity of this Order. - - - :return: The quantity of this Order. - :rtype: int - """ - return self._quantity - - @quantity.setter - def quantity(self, quantity): - """Sets the quantity of this Order. - - - :param quantity: The quantity of this Order. - :type quantity: int - """ - - self._quantity = quantity - - @property - def ship_date(self): - """Gets the ship_date of this Order. - - - :return: The ship_date of this Order. - :rtype: datetime - """ - return self._ship_date - - @ship_date.setter - def ship_date(self, ship_date): - """Sets the ship_date of this Order. - - - :param ship_date: The ship_date of this Order. - :type ship_date: datetime - """ - - self._ship_date = ship_date - - @property - def status(self): - """Gets the status of this Order. - - Order Status # noqa: E501 - - :return: The status of this Order. - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this Order. - - Order Status # noqa: E501 - - :param status: The status of this Order. - :type status: str - """ - allowed_values = ["placed", "approved", "delivered"] # noqa: E501 - if status not in allowed_values: - raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" - .format(status, allowed_values) - ) - - self._status = status - - @property - def complete(self): - """Gets the complete of this Order. - - - :return: The complete of this Order. - :rtype: bool - """ - return self._complete - - @complete.setter - def complete(self, complete): - """Sets the complete of this Order. - - - :param complete: The complete of this Order. - :type complete: bool - """ - - self._complete = complete diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet.py deleted file mode 100644 index 1473099c5f8e..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet.py +++ /dev/null @@ -1,210 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server.models.category import Category -from openapi_server.models.tag import Tag -from openapi_server import util - -from openapi_server.models.category import Category # noqa: E501 -from openapi_server.models.tag import Tag # noqa: E501 - -class Pet(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, id=None, category=None, name=None, photo_urls=None, tags=None, status=None): # noqa: E501 - """Pet - a model defined in OpenAPI - - :param id: The id of this Pet. # noqa: E501 - :type id: int - :param category: The category of this Pet. # noqa: E501 - :type category: Category - :param name: The name of this Pet. # noqa: E501 - :type name: str - :param photo_urls: The photo_urls of this Pet. # noqa: E501 - :type photo_urls: List[str] - :param tags: The tags of this Pet. # noqa: E501 - :type tags: List[Tag] - :param status: The status of this Pet. # noqa: E501 - :type status: str - """ - self.openapi_types = { - 'id': int, - 'category': Category, - 'name': str, - 'photo_urls': List[str], - 'tags': List[Tag], - 'status': str - } - - self.attribute_map = { - 'id': 'id', - 'category': 'category', - 'name': 'name', - 'photo_urls': 'photoUrls', - 'tags': 'tags', - 'status': 'status' - } - - self._id = id - self._category = category - self._name = name - self._photo_urls = photo_urls - self._tags = tags - self._status = status - - @classmethod - def from_dict(cls, dikt) -> 'Pet': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The Pet of this Pet. # noqa: E501 - :rtype: Pet - """ - return util.deserialize_model(dikt, cls) - - @property - def id(self): - """Gets the id of this Pet. - - - :return: The id of this Pet. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Pet. - - - :param id: The id of this Pet. - :type id: int - """ - - self._id = id - - @property - def category(self): - """Gets the category of this Pet. - - - :return: The category of this Pet. - :rtype: Category - """ - return self._category - - @category.setter - def category(self, category): - """Sets the category of this Pet. - - - :param category: The category of this Pet. - :type category: Category - """ - - self._category = category - - @property - def name(self): - """Gets the name of this Pet. - - - :return: The name of this Pet. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Pet. - - - :param name: The name of this Pet. - :type name: str - """ - if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def photo_urls(self): - """Gets the photo_urls of this Pet. - - - :return: The photo_urls of this Pet. - :rtype: List[str] - """ - return self._photo_urls - - @photo_urls.setter - def photo_urls(self, photo_urls): - """Sets the photo_urls of this Pet. - - - :param photo_urls: The photo_urls of this Pet. - :type photo_urls: List[str] - """ - if photo_urls is None: - raise ValueError("Invalid value for `photo_urls`, must not be `None`") # noqa: E501 - - self._photo_urls = photo_urls - - @property - def tags(self): - """Gets the tags of this Pet. - - - :return: The tags of this Pet. - :rtype: List[Tag] - """ - return self._tags - - @tags.setter - def tags(self, tags): - """Sets the tags of this Pet. - - - :param tags: The tags of this Pet. - :type tags: List[Tag] - """ - - self._tags = tags - - @property - def status(self): - """Gets the status of this Pet. - - pet status in the store # noqa: E501 - - :return: The status of this Pet. - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this Pet. - - pet status in the store # noqa: E501 - - :param status: The status of this Pet. - :type status: str - """ - allowed_values = ["available", "pending", "sold"] # noqa: E501 - if status not in allowed_values: - raise ValueError( - "Invalid value for `status` ({0}), must be one of {1}" - .format(status, allowed_values) - ) - - self._status = status diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py deleted file mode 100644 index 1f682346e4fb..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/pet_form.py +++ /dev/null @@ -1,98 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model_ import Model -from openapi_server import util - - -class PetForm(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, name=None, status=None): # noqa: E501 - """PetForm - a model defined in OpenAPI - - :param name: The name of this PetForm. # noqa: E501 - :type name: str - :param status: The status of this PetForm. # noqa: E501 - :type status: str - """ - self.openapi_types = { - 'name': str, - 'status': str - } - - self.attribute_map = { - 'name': 'name', - 'status': 'status' - } - - self._name = name - self._status = status - - @classmethod - def from_dict(cls, dikt) -> 'PetForm': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The PetForm of this PetForm. # noqa: E501 - :rtype: PetForm - """ - return util.deserialize_model(dikt, cls) - - @property - def name(self): - """Gets the name of this PetForm. - - Updated name of the pet # noqa: E501 - - :return: The name of this PetForm. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this PetForm. - - Updated name of the pet # noqa: E501 - - :param name: The name of this PetForm. - :type name: str - """ - if name is None: - raise ValueError("Invalid value for `name`, must not be `None`") # noqa: E501 - - self._name = name - - @property - def status(self): - """Gets the status of this PetForm. - - Updated status of the pet # noqa: E501 - - :return: The status of this PetForm. - :rtype: str - """ - return self._status - - @status.setter - def status(self, status): - """Sets the status of this PetForm. - - Updated status of the pet # noqa: E501 - - :param status: The status of this PetForm. - :type status: str - """ - if status is None: - raise ValueError("Invalid value for `status`, must not be `None`") # noqa: E501 - - self._status = status diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py deleted file mode 100644 index ad3294da3e7f..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/status_enum.py +++ /dev/null @@ -1,43 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server import util - - -class StatusEnum(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - """ - allowed enum values - """ - AVAILABLE = "available" - PENDING = "pending" - SOLD = "sold" - def __init__(self): # noqa: E501 - """StatusEnum - a model defined in OpenAPI - - """ - self.openapi_types = { - } - - self.attribute_map = { - } - - @classmethod - def from_dict(cls, dikt) -> 'StatusEnum': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The statusEnum of this StatusEnum. # noqa: E501 - :rtype: StatusEnum - """ - return util.deserialize_model(dikt, cls) diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/tag.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/tag.py deleted file mode 100644 index c4dfa927b864..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/tag.py +++ /dev/null @@ -1,90 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server import util - - -class Tag(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, id=None, name=None): # noqa: E501 - """Tag - a model defined in OpenAPI - - :param id: The id of this Tag. # noqa: E501 - :type id: int - :param name: The name of this Tag. # noqa: E501 - :type name: str - """ - self.openapi_types = { - 'id': int, - 'name': str - } - - self.attribute_map = { - 'id': 'id', - 'name': 'name' - } - - self._id = id - self._name = name - - @classmethod - def from_dict(cls, dikt) -> 'Tag': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The Tag of this Tag. # noqa: E501 - :rtype: Tag - """ - return util.deserialize_model(dikt, cls) - - @property - def id(self): - """Gets the id of this Tag. - - - :return: The id of this Tag. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this Tag. - - - :param id: The id of this Tag. - :type id: int - """ - - self._id = id - - @property - def name(self): - """Gets the name of this Tag. - - - :return: The name of this Tag. - :rtype: str - """ - return self._name - - @name.setter - def name(self, name): - """Sets the name of this Tag. - - - :param name: The name of this Tag. - :type name: str - """ - - self._name = name diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py deleted file mode 100644 index 3e566f6837aa..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/upload_form.py +++ /dev/null @@ -1,96 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model_ import Model -from openapi_server import util - - -class UploadForm(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, additional_metadata=None, file=None): # noqa: E501 - """UploadForm - a model defined in OpenAPI - - :param additional_metadata: The additional_metadata of this UploadForm. # noqa: E501 - :type additional_metadata: str - :param file: The file of this UploadForm. # noqa: E501 - :type file: file - """ - self.openapi_types = { - 'additional_metadata': str, - 'file': file - } - - self.attribute_map = { - 'additional_metadata': 'additionalMetadata', - 'file': 'file' - } - - self._additional_metadata = additional_metadata - self._file = file - - @classmethod - def from_dict(cls, dikt) -> 'UploadForm': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The UploadForm of this UploadForm. # noqa: E501 - :rtype: UploadForm - """ - return util.deserialize_model(dikt, cls) - - @property - def additional_metadata(self): - """Gets the additional_metadata of this UploadForm. - - Additional data to pass to server # noqa: E501 - - :return: The additional_metadata of this UploadForm. - :rtype: str - """ - return self._additional_metadata - - @additional_metadata.setter - def additional_metadata(self, additional_metadata): - """Sets the additional_metadata of this UploadForm. - - Additional data to pass to server # noqa: E501 - - :param additional_metadata: The additional_metadata of this UploadForm. - :type additional_metadata: str - """ - - self._additional_metadata = additional_metadata - - @property - def file(self): - """Gets the file of this UploadForm. - - file to upload # noqa: E501 - - :return: The file of this UploadForm. - :rtype: file - """ - return self._file - - @file.setter - def file(self, file): - """Sets the file of this UploadForm. - - file to upload # noqa: E501 - - :param file: The file of this UploadForm. - :type file: file - """ - if file is None: - raise ValueError("Invalid value for `file`, must not be `None`") # noqa: E501 - - self._file = file diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/models/user.py b/samples/openapi3/server/petstore/python-flask/openapi_server/models/user.py deleted file mode 100644 index 8ed94b32f48a..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/models/user.py +++ /dev/null @@ -1,248 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -from datetime import date, datetime # noqa: F401 - -from typing import List, Dict # noqa: F401 - -from openapi_server.models.base_model import Model -from openapi_server import util - - -class User(Model): - """NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech). - - Do not edit the class manually. - """ - - def __init__(self, id=None, username=None, first_name=None, last_name=None, email=None, password=None, phone=None, user_status=None): # noqa: E501 - """User - a model defined in OpenAPI - - :param id: The id of this User. # noqa: E501 - :type id: int - :param username: The username of this User. # noqa: E501 - :type username: str - :param first_name: The first_name of this User. # noqa: E501 - :type first_name: str - :param last_name: The last_name of this User. # noqa: E501 - :type last_name: str - :param email: The email of this User. # noqa: E501 - :type email: str - :param password: The password of this User. # noqa: E501 - :type password: str - :param phone: The phone of this User. # noqa: E501 - :type phone: str - :param user_status: The user_status of this User. # noqa: E501 - :type user_status: int - """ - self.openapi_types = { - 'id': int, - 'username': str, - 'first_name': str, - 'last_name': str, - 'email': str, - 'password': str, - 'phone': str, - 'user_status': int - } - - self.attribute_map = { - 'id': 'id', - 'username': 'username', - 'first_name': 'firstName', - 'last_name': 'lastName', - 'email': 'email', - 'password': 'password', - 'phone': 'phone', - 'user_status': 'userStatus' - } - - self._id = id - self._username = username - self._first_name = first_name - self._last_name = last_name - self._email = email - self._password = password - self._phone = phone - self._user_status = user_status - - @classmethod - def from_dict(cls, dikt) -> 'User': - """Returns the dict as a model - - :param dikt: A dict. - :type: dict - :return: The User of this User. # noqa: E501 - :rtype: User - """ - return util.deserialize_model(dikt, cls) - - @property - def id(self): - """Gets the id of this User. - - - :return: The id of this User. - :rtype: int - """ - return self._id - - @id.setter - def id(self, id): - """Sets the id of this User. - - - :param id: The id of this User. - :type id: int - """ - - self._id = id - - @property - def username(self): - """Gets the username of this User. - - - :return: The username of this User. - :rtype: str - """ - return self._username - - @username.setter - def username(self, username): - """Sets the username of this User. - - - :param username: The username of this User. - :type username: str - """ - - self._username = username - - @property - def first_name(self): - """Gets the first_name of this User. - - - :return: The first_name of this User. - :rtype: str - """ - return self._first_name - - @first_name.setter - def first_name(self, first_name): - """Sets the first_name of this User. - - - :param first_name: The first_name of this User. - :type first_name: str - """ - - self._first_name = first_name - - @property - def last_name(self): - """Gets the last_name of this User. - - - :return: The last_name of this User. - :rtype: str - """ - return self._last_name - - @last_name.setter - def last_name(self, last_name): - """Sets the last_name of this User. - - - :param last_name: The last_name of this User. - :type last_name: str - """ - - self._last_name = last_name - - @property - def email(self): - """Gets the email of this User. - - - :return: The email of this User. - :rtype: str - """ - return self._email - - @email.setter - def email(self, email): - """Sets the email of this User. - - - :param email: The email of this User. - :type email: str - """ - - self._email = email - - @property - def password(self): - """Gets the password of this User. - - - :return: The password of this User. - :rtype: str - """ - return self._password - - @password.setter - def password(self, password): - """Sets the password of this User. - - - :param password: The password of this User. - :type password: str - """ - - self._password = password - - @property - def phone(self): - """Gets the phone of this User. - - - :return: The phone of this User. - :rtype: str - """ - return self._phone - - @phone.setter - def phone(self, phone): - """Sets the phone of this User. - - - :param phone: The phone of this User. - :type phone: str - """ - - self._phone = phone - - @property - def user_status(self): - """Gets the user_status of this User. - - User Status # noqa: E501 - - :return: The user_status of this User. - :rtype: int - """ - return self._user_status - - @user_status.setter - def user_status(self, user_status): - """Sets the user_status of this User. - - User Status # noqa: E501 - - :param user_status: The user_status of this User. - :type user_status: int - """ - - self._user_status = user_status diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml b/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml deleted file mode 100644 index c863de3bfe52..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/openapi/openapi.yaml +++ /dev/null @@ -1,924 +0,0 @@ -openapi: 3.0.1 -info: - description: "This is a sample server Petstore server. For this sample, you can\ - \ use the api key `special-key` to test the authorization filters." - license: - name: Apache-2.0 - url: https://www.apache.org/licenses/LICENSE-2.0.html - title: OpenAPI Petstore - version: 1.0.0 -externalDocs: - description: Find out more about Swagger - url: http://swagger.io -servers: -- url: http://petstore.swagger.io/v2 -tags: -- description: Everything about your Pets - name: pet -- description: Access to Petstore orders - name: store -- description: Operations about user - name: user -paths: - /pet: - post: - description: "" - operationId: add_pet - requestBody: - $ref: '#/components/requestBodies/Pet' - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - write:pets - - read:pets - summary: Add a new pet to the store - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - put: - description: "" - operationId: update_pet - requestBody: - $ref: '#/components/requestBodies/Pet' - responses: - "400": - description: Invalid ID supplied - "404": - description: Pet not found - "405": - description: Validation exception - security: - - petstore_auth: - - write:pets - - read:pets - summary: Update an existing pet - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - /pet/findByStatus: - get: - description: Multiple status values can be provided with comma separated strings - operationId: find_pets_by_status - parameters: - - description: Status values that need to be considered for filter - explode: false - in: query - name: status - required: true - schema: - items: - default: available - enum: - - available - - pending - - sold - type: string - type: array - style: form - responses: - "200": - content: - application/xml: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - application/json: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - description: successful operation - "400": - description: Invalid status value - security: - - petstore_auth: - - read:pets - summary: Finds Pets by status - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - /pet/findByTags: - get: - deprecated: true - description: "Multiple tags can be provided with comma separated strings. Use\ - \ tag1, tag2, tag3 for testing." - operationId: find_pets_by_tags - parameters: - - description: Tags to filter by - explode: false - in: query - name: tags - required: true - schema: - items: - type: string - type: array - style: form - responses: - "200": - content: - application/xml: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - application/json: - schema: - items: - $ref: '#/components/schemas/Pet' - type: array - description: successful operation - "400": - description: Invalid tag value - security: - - petstore_auth: - - read:pets - summary: Finds Pets by tags - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - /pet/{petId}: - delete: - description: "" - operationId: delete_pet - parameters: - - explode: false - in: header - name: api_key - required: false - schema: - type: string - style: simple - - description: Pet id to delete - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - responses: - "400": - description: Invalid pet value - security: - - petstore_auth: - - write:pets - - read:pets - summary: Deletes a pet - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - get: - description: Returns a single pet - operationId: get_pet_by_id - parameters: - - description: ID of pet to return - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Pet' - application/json: - schema: - $ref: '#/components/schemas/Pet' - description: successful operation - "400": - description: Invalid ID supplied - "404": - description: Pet not found - security: - - api_key: [] - summary: Find pet by ID - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - patch: - description: "" - operationId: update_pet_status_with_enum - parameters: - - description: ID of pet to return - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - - description: The required status - example: pending - explode: true - in: query - name: status - required: true - schema: - $ref: '#/components/schemas/statusEnum' - style: form - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Pet' - application/json: - schema: - $ref: '#/components/schemas/Pet' - description: successful operation - "400": - description: Invalid ID supplied - "404": - description: Pet not found - summary: Set the status of a pet in the store using an enum - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - post: - description: "" - operationId: update_pet_with_form - parameters: - - description: ID of pet that needs to be updated - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - requestBody: - $ref: '#/components/requestBodies/PetForm' - responses: - "405": - description: Invalid input - security: - - petstore_auth: - - write:pets - - read:pets - summary: Updates a pet in the store with form data - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - /pet/{petId}/uploadImage: - post: - description: "" - operationId: upload_file - parameters: - - description: ID of pet to update - explode: false - in: path - name: petId - required: true - schema: - format: int64 - type: integer - style: simple - requestBody: - $ref: '#/components/requestBodies/UploadForm' - responses: - "200": - content: - application/json: - schema: - $ref: '#/components/schemas/ApiResponse' - description: successful operation - security: - - petstore_auth: - - write:pets - - read:pets - summary: uploads an image - tags: - - pet - x-openapi-router-controller: openapi_server.controllers.pet_controller - /store/inventory: - get: - description: Returns a map of status codes to quantities - operationId: get_inventory - responses: - "200": - content: - application/json: - schema: - additionalProperties: - format: int32 - type: integer - type: object - description: successful operation - security: - - api_key: [] - summary: Returns pet inventories by status - tags: - - store - x-openapi-router-controller: openapi_server.controllers.store_controller - /store/order: - post: - description: "" - operationId: place_order - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/Order' - description: order placed for purchasing the pet - required: true - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Order' - application/json: - schema: - $ref: '#/components/schemas/Order' - description: successful operation - "400": - description: Invalid Order - summary: Place an order for a pet - tags: - - store - x-openapi-router-controller: openapi_server.controllers.store_controller - /store/order/{orderId}: - delete: - description: For valid response try integer IDs with value < 1000. Anything - above 1000 or nonintegers will generate API errors - operationId: delete_order - parameters: - - description: ID of the order that needs to be deleted - explode: false - in: path - name: orderId - required: true - schema: - type: string - style: simple - responses: - "400": - description: Invalid ID supplied - "404": - description: Order not found - summary: Delete purchase order by ID - tags: - - store - x-openapi-router-controller: openapi_server.controllers.store_controller - get: - description: For valid response try integer IDs with value <= 5 or > 10. Other - values will generate exceptions - operationId: get_order_by_id - parameters: - - description: ID of pet that needs to be fetched - explode: false - in: path - name: orderId - required: true - schema: - format: int64 - maximum: 5 - minimum: 1 - type: integer - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/Order' - application/json: - schema: - $ref: '#/components/schemas/Order' - description: successful operation - "400": - description: Invalid ID supplied - "404": - description: Order not found - summary: Find purchase order by ID - tags: - - store - x-openapi-router-controller: openapi_server.controllers.store_controller - /user: - post: - description: This can only be done by the logged in user. - operationId: create_user - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/User' - description: Created user object - required: true - responses: - default: - description: successful operation - security: - - auth_cookie: [] - summary: Create user - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - /user/createWithArray: - post: - description: "" - operationId: create_users_with_array_input - requestBody: - $ref: '#/components/requestBodies/UserArray' - responses: - default: - description: successful operation - security: - - auth_cookie: [] - summary: Creates list of users with given input array - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - /user/createWithList: - post: - description: "" - operationId: create_users_with_list_input - requestBody: - $ref: '#/components/requestBodies/UserArray' - responses: - default: - description: successful operation - security: - - auth_cookie: [] - summary: Creates list of users with given input array - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - /user/login: - get: - description: "" - operationId: login_user - parameters: - - description: The user name for login - explode: true - in: query - name: username - required: true - schema: - pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" - type: string - style: form - - description: The password for login in clear text - explode: true - in: query - name: password - required: true - schema: - type: string - style: form - responses: - "200": - content: - application/xml: - schema: - type: string - application/json: - schema: - type: string - description: successful operation - headers: - Set-Cookie: - description: Cookie authentication key for use with the `auth_cookie` - apiKey authentication. - explode: false - schema: - example: AUTH_KEY=abcde12345; Path=/; HttpOnly - type: string - style: simple - X-Rate-Limit: - description: calls per hour allowed by the user - explode: false - schema: - format: int32 - type: integer - style: simple - X-Expires-After: - description: date in UTC when token expires - explode: false - schema: - format: date-time - type: string - style: simple - "400": - description: Invalid username/password supplied - summary: Logs user into the system - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - /user/logout: - get: - description: "" - operationId: logout_user - responses: - default: - description: successful operation - security: - - auth_cookie: [] - summary: Logs out current logged in user session - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - /user/{username}: - delete: - description: This can only be done by the logged in user. - operationId: delete_user - parameters: - - description: The name that needs to be deleted - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - responses: - "400": - description: Invalid username supplied - "404": - description: User not found - security: - - auth_cookie: [] - summary: Delete user - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - get: - description: "" - operationId: get_user_by_name - parameters: - - description: The name that needs to be fetched. Use user1 for testing. - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - responses: - "200": - content: - application/xml: - schema: - $ref: '#/components/schemas/User' - application/json: - schema: - $ref: '#/components/schemas/User' - description: successful operation - "400": - description: Invalid username supplied - "404": - description: User not found - summary: Get user by user name - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller - put: - description: This can only be done by the logged in user. - operationId: update_user - parameters: - - description: name that need to be deleted - explode: false - in: path - name: username - required: true - schema: - type: string - style: simple - requestBody: - content: - application/json: - schema: - $ref: '#/components/schemas/User' - description: Updated user object - required: true - responses: - "400": - description: Invalid user supplied - "404": - description: User not found - security: - - auth_cookie: [] - summary: Updated user - tags: - - user - x-openapi-router-controller: openapi_server.controllers.user_controller -components: - parameters: - statusEnum: - description: The required status - example: pending - explode: true - in: query - name: status - required: true - schema: - $ref: '#/components/schemas/statusEnum' - style: form - requestBodies: - UserArray: - content: - application/json: - schema: - items: - $ref: '#/components/schemas/User' - type: array - description: List of user objects - required: true - Pet: - content: - application/json: - schema: - $ref: '#/components/schemas/Pet' - application/xml: - schema: - $ref: '#/components/schemas/Pet' - description: Pet object that needs to be added to the store - required: true - PetForm: - content: - application/x-www-form-urlencoded: - example: - name: fluffy - status: available - schema: - $ref: '#/components/schemas/PetForm' - UploadForm: - content: - multipart/form-data: - example: - additionalMetadata: additional metadata example - file: c29tZSB0ZXN0IGRhdGEK - schema: - $ref: '#/components/schemas/UploadForm' - schemas: - Order: - description: An order for a pets from the pet store - example: - petId: 6 - quantity: 1 - id: 0 - shipDate: 2000-01-23T04:56:07.000+00:00 - complete: false - status: placed - properties: - id: - format: int64 - title: id - type: integer - petId: - format: int64 - title: petId - type: integer - quantity: - format: int32 - title: quantity - type: integer - shipDate: - format: date-time - title: shipDate - type: string - status: - description: Order Status - enum: - - placed - - approved - - delivered - title: status - type: string - complete: - default: false - title: complete - type: boolean - title: Pet Order - type: object - xml: - name: Order - Category: - description: A category for a pet - example: - name: name - id: 6 - properties: - id: - format: int64 - title: id - type: integer - name: - pattern: "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$" - title: name - type: string - title: Pet category - type: object - xml: - name: Category - User: - description: A User who is purchasing from the pet store - example: - firstName: firstName - lastName: lastName - password: password - userStatus: 6 - phone: phone - id: 0 - email: email - username: username - properties: - id: - format: int64 - title: id - type: integer - username: - title: username - type: string - firstName: - title: firstName - type: string - lastName: - title: lastName - type: string - email: - title: email - type: string - password: - title: password - type: string - phone: - title: phone - type: string - userStatus: - description: User Status - format: int32 - title: userStatus - type: integer - title: a User - type: object - xml: - name: User - Tag: - description: A tag for a pet - example: - name: name - id: 1 - properties: - id: - format: int64 - title: id - type: integer - name: - title: name - type: string - title: Pet Tag - type: object - xml: - name: Tag - Pet: - description: A pet for sale in the pet store - example: - photoUrls: - - photoUrls - - photoUrls - name: doggie - id: 0 - category: - name: name - id: 6 - tags: - - name: name - id: 1 - - name: name - id: 1 - status: available - properties: - id: - format: int64 - title: id - type: integer - category: - $ref: '#/components/schemas/Category' - name: - example: doggie - title: name - type: string - photoUrls: - items: - type: string - title: photoUrls - type: array - xml: - name: photoUrl - wrapped: true - tags: - items: - $ref: '#/components/schemas/Tag' - title: tags - type: array - xml: - name: tag - wrapped: true - status: - description: pet status in the store - enum: - - available - - pending - - sold - title: status - type: string - required: - - name - - photoUrls - title: a Pet - type: object - xml: - name: Pet - PetForm: - description: A form for updating a pet - properties: - name: - description: Updated name of the pet - title: name - type: string - status: - description: Updated status of the pet - title: status - type: string - required: - - name - - status - title: A pet form - type: object - UploadForm: - description: A form for attaching files to a pet - properties: - additionalMetadata: - description: Additional data to pass to server - title: additionalMetadata - type: string - file: - description: file to upload - format: binary - title: file - type: string - required: - - file - title: An upload form - type: object - ApiResponse: - description: Describes the result of uploading an image resource - example: - code: 0 - type: type - message: message - properties: - code: - format: int32 - title: code - type: integer - type: - title: type - type: string - message: - title: message - type: string - title: An uploaded response - type: object - statusEnum: - description: pet status in the store - enum: - - available - - pending - - sold - title: statusEnum - type: string - securitySchemes: - petstore_auth: - flows: - implicit: - authorizationUrl: http://petstore.swagger.io/api/oauth/dialog - scopes: - write:pets: modify pets in your account - read:pets: read your pets - type: oauth2 - x-tokenInfoFunc: openapi_server.controllers.security_controller.info_from_petstore_auth - x-scopeValidateFunc: openapi_server.controllers.security_controller.validate_scope_petstore_auth - api_key: - in: header - name: api_key - type: apiKey - x-apikeyInfoFunc: openapi_server.controllers.security_controller.info_from_api_key - auth_cookie: - in: cookie - name: AUTH_KEY - type: apiKey - x-apikeyInfoFunc: openapi_server.controllers.security_controller.info_from_auth_cookie diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/test/__init__.py b/samples/openapi3/server/petstore/python-flask/openapi_server/test/__init__.py deleted file mode 100644 index 364aba9fbf88..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/test/__init__.py +++ /dev/null @@ -1,16 +0,0 @@ -import logging - -import connexion -from flask_testing import TestCase - -from openapi_server.encoder import JSONEncoder - - -class BaseTestCase(TestCase): - - def create_app(self): - logging.getLogger('connexion.operation').setLevel('ERROR') - app = connexion.App(__name__, specification_dir='../openapi/') - app.app.json_encoder = JSONEncoder - app.add_api('openapi.yaml', pythonic_params=True) - return app.app diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py deleted file mode 100644 index 9e7923d205f5..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_pet_controller.py +++ /dev/null @@ -1,220 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -import unittest - -from flask import json -from io import BytesIO - -from openapi_server.models.api_response import ApiResponse # noqa: E501 -from openapi_server.models.pet import Pet # noqa: E501 -from openapi_server.models.pet_form import PetForm # noqa: E501 -from openapi_server.models.status_enum import StatusEnum # noqa: E501 -from openapi_server.models.upload_form import UploadForm # noqa: E501 -from openapi_server.test import BaseTestCase - - -class TestPetController(BaseTestCase): - """PetController integration test stubs""" - - @unittest.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") - def test_add_pet(self): - """Test case for add_pet - - Add a new pet to the store - """ - pet = { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" -} - headers = { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet', - method='POST', - headers=headers, - data=json.dumps(pet), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_delete_pet(self): - """Test case for delete_pet - - Deletes a pet - """ - headers = { - 'api_key': 'api_key_example', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet/{pet_id}'.format(pet_id=56), - method='DELETE', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_find_pets_by_status(self): - """Test case for find_pets_by_status - - Finds Pets by status - """ - query_string = [('status', 'available')] - headers = { - 'Accept': 'application/json', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet/findByStatus', - method='GET', - headers=headers, - query_string=query_string) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_find_pets_by_tags(self): - """Test case for find_pets_by_tags - - Finds Pets by tags - """ - query_string = [('tags', 'tags_example')] - headers = { - 'Accept': 'application/json', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet/findByTags', - method='GET', - headers=headers, - query_string=query_string) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_get_pet_by_id(self): - """Test case for get_pet_by_id - - Find pet by ID - """ - headers = { - 'Accept': 'application/json', - 'api_key': 'special-key', - } - response = self.client.open( - '/v2/pet/{pet_id}'.format(pet_id=56), - method='GET', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - @unittest.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") - def test_update_pet(self): - """Test case for update_pet - - Update an existing pet - """ - pet = { - "photoUrls" : [ "photoUrls", "photoUrls" ], - "name" : "doggie", - "id" : 0, - "category" : { - "name" : "name", - "id" : 6 - }, - "tags" : [ { - "name" : "name", - "id" : 1 - }, { - "name" : "name", - "id" : 1 - } ], - "status" : "available" -} - headers = { - 'Content-Type': 'application/json', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet', - method='PUT', - headers=headers, - data=json.dumps(pet), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_update_pet_status_with_enum(self): - """Test case for update_pet_status_with_enum - - Set the status of a pet in the store using an enum - """ - query_string = [('status', pending)] - headers = { - 'Accept': 'application/json', - } - response = self.client.open( - '/v2/pet/{pet_id}'.format(pet_id=56), - method='PATCH', - headers=headers, - query_string=query_string) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - @unittest.skip("application/x-www-form-urlencoded not supported by Connexion") - def test_update_pet_with_form(self): - """Test case for update_pet_with_form - - Updates a pet in the store with form data - """ - pet_form = {"name":"fluffy","status":"available"} - headers = { - 'Content-Type': 'application/x-www-form-urlencoded', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet/{pet_id}'.format(pet_id=56), - method='POST', - headers=headers, - data=json.dumps(pet_form), - content_type='application/x-www-form-urlencoded') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - @unittest.skip("multipart/form-data not supported by Connexion") - def test_upload_file(self): - """Test case for upload_file - - uploads an image - """ - upload_form = {"additionalMetadata":"additional metadata example","file":"c29tZSB0ZXN0IGRhdGEK"} - headers = { - 'Accept': 'application/json', - 'Content-Type': 'multipart/form-data', - 'Authorization': 'Bearer special-key', - } - response = self.client.open( - '/v2/pet/{pet_id}/uploadImage'.format(pet_id=56), - method='POST', - headers=headers, - data=json.dumps(upload_form), - content_type='multipart/form-data') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_store_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_store_controller.py deleted file mode 100644 index 23049bc0e3da..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_store_controller.py +++ /dev/null @@ -1,89 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -import unittest - -from flask import json -from io import BytesIO - -from openapi_server.models.order import Order # noqa: E501 -from openapi_server.test import BaseTestCase - - -class TestStoreController(BaseTestCase): - """StoreController integration test stubs""" - - def test_delete_order(self): - """Test case for delete_order - - Delete purchase order by ID - """ - headers = { - } - response = self.client.open( - '/v2/store/order/{order_id}'.format(order_id='order_id_example'), - method='DELETE', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_get_inventory(self): - """Test case for get_inventory - - Returns pet inventories by status - """ - headers = { - 'Accept': 'application/json', - 'api_key': 'special-key', - } - response = self.client.open( - '/v2/store/inventory', - method='GET', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_get_order_by_id(self): - """Test case for get_order_by_id - - Find purchase order by ID - """ - headers = { - 'Accept': 'application/json', - } - response = self.client.open( - '/v2/store/order/{order_id}'.format(order_id=5), - method='GET', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_place_order(self): - """Test case for place_order - - Place an order for a pet - """ - order = { - "petId" : 6, - "quantity" : 1, - "id" : 0, - "shipDate" : "2000-01-23T04:56:07.000+00:00", - "complete" : false, - "status" : "placed" -} - headers = { - 'Accept': 'application/json', - 'Content-Type': 'application/json', - } - response = self.client.open( - '/v2/store/order', - method='POST', - headers=headers, - data=json.dumps(order), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_user_controller.py b/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_user_controller.py deleted file mode 100644 index 36736dd6078a..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/test/test_user_controller.py +++ /dev/null @@ -1,193 +0,0 @@ -# coding: utf-8 - -from __future__ import absolute_import -import unittest - -from flask import json -from io import BytesIO - -from openapi_server.models.user import User # noqa: E501 -from openapi_server.test import BaseTestCase - - -class TestUserController(BaseTestCase): - """UserController integration test stubs""" - - def test_create_user(self): - """Test case for create_user - - Create user - """ - user = { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" -} - headers = { - 'Content-Type': 'application/json', - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user', - method='POST', - headers=headers, - data=json.dumps(user), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_create_users_with_array_input(self): - """Test case for create_users_with_array_input - - Creates list of users with given input array - """ - user = { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" -} - headers = { - 'Content-Type': 'application/json', - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user/createWithArray', - method='POST', - headers=headers, - data=json.dumps(user), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_create_users_with_list_input(self): - """Test case for create_users_with_list_input - - Creates list of users with given input array - """ - user = { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" -} - headers = { - 'Content-Type': 'application/json', - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user/createWithList', - method='POST', - headers=headers, - data=json.dumps(user), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_delete_user(self): - """Test case for delete_user - - Delete user - """ - headers = { - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user/{username}'.format(username='username_example'), - method='DELETE', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_get_user_by_name(self): - """Test case for get_user_by_name - - Get user by user name - """ - headers = { - 'Accept': 'application/json', - } - response = self.client.open( - '/v2/user/{username}'.format(username='username_example'), - method='GET', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_login_user(self): - """Test case for login_user - - Logs user into the system - """ - query_string = [('username', 'username_example'), - ('password', 'password_example')] - headers = { - 'Accept': 'application/json', - } - response = self.client.open( - '/v2/user/login', - method='GET', - headers=headers, - query_string=query_string) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_logout_user(self): - """Test case for logout_user - - Logs out current logged in user session - """ - headers = { - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user/logout', - method='GET', - headers=headers) - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - def test_update_user(self): - """Test case for update_user - - Updated user - """ - user = { - "firstName" : "firstName", - "lastName" : "lastName", - "password" : "password", - "userStatus" : 6, - "phone" : "phone", - "id" : 0, - "email" : "email", - "username" : "username" -} - headers = { - 'Content-Type': 'application/json', - 'auth_cookie': 'special-key', - } - response = self.client.open( - '/v2/user/{username}'.format(username='username_example'), - method='PUT', - headers=headers, - data=json.dumps(user), - content_type='application/json') - self.assert200(response, - 'Response body is : ' + response.data.decode('utf-8')) - - -if __name__ == '__main__': - unittest.main() diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/typing_utils.py b/samples/openapi3/server/petstore/python-flask/openapi_server/typing_utils.py deleted file mode 100644 index 0563f81fd534..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/typing_utils.py +++ /dev/null @@ -1,32 +0,0 @@ -# coding: utf-8 - -import sys - -if sys.version_info < (3, 7): - import typing - - def is_generic(klass): - """ Determine whether klass is a generic class """ - return type(klass) == typing.GenericMeta - - def is_dict(klass): - """ Determine whether klass is a Dict """ - return klass.__extra__ == dict - - def is_list(klass): - """ Determine whether klass is a List """ - return klass.__extra__ == list - -else: - - def is_generic(klass): - """ Determine whether klass is a generic class """ - return hasattr(klass, '__origin__') - - def is_dict(klass): - """ Determine whether klass is a Dict """ - return klass.__origin__ == dict - - def is_list(klass): - """ Determine whether klass is a List """ - return klass.__origin__ == list diff --git a/samples/openapi3/server/petstore/python-flask/openapi_server/util.py b/samples/openapi3/server/petstore/python-flask/openapi_server/util.py deleted file mode 100644 index f5f27cfdaba6..000000000000 --- a/samples/openapi3/server/petstore/python-flask/openapi_server/util.py +++ /dev/null @@ -1,147 +0,0 @@ -import datetime - -import typing -from openapi_server import typing_utils - - -def _deserialize(data, klass): - """Deserializes dict, list, str into an object. - - :param data: dict, list or str. - :param klass: class literal, or string of class name. - - :return: object. - """ - if data is None: - return None - - if klass == int or klass in (float, str, bool, bytearray): - return _deserialize_primitive(data, klass) - elif klass == object: - return _deserialize_object(data) - elif klass == datetime.date: - return deserialize_date(data) - elif klass == datetime.datetime: - return deserialize_datetime(data) - elif typing_utils.is_generic(klass): - if typing_utils.is_list(klass): - return _deserialize_list(data, klass.__args__[0]) - if typing_utils.is_dict(klass): - return _deserialize_dict(data, klass.__args__[1]) - else: - return deserialize_model(data, klass) - - -def _deserialize_primitive(data, klass): - """Deserializes to primitive type. - - :param data: data to deserialize. - :param klass: class literal. - - :return: int, long, float, str, bool. - :rtype: int | long | float | str | bool - """ - try: - value = klass(data) - except UnicodeEncodeError: - value = str(data) - except TypeError: - value = data - return value - - -def _deserialize_object(value): - """Return an original value. - - :return: object. - """ - return value - - -def deserialize_date(string): - """Deserializes string to date. - - :param string: str. - :type string: str - :return: date. - :rtype: date - """ - if string is None: - return None - - try: - from dateutil.parser import parse - return parse(string).date() - except ImportError: - return string - - -def deserialize_datetime(string): - """Deserializes string to datetime. - - The string should be in iso8601 datetime format. - - :param string: str. - :type string: str - :return: datetime. - :rtype: datetime - """ - if string is None: - return None - - try: - from dateutil.parser import parse - return parse(string) - except ImportError: - return string - - -def deserialize_model(data, klass): - """Deserializes list or dict to model. - - :param data: dict, list. - :type data: dict | list - :param klass: class literal. - :return: model object. - """ - instance = klass() - - if not instance.openapi_types: - return data - - for attr, attr_type in instance.openapi_types.items(): - if data is not None \ - and instance.attribute_map[attr] in data \ - and isinstance(data, (list, dict)): - value = data[instance.attribute_map[attr]] - setattr(instance, attr, _deserialize(value, attr_type)) - - return instance - - -def _deserialize_list(data, boxed_type): - """Deserializes a list and its elements. - - :param data: list to deserialize. - :type data: list - :param boxed_type: class literal. - - :return: deserialized list. - :rtype: list - """ - return [_deserialize(sub_data, boxed_type) - for sub_data in data] - - -def _deserialize_dict(data, boxed_type): - """Deserializes a dict and its elements. - - :param data: dict to deserialize. - :type data: dict - :param boxed_type: class literal. - - :return: deserialized dict. - :rtype: dict - """ - return {k: _deserialize(v, boxed_type) - for k, v in data.items()} diff --git a/samples/openapi3/server/petstore/python-flask/requirements.txt b/samples/openapi3/server/petstore/python-flask/requirements.txt deleted file mode 100644 index be4c8a3a02c1..000000000000 --- a/samples/openapi3/server/petstore/python-flask/requirements.txt +++ /dev/null @@ -1,11 +0,0 @@ -connexion[swagger-ui] >= 2.6.0; python_version>="3.6" -# 2.3 is the last version that supports python 3.4-3.5 -connexion[swagger-ui] <= 2.3.0; python_version=="3.5" or python_version=="3.4" -# connexion requires werkzeug but connexion < 2.4.0 does not install werkzeug -# we must peg werkzeug versions below to fix connexion -# https://github.com/zalando/connexion/pull/1044 -werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" -swagger-ui-bundle >= 0.0.2 -python_dateutil >= 2.6.0 -setuptools >= 21.0.0 -Flask == 2.1.1 diff --git a/samples/openapi3/server/petstore/python-flask/setup.py b/samples/openapi3/server/petstore/python-flask/setup.py deleted file mode 100644 index 1cd2660efd67..000000000000 --- a/samples/openapi3/server/petstore/python-flask/setup.py +++ /dev/null @@ -1,39 +0,0 @@ -# coding: utf-8 - -import sys -from setuptools import setup, find_packages - -NAME = "openapi_server" -VERSION = "1.0.0" - -# To install the library, run the following -# -# python setup.py install -# -# prerequisite: setuptools -# http://pypi.python.org/pypi/setuptools - -REQUIRES = [ - "connexion>=2.0.2", - "swagger-ui-bundle>=0.0.2", - "python_dateutil>=2.6.0" -] - -setup( - name=NAME, - version=VERSION, - description="OpenAPI Petstore", - author_email="", - url="", - keywords=["OpenAPI", "OpenAPI Petstore"], - install_requires=REQUIRES, - packages=find_packages(), - package_data={'': ['openapi/openapi.yaml']}, - include_package_data=True, - entry_points={ - 'console_scripts': ['openapi_server=openapi_server.__main__:main']}, - long_description="""\ - This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. - """ -) - diff --git a/samples/openapi3/server/petstore/python-flask/test-requirements.txt b/samples/openapi3/server/petstore/python-flask/test-requirements.txt deleted file mode 100644 index 58f51d6a0027..000000000000 --- a/samples/openapi3/server/petstore/python-flask/test-requirements.txt +++ /dev/null @@ -1,4 +0,0 @@ -pytest~=7.1.0 -pytest-cov>=2.8.1 -pytest-randomly>=1.2.3 -Flask-Testing==0.8.1 diff --git a/samples/openapi3/server/petstore/python-flask/tox.ini b/samples/openapi3/server/petstore/python-flask/tox.ini deleted file mode 100644 index f66b2d84cdaa..000000000000 --- a/samples/openapi3/server/petstore/python-flask/tox.ini +++ /dev/null @@ -1,11 +0,0 @@ -[tox] -envlist = py3 -skipsdist=True - -[testenv] -deps=-r{toxinidir}/requirements.txt - -r{toxinidir}/test-requirements.txt - {toxinidir} - -commands= - pytest --cov=openapi_server diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/FILES b/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/FILES index a44588157f3b..392c6ed21180 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/FILES @@ -4,9 +4,7 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/BarApi.java -src/main/java/org/openapitools/api/BarApiController.java src/main/java/org/openapitools/api/FooApi.java -src/main/java/org/openapitools/api/FooApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/VERSION b/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/spring-boot-oneof/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java index f79476d21cc1..467a37c03701 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/BarApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -71,7 +71,7 @@ default ResponseEntity createBar( getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "{ \"id\" : \"id\", \"fooPropB\" : \"fooPropB\", \"barPropA\" : \"barPropA\" }"; + String exampleString = "{ \"foo\" : { \"fooPropA\" : \"fooPropA\", \"fooPropB\" : \"fooPropB\" }, \"id\" : \"id\", \"fooPropB\" : \"fooPropB\", \"barPropA\" : \"barPropA\" }"; ApiUtil.setExampleResponse(request, "application/json", exampleString); break; } diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java index d07098a1e930..f4f9fdde842b 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/api/FooApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -71,7 +71,7 @@ default ResponseEntity createFoo( getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("application/json"))) { - String exampleString = "null"; + String exampleString = "{ \"fooPropA\" : \"fooPropA\", \"fooPropB\" : \"fooPropB\" }"; ApiUtil.setExampleResponse(request, "application/json", exampleString); break; } @@ -109,7 +109,7 @@ default ResponseEntity> getAllFoos( getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { if (mediaType.isCompatibleWith(MediaType.valueOf("application/json;charset=utf-8"))) { - String exampleString = "[ null, null ]"; + String exampleString = "[ { \"fooPropA\" : \"fooPropA\", \"fooPropB\" : \"fooPropB\" }, { \"fooPropA\" : \"fooPropA\", \"fooPropB\" : \"fooPropB\" } ]"; ApiUtil.setExampleResponse(request, "application/json;charset=utf-8", exampleString); break; } diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/BarRefOrValue.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/BarRefOrValue.java index 151f8f044417..78ae32a3fb1c 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/BarRefOrValue.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/BarRefOrValue.java @@ -9,6 +9,7 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.openapitools.model.Bar; import org.openapitools.model.BarRef; +import org.openapitools.model.FooRefOrValue; import org.openapitools.jackson.nullable.JsonNullable; import java.time.OffsetDateTime; import javax.validation.Valid; diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/PizzaSpeziale.java b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/PizzaSpeziale.java index d80898c93917..b4687b46c012 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/PizzaSpeziale.java +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/java/org/openapitools/model/PizzaSpeziale.java @@ -7,8 +7,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; -import org.openapitools.model.Pizza; import java.math.BigDecimal; +import org.openapitools.model.Pizza; import org.openapitools.jackson.nullable.JsonNullable; import java.time.OffsetDateTime; import javax.validation.Valid; diff --git a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/resources/openapi.yaml index ccb24753a016..c00644ba9add 100644 --- a/samples/openapi3/server/petstore/spring-boot-oneof/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/spring-boot-oneof/src/main/resources/openapi.yaml @@ -189,7 +189,9 @@ components: allOf: - $ref: '#/components/schemas/Entity' example: - foo: null + foo: + fooPropA: fooPropA + fooPropB: fooPropB id: id fooPropB: fooPropB barPropA: barPropA diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/FILES b/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/FILES index 48cc81960647..b15e2c45d45d 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/FILES @@ -4,11 +4,8 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java src/main/java/org/openapitools/model/Category.java diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/VERSION b/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java index 133223e5e7cc..524f05c4a8e2 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java index 93afbb176bba..423acf765d10 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java index 7ca7bcff5730..b216fcc084a0 100644 --- a/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/spring-boot-springdoc/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -101,7 +101,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -134,7 +134,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/openapi3/server/petstore/springboot-3/.openapi-generator/FILES b/samples/openapi3/server/petstore/springboot-3/.openapi-generator/FILES index 48cc81960647..b15e2c45d45d 100644 --- a/samples/openapi3/server/petstore/springboot-3/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/springboot-3/.openapi-generator/FILES @@ -4,11 +4,8 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java src/main/java/org/openapitools/model/Category.java diff --git a/samples/openapi3/server/petstore/springboot-3/.openapi-generator/VERSION b/samples/openapi3/server/petstore/springboot-3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/springboot-3/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/springboot-3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot-3/pom.xml b/samples/openapi3/server/petstore/springboot-3/pom.xml index d43a0e5dd4b4..478e3a2a2669 100644 --- a/samples/openapi3/server/petstore/springboot-3/pom.xml +++ b/samples/openapi3/server/petstore/springboot-3/pom.xml @@ -68,6 +68,15 @@ com.fasterxml.jackson.dataformat jackson-dataformat-yaml + + + jakarta.xml.bind + jakarta.xml.bind-api + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + com.fasterxml.jackson.datatype jackson-datatype-jsr310 diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java index 2def7037cfce..4315785bdb12 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java index 6c7f49de370d..faf96a6d4bb2 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java index a19f2eebd5a0..72b938008774 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -101,7 +101,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -134,7 +134,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Category.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Category.java index f288a0edde9d..ef872174203c 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Category.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Category.java @@ -8,8 +8,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -19,6 +22,10 @@ */ @Schema(name = "Category", description = "A category for a pet") +@JacksonXmlRootElement(localName = "Category") +@XmlRootElement(name = "Category") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Category { @@ -38,6 +45,7 @@ public Category id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -58,6 +66,7 @@ public Category name(String name) { @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/ModelApiResponse.java index 369df105a62e..40a8c0bbeeff 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -9,8 +9,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -21,6 +24,10 @@ @Schema(name = "ApiResponse", description = "Describes the result of uploading an image resource") @JsonTypeName("ApiResponse") +@JacksonXmlRootElement(localName = "ModelApiResponse") +@XmlRootElement(name = "ModelApiResponse") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ModelApiResponse { @@ -42,6 +49,7 @@ public ModelApiResponse code(Integer code) { @Schema(name = "code", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("code") + @JacksonXmlProperty(localName = "code") public Integer getCode() { return code; } @@ -62,6 +70,7 @@ public ModelApiResponse type(String type) { @Schema(name = "type", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("type") + @JacksonXmlProperty(localName = "type") public String getType() { return type; } @@ -82,6 +91,7 @@ public ModelApiResponse message(String message) { @Schema(name = "message", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("message") + @JacksonXmlProperty(localName = "message") public String getMessage() { return message; } diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Order.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Order.java index 906d04ddd72a..427dd3db5f1e 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Order.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Order.java @@ -11,8 +11,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -22,6 +25,10 @@ */ @Schema(name = "Order", description = "An order for a pets from the pet store") +@JacksonXmlRootElement(localName = "Order") +@XmlRootElement(name = "Order") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Order { @@ -87,6 +94,7 @@ public Order id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -107,6 +115,7 @@ public Order petId(Long petId) { @Schema(name = "petId", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("petId") + @JacksonXmlProperty(localName = "petId") public Long getPetId() { return petId; } @@ -127,6 +136,7 @@ public Order quantity(Integer quantity) { @Schema(name = "quantity", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("quantity") + @JacksonXmlProperty(localName = "quantity") public Integer getQuantity() { return quantity; } @@ -147,6 +157,7 @@ public Order shipDate(OffsetDateTime shipDate) { @Valid @Schema(name = "shipDate", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("shipDate") + @JacksonXmlProperty(localName = "shipDate") public OffsetDateTime getShipDate() { return shipDate; } @@ -167,6 +178,7 @@ public Order status(StatusEnum status) { @Schema(name = "status", description = "Order Status", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("status") + @JacksonXmlProperty(localName = "status") public StatusEnum getStatus() { return status; } @@ -187,6 +199,7 @@ public Order complete(Boolean complete) { @Schema(name = "complete", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("complete") + @JacksonXmlProperty(localName = "complete") public Boolean getComplete() { return complete; } diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Pet.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Pet.java index 7c6d9a828f2c..dcaeffc6c0fd 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Pet.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Pet.java @@ -14,8 +14,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -25,6 +28,10 @@ */ @Schema(name = "Pet", description = "A pet for sale in the pet store") +@JacksonXmlRootElement(localName = "Pet") +@XmlRootElement(name = "Pet") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Pet { @@ -104,6 +111,7 @@ public Pet id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -124,6 +132,7 @@ public Pet category(Category category) { @Valid @Schema(name = "category", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("category") + @JacksonXmlProperty(localName = "Category") public Category getCategory() { return category; } @@ -144,6 +153,7 @@ public Pet name(String name) { @NotNull @Schema(name = "name", example = "doggie", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } @@ -172,6 +182,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { @NotNull @Schema(name = "photoUrls", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("photoUrls") + @JacksonXmlProperty(localName = "photoUrl") public List getPhotoUrls() { return photoUrls; } @@ -200,6 +211,7 @@ public Pet addTagsItem(Tag tagsItem) { @Valid @Schema(name = "tags", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("tags") + @JacksonXmlProperty(localName = "tag") public List<@Valid Tag> getTags() { return tags; } @@ -221,6 +233,7 @@ public Pet status(StatusEnum status) { @Schema(name = "status", description = "pet status in the store", deprecated = true, requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("status") + @JacksonXmlProperty(localName = "status") @Deprecated public StatusEnum getStatus() { return status; diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Tag.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Tag.java index 2f0f6cb47607..beab7013baa3 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Tag.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/Tag.java @@ -8,8 +8,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -19,6 +22,10 @@ */ @Schema(name = "Tag", description = "A tag for a pet") +@JacksonXmlRootElement(localName = "Tag") +@XmlRootElement(name = "Tag") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Tag { @@ -38,6 +45,7 @@ public Tag id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -58,6 +66,7 @@ public Tag name(String name) { @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } diff --git a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/User.java b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/User.java index 55f1824b9417..160ab08de281 100644 --- a/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/User.java +++ b/samples/openapi3/server/petstore/springboot-3/src/main/java/org/openapitools/model/User.java @@ -8,8 +8,11 @@ import java.time.OffsetDateTime; import jakarta.validation.Valid; import jakarta.validation.constraints.*; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement; +import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.xml.bind.annotation.*; import java.util.*; import jakarta.annotation.Generated; @@ -19,6 +22,10 @@ */ @Schema(name = "User", description = "A User who is purchasing from the pet store") +@JacksonXmlRootElement(localName = "User") +@XmlRootElement(name = "User") +@XmlAccessorType(XmlAccessType.FIELD) + @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class User { @@ -50,6 +57,7 @@ public User id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -70,6 +78,7 @@ public User username(String username) { @Schema(name = "username", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("username") + @JacksonXmlProperty(localName = "username") public String getUsername() { return username; } @@ -90,6 +99,7 @@ public User firstName(String firstName) { @Schema(name = "firstName", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("firstName") + @JacksonXmlProperty(localName = "firstName") public String getFirstName() { return firstName; } @@ -110,6 +120,7 @@ public User lastName(String lastName) { @Schema(name = "lastName", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("lastName") + @JacksonXmlProperty(localName = "lastName") public String getLastName() { return lastName; } @@ -130,6 +141,7 @@ public User email(String email) { @Schema(name = "email", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("email") + @JacksonXmlProperty(localName = "email") public String getEmail() { return email; } @@ -150,6 +162,7 @@ public User password(String password) { @Schema(name = "password", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("password") + @JacksonXmlProperty(localName = "password") public String getPassword() { return password; } @@ -170,6 +183,7 @@ public User phone(String phone) { @Schema(name = "phone", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("phone") + @JacksonXmlProperty(localName = "phone") public String getPhone() { return phone; } @@ -190,6 +204,7 @@ public User userStatus(Integer userStatus) { @Schema(name = "userStatus", description = "User Status", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("userStatus") + @JacksonXmlProperty(localName = "userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/openapi3/server/petstore/springboot-3/src/test/java/org/openapitools/JacksonTest.java b/samples/openapi3/server/petstore/springboot-3/src/test/java/org/openapitools/JacksonTest.java new file mode 100644 index 000000000000..b6897b9fb4d7 --- /dev/null +++ b/samples/openapi3/server/petstore/springboot-3/src/test/java/org/openapitools/JacksonTest.java @@ -0,0 +1,34 @@ +package org.openapitools; + +import static org.assertj.core.api.Assertions.assertThat; + +import org.junit.jupiter.api.Test; +import org.openapitools.model.Pet; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.dataformat.xml.XmlMapper; + +@SpringBootTest +class JacksonTest { + + @Test + void shouldSerializeToXml() throws JsonProcessingException { + // Given + XmlMapper mapper = new XmlMapper(); + Pet pet = new Pet() + .name("Red") + .status(Pet.StatusEnum.AVAILABLE); + + // When + String xmlPet = mapper.writeValueAsString(pet); + Pet deserializedPet = mapper.readValue(xmlPet, Pet.class); + + // Then + assertThat(deserializedPet) + .isNotNull() + .returns("Red", Pet::getName); + } +} \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/FILES b/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/FILES index 8e12e3455c0a..c875e2014289 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/FILES @@ -3,23 +3,17 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/VERSION b/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/springboot-delegate/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index 7acf3f70c2a0..c2a42294405f 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index ec2981e02369..6b0c4c64aa32 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 38208d498d7f..be408eea4dec 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index ef8adaf2a5f6..47c051e86181 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 8bb1ab6ad136..4d2cb27c3b61 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index c6de11dca385..bf34fd21ab6f 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -90,7 +90,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithArrayInput(user); } @@ -119,7 +119,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithListInput(user); } diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java index 8f4502411c53..a67248a54f31 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -47,7 +47,7 @@ default ResponseEntity createUser(User user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default ResponseEntity createUsersWithArrayInput(List user) { + default ResponseEntity createUsersWithArrayInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -60,7 +60,7 @@ default ResponseEntity createUsersWithArrayInput(List user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default ResponseEntity createUsersWithListInput(List user) { + default ResponseEntity createUsersWithListInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java index 9f1e50085dac..32a273fe3286 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @Schema(name = "array_array_of_model", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java index dfc230959b20..a820d6f30a0b 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java @@ -409,7 +409,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-delegate/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES b/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES index 8e1c754a6cd6..0f85b5e51c33 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION b/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java index 2fa946a0eda8..c4e592c14bc6 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index f9de7344ba4e..6fc9b1738300 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 3611e8efe2fe..bac8f3b15273 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java index 2ada20b139d0..f45a1124a9ef 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java index 8872ce90d1ca..6d196e3d5c11 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java index 0c90bce5451c..01bc987a916d 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -95,7 +95,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -125,7 +125,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java index 9f1e50085dac..32a273fe3286 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @Schema(name = "array_array_of_model", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java index dfc230959b20..a820d6f30a0b 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java @@ -409,7 +409,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml +++ b/samples/openapi3/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/openapi3/server/petstore/springboot-source/.openapi-generator/FILES b/samples/openapi3/server/petstore/springboot-source/.openapi-generator/FILES index 3a114308838f..ca0f61c4ae78 100644 --- a/samples/openapi3/server/petstore/springboot-source/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/springboot-source/.openapi-generator/FILES @@ -4,11 +4,8 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/model/Category.java src/main/java/org/openapitools/model/ModelApiResponse.java diff --git a/samples/openapi3/server/petstore/springboot-source/.openapi-generator/VERSION b/samples/openapi3/server/petstore/springboot-source/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/springboot-source/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/springboot-source/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java index 1884e7c96d61..3aa5b4489f15 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java index 312c65eb077c..5ad4bd3ac598 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java index 7b99a0122ea0..fcf70bacf748 100644 --- a/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot-source/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -65,7 +65,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -86,7 +86,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/openapi3/server/petstore/springboot/.openapi-generator/FILES b/samples/openapi3/server/petstore/springboot/.openapi-generator/FILES index 60d8efc53ef4..472c803491fc 100644 --- a/samples/openapi3/server/petstore/springboot/.openapi-generator/FILES +++ b/samples/openapi3/server/petstore/springboot/.openapi-generator/FILES @@ -4,11 +4,8 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java src/main/java/org/openapitools/model/Category.java diff --git a/samples/openapi3/server/petstore/springboot/.openapi-generator/VERSION b/samples/openapi3/server/petstore/springboot/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/openapi3/server/petstore/springboot/.openapi-generator/VERSION +++ b/samples/openapi3/server/petstore/springboot/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java index da720da885fa..b155fae08920 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java index 219dfe0e9414..d7a77b09bb6d 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java index 143037d3d6ff..42630414a19a 100644 --- a/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/openapi3/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -102,7 +102,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -135,7 +135,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/schema/petstore/ktorm-modelMutable/.openapi-generator/VERSION b/samples/schema/petstore/ktorm-modelMutable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/schema/petstore/ktorm-modelMutable/.openapi-generator/VERSION +++ b/samples/schema/petstore/ktorm-modelMutable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/ktorm/.openapi-generator/VERSION b/samples/schema/petstore/ktorm/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/schema/petstore/ktorm/.openapi-generator/VERSION +++ b/samples/schema/petstore/ktorm/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/mysql/.openapi-generator/VERSION b/samples/schema/petstore/mysql/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/schema/petstore/mysql/.openapi-generator/VERSION +++ b/samples/schema/petstore/mysql/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION +++ b/samples/schema/petstore/wsdl-schema/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/postman-collection/.openapi-generator/VERSION b/samples/schema/postman-collection/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/schema/postman-collection/.openapi-generator/VERSION +++ b/samples/schema/postman-collection/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/schema/postman-collection/postman.json b/samples/schema/postman-collection/postman.json index c7f6b04c7521..95542f3ff146 100644 --- a/samples/schema/postman-collection/postman.json +++ b/samples/schema/postman-collection/postman.json @@ -13,7 +13,7 @@ "name": "default", "item": [ { - "name": "/users/{userId} (DEPRECATED)", + "name": "/users/:userId (DEPRECATED)", "description": "Update the information of an existing user.", "item": [ { @@ -24,21 +24,25 @@ { "key": "Content-Type", "value": "application/json", + "description": "", "disabled": false }, { "key": "Accept", "value": "application/json", + "description": "", "disabled": false }, { "key": "strCode", "value": "code_one", + "description": "Code as header", "disabled": false }, { "key": "strCode2", "value": "", + "description": "Code as header2", "disabled": true } ], @@ -52,13 +56,13 @@ } }, "url": { - "raw": "{{baseUrl}}/users/{userId}", + "raw": "{{baseUrl}}/users/:userId", "host": [ "{{baseUrl}}" ], "path": [ "users", - "{userId}" + ":userId" ], "variable": [ { @@ -81,7 +85,7 @@ "name": "advanced", "item": [ { - "name": "/groups/{groupId}", + "name": "/groups/:groupId", "description": "Get group of users", "item": [ { @@ -92,6 +96,7 @@ { "key": "Accept", "value": "application/json", + "description": "", "disabled": false } ], @@ -105,18 +110,18 @@ } }, "url": { - "raw": "{{baseUrl}}/groups/{groupId}", + "raw": "{{baseUrl}}/groups/:groupId", "host": [ "{{baseUrl}}" ], "path": [ "groups", - "{groupId}" + ":groupId" ], "variable": [ { "key": "groupId", - "value": "", + "value": "1", "description": "group Id" } ], @@ -129,7 +134,7 @@ ] }, { - "name": "/users/{userId}", + "name": "/users/:userId", "description": "Retrieve the information of the user with the matching user ID.", "item": [ { @@ -140,16 +145,19 @@ { "key": "Accept", "value": "application/json", + "description": "", "disabled": false }, { "key": "strCode", "value": "code_one", + "description": "Code as header", "disabled": false }, { "key": "strCode2", "value": "", + "description": "Code as header2", "disabled": true } ], @@ -163,13 +171,13 @@ } }, "url": { - "raw": "{{baseUrl}}/users/{userId}", + "raw": "{{baseUrl}}/users/:userId", "host": [ "{{baseUrl}}" ], "path": [ "users", - "{userId}" + ":userId" ], "variable": [ { @@ -192,33 +200,30 @@ "name": "basic", "item": [ { - "name": "/users/", - "description": "Retrieve the information of the user with the matching user ID.", + "name": "/user", + "description": "Create a new user.", "item": [ { - "name": "Get User Info by Query Param", + "name": "Example request for Get User", "request": { - "method": "GET", + "method": "POST", "header": [ { - "key": "Accept", + "key": "Content-Type", "value": "application/json", + "description": "", "disabled": false }, { - "key": "Custom-Header", - "value": "", - "disabled": true - }, - { - "key": "Another-Custom-Header", - "value": "abc", + "key": "Accept", + "value": "application/json", + "description": "", "disabled": false } ], "body": { "mode": "raw", - "raw": "", + "raw": "{\n \"id\" : 777,\n \"firstName\" : \"Alotta\",\n \"lastName\" : \"Rotta\",\n \"email\" : \"alotta.rotta@gmail.com\",\n \"dateOfBirth\" : \"1997-10-31\",\n \"emailVerified\" : true,\n \"createDate\" : \"2019-08-24\"\n}", "options": { "raw": { "language": "json" @@ -226,50 +231,54 @@ } }, "url": { - "raw": "{{baseUrl}}/users/", + "raw": "{{baseUrl}}/user", "host": [ "{{baseUrl}}" ], "path": [ - "users" + "user" ], "variable": [ ], "query": [ - { - "key": "pUserId", - "value": "888" - } ] }, - "description": "Retrieve the information of the user with the matching user ID." + "description": "Create a new user." } } ] }, { - "name": "/user", - "description": "Create a new user.", + "name": "/users/", + "description": "Retrieve the information of the user with the matching user ID.", "item": [ { - "name": "Example request for Get User", + "name": "Get User Info by Query Param", "request": { - "method": "POST", + "method": "GET", "header": [ { - "key": "Content-Type", + "key": "Accept", "value": "application/json", + "description": "", "disabled": false }, { - "key": "Accept", - "value": "application/json", + "key": "Custom-Header", + "value": "", + "description": "Custom HTTP header", + "disabled": true + }, + { + "key": "Another-Custom-Header", + "value": "abc", + "description": "Custom HTTP header with default", "disabled": false } ], "body": { "mode": "raw", - "raw": "{\n \"id\" : 777,\n \"firstName\" : \"Alotta\",\n \"lastName\" : \"Rotta\",\n \"email\" : \"alotta.rotta@gmail.com\",\n \"dateOfBirth\" : \"1997-10-31\",\n \"emailVerified\" : true,\n \"createDate\" : \"2019-08-24\"\n}", + "raw": "", "options": { "raw": { "language": "json" @@ -277,19 +286,25 @@ } }, "url": { - "raw": "{{baseUrl}}/user", + "raw": "{{baseUrl}}/users/", "host": [ "{{baseUrl}}" ], "path": [ - "user" + "users" ], "variable": [ ], "query": [ + { + "key": "pUserId", + "value": "888", + "description": "Query Id.", + "disabled": false + } ] }, - "description": "Create a new user." + "description": "Retrieve the information of the user with the matching user ID." } } ] diff --git a/samples/schema/postman-collection/python/requirements.txt b/samples/schema/postman-collection/python/requirements.txt new file mode 100644 index 000000000000..160d222b6896 --- /dev/null +++ b/samples/schema/postman-collection/python/requirements.txt @@ -0,0 +1,3 @@ +python_dateutil >= 2.5.3 +setuptools >= 21.0.0 +pydantic >= 2 diff --git a/samples/schema/postman-collection/python/setup.cfg b/samples/schema/postman-collection/python/setup.cfg new file mode 100644 index 000000000000..11433ee875ab --- /dev/null +++ b/samples/schema/postman-collection/python/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length=99 diff --git a/samples/schema/postman-collection/python/test-requirements.txt b/samples/schema/postman-collection/python/test-requirements.txt new file mode 100644 index 000000000000..3a0d0b939a1e --- /dev/null +++ b/samples/schema/postman-collection/python/test-requirements.txt @@ -0,0 +1,3 @@ +pytest~=7.1.3 +pytest-cov>=2.8.1 +pytest-randomly>=3.12.0 diff --git a/samples/schema/postman-collection/python/test/__init__.py b/samples/schema/postman-collection/python/test/__init__.py new file mode 100644 index 000000000000..e69de29bb2d1 diff --git a/samples/schema/postman-collection/python/test/test_auth.py b/samples/schema/postman-collection/python/test/test_auth.py new file mode 100644 index 000000000000..48ee8f1ae524 --- /dev/null +++ b/samples/schema/postman-collection/python/test/test_auth.py @@ -0,0 +1,34 @@ +""" + Testing Postman generator output +""" +from __future__ import absolute_import + +import unittest + +import json + + +class TestParameters(unittest.TestCase): + + def setUp(self): + with open('./postman.json', 'r') as file: + self.json_data = json.load(file) + + def tearDown(self): + pass + + def test_security_schemes(self): + # auth + self.assertEqual(self.json_data['auth']['type'], 'basic') + + self.assertEqual(self.json_data['auth']['basic'][0]['key'], 'username') + self.assertEqual(self.json_data['auth']['basic'][0]['value'], '{{USERNAME}}') + self.assertEqual(self.json_data['auth']['basic'][0]['type'], 'string') + + self.assertEqual(self.json_data['auth']['basic'][1]['key'], 'password') + self.assertEqual(self.json_data['auth']['basic'][1]['value'], '{{PASSWORD}}') + self.assertEqual(self.json_data['auth']['basic'][1]['type'], 'string') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/schema/postman-collection/python/test/test_endpoints.py b/samples/schema/postman-collection/python/test/test_endpoints.py new file mode 100644 index 000000000000..6db1cd5b7463 --- /dev/null +++ b/samples/schema/postman-collection/python/test/test_endpoints.py @@ -0,0 +1,27 @@ +""" + Testing Postman generator output +""" +from __future__ import absolute_import + +import unittest + +import json + + +class TestParameters(unittest.TestCase): + + def setUp(self): + with open('./postman.json', 'r') as file: + self.json_data = json.load(file) + + def tearDown(self): + pass + + def test_endpoint_deprecated(self): + # path + path = self.json_data['item'][0]['item'][0] + self.assertEqual(path['name'], '/users/:userId (DEPRECATED)') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/schema/postman-collection/python/test/test_info.py b/samples/schema/postman-collection/python/test/test_info.py new file mode 100644 index 000000000000..d3e07e575a2b --- /dev/null +++ b/samples/schema/postman-collection/python/test/test_info.py @@ -0,0 +1,25 @@ +""" + Testing Postman generator output +""" +from __future__ import absolute_import + +import unittest + +import json + + +class TestInfo(unittest.TestCase): + + def setUp(self): + with open('./postman.json', 'r') as file: + self.json_data = json.load(file) + + def tearDown(self): + pass + + def test_collection_name(self): + self.assertEqual(self.json_data['info']['name'], 'Sample project') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/schema/postman-collection/python/test/test_parameters.py b/samples/schema/postman-collection/python/test/test_parameters.py new file mode 100644 index 000000000000..947ba8f22f58 --- /dev/null +++ b/samples/schema/postman-collection/python/test/test_parameters.py @@ -0,0 +1,50 @@ +""" + Testing Postman generator output +""" +from __future__ import absolute_import + +import unittest + +import json + + +class TestParameters(unittest.TestCase): + + def setUp(self): + with open('./postman.json', 'r') as file: + self.json_data = json.load(file) + + def tearDown(self): + pass + + def test_request_parameter_description(self): + # request url + request = self.json_data['item'][2]['item'][1]['item'][0]['request'] + self.assertEqual(request['url']['raw'], '{{baseUrl}}/users/') + # first query parameter + self.assertEqual(request['url']['query'][0]['key'], 'pUserId') + self.assertEqual(request['url']['query'][0]['value'], '888') + self.assertEqual(request['url']['query'][0]['description'], 'Query Id.') + + def test_request_parameter_required(self): + # request url + request = self.json_data['item'][2]['item'][1]['item'][0]['request'] + self.assertEqual(request['url']['raw'], '{{baseUrl}}/users/') + # first query parameter + self.assertEqual(request['url']['query'][0]['disabled'], False) + + def test_request_header(self): + # request url + request = self.json_data['item'][2]['item'][1]['item'][0]['request'] + self.assertEqual(request['url']['raw'], '{{baseUrl}}/users/') + # headers + self.assertEqual(request['header'][0]['key'], 'Accept') + self.assertEqual(request['header'][0]['disabled'], False) + self.assertEqual(request['header'][1]['key'], 'Custom-Header') + self.assertEqual(request['header'][1]['disabled'], True) + self.assertEqual(request['header'][2]['key'], 'Another-Custom-Header') + self.assertEqual(request['header'][2]['disabled'], False) + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/schema/postman-collection/python/test/test_variables.py b/samples/schema/postman-collection/python/test/test_variables.py new file mode 100644 index 000000000000..180b169876e9 --- /dev/null +++ b/samples/schema/postman-collection/python/test/test_variables.py @@ -0,0 +1,32 @@ +""" + Testing Postman generator output +""" +from __future__ import absolute_import + +import unittest + +import json + + +class TestParameters(unittest.TestCase): + + def setUp(self): + with open('./postman.json', 'r') as file: + self.json_data = json.load(file) + + def tearDown(self): + pass + + def test_security_schemes(self): + # variable + variable = self.json_data['variable'] + + self.assertEqual(len(variable), 4) + + self.assertEqual(variable[0]['key'], 'baseUrl') + self.assertEqual(variable[0]['value'], 'http://localhost:{port}/{version}') + self.assertEqual(variable[0]['type'], 'string') + + +if __name__ == '__main__': + unittest.main() diff --git a/samples/server/others/kotlin-server/jaxrs-spec/.openapi-generator/VERSION b/samples/server/others/kotlin-server/jaxrs-spec/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/others/kotlin-server/jaxrs-spec/.openapi-generator/VERSION +++ b/samples/server/others/kotlin-server/jaxrs-spec/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-3.1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-5.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-NewtonsoftFalse/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-nullableReferenceTypes/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-pocoModels/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-pocoModels/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0-pocoModels/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-pocoModels/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-project4Models/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0-useSwashBuckle/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore-6.0/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore-6.0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore-6.0/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore-6.0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/aspnetcore/.openapi-generator/VERSION +++ b/samples/server/petstore/aspnetcore/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-pistache/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h index 22854f6ccfd8..f4cf03bbc25e 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIApiRouter.h @@ -34,7 +34,7 @@ namespace OpenAPI { class OAIApiRequestHandler : public QHttpEngine::QObjectHandler { Q_OBJECT -signals: +Q_SIGNALS: void requestReceived(QHttpEngine::Socket *socket); protected: @@ -44,10 +44,10 @@ class OAIApiRequestHandler : public QHttpEngine::QObjectHandler // If the slot requires all data to be received, check to see if this is // already the case, otherwise, wait until the rest of it arrives if (socket->bytesAvailable() >= socket->contentLength()) { - emit requestReceived(socket); + Q_EMIT requestReceived(socket); } else { connect(socket, &QHttpEngine::Socket::readChannelFinished, [this, socket]() { - emit requestReceived(socket); + Q_EMIT requestReceived(socket); }); } } diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h index 94ed60e72bb2..d058cda73cbd 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIPetApiHandler.h @@ -31,7 +31,7 @@ class OAIPetApiHandler : public QObject virtual ~OAIPetApiHandler(); -public slots: +public Q_SLOTS: virtual void addPet(OAIPet body); virtual void deletePet(qint64 pet_id, QString api_key); virtual void findPetsByStatus(QList status); diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h index 084028eae63d..2a9a5718f6b7 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIStoreApiHandler.h @@ -29,7 +29,7 @@ class OAIStoreApiHandler : public QObject virtual ~OAIStoreApiHandler(); -public slots: +public Q_SLOTS: virtual void deleteOrder(QString order_id); virtual void getInventory(); virtual void getOrderById(qint64 order_id); diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h index a8bfc48c4fe2..83b56110c1d3 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/handlers/OAIUserApiHandler.h @@ -29,7 +29,7 @@ class OAIUserApiHandler : public QObject virtual ~OAIUserApiHandler(); -public slots: +public Q_SLOTS: virtual void createUser(OAIUser body); virtual void createUsersWithArrayInput(QList body); virtual void createUsersWithListInput(QList body); diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp index 5bb418382d7a..f9fc329c4a4f 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.cpp @@ -63,7 +63,7 @@ void OAIPetApiRequest::addPetRequest(){ ::OpenAPI::fromJsonValue(body, obj); - emit addPet(body); + Q_EMIT addPet(body); } @@ -81,7 +81,7 @@ void OAIPetApiRequest::deletePetRequest(const QString& pet_idstr){ } - emit deletePet(pet_id, api_key); + Q_EMIT deletePet(pet_id, api_key); } @@ -97,7 +97,7 @@ void OAIPetApiRequest::findPetsByStatusRequest(){ - emit findPetsByStatus(status); + Q_EMIT findPetsByStatus(status); } @@ -113,7 +113,7 @@ void OAIPetApiRequest::findPetsByTagsRequest(){ - emit findPetsByTags(tags); + Q_EMIT findPetsByTags(tags); } @@ -126,7 +126,7 @@ void OAIPetApiRequest::getPetByIdRequest(const QString& pet_idstr){ fromStringValue(pet_idstr, pet_id); - emit getPetById(pet_id); + Q_EMIT getPetById(pet_id); } @@ -144,7 +144,7 @@ void OAIPetApiRequest::updatePetRequest(){ ::OpenAPI::fromJsonValue(body, obj); - emit updatePet(body); + Q_EMIT updatePet(body); } @@ -159,7 +159,7 @@ void OAIPetApiRequest::updatePetWithFormRequest(const QString& pet_idstr){ QString name; QString status; - emit updatePetWithForm(pet_id, name, status); + Q_EMIT updatePetWithForm(pet_id, name, status); } @@ -174,7 +174,7 @@ void OAIPetApiRequest::uploadFileRequest(const QString& pet_idstr){ QString additional_metadata; OAIHttpFileElement file; - emit uploadFile(pet_id, additional_metadata, file); + Q_EMIT uploadFile(pet_id, additional_metadata, file); } diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h index e4f4192e13fd..c35a8dfcc584 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIPetApiRequest.h @@ -76,7 +76,7 @@ class OAIPetApiRequest : public QObject void setResponseHeaders(const QMultiMap& headers); -signals: +Q_SIGNALS: void addPet(OAIPet body); void deletePet(qint64 pet_id, QString api_key); void findPetsByStatus(QList status); diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp index 1d8d5d7ee38b..3ce1271727ef 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.cpp @@ -58,7 +58,7 @@ void OAIStoreApiRequest::deleteOrderRequest(const QString& order_idstr){ fromStringValue(order_idstr, order_id); - emit deleteOrder(order_id); + Q_EMIT deleteOrder(order_id); } @@ -69,7 +69,7 @@ void OAIStoreApiRequest::getInventoryRequest(){ - emit getInventory(); + Q_EMIT getInventory(); } @@ -82,7 +82,7 @@ void OAIStoreApiRequest::getOrderByIdRequest(const QString& order_idstr){ fromStringValue(order_idstr, order_id); - emit getOrderById(order_id); + Q_EMIT getOrderById(order_id); } @@ -100,7 +100,7 @@ void OAIStoreApiRequest::placeOrderRequest(){ ::OpenAPI::fromJsonValue(body, obj); - emit placeOrder(body); + Q_EMIT placeOrder(body); } diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h index acd12a762a36..a68bad5a2378 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIStoreApiRequest.h @@ -62,7 +62,7 @@ class OAIStoreApiRequest : public QObject void setResponseHeaders(const QMultiMap& headers); -signals: +Q_SIGNALS: void deleteOrder(QString order_id); void getInventory(); void getOrderById(qint64 order_id); diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp index 95f05a39e0d0..d4f56de308c5 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.cpp @@ -63,7 +63,7 @@ void OAIUserApiRequest::createUserRequest(){ ::OpenAPI::fromJsonValue(body, obj); - emit createUser(body); + Q_EMIT createUser(body); } @@ -85,7 +85,7 @@ void OAIUserApiRequest::createUsersWithArrayInputRequest(){ } - emit createUsersWithArrayInput(body); + Q_EMIT createUsersWithArrayInput(body); } @@ -107,7 +107,7 @@ void OAIUserApiRequest::createUsersWithListInputRequest(){ } - emit createUsersWithListInput(body); + Q_EMIT createUsersWithListInput(body); } @@ -120,7 +120,7 @@ void OAIUserApiRequest::deleteUserRequest(const QString& usernamestr){ fromStringValue(usernamestr, username); - emit deleteUser(username); + Q_EMIT deleteUser(username); } @@ -133,7 +133,7 @@ void OAIUserApiRequest::getUserByNameRequest(const QString& usernamestr){ fromStringValue(usernamestr, username); - emit getUserByName(username); + Q_EMIT getUserByName(username); } @@ -154,7 +154,7 @@ void OAIUserApiRequest::loginUserRequest(){ - emit loginUser(username, password); + Q_EMIT loginUser(username, password); } @@ -165,7 +165,7 @@ void OAIUserApiRequest::logoutUserRequest(){ - emit logoutUser(); + Q_EMIT logoutUser(); } @@ -185,7 +185,7 @@ void OAIUserApiRequest::updateUserRequest(const QString& usernamestr){ ::OpenAPI::fromJsonValue(body, obj); - emit updateUser(username, body); + Q_EMIT updateUser(username, body); } diff --git a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h index 1a8869583cbc..35a8cbd9cb8b 100644 --- a/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h +++ b/samples/server/petstore/cpp-qt-qhttpengine-server/server/src/requests/OAIUserApiRequest.h @@ -74,7 +74,7 @@ class OAIUserApiRequest : public QObject void setResponseHeaders(const QMultiMap& headers); -signals: +Q_SIGNALS: void createUser(OAIUser body); void createUsersWithArrayInput(QList body); void createUsersWithListInput(QList body); diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION +++ b/samples/server/petstore/cpp-restbed/generated/3_0/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp index 3f8a86812990..781e87a09a6e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/AnotherFakeApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -197,6 +197,8 @@ void Another_fakeDummyResource::handler_PATCH_internal(const std::shared_ptr const& restbedService); - virtual ~AnotherFakeApi(); + virtual ~AnotherFakeApi(); std::shared_ptr getAnother_fakeDummyResource(); @@ -143,7 +143,7 @@ class AnotherFakeApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spAnother_fakeDummyResource; + std::shared_ptr m_spAnother_fakeDummyResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp index 58514fb2f553..f781eaa3ee08 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -191,6 +191,8 @@ void FooResource::handler_GET_internal(const std::shared_ptr s return; } defaultSessionClose(session, status_code, result); + + } diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h index e11b9ebc35b4..c8077898ff0c 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/DefaultApi.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -130,7 +130,7 @@ class DefaultApi { public: explicit DefaultApi(std::shared_ptr const& restbedService); - virtual ~DefaultApi(); + virtual ~DefaultApi(); std::shared_ptr getFooResource(); @@ -143,7 +143,7 @@ class DefaultApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spFooResource; + std::shared_ptr m_spFooResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp index b8d7c742d36e..ae12d48df310 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -193,6 +193,8 @@ void FakeBigDecimalMapResource::handler_GET_internal(const std::shared_ptrset_path(context + "/fake/additionalProperties-reference"); + this->set_method_handler("POST", + std::bind(&FakeAdditionalProperties_referenceResource::handler_POST_internal, this, + std::placeholders::_1)); +} + +std::pair FakeAdditionalProperties_referenceResource::handleFakeApiException(const FakeApiException& e) +{ + return std::make_pair(e.getStatus(), e.what()); +} + +std::pair FakeAdditionalProperties_referenceResource::handleStdException(const std::exception& e) +{ + return std::make_pair(500, e.what()); +} + +std::pair FakeAdditionalProperties_referenceResource::handleUnspecifiedException() +{ + return std::make_pair(500, "Unknown exception occurred"); +} + +void FakeAdditionalProperties_referenceResource::setResponseHeader(const std::shared_ptr& session, const std::string& header) +{ + session->set_header(header, ""); +} + +void FakeAdditionalProperties_referenceResource::returnResponse(const std::shared_ptr& session, const int status, const std::string& result, std::multimap& responseHeaders) +{ + responseHeaders.insert(std::make_pair("Connection", "close")); + session->close(status, result, responseHeaders); +} + +void FakeAdditionalProperties_referenceResource::defaultSessionClose(const std::shared_ptr& session, const int status, const std::string& result) +{ + session->close(status, result, { {"Connection", "close"} }); +} + +void FakeAdditionalProperties_referenceResource::handler_POST_internal(const std::shared_ptr session) +{ + const auto request = session->get_request(); + // body params or form params here from the body content string + std::string bodyContent = extractBodyContent(session); + std::map requestBody; // TODO + + int status_code = 500; + std::string result = ""; + + try { + status_code = + handler_POST(requestBody); + } + catch(const FakeApiException& e) { + std::tie(status_code, result) = handleFakeApiException(e); + } + catch(const std::exception& e) { + std::tie(status_code, result) = handleStdException(e); + } + catch(...) { + std::tie(status_code, result) = handleUnspecifiedException(); + } + + std::multimap< std::string, std::string > responseHeaders {}; + static const std::vector contentTypes{ + "application/json" + }; + static const std::string acceptTypes{ + "application/json, " + }; + + if (status_code == 200) { + responseHeaders.insert(std::make_pair("Content-Type", selectPreferredContentType(contentTypes))); + if (!acceptTypes.empty()) { + responseHeaders.insert(std::make_pair("Accept", acceptTypes)); + } + + returnResponse(session, 200, result.empty() ? "{}" : result, responseHeaders); + return; + } + defaultSessionClose(session, status_code, result); + + +} + + +int FakeAdditionalProperties_referenceResource::handler_POST( + std::map & requestBody) +{ + return handler_POST_func(requestBody); +} + + +std::string FakeAdditionalProperties_referenceResource::extractBodyContent(const std::shared_ptr& session) { + const auto request = session->get_request(); + int content_length = request->get_header("Content-Length", 0); + std::string bodyContent; + session->fetch(content_length, + [&bodyContent](const std::shared_ptr session, + const restbed::Bytes &body) { + bodyContent = restbed::String::format( + "%.*s\n", (int)body.size(), body.data()); + }); + return bodyContent; +} + +std::string FakeAdditionalProperties_referenceResource::extractFormParamsFromBody(const std::string& paramName, const std::string& body) { + const auto uri = restbed::Uri("urlencoded?" + body, true); + const auto params = uri.get_query_parameters(); + const auto result = params.find(paramName); + if (result != params.cend()) { + return result->second; + } + return ""; +} FakeBody_with_binaryResource::FakeBody_with_binaryResource(const std::string& context /* = "/v2" */) { this->set_path(context + "/fake/body-with-binary"); @@ -1107,6 +1238,8 @@ void FakeBody_with_binaryResource::handler_PUT_internal(const std::shared_ptr return; } defaultSessionClose(session, status_code, result); + + } // x-extension void FakeResource::handler_GET_internal(const std::shared_ptr session) { @@ -1587,6 +1728,8 @@ void FakeResource::handler_GET_internal(const std::shared_ptr return; } defaultSessionClose(session, status_code, result); + + } // x-extension void FakeResource::handler_DELETE_internal(const std::shared_ptr session) { @@ -1632,6 +1775,8 @@ void FakeResource::handler_DELETE_internal(const std::shared_ptr FakeResource::handler_PATCH( @@ -1759,6 +1904,8 @@ void FakeInline_additionalPropertiesResource::handler_POST_internal(const std::s return; } defaultSessionClose(session, status_code, result); + + } @@ -1872,6 +2019,8 @@ void FakeInline_freeform_additionalPropertiesResource::handler_POST_internal(con return; } defaultSessionClose(session, status_code, result); + + } @@ -1984,6 +2133,8 @@ void FakeJsonFormDataResource::handler_GET_internal(const std::shared_ptr FakeApi::getFake } return m_spFakePropertyEnum_intResource; } +std::shared_ptr FakeApi::getFakeAdditionalProperties_referenceResource() { + if (!m_spFakeAdditionalProperties_referenceResource) { + setResource(std::make_shared()); + } + return m_spFakeAdditionalProperties_referenceResource; +} std::shared_ptr FakeApi::getFakeBody_with_binaryResource() { if (!m_spFakeBody_with_binaryResource) { setResource(std::make_shared()); @@ -2416,6 +2577,10 @@ void FakeApi::setResource(std::shared_ptrpublish(m_spFakePropertyEnum_intResource); } +void FakeApi::setResource(std::shared_ptr resource) { + m_spFakeAdditionalProperties_referenceResource = resource; + m_service->publish(m_spFakeAdditionalProperties_referenceResource); +} void FakeApi::setResource(std::shared_ptr resource) { m_spFakeBody_with_binaryResource = resource; m_service->publish(m_spFakeBody_with_binaryResource); @@ -2484,6 +2649,10 @@ void FakeApi::setFakeApiFakePropertyEnum_intResource(std::shared_ptrpublish(m_spFakePropertyEnum_intResource); } +void FakeApi::setFakeApiFakeAdditionalProperties_referenceResource(std::shared_ptr spFakeAdditionalProperties_referenceResource) { + m_spFakeAdditionalProperties_referenceResource = spFakeAdditionalProperties_referenceResource; + m_service->publish(m_spFakeAdditionalProperties_referenceResource); +} void FakeApi::setFakeApiFakeBody_with_binaryResource(std::shared_ptr spFakeBody_with_binaryResource) { m_spFakeBody_with_binaryResource = spFakeBody_with_binaryResource; m_service->publish(m_spFakeBody_with_binaryResource); @@ -2547,6 +2716,9 @@ void FakeApi::publishDefaultResources() { if (!m_spFakePropertyEnum_intResource) { setResource(std::make_shared()); } + if (!m_spFakeAdditionalProperties_referenceResource) { + setResource(std::make_shared()); + } if (!m_spFakeBody_with_binaryResource) { setResource(std::make_shared()); } diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h index 61514147a059..cce6d9bce998 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeApi.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -31,6 +31,7 @@ #include #include +#include "AnyType.h" #include "ChildWithNullable.h" #include "Client.h" #include "EnumClass.h" @@ -542,6 +543,68 @@ class FakePropertyEnum_intResource: public restbed::Resource OuterObjectWithEnumProperty & outerObjectWithEnumProperty); +protected: + ////////////////////////////////////// + // Override these for customization // + ////////////////////////////////////// + + virtual std::string extractBodyContent(const std::shared_ptr& session); + virtual std::string extractFormParamsFromBody(const std::string& paramName, const std::string& body); + + virtual std::pair handleFakeApiException(const FakeApiException& e); + virtual std::pair handleStdException(const std::exception& e); + virtual std::pair handleUnspecifiedException(); + + virtual void setResponseHeader(const std::shared_ptr& session, + const std::string& header); + + virtual void returnResponse(const std::shared_ptr& session, + const int status, const std::string& result, std::multimap& contentType); + virtual void defaultSessionClose(const std::shared_ptr& session, + const int status, const std::string& result); + +private: + void handler_POST_internal(const std::shared_ptr session); +}; + +/// +/// test referenced additionalProperties +/// +/// +/// +/// +class FakeAdditionalProperties_referenceResource: public restbed::Resource +{ +public: + FakeAdditionalProperties_referenceResource(const std::string& context = "/v2"); + virtual ~FakeAdditionalProperties_referenceResource() = default; + + FakeAdditionalProperties_referenceResource( + const FakeAdditionalProperties_referenceResource& other) = default; // copy constructor + FakeAdditionalProperties_referenceResource(FakeAdditionalProperties_referenceResource&& other) noexcept = default; // move constructor + + FakeAdditionalProperties_referenceResource& operator=(const FakeAdditionalProperties_referenceResource& other) = default; // copy assignment + FakeAdditionalProperties_referenceResource& operator=(FakeAdditionalProperties_referenceResource&& other) noexcept = default; // move assignment + + ///////////////////////////////////////////////////// + // Set these to implement the server functionality // + ///////////////////////////////////////////////////// + std::function & requestBody)> handler_POST_func = + [](std::map &) -> int + { throw FakeApiException(501, "Not implemented"); }; + + +protected: + ////////////////////////////////////////////////////////// + // As an alternative to setting the `std::function`s // + // override these to implement the server functionality // + ////////////////////////////////////////////////////////// + + virtual int handler_POST( + std::map & requestBody); + + protected: ////////////////////////////////////// // Override these for customization // @@ -1158,6 +1221,7 @@ using FakeApiFakeOuterCompositeResource [[deprecated]] = FakeApiResources::FakeO using FakeApiFakeOuterNumberResource [[deprecated]] = FakeApiResources::FakeOuterNumberResource; using FakeApiFakeOuterStringResource [[deprecated]] = FakeApiResources::FakeOuterStringResource; using FakeApiFakePropertyEnum_intResource [[deprecated]] = FakeApiResources::FakePropertyEnum_intResource; +using FakeApiFakeAdditionalProperties_referenceResource [[deprecated]] = FakeApiResources::FakeAdditionalProperties_referenceResource; using FakeApiFakeBody_with_binaryResource [[deprecated]] = FakeApiResources::FakeBody_with_binaryResource; using FakeApiFakeBody_with_file_schemaResource [[deprecated]] = FakeApiResources::FakeBody_with_file_schemaResource; using FakeApiFakeBody_with_query_paramsResource [[deprecated]] = FakeApiResources::FakeBody_with_query_paramsResource; @@ -1175,7 +1239,7 @@ class FakeApi { public: explicit FakeApi(std::shared_ptr const& restbedService); - virtual ~FakeApi(); + virtual ~FakeApi(); std::shared_ptr getFakeBigDecimalMapResource(); std::shared_ptr getFakeHealthResource(); @@ -1185,6 +1249,7 @@ class FakeApi std::shared_ptr getFakeOuterNumberResource(); std::shared_ptr getFakeOuterStringResource(); std::shared_ptr getFakePropertyEnum_intResource(); + std::shared_ptr getFakeAdditionalProperties_referenceResource(); std::shared_ptr getFakeBody_with_binaryResource(); std::shared_ptr getFakeBody_with_file_schemaResource(); std::shared_ptr getFakeBody_with_query_paramsResource(); @@ -1203,6 +1268,7 @@ class FakeApi void setResource(std::shared_ptr resource); void setResource(std::shared_ptr resource); void setResource(std::shared_ptr resource); + void setResource(std::shared_ptr resource); void setResource(std::shared_ptr resource); void setResource(std::shared_ptr resource); void setResource(std::shared_ptr resource); @@ -1229,6 +1295,8 @@ class FakeApi [[deprecated("use setResource()")]] virtual void setFakeApiFakePropertyEnum_intResource(std::shared_ptr spFakeApiFakePropertyEnum_intResource); [[deprecated("use setResource()")]] + virtual void setFakeApiFakeAdditionalProperties_referenceResource(std::shared_ptr spFakeApiFakeAdditionalProperties_referenceResource); + [[deprecated("use setResource()")]] virtual void setFakeApiFakeBody_with_binaryResource(std::shared_ptr spFakeApiFakeBody_with_binaryResource); [[deprecated("use setResource()")]] virtual void setFakeApiFakeBody_with_file_schemaResource(std::shared_ptr spFakeApiFakeBody_with_file_schemaResource); @@ -1252,23 +1320,24 @@ class FakeApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spFakeBigDecimalMapResource; - std::shared_ptr m_spFakeHealthResource; - std::shared_ptr m_spFakeHttp_signature_testResource; - std::shared_ptr m_spFakeOuterBooleanResource; - std::shared_ptr m_spFakeOuterCompositeResource; - std::shared_ptr m_spFakeOuterNumberResource; - std::shared_ptr m_spFakeOuterStringResource; - std::shared_ptr m_spFakePropertyEnum_intResource; - std::shared_ptr m_spFakeBody_with_binaryResource; - std::shared_ptr m_spFakeBody_with_file_schemaResource; - std::shared_ptr m_spFakeBody_with_query_paramsResource; - std::shared_ptr m_spFakeResource; - std::shared_ptr m_spFakeInline_additionalPropertiesResource; - std::shared_ptr m_spFakeInline_freeform_additionalPropertiesResource; - std::shared_ptr m_spFakeJsonFormDataResource; - std::shared_ptr m_spFakeNullableResource; - std::shared_ptr m_spFakeTest_query_parametersResource; + std::shared_ptr m_spFakeBigDecimalMapResource; + std::shared_ptr m_spFakeHealthResource; + std::shared_ptr m_spFakeHttp_signature_testResource; + std::shared_ptr m_spFakeOuterBooleanResource; + std::shared_ptr m_spFakeOuterCompositeResource; + std::shared_ptr m_spFakeOuterNumberResource; + std::shared_ptr m_spFakeOuterStringResource; + std::shared_ptr m_spFakePropertyEnum_intResource; + std::shared_ptr m_spFakeAdditionalProperties_referenceResource; + std::shared_ptr m_spFakeBody_with_binaryResource; + std::shared_ptr m_spFakeBody_with_file_schemaResource; + std::shared_ptr m_spFakeBody_with_query_paramsResource; + std::shared_ptr m_spFakeResource; + std::shared_ptr m_spFakeInline_additionalPropertiesResource; + std::shared_ptr m_spFakeInline_freeform_additionalPropertiesResource; + std::shared_ptr m_spFakeJsonFormDataResource; + std::shared_ptr m_spFakeNullableResource; + std::shared_ptr m_spFakeTest_query_parametersResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp index 4e13211d7381..53f6ed0c2a39 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/FakeClassnameTags123Api.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -197,6 +197,8 @@ void Fake_classname_testResource::handler_PATCH_internal(const std::shared_ptr const& restbedService); - virtual ~FakeClassnameTags123Api(); + virtual ~FakeClassnameTags123Api(); std::shared_ptr getFake_classname_testResource(); @@ -143,7 +143,7 @@ class FakeClassnameTags123Api virtual std::shared_ptr service(); protected: - std::shared_ptr m_spFake_classname_testResource; + std::shared_ptr m_spFake_classname_testResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp index 1da63f765781..227aff88b499 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/PetApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -205,6 +205,8 @@ void PetResource::handler_POST_internal(const std::shared_ptr return; } defaultSessionClose(session, status_code, result); + + } // x-extension @@ -270,6 +272,8 @@ void PetResource::handler_PUT_internal(const std::shared_ptr s return; } defaultSessionClose(session, status_code, result); + + } int PetResource::handler_POST( @@ -400,6 +404,8 @@ void PetPetIdResource::handler_DELETE_internal(const std::shared_ptr session) { @@ -509,6 +517,8 @@ void PetPetIdResource::handler_POST_internal(const std::shared_ptr const& restbedService); - virtual ~PetApi(); + virtual ~PetApi(); std::shared_ptr getPetResource(); std::shared_ptr getPetPetIdResource(); @@ -506,12 +506,12 @@ class PetApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spPetResource; - std::shared_ptr m_spPetPetIdResource; - std::shared_ptr m_spPetFindByStatusResource; - std::shared_ptr m_spPetFindByTagsResource; - std::shared_ptr m_spPetPetIdUploadImageResource; - std::shared_ptr m_spFakePetIdUploadImageWithRequiredFileResource; + std::shared_ptr m_spPetResource; + std::shared_ptr m_spPetPetIdResource; + std::shared_ptr m_spPetFindByStatusResource; + std::shared_ptr m_spPetFindByTagsResource; + std::shared_ptr m_spPetPetIdUploadImageResource; + std::shared_ptr m_spFakePetIdUploadImageWithRequiredFileResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp index 8719fd536570..fcc54c005135 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/StoreApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -201,6 +201,8 @@ void StoreOrderOrder_idResource::handler_DELETE_internal(const std::shared_ptr const& restbedService); - virtual ~StoreApi(); + virtual ~StoreApi(); std::shared_ptr getStoreOrderOrder_idResource(); std::shared_ptr getStoreInventoryResource(); @@ -287,9 +287,9 @@ class StoreApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spStoreOrderOrder_idResource; - std::shared_ptr m_spStoreInventoryResource; - std::shared_ptr m_spStoreOrderResource; + std::shared_ptr m_spStoreOrderOrder_idResource; + std::shared_ptr m_spStoreInventoryResource; + std::shared_ptr m_spStoreOrderResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp index 958bce70c981..683a3b5b3479 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/api/UserApi.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ @@ -193,6 +193,8 @@ void UserResource::handler_POST_internal(const std::shared_ptr return; } defaultSessionClose(session, status_code, result); + + } @@ -304,6 +306,8 @@ void UserCreateWithArrayResource::handler_POST_internal(const std::shared_ptr session) { @@ -645,6 +655,8 @@ void UserUsernameResource::handler_PUT_internal(const std::shared_ptr const& restbedService); - virtual ~UserApi(); + virtual ~UserApi(); std::shared_ptr getUserResource(); std::shared_ptr getUserCreateWithArrayResource(); @@ -496,12 +496,12 @@ class UserApi virtual std::shared_ptr service(); protected: - std::shared_ptr m_spUserResource; - std::shared_ptr m_spUserCreateWithArrayResource; - std::shared_ptr m_spUserCreateWithListResource; - std::shared_ptr m_spUserUsernameResource; - std::shared_ptr m_spUserLoginResource; - std::shared_ptr m_spUserLogoutResource; + std::shared_ptr m_spUserResource; + std::shared_ptr m_spUserCreateWithArrayResource; + std::shared_ptr m_spUserCreateWithListResource; + std::shared_ptr m_spUserUsernameResource; + std::shared_ptr m_spUserLoginResource; + std::shared_ptr m_spUserLogoutResource; private: std::shared_ptr m_service; diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp index f639b6496aa0..4054fdf7b61e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h index f0e05f94c671..413d034776cd 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AdditionalPropertiesClass.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp index 68dc488b0101..70a21de40aef 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h index b15e9b4f817b..9bcf93c2f815 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/AllOfWithSingleRef.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp index d66dc0cd3fa0..f96dbedf518c 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h index a169127170d4..1897f5c2fe9a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Animal.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp index d392c00cad8b..e9d322c5f78a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h index 7c6aaa4da853..44855c2f7cc0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ApiResponse.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp index 7337e106b758..f5fd0123e9a0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h index e3d4ac811592..006e1949e70b 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfArrayOfNumberOnly.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp index 5f6d0e2f855f..092456f1f4e8 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h index b0ed3cb04ea8..4dbb6b6d510e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayOfNumberOnly.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp index 57afa82d7909..7224498265b0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h index 5a936f1846c2..66f056b46c39 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ArrayTest.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp index 2cd6cb205b3a..ca2a78748afd 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h index 426bdcd6a2d3..12b7cb06253e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Capitalization.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp index 4407e6c56ccd..cc5110096e1a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h index 3a1197e7dd0f..03b0473407cb 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Cat.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp index fac4005500da..95f2c3aa6546 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h index edba27ba2aaf..7077c92c76cb 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Category.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.cpp index a9f0e8b87707..3294bcfc0032 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.h index fa759c34a63d..09810025cfc8 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ChildWithNullable.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp index 92b063afe693..faa6d51140e7 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h index 438658071d88..cacb8576d717 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ClassModel.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp index 7b81b445fde8..84744bea4757 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h index 6f397154b580..6536b50c4135 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Client.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp index 474196c81679..850a8df11924 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h index 3384cb30a916..297348cb00c0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/DeprecatedObject.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp index 4dbe28a20650..23bd7b469d91 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h index aa32d331eb95..a5b177e23d4b 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Dog.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp index 46259268ed69..eb49841d8fb2 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h index fab7126a9fbd..a07bdd6e0e2a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumArrays.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp index e9c4f22f78f0..ad044d48cea3 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h index a9d51d81ddc6..8d24be806f20 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/EnumClass.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp index 9d6729df2628..f8046c572989 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h index 96907f96cfc6..897978862e74 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Enum_Test.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.cpp index b09e8ebb1339..2f1da008a5a4 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.h index 78f713389b73..cda2279c7ec4 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FakeBigDecimalMap_200_response.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp index 02e757cfc875..3c6547871edf 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h index 6a11ee350f6a..7b447f28b74b 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/File.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp index 0c93c8bf8296..2968e752f9ad 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h index 30f2bd83445d..b8f4bccac5cf 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/FileSchemaTestClass.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp index fe9264a14772..7262502b7c14 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h index 63788973d8c1..24fa719f6836 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Foo.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp index 81fffb9c9a8e..4bcf9450e768 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h index b910fec8c9d4..a4af77d4c273 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Format_test.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp index 18516a134057..9b94c6a0e60d 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h index b1320dec3847..ce5d985ad446 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HasOnlyReadOnly.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp index d8e27e37c58c..5b4cfedd8411 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h index 494c2de0eaab..1c47483df28c 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/HealthCheckResult.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp index 44fa37e81a0b..d2154cc6f790 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h index c204ee774923..ab2551d00675 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/List.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp index 4f993f0bfbc7..f61ea2c637c0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h index abce4fced57c..b89508de0119 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MapTest.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp index ed22d11fbfe0..69000f7cb428 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h index 765a9b57fbf1..c55ce8418118 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/MixedPropertiesAndAdditionalPropertiesClass.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp index 3410be5ba569..1cd61850356c 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h index 7d1da5eb818a..4a66a66b75df 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Name.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp index 557a91641fe4..de4fac52e7b4 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h index 7fbe1201b805..ac983f371c2e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NullableClass.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp index b517063a3529..cdb95798c236 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h index 2c26c173fb49..b30d1230a3dc 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/NumberOnly.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp index 76d7fc447e2b..3f17959229de 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h index 6efd93e23e53..058ed4f34b2f 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ObjectWithDeprecatedFields.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp index dd49a1c52803..dced28055d05 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h index 9c87055ebe90..6d0e7636da5f 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Order.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp index f32037763242..7d7429bedb6f 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h index a17458cfd45c..052bc623bed3 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterComposite.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp index 3f4545879e77..891a60258811 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h index 8bc5090beb94..0dab7b1cfed0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnum.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp index 2421acd14be2..50f5d58cf706 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h index c48a9e9c6f8b..75cccfb65cc5 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumDefaultValue.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp index e607454a025a..a5783ca544d9 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h index 860b7d8ca73a..3a44abe4b77a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumInteger.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp index 283d888542c3..5691db6dcf14 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h index c2001c0c702f..eca674682882 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterEnumIntegerDefaultValue.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp index 78f44dc15196..21a4027886a2 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h index 54894bbae9bd..19a113f9ffc6 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/OuterObjectWithEnumProperty.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.cpp index 11781e0f2d32..9ba696e72136 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.h index 9fad5f85d671..c2a09a6ce65e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ParentWithNullable.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp index 64da3ddb67cb..8b714a391ebb 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h index 4c1106f0ce2f..793d6271b975 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Pet.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp index 036d7f80b52a..6b1f17498d72 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h index c24d57254556..ca4d74cc8359 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/ReadOnlyFirst.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp index b541e7f5a67d..e24a4d03b9fd 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h index e37268b88c1a..4f82a28a33d4 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Return.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp index 64a5bba64507..ef8936ab2138 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h index 40ce96531787..22d227f9f4e0 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/SingleRefType.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp index 279984549178..452184bc113b 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h index 23a8064981b9..cebb8f0bd132 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/Tag.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.cpp index 0bb87b05b29d..fcacb473917f 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.h index 89fbf4f6d3fb..5a0014d109a1 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/TestInlineFreeformAdditionalProperties_request.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp index 867bd99903d6..4b25837b3f48 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h index 3208a015d822..b9409bb05e1e 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/User.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp index 8b0d1a049716..eefba5ccb1e1 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h index c253d0a4fbe9..0b046df45a51 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_foo_get_default_response.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp index c865e3c08254..8f280866f319 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h index 47174bdb340b..30c70707c01a 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/_special_model_name_.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h index 1777c3b1e35f..c47a84b4b918 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/helpers.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp index 112925d39e10..4ba7d2e0fbfd 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.cpp @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h index d343697ca47a..5d1e860ef3dc 100644 --- a/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h +++ b/samples/server/petstore/cpp-restbed/generated/3_0/model/r_200_response.h @@ -5,7 +5,7 @@ * The version of the OpenAPI document: 1.0.0 * * - * NOTE: This class is auto generated by OpenAPI-Generator 7.1.0-SNAPSHOT. + * NOTE: This class is auto generated by OpenAPI-Generator 7.3.0-SNAPSHOT. * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/erlang-server/.openapi-generator/VERSION b/samples/server/petstore/erlang-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/erlang-server/.openapi-generator/VERSION +++ b/samples/server/petstore/erlang-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-api-server/.openapi-generator/FILES b/samples/server/petstore/go-api-server/.openapi-generator/FILES index 4c3a2a3a7c74..a02f1779f262 100644 --- a/samples/server/petstore/go-api-server/.openapi-generator/FILES +++ b/samples/server/petstore/go-api-server/.openapi-generator/FILES @@ -16,10 +16,13 @@ go/logger.go go/model_an_object.go go/model_api_response.go go/model_category.go +go/model_colour.go +go/model_gender.go go/model_order.go go/model_order_info.go go/model_pet.go go/model_special_info.go +go/model_species.go go/model_tag.go go/model_user.go go/routers.go diff --git a/samples/server/petstore/go-api-server/.openapi-generator/VERSION b/samples/server/petstore/go-api-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/go-api-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-api-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-api-server/api/openapi.yaml b/samples/server/petstore/go-api-server/api/openapi.yaml index cc433a6afd59..65a86866857a 100644 --- a/samples/server/petstore/go-api-server/api/openapi.yaml +++ b/samples/server/petstore/go-api-server/api/openapi.yaml @@ -81,6 +81,30 @@ paths: description: Multiple status values can be provided with comma separated strings operationId: findPetsByStatus parameters: + - description: Entity type + explode: false + in: path + name: inlineEnumPath + required: false + schema: + enum: + - OPTION_1 + - OPTION_2 + - OPTION_3 + type: string + style: simple + - description: Entity type + explode: true + in: query + name: inlineEnum + required: false + schema: + enum: + - OPTION_1 + - OPTION_2 + - OPTION_3 + type: string + style: form - deprecated: true description: Status values that need to be considered for filter explode: false @@ -119,6 +143,61 @@ paths: summary: Finds Pets by status tags: - pet + /pet/searchPetWithManyFilters: + get: + description: Search endpoint + operationId: searchPet + parameters: + - description: age of the pet + explode: true + in: query + name: age + required: false + schema: + format: int64 + nullable: true + type: integer + style: form + - description: Price of the pet + explode: true + in: query + name: price + required: false + schema: + nullable: true + type: number + style: form + - description: Find pets born after this date + explode: false + in: query + name: bornAfter + required: false + schema: + format: date-time + nullable: true + type: string + style: form + - description: Is the pet classified as old + explode: true + in: query + name: old + required: false + schema: + nullable: true + type: boolean + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + summary: Search Pets by filters + tags: + - pet /pet/findByTags: get: deprecated: true @@ -136,6 +215,31 @@ paths: type: string type: array style: form + - description: Find pets born after this date + explode: false + in: query + name: bornAfter + required: true + schema: + format: date-time + type: string + style: form + - description: Find pets born before this date + explode: false + in: query + name: bornBefore + required: false + schema: + format: date-time + type: string + style: form + - explode: true + in: query + name: colour + required: false + schema: + $ref: '#/components/schemas/Colour' + style: form responses: "200": content: @@ -158,6 +262,54 @@ paths: summary: Finds Pets by tags tags: - pet + /pet/filterPets/{gender}: + get: + operationId: filterPetsByCategory + parameters: + - explode: false + in: path + name: gender + required: true + schema: + $ref: '#/components/schemas/Gender' + style: simple + - description: Species to filter by + explode: false + in: query + name: species + required: true + schema: + $ref: '#/components/schemas/Species' + style: form + - description: Species to omit from results + explode: false + in: query + name: notSpecies + required: false + schema: + items: + $ref: '#/components/schemas/Species' + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid species value + summary: Finds Pets + tags: + - pet /pet/{petId}: delete: description: "" @@ -250,6 +402,34 @@ paths: tags: - pet /pet/{petId}/uploadImage: + get: + description: Returns the image for the Pet that has been previously uploaded + operationId: getPetImageById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + image/jpeg: + schema: + format: binary + type: string + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + summary: Returns the image for the Pet that has been previously uploaded + tags: + - pet post: description: "" operationId: uploadFile @@ -598,6 +778,97 @@ paths: summary: Updated user tags: - user + /fake/uploadImage/array of_file: + post: + description: "" + operationId: uploadFileArrayOfFiles + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileArrayOfFiles_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads images (array of files) + tags: + - pet + /pets/boolean/parsing: + get: + operationId: GetPetsUsingBooleanQueryParameters + parameters: + - explode: true + in: query + name: expr + required: true + schema: + type: boolean + style: form + - explode: true + in: query + name: grouping + required: false + schema: + type: boolean + style: form + - explode: true + in: query + name: inactive + required: false + schema: + default: false + type: boolean + style: form + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + summary: Get the pets by only using boolean query parameters + tags: + - pet + /pets/byTime/{createdTime}: + get: + operationId: GetPetsByTime + parameters: + - explode: false + in: path + name: createdTime + required: true + schema: + format: date-time + type: string + style: simple + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + summary: Get the pets by time + tags: + - pet components: requestBodies: UserArray: @@ -987,6 +1258,26 @@ components: type: object xml: name: Pet + Species: + enum: + - cat + - dog + - fish + - goat + - pig + title: The species of a pet + type: string + Gender: + enum: + - male + - female + type: string + Colour: + enum: + - Blue + - White + nullable: true + type: string ApiResponse: description: Describes the result of uploading an image resource example: @@ -1017,11 +1308,28 @@ components: additionalMetadata: description: Additional data to pass to server type: string + extraOptionalMetadata: + description: More data to pass to server + items: + type: string + type: array file: description: file to upload format: binary type: string type: object + uploadFileArrayOfFiles_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + files: + description: files to upload + items: + format: binary + type: string + type: array + type: object an_Object: description: An array 3-deep. example: diff --git a/samples/server/petstore/go-api-server/go/api.go b/samples/server/petstore/go-api-server/go/api.go index 0f6f14dea75f..a1ab21e90417 100644 --- a/samples/server/petstore/go-api-server/go/api.go +++ b/samples/server/petstore/go-api-server/go/api.go @@ -12,6 +12,7 @@ package petstoreserver import ( "context" "net/http" + "time" "os" ) @@ -23,13 +24,19 @@ import ( type PetAPIRouter interface { AddPet(http.ResponseWriter, *http.Request) DeletePet(http.ResponseWriter, *http.Request) + FilterPetsByCategory(http.ResponseWriter, *http.Request) FindPetsByStatus(http.ResponseWriter, *http.Request) // Deprecated FindPetsByTags(http.ResponseWriter, *http.Request) GetPetById(http.ResponseWriter, *http.Request) + GetPetImageById(http.ResponseWriter, *http.Request) + GetPetsByTime(http.ResponseWriter, *http.Request) + GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) + SearchPet(http.ResponseWriter, *http.Request) UpdatePet(http.ResponseWriter, *http.Request) UpdatePetWithForm(http.ResponseWriter, *http.Request) UploadFile(http.ResponseWriter, *http.Request) + UploadFileArrayOfFiles(http.ResponseWriter, *http.Request) } // StoreAPIRouter defines the required methods for binding the api requests to a responses for the StoreAPI // The StoreAPIRouter implementation should parse necessary information from the http request, @@ -62,13 +69,19 @@ type UserAPIRouter interface { type PetAPIServicer interface { AddPet(context.Context, Pet) (ImplResponse, error) DeletePet(context.Context, int64, string) (ImplResponse, error) - FindPetsByStatus(context.Context, []string) (ImplResponse, error) + FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) + FindPetsByStatus(context.Context, []string, string, string) (ImplResponse, error) // Deprecated - FindPetsByTags(context.Context, []string) (ImplResponse, error) + FindPetsByTags(context.Context, []string, time.Time, time.Time, Colour) (ImplResponse, error) GetPetById(context.Context, int64) (ImplResponse, error) + GetPetImageById(context.Context, int64) (ImplResponse, error) + GetPetsByTime(context.Context, time.Time) (ImplResponse, error) + GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) + SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) UpdatePet(context.Context, Pet) (ImplResponse, error) UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error) - UploadFile(context.Context, int64, string, *os.File) (ImplResponse, error) + UploadFile(context.Context, int64, string, []string, *os.File) (ImplResponse, error) + UploadFileArrayOfFiles(context.Context, int64, string, []*os.File) (ImplResponse, error) } diff --git a/samples/server/petstore/go-api-server/go/api_pet.go b/samples/server/petstore/go-api-server/go/api_pet.go index 0161ba41d6cf..925d27a78ecb 100644 --- a/samples/server/petstore/go-api-server/go/api_pet.go +++ b/samples/server/petstore/go-api-server/go/api_pet.go @@ -13,6 +13,8 @@ import ( "encoding/json" "net/http" "strings" + "time" + "os" "github.com/gorilla/mux" ) @@ -60,6 +62,11 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}", c.DeletePet, }, + "FilterPetsByCategory": Route{ + strings.ToUpper("Get"), + "/v2/pet/filterPets/{gender}", + c.FilterPetsByCategory, + }, "FindPetsByStatus": Route{ strings.ToUpper("Get"), "/v2/pet/findByStatus", @@ -75,6 +82,26 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}", c.GetPetById, }, + "GetPetImageById": Route{ + strings.ToUpper("Get"), + "/v2/pet/{petId}/uploadImage", + c.GetPetImageById, + }, + "GetPetsByTime": Route{ + strings.ToUpper("Get"), + "/v2/pets/byTime/{createdTime}", + c.GetPetsByTime, + }, + "GetPetsUsingBooleanQueryParameters": Route{ + strings.ToUpper("Get"), + "/v2/pets/boolean/parsing", + c.GetPetsUsingBooleanQueryParameters, + }, + "SearchPet": Route{ + strings.ToUpper("Get"), + "/v2/pet/searchPetWithManyFilters", + c.SearchPet, + }, "UpdatePet": Route{ strings.ToUpper("Put"), "/v2/pet", @@ -90,6 +117,11 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}/uploadImage", c.UploadFile, }, + "UploadFileArrayOfFiles": Route{ + strings.ToUpper("Post"), + "/v2/fake/uploadImage/array of_file", + c.UploadFileArrayOfFiles, + }, } } @@ -142,11 +174,68 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// FilterPetsByCategory - Finds Pets +func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + query := r.URL.Query() + genderParam, err := NewGenderFromValue(params["gender"]) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var speciesParam Species + if query.Has("species") { + param := Species(query.Get("species")) + + speciesParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + return + } + var notSpeciesParam []Species + if query.Has("notSpecies") { + paramSplits := strings.Split(query.Get("notSpecies"), ",") + notSpeciesParam = make([]Species, 0, len(paramSplits)) + for _, param := range paramSplits { + paramEnum, err := NewSpeciesFromValue(param) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + notSpeciesParam = append(notSpeciesParam, paramEnum) + } + } + result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // FindPetsByStatus - Finds Pets by status func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) query := r.URL.Query() - statusParam := strings.Split(query.Get("status"), ",") - result, err := c.service.FindPetsByStatus(r.Context(), statusParam) + var statusParam []string + if query.Has("status") { + statusParam = strings.Split(query.Get("status"), ",") + } + inlineEnumPathParam := params["inlineEnumPath"] + if inlineEnumPathParam == "" { + c.errorHandler(w, r, &RequiredError{"inlineEnumPath"}, nil) + return + } + var inlineEnumParam string + if query.Has("inlineEnum") { + param := query.Get("inlineEnum") + + inlineEnumParam = param + } else { + } + result, err := c.service.FindPetsByStatus(r.Context(), statusParam, inlineEnumPathParam, inlineEnumParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -160,8 +249,42 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque // Deprecated func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - tagsParam := strings.Split(query.Get("tags"), ",") - result, err := c.service.FindPetsByTags(r.Context(), tagsParam) + var tagsParam []string + if query.Has("tags") { + tagsParam = strings.Split(query.Get("tags"), ",") + } + var bornAfterParam time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornAfterParam = param + } else { + c.errorHandler(w, r, &RequiredError{"bornAfter"}, nil) + return + } + var bornBeforeParam time.Time + if query.Has("bornBefore"){ + param, err := parseTime(query.Get("bornBefore")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornBeforeParam = param + } else { + } + var colourParam Colour + if query.Has("colour") { + param := Colour(query.Get("colour")) + + colourParam = param + } else { + } + result, err := c.service.FindPetsByTags(r.Context(), tagsParam, bornAfterParam, bornBeforeParam, colourParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -192,6 +315,170 @@ func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + petIdParam, err := parseNumericParameter[int64]( + params["petId"], + WithRequire[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + result, err := c.service.GetPetImageById(r.Context(), petIdParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsByTime - Get the pets by time +func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { + params := mux.Vars(r) + createdTimeParam, err := parseTime(params["createdTime"]) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + var exprParam bool + if query.Has("expr") { + param, err := parseBoolParameter( + query.Get("expr"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + exprParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) + return + } + var groupingParam bool + if query.Has("grouping") { + param, err := parseBoolParameter( + query.Get("grouping"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + groupingParam = param + } else { + } + var inactiveParam bool + if query.Has("inactive") { + param, err := parseBoolParameter( + query.Get("inactive"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + inactiveParam = param + } else { + var param bool = false + inactiveParam = param + } + result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// SearchPet - Search Pets by filters +func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + var ageParam *int64 + if query.Has("age") { + param, err := parseNumericParameter[int64]( + query.Get("age"), + WithParse[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + ageParam = ¶m + } else { + } + var priceParam *float32 + if query.Has("price") { + param, err := parseNumericParameter[float32]( + query.Get("price"), + WithParse[float32](parseFloat32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + priceParam = ¶m + } else { + } + var bornAfterParam *time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornAfterParam = ¶m + } else { + } + var oldParam *bool + if query.Has("old") { + param, err := parseBoolParameter( + query.Get("old"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + oldParam = ¶m + } else { + } + result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // UpdatePet - Update an existing pet func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { petParam := Pet{} @@ -234,10 +521,10 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - + nameParam := r.FormValue("name") - + statusParam := r.FormValue("status") result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) @@ -265,18 +552,65 @@ func (c *PetAPIController) UploadFile(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - + additionalMetadataParam := r.FormValue("additionalMetadata") - fileParam, err := ReadFormFileToTempFile(r, "file") + + extraOptionalMetadataParam := strings.Split(r.FormValue("extraOptionalMetadata"), ",") + var fileParam *os.File + { + param, err := ReadFormFileToTempFile(r, "file") + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + fileParam = param + } + + + result, err := c.service.UploadFile(r.Context(), petIdParam, additionalMetadataParam, extraOptionalMetadataParam, fileParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// UploadFileArrayOfFiles - uploads images (array of files) +func (c *PetAPIController) UploadFileArrayOfFiles(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(32 << 20); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + params := mux.Vars(r) + petIdParam, err := parseNumericParameter[int64]( + params["petId"], + WithRequire[int64](parseInt64), + ) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.UploadFile(r.Context(), petIdParam, additionalMetadataParam, fileParam) + additionalMetadataParam := r.FormValue("additionalMetadata") + var filesParam []*os.File + { + param, err := ReadFormFilesToTempFiles(r, "files") + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + filesParam = param + } + + + result, err := c.service.UploadFileArrayOfFiles(r.Context(), petIdParam, additionalMetadataParam, filesParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/server/petstore/go-api-server/go/api_pet_service.go b/samples/server/petstore/go-api-server/go/api_pet_service.go index bda4cd897526..6044e65180e0 100644 --- a/samples/server/petstore/go-api-server/go/api_pet_service.go +++ b/samples/server/petstore/go-api-server/go/api_pet_service.go @@ -13,6 +13,7 @@ import ( "context" "net/http" "errors" + "time" "os" ) @@ -52,8 +53,22 @@ func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey strin return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") } +// FilterPetsByCategory - Finds Pets +func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { + // TODO - update FilterPetsByCategory with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") +} + // FindPetsByStatus - Finds Pets by status -func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string) (ImplResponse, error) { +func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string) (ImplResponse, error) { // TODO - update FindPetsByStatus with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -68,7 +83,7 @@ func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string) ( // FindPetsByTags - Finds Pets by tags // Deprecated -func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string) (ImplResponse, error) { +func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { // TODO - update FindPetsByTags with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -98,6 +113,56 @@ func (s *PetAPIService) GetPetById(ctx context.Context, petId int64) (ImplRespon return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented") } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplResponse, error) { + // TODO - update GetPetImageById with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, *os.File{}) or use other options such as http.Ok ... + // return Response(200, *os.File{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetImageById method not implemented") +} + +// GetPetsByTime - Get the pets by time +func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { + // TODO - update GetPetsByTime with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") +} + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { + // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") +} + +// SearchPet - Search Pets by filters +func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { + // TODO - update SearchPet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") +} + // UpdatePet - Update an existing pet func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { // TODO - update UpdatePet with the required logic for this service method. @@ -130,7 +195,7 @@ func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name } // UploadFile - uploads an image -func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, file *os.File) (ImplResponse, error) { +func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { // TODO - update UploadFile with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -139,3 +204,14 @@ func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalM return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") } + +// UploadFileArrayOfFiles - uploads images (array of files) +func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { + // TODO - update UploadFileArrayOfFiles with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") +} diff --git a/samples/server/petstore/go-api-server/go/api_store.go b/samples/server/petstore/go-api-server/go/api_store.go index df87b17defa6..a9cf01dd74ef 100644 --- a/samples/server/petstore/go-api-server/go/api_store.go +++ b/samples/server/petstore/go-api-server/go/api_store.go @@ -77,6 +77,10 @@ func (c *StoreAPIController) Routes() Routes { func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) orderIdParam := params["orderId"] + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) + return + } result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { diff --git a/samples/server/petstore/go-api-server/go/api_user.go b/samples/server/petstore/go-api-server/go/api_user.go index cb2aff7dd434..2828512c89ff 100644 --- a/samples/server/petstore/go-api-server/go/api_user.go +++ b/samples/server/petstore/go-api-server/go/api_user.go @@ -175,14 +175,24 @@ func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) query := r.URL.Query() usernameParam := params["username"] - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) return } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } result, err := c.service.DeleteUser(r.Context(), usernameParam, booleanTestParam) // If an error occurred, encode the error with the status code if err != nil { @@ -197,6 +207,10 @@ func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) usernameParam := params["username"] + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } result, err := c.service.GetUserByName(r.Context(), usernameParam) // If an error occurred, encode the error with the status code if err != nil { @@ -210,16 +224,38 @@ func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - usernameParam := query.Get("username") - passwordParam := query.Get("password") - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) + var usernameParam string + if query.Has("username") { + param := query.Get("username") + + usernameParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "username"}, nil) return } + var passwordParam string + if query.Has("password") { + param := query.Get("password") + + passwordParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "password"}, nil) + return + } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } result, err := c.service.LoginUser(r.Context(), usernameParam, passwordParam, booleanTestParam) // If an error occurred, encode the error with the status code if err != nil { @@ -246,6 +282,10 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { params := mux.Vars(r) usernameParam := params["username"] + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } userParam := User{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() diff --git a/samples/server/petstore/go-api-server/go/model_colour.go b/samples/server/petstore/go-api-server/go/model_colour.go new file mode 100644 index 000000000000..3a1569cd0961 --- /dev/null +++ b/samples/server/petstore/go-api-server/go/model_colour.go @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Colour string + +// List of Colour +const ( + BLUE Colour = "Blue" + WHITE Colour = "White" +) + +// AllowedColourEnumValues is all the allowed values of Colour enum +var AllowedColourEnumValues = []Colour{ + "Blue", + "White", +} + +// validColourEnumValue provides a map of Colours for fast verification of use input +var validColourEnumValues = map[Colour]struct{}{ + "Blue": {}, + "White": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Colour) IsValid() bool { + _, ok := validColourEnumValues[v] + return ok +} + +// NewColourFromValue returns a pointer to a valid Colour +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewColourFromValue(v string) (Colour, error) { + ev := Colour(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Colour: valid values are %v", v, AllowedColourEnumValues) + } +} + + + +// AssertColourRequired checks if the required fields are not zero-ed +func AssertColourRequired(obj Colour) error { + return nil +} + +// AssertColourConstraints checks if the values respects the defined constraints +func AssertColourConstraints(obj Colour) error { + return nil +} diff --git a/samples/server/petstore/go-api-server/go/model_gender.go b/samples/server/petstore/go-api-server/go/model_gender.go new file mode 100644 index 000000000000..16583a0c400b --- /dev/null +++ b/samples/server/petstore/go-api-server/go/model_gender.go @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Gender string + +// List of Gender +const ( + MALE Gender = "male" + FEMALE Gender = "female" +) + +// AllowedGenderEnumValues is all the allowed values of Gender enum +var AllowedGenderEnumValues = []Gender{ + "male", + "female", +} + +// validGenderEnumValue provides a map of Genders for fast verification of use input +var validGenderEnumValues = map[Gender]struct{}{ + "male": {}, + "female": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Gender) IsValid() bool { + _, ok := validGenderEnumValues[v] + return ok +} + +// NewGenderFromValue returns a pointer to a valid Gender +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewGenderFromValue(v string) (Gender, error) { + ev := Gender(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Gender: valid values are %v", v, AllowedGenderEnumValues) + } +} + + + +// AssertGenderRequired checks if the required fields are not zero-ed +func AssertGenderRequired(obj Gender) error { + return nil +} + +// AssertGenderConstraints checks if the values respects the defined constraints +func AssertGenderConstraints(obj Gender) error { + return nil +} diff --git a/samples/server/petstore/go-api-server/go/model_species.go b/samples/server/petstore/go-api-server/go/model_species.go new file mode 100644 index 000000000000..4e6fc567e6a4 --- /dev/null +++ b/samples/server/petstore/go-api-server/go/model_species.go @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Species string + +// List of Species +const ( + CAT Species = "cat" + DOG Species = "dog" + FISH Species = "fish" + GOAT Species = "goat" + PIG Species = "pig" +) + +// AllowedSpeciesEnumValues is all the allowed values of Species enum +var AllowedSpeciesEnumValues = []Species{ + "cat", + "dog", + "fish", + "goat", + "pig", +} + +// validSpeciesEnumValue provides a map of Speciess for fast verification of use input +var validSpeciesEnumValues = map[Species]struct{}{ + "cat": {}, + "dog": {}, + "fish": {}, + "goat": {}, + "pig": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Species) IsValid() bool { + _, ok := validSpeciesEnumValues[v] + return ok +} + +// NewSpeciesFromValue returns a pointer to a valid Species +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewSpeciesFromValue(v string) (Species, error) { + ev := Species(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Species: valid values are %v", v, AllowedSpeciesEnumValues) + } +} + + + +// AssertSpeciesRequired checks if the required fields are not zero-ed +func AssertSpeciesRequired(obj Species) error { + return nil +} + +// AssertSpeciesConstraints checks if the values respects the defined constraints +func AssertSpeciesConstraints(obj Species) error { + return nil +} diff --git a/samples/server/petstore/go-api-server/go/routers.go b/samples/server/petstore/go-api-server/go/routers.go index 1fb27970fdcc..a22936ca05a6 100644 --- a/samples/server/petstore/go-api-server/go/routers.go +++ b/samples/server/petstore/go-api-server/go/routers.go @@ -12,8 +12,9 @@ package petstoreserver import ( "encoding/json" "errors" + "time" "github.com/gorilla/mux" - "io/ioutil" + "io" "mime/multipart" "net/http" "os" @@ -68,7 +69,25 @@ func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, wHeader.Add(key, value) } } + + f, ok := i.(*os.File) + if ok { + data, err := io.ReadAll(f) + if err != nil { + return err + } + wHeader.Set("Content-Type", http.DetectContentType(data)) + wHeader.Set("Content-Disposition", "attachment; filename="+f.Name()) + if status != nil { + w.WriteHeader(*status) + } else { + w.WriteHeader(http.StatusOK) + } + _, err = w.Write(data) + return err + } wHeader.Set("Content-Type", "application/json; charset=UTF-8") + if status != nil { w.WriteHeader(*status) } else { @@ -121,21 +140,42 @@ func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error defer formFile.Close() - fileBytes, err := ioutil.ReadAll(formFile) + // Use .* as suffix, because the asterisk is a placeholder for the random value, + // and the period allows consumers of this file to remove the suffix to obtain the original file name + file, err := os.CreateTemp("", fileHeader.Filename+".*") if err != nil { return nil, err } - file, err := ioutil.TempFile("", fileHeader.Filename) + defer file.Close() + + _, err = io.Copy(file, formFile) if err != nil { return nil, err } + + return file, nil +} - defer file.Close() - - file.Write(fileBytes) +func parseTimes(param string) ([]time.Time, error) { + splits := strings.Split(param, ",") + times := make([]time.Time, 0, len(splits)) + for _, v := range splits { + t, err := parseTime(v) + if err != nil { + return nil, err + } + times = append(times, t) + } + return times, nil +} - return file, nil +// parseTime will parses a string parameter into a time.Time using the RFC3339 format +func parseTime(param string) (time.Time, error) { + if param == "" { + return time.Time{}, nil + } + return time.Parse(time.RFC3339, param) } type Number interface { diff --git a/samples/server/petstore/go-chi-server/.openapi-generator/FILES b/samples/server/petstore/go-chi-server/.openapi-generator/FILES index 4c3a2a3a7c74..a02f1779f262 100644 --- a/samples/server/petstore/go-chi-server/.openapi-generator/FILES +++ b/samples/server/petstore/go-chi-server/.openapi-generator/FILES @@ -16,10 +16,13 @@ go/logger.go go/model_an_object.go go/model_api_response.go go/model_category.go +go/model_colour.go +go/model_gender.go go/model_order.go go/model_order_info.go go/model_pet.go go/model_special_info.go +go/model_species.go go/model_tag.go go/model_user.go go/routers.go diff --git a/samples/server/petstore/go-chi-server/.openapi-generator/VERSION b/samples/server/petstore/go-chi-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/go-chi-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-chi-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-chi-server/api/openapi.yaml b/samples/server/petstore/go-chi-server/api/openapi.yaml index cc433a6afd59..65a86866857a 100644 --- a/samples/server/petstore/go-chi-server/api/openapi.yaml +++ b/samples/server/petstore/go-chi-server/api/openapi.yaml @@ -81,6 +81,30 @@ paths: description: Multiple status values can be provided with comma separated strings operationId: findPetsByStatus parameters: + - description: Entity type + explode: false + in: path + name: inlineEnumPath + required: false + schema: + enum: + - OPTION_1 + - OPTION_2 + - OPTION_3 + type: string + style: simple + - description: Entity type + explode: true + in: query + name: inlineEnum + required: false + schema: + enum: + - OPTION_1 + - OPTION_2 + - OPTION_3 + type: string + style: form - deprecated: true description: Status values that need to be considered for filter explode: false @@ -119,6 +143,61 @@ paths: summary: Finds Pets by status tags: - pet + /pet/searchPetWithManyFilters: + get: + description: Search endpoint + operationId: searchPet + parameters: + - description: age of the pet + explode: true + in: query + name: age + required: false + schema: + format: int64 + nullable: true + type: integer + style: form + - description: Price of the pet + explode: true + in: query + name: price + required: false + schema: + nullable: true + type: number + style: form + - description: Find pets born after this date + explode: false + in: query + name: bornAfter + required: false + schema: + format: date-time + nullable: true + type: string + style: form + - description: Is the pet classified as old + explode: true + in: query + name: old + required: false + schema: + nullable: true + type: boolean + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + summary: Search Pets by filters + tags: + - pet /pet/findByTags: get: deprecated: true @@ -136,6 +215,31 @@ paths: type: string type: array style: form + - description: Find pets born after this date + explode: false + in: query + name: bornAfter + required: true + schema: + format: date-time + type: string + style: form + - description: Find pets born before this date + explode: false + in: query + name: bornBefore + required: false + schema: + format: date-time + type: string + style: form + - explode: true + in: query + name: colour + required: false + schema: + $ref: '#/components/schemas/Colour' + style: form responses: "200": content: @@ -158,6 +262,54 @@ paths: summary: Finds Pets by tags tags: - pet + /pet/filterPets/{gender}: + get: + operationId: filterPetsByCategory + parameters: + - explode: false + in: path + name: gender + required: true + schema: + $ref: '#/components/schemas/Gender' + style: simple + - description: Species to filter by + explode: false + in: query + name: species + required: true + schema: + $ref: '#/components/schemas/Species' + style: form + - description: Species to omit from results + explode: false + in: query + name: notSpecies + required: false + schema: + items: + $ref: '#/components/schemas/Species' + type: array + style: form + responses: + "200": + content: + application/xml: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + application/json: + schema: + items: + $ref: '#/components/schemas/Pet' + type: array + description: successful operation + "400": + description: Invalid species value + summary: Finds Pets + tags: + - pet /pet/{petId}: delete: description: "" @@ -250,6 +402,34 @@ paths: tags: - pet /pet/{petId}/uploadImage: + get: + description: Returns the image for the Pet that has been previously uploaded + operationId: getPetImageById + parameters: + - description: ID of pet to return + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + responses: + "200": + content: + image/jpeg: + schema: + format: binary + type: string + description: successful operation + "400": + description: Invalid ID supplied + "404": + description: Pet not found + summary: Returns the image for the Pet that has been previously uploaded + tags: + - pet post: description: "" operationId: uploadFile @@ -598,6 +778,97 @@ paths: summary: Updated user tags: - user + /fake/uploadImage/array of_file: + post: + description: "" + operationId: uploadFileArrayOfFiles + parameters: + - description: ID of pet to update + explode: false + in: path + name: petId + required: true + schema: + format: int64 + type: integer + style: simple + requestBody: + content: + multipart/form-data: + schema: + $ref: '#/components/schemas/uploadFileArrayOfFiles_request' + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + security: + - petstore_auth: + - write:pets + - read:pets + summary: uploads images (array of files) + tags: + - pet + /pets/boolean/parsing: + get: + operationId: GetPetsUsingBooleanQueryParameters + parameters: + - explode: true + in: query + name: expr + required: true + schema: + type: boolean + style: form + - explode: true + in: query + name: grouping + required: false + schema: + type: boolean + style: form + - explode: true + in: query + name: inactive + required: false + schema: + default: false + type: boolean + style: form + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + summary: Get the pets by only using boolean query parameters + tags: + - pet + /pets/byTime/{createdTime}: + get: + operationId: GetPetsByTime + parameters: + - explode: false + in: path + name: createdTime + required: true + schema: + format: date-time + type: string + style: simple + responses: + "200": + content: + application/json: + schema: + $ref: '#/components/schemas/ApiResponse' + description: successful operation + summary: Get the pets by time + tags: + - pet components: requestBodies: UserArray: @@ -987,6 +1258,26 @@ components: type: object xml: name: Pet + Species: + enum: + - cat + - dog + - fish + - goat + - pig + title: The species of a pet + type: string + Gender: + enum: + - male + - female + type: string + Colour: + enum: + - Blue + - White + nullable: true + type: string ApiResponse: description: Describes the result of uploading an image resource example: @@ -1017,11 +1308,28 @@ components: additionalMetadata: description: Additional data to pass to server type: string + extraOptionalMetadata: + description: More data to pass to server + items: + type: string + type: array file: description: file to upload format: binary type: string type: object + uploadFileArrayOfFiles_request: + properties: + additionalMetadata: + description: Additional data to pass to server + type: string + files: + description: files to upload + items: + format: binary + type: string + type: array + type: object an_Object: description: An array 3-deep. example: diff --git a/samples/server/petstore/go-chi-server/go/api.go b/samples/server/petstore/go-chi-server/go/api.go index 0f6f14dea75f..a1ab21e90417 100644 --- a/samples/server/petstore/go-chi-server/go/api.go +++ b/samples/server/petstore/go-chi-server/go/api.go @@ -12,6 +12,7 @@ package petstoreserver import ( "context" "net/http" + "time" "os" ) @@ -23,13 +24,19 @@ import ( type PetAPIRouter interface { AddPet(http.ResponseWriter, *http.Request) DeletePet(http.ResponseWriter, *http.Request) + FilterPetsByCategory(http.ResponseWriter, *http.Request) FindPetsByStatus(http.ResponseWriter, *http.Request) // Deprecated FindPetsByTags(http.ResponseWriter, *http.Request) GetPetById(http.ResponseWriter, *http.Request) + GetPetImageById(http.ResponseWriter, *http.Request) + GetPetsByTime(http.ResponseWriter, *http.Request) + GetPetsUsingBooleanQueryParameters(http.ResponseWriter, *http.Request) + SearchPet(http.ResponseWriter, *http.Request) UpdatePet(http.ResponseWriter, *http.Request) UpdatePetWithForm(http.ResponseWriter, *http.Request) UploadFile(http.ResponseWriter, *http.Request) + UploadFileArrayOfFiles(http.ResponseWriter, *http.Request) } // StoreAPIRouter defines the required methods for binding the api requests to a responses for the StoreAPI // The StoreAPIRouter implementation should parse necessary information from the http request, @@ -62,13 +69,19 @@ type UserAPIRouter interface { type PetAPIServicer interface { AddPet(context.Context, Pet) (ImplResponse, error) DeletePet(context.Context, int64, string) (ImplResponse, error) - FindPetsByStatus(context.Context, []string) (ImplResponse, error) + FilterPetsByCategory(context.Context, Gender, Species, []Species) (ImplResponse, error) + FindPetsByStatus(context.Context, []string, string, string) (ImplResponse, error) // Deprecated - FindPetsByTags(context.Context, []string) (ImplResponse, error) + FindPetsByTags(context.Context, []string, time.Time, time.Time, Colour) (ImplResponse, error) GetPetById(context.Context, int64) (ImplResponse, error) + GetPetImageById(context.Context, int64) (ImplResponse, error) + GetPetsByTime(context.Context, time.Time) (ImplResponse, error) + GetPetsUsingBooleanQueryParameters(context.Context, bool, bool, bool) (ImplResponse, error) + SearchPet(context.Context, *int64, *float32, *time.Time, *bool) (ImplResponse, error) UpdatePet(context.Context, Pet) (ImplResponse, error) UpdatePetWithForm(context.Context, int64, string, string) (ImplResponse, error) - UploadFile(context.Context, int64, string, *os.File) (ImplResponse, error) + UploadFile(context.Context, int64, string, []string, *os.File) (ImplResponse, error) + UploadFileArrayOfFiles(context.Context, int64, string, []*os.File) (ImplResponse, error) } diff --git a/samples/server/petstore/go-chi-server/go/api_pet.go b/samples/server/petstore/go-chi-server/go/api_pet.go index 0efd81a77e9f..322476ada1a8 100644 --- a/samples/server/petstore/go-chi-server/go/api_pet.go +++ b/samples/server/petstore/go-chi-server/go/api_pet.go @@ -13,6 +13,8 @@ import ( "encoding/json" "net/http" "strings" + "time" + "os" "github.com/go-chi/chi/v5" ) @@ -60,6 +62,11 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}", c.DeletePet, }, + "FilterPetsByCategory": Route{ + strings.ToUpper("Get"), + "/v2/pet/filterPets/{gender}", + c.FilterPetsByCategory, + }, "FindPetsByStatus": Route{ strings.ToUpper("Get"), "/v2/pet/findByStatus", @@ -75,6 +82,26 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}", c.GetPetById, }, + "GetPetImageById": Route{ + strings.ToUpper("Get"), + "/v2/pet/{petId}/uploadImage", + c.GetPetImageById, + }, + "GetPetsByTime": Route{ + strings.ToUpper("Get"), + "/v2/pets/byTime/{createdTime}", + c.GetPetsByTime, + }, + "GetPetsUsingBooleanQueryParameters": Route{ + strings.ToUpper("Get"), + "/v2/pets/boolean/parsing", + c.GetPetsUsingBooleanQueryParameters, + }, + "SearchPet": Route{ + strings.ToUpper("Get"), + "/v2/pet/searchPetWithManyFilters", + c.SearchPet, + }, "UpdatePet": Route{ strings.ToUpper("Put"), "/v2/pet", @@ -90,6 +117,11 @@ func (c *PetAPIController) Routes() Routes { "/v2/pet/{petId}/uploadImage", c.UploadFile, }, + "UploadFileArrayOfFiles": Route{ + strings.ToUpper("Post"), + "/v2/fake/uploadImage/array of_file", + c.UploadFileArrayOfFiles, + }, } } @@ -141,11 +173,66 @@ func (c *PetAPIController) DeletePet(w http.ResponseWriter, r *http.Request) { EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// FilterPetsByCategory - Finds Pets +func (c *PetAPIController) FilterPetsByCategory(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + genderParam, err := NewGenderFromValue(chi.URLParam(r, "gender")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + var speciesParam Species + if query.Has("species") { + param := Species(query.Get("species")) + + speciesParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "species"}, nil) + return + } + var notSpeciesParam []Species + if query.Has("notSpecies") { + paramSplits := strings.Split(query.Get("notSpecies"), ",") + notSpeciesParam = make([]Species, 0, len(paramSplits)) + for _, param := range paramSplits { + paramEnum, err := NewSpeciesFromValue(param) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + notSpeciesParam = append(notSpeciesParam, paramEnum) + } + } + result, err := c.service.FilterPetsByCategory(r.Context(), genderParam, speciesParam, notSpeciesParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // FindPetsByStatus - Finds Pets by status func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - statusParam := strings.Split(query.Get("status"), ",") - result, err := c.service.FindPetsByStatus(r.Context(), statusParam) + var statusParam []string + if query.Has("status") { + statusParam = strings.Split(query.Get("status"), ",") + } + inlineEnumPathParam := chi.URLParam(r, "inlineEnumPath") + if inlineEnumPathParam == "" { + c.errorHandler(w, r, &RequiredError{"inlineEnumPath"}, nil) + return + } + var inlineEnumParam string + if query.Has("inlineEnum") { + param := query.Get("inlineEnum") + + inlineEnumParam = param + } else { + } + result, err := c.service.FindPetsByStatus(r.Context(), statusParam, inlineEnumPathParam, inlineEnumParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -159,8 +246,42 @@ func (c *PetAPIController) FindPetsByStatus(w http.ResponseWriter, r *http.Reque // Deprecated func (c *PetAPIController) FindPetsByTags(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - tagsParam := strings.Split(query.Get("tags"), ",") - result, err := c.service.FindPetsByTags(r.Context(), tagsParam) + var tagsParam []string + if query.Has("tags") { + tagsParam = strings.Split(query.Get("tags"), ",") + } + var bornAfterParam time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornAfterParam = param + } else { + c.errorHandler(w, r, &RequiredError{"bornAfter"}, nil) + return + } + var bornBeforeParam time.Time + if query.Has("bornBefore"){ + param, err := parseTime(query.Get("bornBefore")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornBeforeParam = param + } else { + } + var colourParam Colour + if query.Has("colour") { + param := Colour(query.Get("colour")) + + colourParam = param + } else { + } + result, err := c.service.FindPetsByTags(r.Context(), tagsParam, bornAfterParam, bornBeforeParam, colourParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) @@ -190,6 +311,168 @@ func (c *PetAPIController) GetPetById(w http.ResponseWriter, r *http.Request) { EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (c *PetAPIController) GetPetImageById(w http.ResponseWriter, r *http.Request) { + petIdParam, err := parseNumericParameter[int64]( + chi.URLParam(r, "petId"), + WithRequire[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + result, err := c.service.GetPetImageById(r.Context(), petIdParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsByTime - Get the pets by time +func (c *PetAPIController) GetPetsByTime(w http.ResponseWriter, r *http.Request) { + createdTimeParam, err := parseTime(chi.URLParam(r, "createdTime")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + result, err := c.service.GetPetsByTime(r.Context(), createdTimeParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (c *PetAPIController) GetPetsUsingBooleanQueryParameters(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + var exprParam bool + if query.Has("expr") { + param, err := parseBoolParameter( + query.Get("expr"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + exprParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "expr"}, nil) + return + } + var groupingParam bool + if query.Has("grouping") { + param, err := parseBoolParameter( + query.Get("grouping"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + groupingParam = param + } else { + } + var inactiveParam bool + if query.Has("inactive") { + param, err := parseBoolParameter( + query.Get("inactive"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + inactiveParam = param + } else { + var param bool = false + inactiveParam = param + } + result, err := c.service.GetPetsUsingBooleanQueryParameters(r.Context(), exprParam, groupingParam, inactiveParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// SearchPet - Search Pets by filters +func (c *PetAPIController) SearchPet(w http.ResponseWriter, r *http.Request) { + query := r.URL.Query() + var ageParam *int64 + if query.Has("age") { + param, err := parseNumericParameter[int64]( + query.Get("age"), + WithParse[int64](parseInt64), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + ageParam = ¶m + } else { + } + var priceParam *float32 + if query.Has("price") { + param, err := parseNumericParameter[float32]( + query.Get("price"), + WithParse[float32](parseFloat32), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + priceParam = ¶m + } else { + } + var bornAfterParam *time.Time + if query.Has("bornAfter"){ + param, err := parseTime(query.Get("bornAfter")) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + bornAfterParam = ¶m + } else { + } + var oldParam *bool + if query.Has("old") { + param, err := parseBoolParameter( + query.Get("old"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + oldParam = ¶m + } else { + } + result, err := c.service.SearchPet(r.Context(), ageParam, priceParam, bornAfterParam, oldParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + // UpdatePet - Update an existing pet func (c *PetAPIController) UpdatePet(w http.ResponseWriter, r *http.Request) { petParam := Pet{} @@ -231,10 +514,10 @@ func (c *PetAPIController) UpdatePetWithForm(w http.ResponseWriter, r *http.Requ c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - + nameParam := r.FormValue("name") - + statusParam := r.FormValue("status") result, err := c.service.UpdatePetWithForm(r.Context(), petIdParam, nameParam, statusParam) @@ -261,18 +544,64 @@ func (c *PetAPIController) UploadFile(w http.ResponseWriter, r *http.Request) { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - + additionalMetadataParam := r.FormValue("additionalMetadata") - fileParam, err := ReadFormFileToTempFile(r, "file") + + extraOptionalMetadataParam := strings.Split(r.FormValue("extraOptionalMetadata"), ",") + var fileParam *os.File + { + param, err := ReadFormFileToTempFile(r, "file") + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + fileParam = param + } + + + result, err := c.service.UploadFile(r.Context(), petIdParam, additionalMetadataParam, extraOptionalMetadataParam, fileParam) + // If an error occurred, encode the error with the status code + if err != nil { + c.errorHandler(w, r, err, &result) + return + } + // If no error, encode the body and the result code + EncodeJSONResponse(result.Body, &result.Code, result.Headers, w) +} + +// UploadFileArrayOfFiles - uploads images (array of files) +func (c *PetAPIController) UploadFileArrayOfFiles(w http.ResponseWriter, r *http.Request) { + if err := r.ParseMultipartForm(32 << 20); err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + petIdParam, err := parseNumericParameter[int64]( + chi.URLParam(r, "petId"), + WithRequire[int64](parseInt64), + ) if err != nil { c.errorHandler(w, r, &ParsingError{Err: err}, nil) return } - result, err := c.service.UploadFile(r.Context(), petIdParam, additionalMetadataParam, fileParam) + additionalMetadataParam := r.FormValue("additionalMetadata") + var filesParam []*os.File + { + param, err := ReadFormFilesToTempFiles(r, "files") + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + filesParam = param + } + + + result, err := c.service.UploadFileArrayOfFiles(r.Context(), petIdParam, additionalMetadataParam, filesParam) // If an error occurred, encode the error with the status code if err != nil { c.errorHandler(w, r, err, &result) diff --git a/samples/server/petstore/go-chi-server/go/api_pet_service.go b/samples/server/petstore/go-chi-server/go/api_pet_service.go index bda4cd897526..6044e65180e0 100644 --- a/samples/server/petstore/go-chi-server/go/api_pet_service.go +++ b/samples/server/petstore/go-chi-server/go/api_pet_service.go @@ -13,6 +13,7 @@ import ( "context" "net/http" "errors" + "time" "os" ) @@ -52,8 +53,22 @@ func (s *PetAPIService) DeletePet(ctx context.Context, petId int64, apiKey strin return Response(http.StatusNotImplemented, nil), errors.New("DeletePet method not implemented") } +// FilterPetsByCategory - Finds Pets +func (s *PetAPIService) FilterPetsByCategory(ctx context.Context, gender Gender, species Species, notSpecies []Species) (ImplResponse, error) { + // TODO - update FilterPetsByCategory with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("FilterPetsByCategory method not implemented") +} + // FindPetsByStatus - Finds Pets by status -func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string) (ImplResponse, error) { +func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string, inlineEnumPath string, inlineEnum string) (ImplResponse, error) { // TODO - update FindPetsByStatus with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -68,7 +83,7 @@ func (s *PetAPIService) FindPetsByStatus(ctx context.Context, status []string) ( // FindPetsByTags - Finds Pets by tags // Deprecated -func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string) (ImplResponse, error) { +func (s *PetAPIService) FindPetsByTags(ctx context.Context, tags []string, bornAfter time.Time, bornBefore time.Time, colour Colour) (ImplResponse, error) { // TODO - update FindPetsByTags with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -98,6 +113,56 @@ func (s *PetAPIService) GetPetById(ctx context.Context, petId int64) (ImplRespon return Response(http.StatusNotImplemented, nil), errors.New("GetPetById method not implemented") } +// GetPetImageById - Returns the image for the Pet that has been previously uploaded +func (s *PetAPIService) GetPetImageById(ctx context.Context, petId int64) (ImplResponse, error) { + // TODO - update GetPetImageById with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, *os.File{}) or use other options such as http.Ok ... + // return Response(200, *os.File{}), nil + + // TODO: Uncomment the next line to return response Response(400, {}) or use other options such as http.Ok ... + // return Response(400, nil),nil + + // TODO: Uncomment the next line to return response Response(404, {}) or use other options such as http.Ok ... + // return Response(404, nil),nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetImageById method not implemented") +} + +// GetPetsByTime - Get the pets by time +func (s *PetAPIService) GetPetsByTime(ctx context.Context, createdTime time.Time) (ImplResponse, error) { + // TODO - update GetPetsByTime with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsByTime method not implemented") +} + +// GetPetsUsingBooleanQueryParameters - Get the pets by only using boolean query parameters +func (s *PetAPIService) GetPetsUsingBooleanQueryParameters(ctx context.Context, expr bool, grouping bool, inactive bool) (ImplResponse, error) { + // TODO - update GetPetsUsingBooleanQueryParameters with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("GetPetsUsingBooleanQueryParameters method not implemented") +} + +// SearchPet - Search Pets by filters +func (s *PetAPIService) SearchPet(ctx context.Context, age *int64, price *float32, bornAfter *time.Time, old *bool) (ImplResponse, error) { + // TODO - update SearchPet with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, []Pet{}) or use other options such as http.Ok ... + // return Response(200, []Pet{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("SearchPet method not implemented") +} + // UpdatePet - Update an existing pet func (s *PetAPIService) UpdatePet(ctx context.Context, pet Pet) (ImplResponse, error) { // TODO - update UpdatePet with the required logic for this service method. @@ -130,7 +195,7 @@ func (s *PetAPIService) UpdatePetWithForm(ctx context.Context, petId int64, name } // UploadFile - uploads an image -func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, file *os.File) (ImplResponse, error) { +func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalMetadata string, extraOptionalMetadata []string, file *os.File) (ImplResponse, error) { // TODO - update UploadFile with the required logic for this service method. // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. @@ -139,3 +204,14 @@ func (s *PetAPIService) UploadFile(ctx context.Context, petId int64, additionalM return Response(http.StatusNotImplemented, nil), errors.New("UploadFile method not implemented") } + +// UploadFileArrayOfFiles - uploads images (array of files) +func (s *PetAPIService) UploadFileArrayOfFiles(ctx context.Context, petId int64, additionalMetadata string, files []*os.File) (ImplResponse, error) { + // TODO - update UploadFileArrayOfFiles with the required logic for this service method. + // Add api_pet_service.go to the .openapi-generator-ignore to avoid overwriting this service implementation when updating open api generation. + + // TODO: Uncomment the next line to return response Response(200, ApiResponse{}) or use other options such as http.Ok ... + // return Response(200, ApiResponse{}), nil + + return Response(http.StatusNotImplemented, nil), errors.New("UploadFileArrayOfFiles method not implemented") +} diff --git a/samples/server/petstore/go-chi-server/go/api_store.go b/samples/server/petstore/go-chi-server/go/api_store.go index 7b131249078c..3a2d0a3032b9 100644 --- a/samples/server/petstore/go-chi-server/go/api_store.go +++ b/samples/server/petstore/go-chi-server/go/api_store.go @@ -76,6 +76,10 @@ func (c *StoreAPIController) Routes() Routes { // DeleteOrder - Delete purchase order by ID func (c *StoreAPIController) DeleteOrder(w http.ResponseWriter, r *http.Request) { orderIdParam := chi.URLParam(r, "orderId") + if orderIdParam == "" { + c.errorHandler(w, r, &RequiredError{"orderId"}, nil) + return + } result, err := c.service.DeleteOrder(r.Context(), orderIdParam) // If an error occurred, encode the error with the status code if err != nil { diff --git a/samples/server/petstore/go-chi-server/go/api_user.go b/samples/server/petstore/go-chi-server/go/api_user.go index 8cfdb13a4a6b..43f8c8974845 100644 --- a/samples/server/petstore/go-chi-server/go/api_user.go +++ b/samples/server/petstore/go-chi-server/go/api_user.go @@ -174,14 +174,24 @@ func (c *UserAPIController) CreateUsersWithListInput(w http.ResponseWriter, r *h func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() usernameParam := chi.URLParam(r, "username") - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) return } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } result, err := c.service.DeleteUser(r.Context(), usernameParam, booleanTestParam) // If an error occurred, encode the error with the status code if err != nil { @@ -195,6 +205,10 @@ func (c *UserAPIController) DeleteUser(w http.ResponseWriter, r *http.Request) { // GetUserByName - Get user by user name func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } result, err := c.service.GetUserByName(r.Context(), usernameParam) // If an error occurred, encode the error with the status code if err != nil { @@ -208,16 +222,38 @@ func (c *UserAPIController) GetUserByName(w http.ResponseWriter, r *http.Request // LoginUser - Logs user into the system func (c *UserAPIController) LoginUser(w http.ResponseWriter, r *http.Request) { query := r.URL.Query() - usernameParam := query.Get("username") - passwordParam := query.Get("password") - booleanTestParam, err := parseBoolParameter( - query.Get("boolean_test"), - WithParse[bool](parseBool), - ) - if err != nil { - w.WriteHeader(500) + var usernameParam string + if query.Has("username") { + param := query.Get("username") + + usernameParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "username"}, nil) return } + var passwordParam string + if query.Has("password") { + param := query.Get("password") + + passwordParam = param + } else { + c.errorHandler(w, r, &RequiredError{Field: "password"}, nil) + return + } + var booleanTestParam bool + if query.Has("boolean_test") { + param, err := parseBoolParameter( + query.Get("boolean_test"), + WithParse[bool](parseBool), + ) + if err != nil { + c.errorHandler(w, r, &ParsingError{Err: err}, nil) + return + } + + booleanTestParam = param + } else { + } result, err := c.service.LoginUser(r.Context(), usernameParam, passwordParam, booleanTestParam) // If an error occurred, encode the error with the status code if err != nil { @@ -243,6 +279,10 @@ func (c *UserAPIController) LogoutUser(w http.ResponseWriter, r *http.Request) { // UpdateUser - Updated user func (c *UserAPIController) UpdateUser(w http.ResponseWriter, r *http.Request) { usernameParam := chi.URLParam(r, "username") + if usernameParam == "" { + c.errorHandler(w, r, &RequiredError{"username"}, nil) + return + } userParam := User{} d := json.NewDecoder(r.Body) d.DisallowUnknownFields() diff --git a/samples/server/petstore/go-chi-server/go/model_colour.go b/samples/server/petstore/go-chi-server/go/model_colour.go new file mode 100644 index 000000000000..3a1569cd0961 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_colour.go @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Colour string + +// List of Colour +const ( + BLUE Colour = "Blue" + WHITE Colour = "White" +) + +// AllowedColourEnumValues is all the allowed values of Colour enum +var AllowedColourEnumValues = []Colour{ + "Blue", + "White", +} + +// validColourEnumValue provides a map of Colours for fast verification of use input +var validColourEnumValues = map[Colour]struct{}{ + "Blue": {}, + "White": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Colour) IsValid() bool { + _, ok := validColourEnumValues[v] + return ok +} + +// NewColourFromValue returns a pointer to a valid Colour +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewColourFromValue(v string) (Colour, error) { + ev := Colour(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Colour: valid values are %v", v, AllowedColourEnumValues) + } +} + + + +// AssertColourRequired checks if the required fields are not zero-ed +func AssertColourRequired(obj Colour) error { + return nil +} + +// AssertColourConstraints checks if the values respects the defined constraints +func AssertColourConstraints(obj Colour) error { + return nil +} diff --git a/samples/server/petstore/go-chi-server/go/model_gender.go b/samples/server/petstore/go-chi-server/go/model_gender.go new file mode 100644 index 000000000000..16583a0c400b --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_gender.go @@ -0,0 +1,66 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Gender string + +// List of Gender +const ( + MALE Gender = "male" + FEMALE Gender = "female" +) + +// AllowedGenderEnumValues is all the allowed values of Gender enum +var AllowedGenderEnumValues = []Gender{ + "male", + "female", +} + +// validGenderEnumValue provides a map of Genders for fast verification of use input +var validGenderEnumValues = map[Gender]struct{}{ + "male": {}, + "female": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Gender) IsValid() bool { + _, ok := validGenderEnumValues[v] + return ok +} + +// NewGenderFromValue returns a pointer to a valid Gender +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewGenderFromValue(v string) (Gender, error) { + ev := Gender(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Gender: valid values are %v", v, AllowedGenderEnumValues) + } +} + + + +// AssertGenderRequired checks if the required fields are not zero-ed +func AssertGenderRequired(obj Gender) error { + return nil +} + +// AssertGenderConstraints checks if the values respects the defined constraints +func AssertGenderConstraints(obj Gender) error { + return nil +} diff --git a/samples/server/petstore/go-chi-server/go/model_species.go b/samples/server/petstore/go-chi-server/go/model_species.go new file mode 100644 index 000000000000..4e6fc567e6a4 --- /dev/null +++ b/samples/server/petstore/go-chi-server/go/model_species.go @@ -0,0 +1,75 @@ +/* + * OpenAPI Petstore + * + * This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + * + * API version: 1.0.0 + * Generated by: OpenAPI Generator (https://openapi-generator.tech) + */ + +package petstoreserver + + +import ( + "fmt" +) + + + +type Species string + +// List of Species +const ( + CAT Species = "cat" + DOG Species = "dog" + FISH Species = "fish" + GOAT Species = "goat" + PIG Species = "pig" +) + +// AllowedSpeciesEnumValues is all the allowed values of Species enum +var AllowedSpeciesEnumValues = []Species{ + "cat", + "dog", + "fish", + "goat", + "pig", +} + +// validSpeciesEnumValue provides a map of Speciess for fast verification of use input +var validSpeciesEnumValues = map[Species]struct{}{ + "cat": {}, + "dog": {}, + "fish": {}, + "goat": {}, + "pig": {}, +} + +// IsValid return true if the value is valid for the enum, false otherwise +func (v Species) IsValid() bool { + _, ok := validSpeciesEnumValues[v] + return ok +} + +// NewSpeciesFromValue returns a pointer to a valid Species +// for the value passed as argument, or an error if the value passed is not allowed by the enum +func NewSpeciesFromValue(v string) (Species, error) { + ev := Species(v) + if ev.IsValid() { + return ev, nil + } else { + return "", fmt.Errorf("invalid value '%v' for Species: valid values are %v", v, AllowedSpeciesEnumValues) + } +} + + + +// AssertSpeciesRequired checks if the required fields are not zero-ed +func AssertSpeciesRequired(obj Species) error { + return nil +} + +// AssertSpeciesConstraints checks if the values respects the defined constraints +func AssertSpeciesConstraints(obj Species) error { + return nil +} diff --git a/samples/server/petstore/go-chi-server/go/routers.go b/samples/server/petstore/go-chi-server/go/routers.go index af326677bf45..07d148352e28 100644 --- a/samples/server/petstore/go-chi-server/go/routers.go +++ b/samples/server/petstore/go-chi-server/go/routers.go @@ -12,9 +12,10 @@ package petstoreserver import ( "encoding/json" "errors" + "time" "github.com/go-chi/chi/v5" "github.com/go-chi/chi/v5/middleware" - "io/ioutil" + "io" "mime/multipart" "net/http" "os" @@ -64,7 +65,25 @@ func EncodeJSONResponse(i interface{}, status *int, headers map[string][]string, wHeader.Add(key, value) } } + + f, ok := i.(*os.File) + if ok { + data, err := io.ReadAll(f) + if err != nil { + return err + } + wHeader.Set("Content-Type", http.DetectContentType(data)) + wHeader.Set("Content-Disposition", "attachment; filename="+f.Name()) + if status != nil { + w.WriteHeader(*status) + } else { + w.WriteHeader(http.StatusOK) + } + _, err = w.Write(data) + return err + } wHeader.Set("Content-Type", "application/json; charset=UTF-8") + if status != nil { w.WriteHeader(*status) } else { @@ -117,21 +136,42 @@ func readFileHeaderToTempFile(fileHeader *multipart.FileHeader) (*os.File, error defer formFile.Close() - fileBytes, err := ioutil.ReadAll(formFile) + // Use .* as suffix, because the asterisk is a placeholder for the random value, + // and the period allows consumers of this file to remove the suffix to obtain the original file name + file, err := os.CreateTemp("", fileHeader.Filename+".*") if err != nil { return nil, err } - file, err := ioutil.TempFile("", fileHeader.Filename) + defer file.Close() + + _, err = io.Copy(file, formFile) if err != nil { return nil, err } + + return file, nil +} - defer file.Close() - - file.Write(fileBytes) +func parseTimes(param string) ([]time.Time, error) { + splits := strings.Split(param, ",") + times := make([]time.Time, 0, len(splits)) + for _, v := range splits { + t, err := parseTime(v) + if err != nil { + return nil, err + } + times = append(times, t) + } + return times, nil +} - return file, nil +// parseTime will parses a string parameter into a time.Time using the RFC3339 format +func parseTime(param string) (time.Time, error) { + if param == "" { + return time.Time{}, nil + } + return time.Parse(time.RFC3339, param) } type Number interface { diff --git a/samples/server/petstore/go-echo-server/.openapi-generator/VERSION b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/go-echo-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-echo-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-echo-server/handlers/api_pet.go b/samples/server/petstore/go-echo-server/handlers/api_pet.go index af6117b162bc..865529ccc9e8 100644 --- a/samples/server/petstore/go-echo-server/handlers/api_pet.go +++ b/samples/server/petstore/go-echo-server/handlers/api_pet.go @@ -1,70 +1,71 @@ package handlers import ( - "gitlab.com/openapitools/petstore/models" - "github.com/labstack/echo/v4" - "net/http" + "gitlab.com/openapitools/petstore/models" + "github.com/labstack/echo/v4" + "net/http" ) // AddPet - Add a new pet to the store func (c *Container) AddPet(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // DeletePet - Deletes a pet func (c *Container) DeletePet(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // FindPetsByStatus - Finds Pets by status func (c *Container) FindPetsByStatus(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // FindPetsByTags - Finds Pets by tags // Deprecated func (c *Container) FindPetsByTags(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // GetPetById - Find pet by ID func (c *Container) GetPetById(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // UpdatePet - Update an existing pet func (c *Container) UpdatePet(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // UpdatePetWithForm - Updates a pet in the store with form data func (c *Container) UpdatePetWithForm(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // UploadFile - uploads an image func (c *Container) UploadFile(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } + diff --git a/samples/server/petstore/go-echo-server/handlers/api_store.go b/samples/server/petstore/go-echo-server/handlers/api_store.go index a994e5020a72..a196ab87e295 100644 --- a/samples/server/petstore/go-echo-server/handlers/api_store.go +++ b/samples/server/petstore/go-echo-server/handlers/api_store.go @@ -1,37 +1,38 @@ package handlers import ( - "gitlab.com/openapitools/petstore/models" - "github.com/labstack/echo/v4" - "net/http" + "gitlab.com/openapitools/petstore/models" + "github.com/labstack/echo/v4" + "net/http" ) // DeleteOrder - Delete purchase order by ID func (c *Container) DeleteOrder(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // GetInventory - Returns pet inventories by status func (c *Container) GetInventory(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // GetOrderById - Find purchase order by ID func (c *Container) GetOrderById(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // PlaceOrder - Place an order for a pet func (c *Container) PlaceOrder(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } + diff --git a/samples/server/petstore/go-echo-server/handlers/api_user.go b/samples/server/petstore/go-echo-server/handlers/api_user.go index 8f695e3c7d33..1e1e03de8bed 100644 --- a/samples/server/petstore/go-echo-server/handlers/api_user.go +++ b/samples/server/petstore/go-echo-server/handlers/api_user.go @@ -1,69 +1,70 @@ package handlers import ( - "gitlab.com/openapitools/petstore/models" - "github.com/labstack/echo/v4" - "net/http" + "gitlab.com/openapitools/petstore/models" + "github.com/labstack/echo/v4" + "net/http" ) // CreateUser - Create user func (c *Container) CreateUser(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // CreateUsersWithArrayInput - Creates list of users with given input array func (c *Container) CreateUsersWithArrayInput(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // CreateUsersWithListInput - Creates list of users with given input array func (c *Container) CreateUsersWithListInput(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // DeleteUser - Delete user func (c *Container) DeleteUser(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // GetUserByName - Get user by user name func (c *Container) GetUserByName(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // LoginUser - Logs user into the system func (c *Container) LoginUser(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // LogoutUser - Logs out current logged in user session func (c *Container) LogoutUser(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } // UpdateUser - Updated user func (c *Container) UpdateUser(ctx echo.Context) error { - return ctx.JSON(http.StatusOK, models.HelloWorld { - Message: "Hello World", - }) + return ctx.JSON(http.StatusOK, models.HelloWorld { + Message: "Hello World", + }) } + diff --git a/samples/server/petstore/go-echo-server/handlers/container.go b/samples/server/petstore/go-echo-server/handlers/container.go index 330a32f51534..2e4aa441e22c 100644 --- a/samples/server/petstore/go-echo-server/handlers/container.go +++ b/samples/server/petstore/go-echo-server/handlers/container.go @@ -6,6 +6,6 @@ type Container struct { // NewContainer returns an empty or an initialized container for your handlers. func NewContainer() (Container, error) { - c := Container{} - return c, nil -} \ No newline at end of file + c := Container{} + return c, nil +} diff --git a/samples/server/petstore/go-echo-server/main.go b/samples/server/petstore/go-echo-server/main.go index b96dcb776ef5..8e1095eaee45 100644 --- a/samples/server/petstore/go-echo-server/main.go +++ b/samples/server/petstore/go-echo-server/main.go @@ -9,7 +9,7 @@ import ( func main() { e := echo.New() - //todo: handle the error! + //todo: handle the error! c, _ := handlers.NewContainer() // Middleware @@ -80,4 +80,4 @@ func main() { // Start server e.Logger.Fatal(e.Start(":8080")) -} \ No newline at end of file +} diff --git a/samples/server/petstore/go-echo-server/models/hello-world.go b/samples/server/petstore/go-echo-server/models/hello-world.go index 98b4d20cb613..b939ad04f792 100644 --- a/samples/server/petstore/go-echo-server/models/hello-world.go +++ b/samples/server/petstore/go-echo-server/models/hello-world.go @@ -2,5 +2,5 @@ package models // HelloWorld is a sample data structure to make sure each endpoint return something. type HelloWorld struct { - Message string `json:"message"` -} \ No newline at end of file + Message string `json:"message"` +} diff --git a/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION b/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION +++ b/samples/server/petstore/go-gin-api-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/go-gin-api-server/go.sum b/samples/server/petstore/go-gin-api-server/go.sum index bfad1c04dee6..5a6c9b3832cc 100644 --- a/samples/server/petstore/go-gin-api-server/go.sum +++ b/samples/server/petstore/go-gin-api-server/go.sum @@ -1,16 +1,19 @@ github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= github.com/bytedance/sonic v1.8.0 h1:ea0Xadu+sHlu7x5O3gKhRpQ1IKiMrSiHttPF0ybECuA= github.com/bytedance/sonic v1.8.0/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= +github.com/bytedance/sonic v1.9.1/go.mod h1:i736AoUSYt75HyZLoJW9ERYxcy6eaN6h4BZXU064P/U= github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 h1:qSGYFH7+jGhDF8vLC+iwCD4WpbV1EBDSzWkJODFLams= github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.2/go.mod h1:zApsH/mKG4w07erKIaJPFiX0Tsq9BFQgN3qGY5GnNgA= github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= github.com/gin-gonic/gin v1.9.0 h1:OjyFBKICoexlu99ctXNR2gg+c5pKrKMuyjgARg9qeY8= github.com/gin-gonic/gin v1.9.0/go.mod h1:W1Me9+hsUSyj3CePGrd1/QrKJMSJ1Tu/0hFEH89961k= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s= github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA= github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY= @@ -18,8 +21,10 @@ github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJn github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= github.com/go-playground/validator/v10 v10.11.2 h1:q3SHpufmypg+erIExEKUmsgmhDTyhcJ38oeKGACXohU= github.com/go-playground/validator/v10 v10.11.2/go.mod h1:NieE624vt4SCTJtD87arVLvdmjPAeV8BQlHtMnw9D7s= +github.com/go-playground/validator/v10 v10.14.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= github.com/goccy/go-json v0.10.0 h1:mXKd9Qw4NuzShiRlOXKews24ufknHO7gx30lsDyokKA= github.com/goccy/go-json v0.10.0/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= github.com/google/go-cmp v0.5.5 h1:Khx7svrCpmxxtHBq5j2mp/xVjsi8hQMfNLvJFAlrGgU= github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= @@ -28,18 +33,23 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.4/go.mod h1:RVVoqg1df56z8g3pUjL/3lE5UfnlrJX8tyFgg4nqhuY= github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= github.com/leodido/go-urn v1.2.1 h1:BqpAaACuzVSgi/VLzGZIobT2z4v53pjosyNd9Yv6n/w= github.com/leodido/go-urn v1.2.1/go.mod h1:zt4jvISO2HfUBqxjfIshjdMTYS56ZS/qv49ictyFfxY= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= github.com/mattn/go-isatty v0.0.17 h1:BTarxUcIeDqL27Mc+vyvdWYSL28zpIhv3RoTdsLMPng= github.com/mattn/go-isatty v0.0.17/go.mod h1:kYGgaQfpe5nmfYZH+SKPsOc2e4SrIfOl2e/yFXSvRLM= +github.com/mattn/go-isatty v0.0.19/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421 h1:ZqeYNhU3OHLH3mGKHDcjJRFFRrJa6eAM5H+CtDdOsPc= github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M= github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk= github.com/pelletier/go-toml/v2 v2.0.6 h1:nrzqCb7j9cDFj2coyLNLaZuJTLjWjlaz6nvTvIwycIU= github.com/pelletier/go-toml/v2 v2.0.6/go.mod h1:eumQOmlWiOPt5WriQQqoM5y18pDHwha2N+QD+EUNTek= +github.com/pelletier/go-toml/v2 v2.0.8/go.mod h1:vuYfssBdrU2XDZ9bYydBu6t+6a6PYNcZljzZR9VXg+4= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8= @@ -53,26 +63,37 @@ github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/ github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.3/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= github.com/ugorji/go/codec v1.2.9 h1:rmenucSohSTiyL09Y+l2OCk+FrMxGMzho2+tjr5ticU= github.com/ugorji/go/codec v1.2.9/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +github.com/ugorji/go/codec v1.2.11/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= golang.org/x/arch v0.0.0-20210923205945-b76863e36670 h1:18EFjUmQOcUvxNYSkA6jO9VAiXCnxFY6NyDX0bHDmkU= golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.3.0/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= golang.org/x/crypto v0.5.0 h1:U/0M97KRkSFvyD/3FSmdP5W5swImpNgle/EHFhOsQPE= golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU= +golang.org/x/crypto v0.9.0/go.mod h1:yrmDGqONDYtNj3tH8X9dzUun2m2lzPa9ngI6/RUPGR0= golang.org/x/net v0.7.0 h1:rJrUqqhjsgNp7KqAIc25s9pZnjU7TUcSY7HcVZjdn1g= golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs= +golang.org/x/net v0.10.0/go.mod h1:0qNGK6F8kojg2nk9dLZ2mShWaEBan6FAoqfSigmmuDg= +golang.org/x/sys v0.0.0-20220704084225-05e143d24a9e/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.0.0-20220811171246-fbc7d0a398ab/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/sys v0.5.0 h1:MUK/U/4lj1t1oPg0HfuXDN/Z1wv31ZJ/YcPiGccS4DU= golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= +golang.org/x/sys v0.8.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg= golang.org/x/text v0.7.0 h1:4BRB4x83lYWy72KwLD/qYDuTu7q9PjSagHvijDw7cLo= golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8= +golang.org/x/text v0.9.0/go.mod h1:e1OnstbJyHTd6l/uOt8jFFHp6TRDWZR/bV3emEE/zU8= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543 h1:E7g+9GITq07hpfrRu66IVDexMakfv52eLZ2CXBWiKr4= golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= google.golang.org/protobuf v1.28.1 h1:d0NfwRgPtno5B1Wa6L2DAG+KivqkdutMf1UhdNx175w= google.golang.org/protobuf v1.28.1/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +google.golang.org/protobuf v1.30.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk= gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/samples/server/petstore/go-gin-api-server/go/api_pet.go b/samples/server/petstore/go-gin-api-server/go/api_pet.go index f5f4ab5716b1..323fc27cf727 100644 --- a/samples/server/petstore/go-gin-api-server/go/api_pet.go +++ b/samples/server/petstore/go-gin-api-server/go/api_pet.go @@ -14,29 +14,62 @@ import ( ) type PetAPI struct { - // Post /v2/pet - // Add a new pet to the store - AddPet gin.HandlerFunc - // Delete /v2/pet/:petId - // Deletes a pet - DeletePet gin.HandlerFunc - // Get /v2/pet/findByStatus - // Finds Pets by status - FindPetsByStatus gin.HandlerFunc - // Get /v2/pet/findByTags - // Finds Pets by tags - // Deprecated - FindPetsByTags gin.HandlerFunc - // Get /v2/pet/:petId - // Find pet by ID - GetPetById gin.HandlerFunc - // Put /v2/pet - // Update an existing pet - UpdatePet gin.HandlerFunc - // Post /v2/pet/:petId - // Updates a pet in the store with form data - UpdatePetWithForm gin.HandlerFunc - // Post /v2/pet/:petId/uploadImage - // uploads an image - UploadFile gin.HandlerFunc } + +// Post /v2/pet +// Add a new pet to the store +func (api *PetAPI) AddPet(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Delete /v2/pet/:petId +// Deletes a pet +func (api *PetAPI) DeletePet(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/pet/findByStatus +// Finds Pets by status +func (api *PetAPI) FindPetsByStatus(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/pet/findByTags +// Finds Pets by tags +// Deprecated +func (api *PetAPI) FindPetsByTags(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/pet/:petId +// Find pet by ID +func (api *PetAPI) GetPetById(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Put /v2/pet +// Update an existing pet +func (api *PetAPI) UpdatePet(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Post /v2/pet/:petId +// Updates a pet in the store with form data +func (api *PetAPI) UpdatePetWithForm(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Post /v2/pet/:petId/uploadImage +// uploads an image +func (api *PetAPI) UploadFile(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + diff --git a/samples/server/petstore/go-gin-api-server/go/api_store.go b/samples/server/petstore/go-gin-api-server/go/api_store.go index 4987a93862d7..41db6e84633b 100644 --- a/samples/server/petstore/go-gin-api-server/go/api_store.go +++ b/samples/server/petstore/go-gin-api-server/go/api_store.go @@ -14,16 +14,33 @@ import ( ) type StoreAPI struct { - // Delete /v2/store/order/:orderId - // Delete purchase order by ID - DeleteOrder gin.HandlerFunc - // Get /v2/store/inventory - // Returns pet inventories by status - GetInventory gin.HandlerFunc - // Get /v2/store/order/:orderId - // Find purchase order by ID - GetOrderById gin.HandlerFunc - // Post /v2/store/order - // Place an order for a pet - PlaceOrder gin.HandlerFunc } + +// Delete /v2/store/order/:orderId +// Delete purchase order by ID +func (api *StoreAPI) DeleteOrder(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/store/inventory +// Returns pet inventories by status +func (api *StoreAPI) GetInventory(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/store/order/:orderId +// Find purchase order by ID +func (api *StoreAPI) GetOrderById(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Post /v2/store/order +// Place an order for a pet +func (api *StoreAPI) PlaceOrder(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + diff --git a/samples/server/petstore/go-gin-api-server/go/api_user.go b/samples/server/petstore/go-gin-api-server/go/api_user.go index bfd6f9fba4c8..218b79131ebc 100644 --- a/samples/server/petstore/go-gin-api-server/go/api_user.go +++ b/samples/server/petstore/go-gin-api-server/go/api_user.go @@ -14,28 +14,61 @@ import ( ) type UserAPI struct { - // Post /v2/user - // Create user - CreateUser gin.HandlerFunc - // Post /v2/user/createWithArray - // Creates list of users with given input array - CreateUsersWithArrayInput gin.HandlerFunc - // Post /v2/user/createWithList - // Creates list of users with given input array - CreateUsersWithListInput gin.HandlerFunc - // Delete /v2/user/:username - // Delete user - DeleteUser gin.HandlerFunc - // Get /v2/user/:username - // Get user by user name - GetUserByName gin.HandlerFunc - // Get /v2/user/login - // Logs user into the system - LoginUser gin.HandlerFunc - // Get /v2/user/logout - // Logs out current logged in user session - LogoutUser gin.HandlerFunc - // Put /v2/user/:username - // Updated user - UpdateUser gin.HandlerFunc } + +// Post /v2/user +// Create user +func (api *UserAPI) CreateUser(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Post /v2/user/createWithArray +// Creates list of users with given input array +func (api *UserAPI) CreateUsersWithArrayInput(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Post /v2/user/createWithList +// Creates list of users with given input array +func (api *UserAPI) CreateUsersWithListInput(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Delete /v2/user/:username +// Delete user +func (api *UserAPI) DeleteUser(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/user/:username +// Get user by user name +func (api *UserAPI) GetUserByName(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/user/login +// Logs user into the system +func (api *UserAPI) LoginUser(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Get /v2/user/logout +// Logs out current logged in user session +func (api *UserAPI) LogoutUser(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + +// Put /v2/user/:username +// Updated user +func (api *UserAPI) UpdateUser(c *gin.Context) { + // Your handler implementation + c.JSON(200, gin.H{"status": "OK"}) +} + diff --git a/samples/server/petstore/go-gin-api-server/go/routers.go b/samples/server/petstore/go-gin-api-server/go/routers.go index f63c9490433b..b528b1521c21 100644 --- a/samples/server/petstore/go-gin-api-server/go/routers.go +++ b/samples/server/petstore/go-gin-api-server/go/routers.go @@ -67,8 +67,7 @@ type ApiHandleFunctions struct { } func getRoutes(handleFunctions ApiHandleFunctions) []Route { - return []Route{ - + return []Route{ { "AddPet", http.MethodPost, diff --git a/samples/server/petstore/haskell-servant/.openapi-generator/VERSION b/samples/server/petstore/haskell-servant/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/haskell-servant/.openapi-generator/VERSION +++ b/samples/server/petstore/haskell-servant/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/haskell-yesod/.openapi-generator/VERSION b/samples/server/petstore/haskell-yesod/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/haskell-yesod/.openapi-generator/VERSION +++ b/samples/server/petstore/haskell-yesod/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-camel/.openapi-generator/VERSION b/samples/server/petstore/java-camel/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-camel/.openapi-generator/VERSION +++ b/samples/server/petstore/java-camel/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-camel/pom.xml b/samples/server/petstore/java-camel/pom.xml index 1aa3ea4a705b..640df9e4b9cd 100644 --- a/samples/server/petstore/java-camel/pom.xml +++ b/samples/server/petstore/java-camel/pom.xml @@ -1,6 +1,6 @@ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/RestConfiguration.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/RestConfiguration.java index 3ee63ee3c211..097e477e7594 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/RestConfiguration.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/RestConfiguration.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/ValidationErrorProcessor.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/ValidationErrorProcessor.java index a061a61c7b13..e8b6d1635410 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/ValidationErrorProcessor.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/ValidationErrorProcessor.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApi.java index 6a3545cb3488..613701005305 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiRoutesImpl.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiRoutesImpl.java index 50588aebaa8a..bf02d9248d9c 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiRoutesImpl.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiRoutesImpl.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiValidator.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiValidator.java index dbb016feedb6..7b883818974a 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiValidator.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/PetApiValidator.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApi.java index e8f0a41a0e0c..dc29d21eac66 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiRoutesImpl.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiRoutesImpl.java index e946f024254b..70c96323655b 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiRoutesImpl.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiRoutesImpl.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiValidator.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiValidator.java index 3e04b2a908d9..67e4f4c67fcc 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiValidator.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/StoreApiValidator.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApi.java index 4686d6ba018a..63e22e3d1953 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiRoutesImpl.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiRoutesImpl.java index bae28e48aec3..9dd99cf9dfe9 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiRoutesImpl.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiRoutesImpl.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiValidator.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiValidator.java index 09f04702fe47..274069b2386e 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiValidator.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/api/UserApiValidator.java @@ -1,5 +1,5 @@ /** -* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +* NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Category.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Category.java index 5fe001a360f0..96728fdbbfab 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Category.java @@ -30,10 +30,8 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class Category { - @JacksonXmlProperty(localName = "id") private Long id; - @JacksonXmlProperty(localName = "name") private String name; public Category id(Long id) { @@ -48,6 +46,7 @@ public Category id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -68,6 +67,7 @@ public Category name(String name) { @Pattern(regexp = "^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$") @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/ModelApiResponse.java index 37ee933d1276..fbd6b3716d91 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -32,13 +32,10 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class ModelApiResponse { - @JacksonXmlProperty(localName = "code") private Integer code; - @JacksonXmlProperty(localName = "type") private String type; - @JacksonXmlProperty(localName = "message") private String message; public ModelApiResponse code(Integer code) { @@ -53,6 +50,7 @@ public ModelApiResponse code(Integer code) { @Schema(name = "code", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("code") + @JacksonXmlProperty(localName = "code") public Integer getCode() { return code; } @@ -73,6 +71,7 @@ public ModelApiResponse type(String type) { @Schema(name = "type", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("type") + @JacksonXmlProperty(localName = "type") public String getType() { return type; } @@ -93,6 +92,7 @@ public ModelApiResponse message(String message) { @Schema(name = "message", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("message") + @JacksonXmlProperty(localName = "message") public String getMessage() { return message; } diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Order.java index 19cc6ec9bf51..89df3e0d8cff 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Order.java @@ -33,16 +33,12 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class Order { - @JacksonXmlProperty(localName = "id") private Long id; - @JacksonXmlProperty(localName = "petId") private Long petId; - @JacksonXmlProperty(localName = "quantity") private Integer quantity; - @JacksonXmlProperty(localName = "shipDate") @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) private Date shipDate; @@ -83,10 +79,8 @@ public static StatusEnum fromValue(String value) { } } - @JacksonXmlProperty(localName = "status") private StatusEnum status; - @JacksonXmlProperty(localName = "complete") private Boolean complete = false; public Order id(Long id) { @@ -101,6 +95,7 @@ public Order id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -121,6 +116,7 @@ public Order petId(Long petId) { @Schema(name = "petId", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("petId") + @JacksonXmlProperty(localName = "petId") public Long getPetId() { return petId; } @@ -141,6 +137,7 @@ public Order quantity(Integer quantity) { @Schema(name = "quantity", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("quantity") + @JacksonXmlProperty(localName = "quantity") public Integer getQuantity() { return quantity; } @@ -161,6 +158,7 @@ public Order shipDate(Date shipDate) { @Valid @Schema(name = "shipDate", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("shipDate") + @JacksonXmlProperty(localName = "shipDate") public Date getShipDate() { return shipDate; } @@ -181,6 +179,7 @@ public Order status(StatusEnum status) { @Schema(name = "status", description = "Order Status", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("status") + @JacksonXmlProperty(localName = "status") public StatusEnum getStatus() { return status; } @@ -201,6 +200,7 @@ public Order complete(Boolean complete) { @Schema(name = "complete", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("complete") + @JacksonXmlProperty(localName = "complete") public Boolean getComplete() { return complete; } diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Pet.java index 0f7d2a1f6f64..c7e6fb40e960 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Pet.java @@ -36,20 +36,15 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class Pet { - @JacksonXmlProperty(localName = "id") private Long id; - @JacksonXmlProperty(localName = "Category") private Category category; - @JacksonXmlProperty(localName = "name") private String name; - @JacksonXmlProperty(localName = "photoUrl") @Valid private List photoUrls = new ArrayList<>(); - @JacksonXmlProperty(localName = "tag") @Valid private List<@Valid Tag> tags; @@ -90,7 +85,6 @@ public static StatusEnum fromValue(String value) { } } - @JacksonXmlProperty(localName = "status") @Deprecated private StatusEnum status; @@ -118,6 +112,7 @@ public Pet id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -138,6 +133,7 @@ public Pet category(Category category) { @Valid @Schema(name = "category", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("category") + @JacksonXmlProperty(localName = "Category") public Category getCategory() { return category; } @@ -158,6 +154,7 @@ public Pet name(String name) { @NotNull @Schema(name = "name", example = "doggie", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } @@ -186,6 +183,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { @NotNull @Schema(name = "photoUrls", requiredMode = Schema.RequiredMode.REQUIRED) @JsonProperty("photoUrls") + @JacksonXmlProperty(localName = "photoUrl") public List getPhotoUrls() { return photoUrls; } @@ -214,6 +212,7 @@ public Pet addTagsItem(Tag tagsItem) { @Valid @Schema(name = "tags", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("tags") + @JacksonXmlProperty(localName = "tag") public List<@Valid Tag> getTags() { return tags; } @@ -235,6 +234,7 @@ public Pet status(StatusEnum status) { @Schema(name = "status", description = "pet status in the store", deprecated = true, requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("status") + @JacksonXmlProperty(localName = "status") @Deprecated public StatusEnum getStatus() { return status; diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Tag.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Tag.java index f2c6219aeb89..f5cbd87233e1 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/Tag.java @@ -30,10 +30,8 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class Tag { - @JacksonXmlProperty(localName = "id") private Long id; - @JacksonXmlProperty(localName = "name") private String name; public Tag id(Long id) { @@ -48,6 +46,7 @@ public Tag id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -68,6 +67,7 @@ public Tag name(String name) { @Schema(name = "name", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("name") + @JacksonXmlProperty(localName = "name") public String getName() { return name; } diff --git a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/User.java b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/User.java index 94ac85834347..23821e2e4fc7 100644 --- a/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/User.java +++ b/samples/server/petstore/java-camel/src/main/java/org/openapitools/model/User.java @@ -30,28 +30,20 @@ @Generated(value = "org.openapitools.codegen.languages.JavaCamelServerCodegen") public class User { - @JacksonXmlProperty(localName = "id") private Long id; - @JacksonXmlProperty(localName = "username") private String username; - @JacksonXmlProperty(localName = "firstName") private String firstName; - @JacksonXmlProperty(localName = "lastName") private String lastName; - @JacksonXmlProperty(localName = "email") private String email; - @JacksonXmlProperty(localName = "password") private String password; - @JacksonXmlProperty(localName = "phone") private String phone; - @JacksonXmlProperty(localName = "userStatus") private Integer userStatus; public User id(Long id) { @@ -66,6 +58,7 @@ public User id(Long id) { @Schema(name = "id", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("id") + @JacksonXmlProperty(localName = "id") public Long getId() { return id; } @@ -86,6 +79,7 @@ public User username(String username) { @Schema(name = "username", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("username") + @JacksonXmlProperty(localName = "username") public String getUsername() { return username; } @@ -106,6 +100,7 @@ public User firstName(String firstName) { @Schema(name = "firstName", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("firstName") + @JacksonXmlProperty(localName = "firstName") public String getFirstName() { return firstName; } @@ -126,6 +121,7 @@ public User lastName(String lastName) { @Schema(name = "lastName", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("lastName") + @JacksonXmlProperty(localName = "lastName") public String getLastName() { return lastName; } @@ -146,6 +142,7 @@ public User email(String email) { @Schema(name = "email", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("email") + @JacksonXmlProperty(localName = "email") public String getEmail() { return email; } @@ -166,6 +163,7 @@ public User password(String password) { @Schema(name = "password", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("password") + @JacksonXmlProperty(localName = "password") public String getPassword() { return password; } @@ -186,6 +184,7 @@ public User phone(String phone) { @Schema(name = "phone", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("phone") + @JacksonXmlProperty(localName = "phone") public String getPhone() { return phone; } @@ -206,6 +205,7 @@ public User userStatus(Integer userStatus) { @Schema(name = "userStatus", description = "User Status", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("userStatus") + @JacksonXmlProperty(localName = "userStatus") public Integer getUserStatus() { return userStatus; } diff --git a/samples/server/petstore/java-camel/src/main/resources/application.properties b/samples/server/petstore/java-camel/src/main/resources/application.properties index 9d51836e13ce..68216d7110bd 100644 --- a/samples/server/petstore/java-camel/src/main/resources/application.properties +++ b/samples/server/petstore/java-camel/src/main/resources/application.properties @@ -1,4 +1,4 @@ -# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). +# NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). # https://openapi-generator.tech # Do not edit the class manually. diff --git a/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION +++ b/samples/server/petstore/java-helidon-server/mp/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/mp/README.md b/samples/server/petstore/java-helidon-server/mp/README.md index 443dc6d1341e..420f8ddd67bc 100644 --- a/samples/server/petstore/java-helidon-server/mp/README.md +++ b/samples/server/petstore/java-helidon-server/mp/README.md @@ -21,6 +21,7 @@ curl -X POST http://petstore.swagger.io:80/v2/outer/composite curl -X POST http://petstore.swagger.io:80/v2/outer/number curl -X POST http://petstore.swagger.io:80/v2/outer/string curl -X POST http://petstore.swagger.io:80/v2/property/enum-int +curl -X POST http://petstore.swagger.io:80/v2/additionalProperties-reference curl -X PUT http://petstore.swagger.io:80/v2/body-with-binary curl -X PUT http://petstore.swagger.io:80/v2/body-with-file-schema curl -X PUT http://petstore.swagger.io:80/v2/body-with-query-params diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java index 856a23d38dca..320ff2d6350e 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeService.java @@ -87,6 +87,11 @@ public interface FakeService { @Produces({ "*/*" }) OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(@Valid @NotNull OuterObjectWithEnumProperty outerObjectWithEnumProperty); + @POST + @Path("/additionalProperties-reference") + @Consumes({ "application/json" }) + void testAdditionalPropertiesReference(@Valid @NotNull Map requestBody); + @PUT @Path("/body-with-binary") @Consumes({ "image/png" }) @@ -113,7 +118,7 @@ public interface FakeService { @GET @Consumes({ "application/x-www-form-urlencoded" }) - void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @QueryParam("enum_query_double") Double enumQueryDouble, @QueryParam("enum_query_model_array") List enumQueryModelArray, @FormParam(value = "enum_form_string_array") List enumFormStringArray, @FormParam(value = "enum_form_string") String enumFormString); + void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray, @HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString, @QueryParam("enum_query_string_array") List enumQueryStringArray, @QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString, @QueryParam("enum_query_integer") Integer enumQueryInteger, @QueryParam("enum_query_double") Double enumQueryDouble, @QueryParam("enum_query_model_array") List<@Valid EnumClass> enumQueryModelArray, @FormParam(value = "enum_form_string_array") List enumFormStringArray, @FormParam(value = "enum_form_string") String enumFormString); @DELETE void testGroupParameters(@QueryParam("required_string_group") @NotNull Integer requiredStringGroup, @HeaderParam("required_boolean_group") @NotNull Boolean requiredBooleanGroup, @QueryParam("required_int64_group") @NotNull Long requiredInt64Group, @QueryParam("string_group") Integer stringGroup, @HeaderParam("boolean_group") Boolean booleanGroup, @QueryParam("int64_group") Long int64Group); diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java index 83412a6d0ea2..a9b10d16ad8f 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/FakeServiceImpl.java @@ -110,6 +110,12 @@ public OuterObjectWithEnumProperty fakePropertyEnumIntegerSerialize(@Valid @NotN return result; } + @POST + @Path("/additionalProperties-reference") + @Consumes({ "application/json" }) + public void testAdditionalPropertiesReference(@Valid @NotNull Map requestBody) { + } + @PUT @Path("/body-with-binary") @Consumes({ "image/png" }) @@ -143,7 +149,7 @@ public void testEndpointParameters(@FormParam(value = "number") BigDecimal numb @GET @Consumes({ "application/x-www-form-urlencoded" }) - public void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString,@QueryParam("enum_query_string_array") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString,@QueryParam("enum_query_integer") Integer enumQueryInteger,@QueryParam("enum_query_double") Double enumQueryDouble,@QueryParam("enum_query_model_array") List enumQueryModelArray,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString) { + public void testEnumParameters(@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@HeaderParam("enum_header_string") @DefaultValue("-efg") String enumHeaderString,@QueryParam("enum_query_string_array") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") String enumQueryString,@QueryParam("enum_query_integer") Integer enumQueryInteger,@QueryParam("enum_query_double") Double enumQueryDouble,@QueryParam("enum_query_model_array") List<@Valid EnumClass> enumQueryModelArray,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString) { } @DELETE diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java index 3b907684f9aa..6a679508b5d6 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserService.java @@ -35,12 +35,12 @@ public interface UserService { @POST @Path("/createWithArray") @Consumes({ "application/json" }) - void createUsersWithArrayInput(@Valid @NotNull List user); + void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> user); @POST @Path("/createWithList") @Consumes({ "application/json" }) - void createUsersWithListInput(@Valid @NotNull List user); + void createUsersWithListInput(@Valid @NotNull List<@Valid User> user); @DELETE @Path("/{username}") diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java index b5189292c8d5..a439f5904dde 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/api/UserServiceImpl.java @@ -37,13 +37,13 @@ public void createUser(@Valid @NotNull User user) { @POST @Path("/createWithArray") @Consumes({ "application/json" }) - public void createUsersWithArrayInput(@Valid @NotNull List user) { + public void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> user) { } @POST @Path("/createWithList") @Consumes({ "application/json" }) - public void createUsersWithListInput(@Valid @NotNull List user) { + public void createUsersWithListInput(@Valid @NotNull List<@Valid User> user) { } @DELETE diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java index bee37780d6b0..d599c7993066 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ArrayTest.java @@ -31,7 +31,7 @@ public class ArrayTest { private List> arrayArrayOfInteger = null; - private List> arrayArrayOfModel = null; + private List> arrayArrayOfModel = null; /** * Get arrayOfString @@ -87,23 +87,23 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } /** * Set arrayArrayOfModel **/ - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; } diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java index 96c548cf136a..0b7086059457 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumArrays.java @@ -53,7 +53,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -62,8 +62,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -102,7 +102,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -111,8 +111,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java index dcd8482b869c..c25829e3bb9b 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumClass.java @@ -39,7 +39,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -48,8 +48,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java index c5054303fc57..9476edffbf91 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/EnumTest.java @@ -56,7 +56,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -65,8 +65,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -105,7 +105,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -114,8 +114,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -154,7 +154,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -163,8 +163,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -203,7 +203,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -212,8 +212,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java index 734eba6873de..1b47816ef284 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java @@ -29,7 +29,7 @@ public class FileSchemaTestClass { private ModelFile _file; - private List files = null; + private List<@Valid ModelFile> files = null; /** * Get _file @@ -55,18 +55,18 @@ public FileSchemaTestClass _file(ModelFile _file) { * Get files * @return files **/ - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } /** * Set files **/ - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java index ceb79d014d52..c98c85ccbebb 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/FormatTest.java @@ -423,7 +423,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java index c36c7ee0cc41..4a446f75cf36 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/MapTest.java @@ -54,7 +54,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -63,8 +63,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java index dc24a224465a..c2c23ed5d786 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java @@ -34,7 +34,7 @@ public class ObjectWithDeprecatedFields { private DeprecatedObject deprecatedRef; - private List bars = null; + private List<@Valid String> bars = null; /** * Get uuid @@ -106,18 +106,18 @@ public ObjectWithDeprecatedFields deprecatedRef(DeprecatedObject deprecatedRef) * @deprecated **/ @Deprecated - public List getBars() { + public List<@Valid String> getBars() { return bars; } /** * Set bars **/ - public void setBars(List bars) { + public void setBars(List<@Valid String> bars) { this.bars = bars; } - public ObjectWithDeprecatedFields bars(List bars) { + public ObjectWithDeprecatedFields bars(List<@Valid String> bars) { this.bars = bars; return this; } diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java index 62b985da196d..707cdd3797f9 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Order.java @@ -59,7 +59,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -68,8 +68,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java index 771c8a4c8f79..794742e314a4 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnum.java @@ -39,7 +39,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -48,8 +48,8 @@ public static OuterEnum fromString(String s) { } } return null; - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java index 8900e4a6bb95..4ea374968f28 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java @@ -39,7 +39,7 @@ public enum OuterEnumDefaultValue { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnumDefaultValue fromString(String s) { + public static OuterEnumDefaultValue fromString(String s) { for (OuterEnumDefaultValue b : OuterEnumDefaultValue.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -48,8 +48,8 @@ public static OuterEnumDefaultValue fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java index e18841134b79..926a9e7aaa9f 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumInteger.java @@ -39,7 +39,7 @@ public enum OuterEnumInteger { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnumInteger fromString(String s) { + public static OuterEnumInteger fromString(String s) { for (OuterEnumInteger b : OuterEnumInteger.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -48,8 +48,8 @@ public static OuterEnumInteger fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java index 0150c204d6aa..dbefa5e7adb3 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java @@ -39,7 +39,7 @@ public enum OuterEnumIntegerDefaultValue { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnumIntegerDefaultValue fromString(String s) { + public static OuterEnumIntegerDefaultValue fromString(String s) { for (OuterEnumIntegerDefaultValue b : OuterEnumIntegerDefaultValue.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -48,8 +48,8 @@ public static OuterEnumIntegerDefaultValue fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ParentWithNullable.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ParentWithNullable.java index beb88e89ed56..3ea71056eb04 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ParentWithNullable.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/ParentWithNullable.java @@ -54,7 +54,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static TypeEnum fromString(String s) { + public static TypeEnum fromString(String s) { for (TypeEnum b : TypeEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -63,8 +63,8 @@ public static TypeEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static TypeEnum fromValue(String value) { for (TypeEnum b : TypeEnum.values()) { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java index 086af461f877..f58096fff738 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/Pet.java @@ -41,7 +41,7 @@ public class Pet { private Set photoUrls = new LinkedHashSet<>(); - private List tags = null; + private List<@Valid Tag> tags = null; public enum StatusEnum { @@ -68,7 +68,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -77,8 +77,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -187,18 +187,18 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } /** * Set tags **/ - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java index 9442b2914d20..785373988abd 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java +++ b/samples/server/petstore/java-helidon-server/mp/src/main/java/org/openapitools/server/model/SingleRefType.java @@ -37,7 +37,7 @@ public enum SingleRefType { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static SingleRefType fromString(String s) { + public static SingleRefType fromString(String s) { for (SingleRefType b : SingleRefType.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -46,8 +46,8 @@ public static SingleRefType fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml index efc990069c1b..a2995b488403 100644 --- a/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml +++ b/samples/server/petstore/java-helidon-server/mp/src/main/resources/META-INF/openapi.yml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION b/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION +++ b/samples/server/petstore/java-helidon-server/se/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-helidon-server/se/README.md b/samples/server/petstore/java-helidon-server/se/README.md index 182694aed7ac..9d1d931646dc 100644 --- a/samples/server/petstore/java-helidon-server/se/README.md +++ b/samples/server/petstore/java-helidon-server/se/README.md @@ -21,6 +21,7 @@ curl -X POST http://petstore.swagger.io:80/v2/fake/outer/composite curl -X POST http://petstore.swagger.io:80/v2/fake/outer/number curl -X POST http://petstore.swagger.io:80/v2/fake/outer/string curl -X POST http://petstore.swagger.io:80/v2/fake/property/enum-int +curl -X POST http://petstore.swagger.io:80/v2/fake/additionalProperties-reference curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-binary curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-file-schema curl -X PUT http://petstore.swagger.io:80/v2/fake/body-with-query-params diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java index 5b20a7daaf8a..320cfd74d393 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeService.java @@ -41,6 +41,7 @@ default void update(Routing.Rules rules) { rules.post("/fake/outer/number", this::fakeOuterNumberSerialize); rules.post("/fake/outer/string", this::fakeOuterStringSerialize); rules.post("/fake/property/enum-int", Handler.create(OuterObjectWithEnumProperty.class, this::fakePropertyEnumIntegerSerialize)); + rules.post("/fake/additionalProperties-reference", this::testAdditionalPropertiesReference); rules.put("/fake/body-with-binary", this::testBodyWithBinary); rules.put("/fake/body-with-file-schema", Handler.create(FileSchemaTestClass.class, this::testBodyWithFileSchema)); rules.put("/fake/body-with-query-params", Handler.create(User.class, this::testBodyWithQueryParams)); @@ -115,6 +116,13 @@ default void update(Routing.Rules rules) { */ void fakePropertyEnumIntegerSerialize(ServerRequest request, ServerResponse response, OuterObjectWithEnumProperty outerObjectWithEnumProperty); + /** + * POST /fake/additionalProperties-reference : test referenced additionalProperties. + * @param request the server request + * @param response the server response + */ + void testAdditionalPropertiesReference(ServerRequest request, ServerResponse response); + /** * PUT /fake/body-with-binary. * @param request the server request diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java index bed72a659342..b92126a893a9 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/api/FakeServiceImpl.java @@ -63,6 +63,10 @@ public void fakePropertyEnumIntegerSerialize(ServerRequest request, ServerRespon response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); } + public void testAdditionalPropertiesReference(ServerRequest request, ServerResponse response) { + response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); + } + public void testBodyWithBinary(ServerRequest request, ServerResponse response) { response.status(HTTP_CODE_NOT_IMPLEMENTED).send(); } diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java index 9f9f831237ce..1266dac5d907 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AdditionalPropertiesClass.java @@ -2,6 +2,8 @@ import java.util.HashMap; import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java index cdf67cc9aa49..63eeb7f67afb 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/AllOfWithSingleRef.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.server.model.SingleRefType; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java index 1aa44d002043..548edc48a8a8 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Animal.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java index acd3cfc6391d..dab2aafb6ad0 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfArrayOfNumberOnly.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java index 780d79670469..96ff5ea0a444 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayOfNumberOnly.java @@ -4,6 +4,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java index 18a0c9a8f9a7..8112ec19d48a 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ArrayTest.java @@ -4,6 +4,8 @@ import java.util.Arrays; import java.util.List; import org.openapitools.server.model.ReadOnlyFirst; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @@ -11,7 +13,7 @@ public class ArrayTest { private List arrayOfString; private List> arrayArrayOfInteger; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; /** * Default constructor. @@ -30,7 +32,7 @@ public ArrayTest() { public ArrayTest( List arrayOfString, List> arrayArrayOfInteger, - List> arrayArrayOfModel + List> arrayArrayOfModel ) { this.arrayOfString = arrayOfString; this.arrayArrayOfInteger = arrayArrayOfInteger; @@ -67,11 +69,11 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { * Get arrayArrayOfModel * @return arrayArrayOfModel */ - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java index ab3f58fcd434..942f62d57fbc 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Capitalization.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java index 663f2a85183a..d0d01e632a5e 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Cat.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java index f449dcdbdcc4..ce9f854b3b91 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Category.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ChildWithNullable.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ChildWithNullable.java index aced0bb7a9ef..ea4c963b2b56 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ChildWithNullable.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ChildWithNullable.java @@ -7,6 +7,8 @@ import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.jackson.nullable.JsonNullable; import org.openapitools.server.model.ParentWithNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java index ba7528f6ddb1..806a179ba10a 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ClassModel.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java index 76c4d19ab60c..3b500ac997ee 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Client.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java index 7add1761a845..4e2b7051130c 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/DeprecatedObject.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java index 2c904956ac4c..f935612575ee 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Dog.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java index da4a33310ba3..ba6203947fe2 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumArrays.java @@ -5,6 +5,8 @@ import java.util.ArrayList; import java.util.Arrays; import java.util.List; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java index d3f6c24ce36c..ce974651d829 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumClass.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java index 54b36a98ed9a..d2d7d27c9414 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/EnumTest.java @@ -8,6 +8,8 @@ import org.openapitools.server.model.OuterEnumDefaultValue; import org.openapitools.server.model.OuterEnumInteger; import org.openapitools.server.model.OuterEnumIntegerDefaultValue; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FakeBigDecimalMap200Response.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FakeBigDecimalMap200Response.java index 3236f8167539..b50b92931cf5 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FakeBigDecimalMap200Response.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FakeBigDecimalMap200Response.java @@ -4,6 +4,8 @@ import java.math.BigDecimal; import java.util.HashMap; import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java index 7ed4f1009d44..34fbdce5ca9e 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FileSchemaTestClass.java @@ -4,13 +4,15 @@ import java.util.Arrays; import java.util.List; import org.openapitools.server.model.ModelFile; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; public class FileSchemaTestClass { private ModelFile _file; - private List files; + private List<@Valid ModelFile> files; /** * Default constructor. @@ -27,7 +29,7 @@ public FileSchemaTestClass() { */ public FileSchemaTestClass( ModelFile _file, - List files + List<@Valid ModelFile> files ) { this._file = _file; this.files = files; @@ -51,11 +53,11 @@ public void setFile(ModelFile _file) { * Get files * @return files */ - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java index 6b3869f6f4ca..e02a00803c22 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Foo.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java index f4716bdfcd1e..40f8d5855417 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FooGetDefaultResponse.java @@ -2,6 +2,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import org.openapitools.server.model.Foo; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java index df656b5b83c4..92e3aef3e80d 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/FormatTest.java @@ -6,6 +6,8 @@ import java.time.LocalDate; import java.time.OffsetDateTime; import java.util.UUID; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @@ -316,7 +318,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java index b5228bf6e66d..50c41f059e3b 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HasOnlyReadOnly.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java index 97e9dba137ad..5b865aa0e3f3 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/HealthCheckResult.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import org.openapitools.jackson.nullable.JsonNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java index 4bef65f6a8e2..f8051c6e3e45 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MapTest.java @@ -4,6 +4,8 @@ import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java index 0a6bef328e2b..9f2e5dc7bbef 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -5,6 +5,8 @@ import java.util.Map; import java.util.UUID; import org.openapitools.server.model.Animal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java index dc685bdf99bd..28f6bd2cdac0 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Model200Response.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java index 10d22866ed5c..81a468f1af79 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelApiResponse.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java index 0721c23130d4..6743c641a001 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelFile.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java index 6bba122e69ea..88000df9959e 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelList.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java index 0b9538b4aafc..a11d5e2b4e49 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ModelReturn.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java index a081e1d5c13a..a3524465b284 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Name.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; /** diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java index 9e9ed3215cd2..fa9e97a3c055 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NullableClass.java @@ -9,6 +9,8 @@ import java.util.List; import java.util.Map; import org.openapitools.jackson.nullable.JsonNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java index 3a003f97091e..7caf3c857f39 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/NumberOnly.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import java.math.BigDecimal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java index 2a6633c0f2cb..4c052bc32816 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ObjectWithDeprecatedFields.java @@ -5,6 +5,8 @@ import java.util.Arrays; import java.util.List; import org.openapitools.server.model.DeprecatedObject; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @@ -13,7 +15,7 @@ public class ObjectWithDeprecatedFields { private String uuid; private BigDecimal id; private DeprecatedObject deprecatedRef; - private List bars; + private List<@Valid String> bars; /** * Default constructor. @@ -34,7 +36,7 @@ public ObjectWithDeprecatedFields( String uuid, BigDecimal id, DeprecatedObject deprecatedRef, - List bars + List<@Valid String> bars ) { this.uuid = uuid; this.id = id; @@ -84,11 +86,11 @@ public void setDeprecatedRef(DeprecatedObject deprecatedRef) { * Get bars * @return bars */ - public List getBars() { + public List<@Valid String> getBars() { return bars; } - public void setBars(List bars) { + public void setBars(List<@Valid String> bars) { this.bars = bars; } diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java index 39a04dc15112..0ca5e240f6f6 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Order.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.time.OffsetDateTime; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java index 92eb34508d3f..696e549642d2 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterComposite.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import java.math.BigDecimal; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java index 3cdb4cdeb794..5a6730ab1b57 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnum.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java index c8110bd330ab..986b7b1f7f60 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumDefaultValue.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java index b6d2661725fe..ad5c4c2d3784 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumInteger.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java index af1fe21752aa..93151449261e 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterEnumIntegerDefaultValue.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java index 54e563c42d3c..cd57e792975e 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/OuterObjectWithEnumProperty.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.server.model.OuterEnumInteger; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ParentWithNullable.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ParentWithNullable.java index 22a7bc13fce2..74568b6224ed 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ParentWithNullable.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ParentWithNullable.java @@ -6,6 +6,8 @@ import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.jackson.nullable.JsonNullable; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java index 2ac850409977..17dd8d5f5170 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Pet.java @@ -10,6 +10,8 @@ import java.util.Set; import org.openapitools.server.model.Category; import org.openapitools.server.model.Tag; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @@ -19,7 +21,7 @@ public class Pet { private Category category; private String name; private Set photoUrls = new LinkedHashSet<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -82,7 +84,7 @@ public Pet( Category category, String name, Set photoUrls, - List tags, + List<@Valid Tag> tags, StatusEnum status ) { this.id = id; @@ -147,11 +149,11 @@ public void setPhotoUrls(Set photoUrls) { * Get tags * @return tags */ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java index e62e2270eea5..6e9d1f16fb1d 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/ReadOnlyFirst.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java index 6689e8a2b60c..d7ada5dddeaf 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SingleRefType.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; import com.fasterxml.jackson.annotation.JsonCreator; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java index 2ab0a3701978..9c14659f899a 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/SpecialModelName.java @@ -1,6 +1,8 @@ package org.openapitools.server.model; import com.fasterxml.jackson.annotation.JsonTypeName; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java index 494d8fcf9280..e0d425d782e2 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/Tag.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/TestInlineFreeformAdditionalPropertiesRequest.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/TestInlineFreeformAdditionalPropertiesRequest.java index ef5a7dabad7f..499fa5013feb 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/TestInlineFreeformAdditionalPropertiesRequest.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/TestInlineFreeformAdditionalPropertiesRequest.java @@ -3,6 +3,8 @@ import com.fasterxml.jackson.annotation.JsonTypeName; import java.util.HashMap; import java.util.Map; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java index 8110b662252a..9decbea90472 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java +++ b/samples/server/petstore/java-helidon-server/se/src/main/java/org/openapitools/server/model/User.java @@ -1,5 +1,7 @@ package org.openapitools.server.model; +import jakarta.validation.constraints.*; +import jakarta.validation.Valid; diff --git a/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml b/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml index efc990069c1b..a2995b488403 100644 --- a/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml +++ b/samples/server/petstore/java-helidon-server/se/src/main/resources/META-INF/openapi.yml @@ -1010,6 +1010,25 @@ paths: - fake x-content-type: application/x-www-form-urlencoded x-accepts: application/json + /fake/additionalProperties-reference: + post: + description: "" + operationId: testAdditionalPropertiesReference + requestBody: + content: + application/json: + schema: + $ref: '#/components/schemas/FreeFormObject' + description: request body + required: true + responses: + "200": + description: successful operation + summary: test referenced additionalProperties + tags: + - fake + x-content-type: application/json + x-accepts: application/json /fake/inline-additionalProperties: post: description: "" @@ -1851,6 +1870,10 @@ components: type: string type: array type: object + FreeFormObject: + additionalProperties: true + description: A schema consisting only of additional properties + type: object OuterEnum: enum: - placed @@ -1919,6 +1942,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/java-micronaut-server/.openapi-generator/VERSION b/samples/server/petstore/java-micronaut-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-micronaut-server/.openapi-generator/VERSION +++ b/samples/server/petstore/java-micronaut-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-micronaut-server/docs/controllers/UserController.md b/samples/server/petstore/java-micronaut-server/docs/controllers/UserController.md index d35eab18468d..c29abaa8a8d4 100644 --- a/samples/server/petstore/java-micronaut-server/docs/controllers/UserController.md +++ b/samples/server/petstore/java-micronaut-server/docs/controllers/UserController.md @@ -51,7 +51,7 @@ Creates list of users with given input array ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**user** | [**List<User>**](../../docs/models/User.md) | List of user object | +**user** | [**List<@Valid User>**](../../docs/models/User.md) | List of user object | ### Authorization @@ -74,7 +74,7 @@ Creates list of users with given input array ### Parameters Name | Type | Description | Notes ------------- | ------------- | ------------- | ------------- -**user** | [**List<User>**](../../docs/models/User.md) | List of user object | +**user** | [**List<@Valid User>**](../../docs/models/User.md) | List of user object | ### Authorization diff --git a/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/controller/UserController.java b/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/controller/UserController.java index 2f97208d1a71..e849f2b51eb7 100644 --- a/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/controller/UserController.java +++ b/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/controller/UserController.java @@ -93,7 +93,7 @@ public Mono createUser( @Produces(value = {}) @Consumes(value = {"application/json"}) public Mono createUsersWithArrayInput( - @Body @NotNull List user + @Body @NotNull List<@Valid User> user ) { // TODO implement createUsersWithArrayInput(); return Mono.error(new HttpStatusException(HttpStatus.NOT_IMPLEMENTED, null)); @@ -123,7 +123,7 @@ public Mono createUsersWithArrayInput( @Produces(value = {}) @Consumes(value = {"application/json"}) public Mono createUsersWithListInput( - @Body @NotNull List user + @Body @NotNull List<@Valid User> user ) { // TODO implement createUsersWithListInput(); return Mono.error(new HttpStatusException(HttpStatus.NOT_IMPLEMENTED, null)); diff --git a/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/model/Pet.java index 7bbb87a186ea..0346cbecedc1 100644 --- a/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/java-micronaut-server/src/main/java/org/openapitools/model/Pet.java @@ -56,7 +56,7 @@ public class Pet { private List photoUrls = new ArrayList<>(); public static final String JSON_PROPERTY_TAGS = "tags"; - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -198,7 +198,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -219,13 +219,13 @@ public Pet addTagsItem(Tag tagsItem) { @Schema(name = "tags", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } @JsonProperty(JSON_PROPERTY_TAGS) @JsonInclude(value = JsonInclude.Include.USE_DEFAULTS) - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-msf4j/.openapi-generator/VERSION +++ b/samples/server/petstore/java-msf4j/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApi.java index a54f5e2a3ee4..c414b0db8f2a 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApi.java @@ -51,7 +51,7 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List body + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List<@Valid User> body ) throws NotFoundException { return delegate.createUsersWithArrayInput(body); @@ -63,7 +63,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List body + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List<@Valid User> body ) throws NotFoundException { return delegate.createUsersWithListInput(body); diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApiService.java index 905aab2c1b61..864db80f2e86 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/api/UserApiService.java @@ -22,9 +22,9 @@ public abstract class UserApiService { public abstract Response createUser(User body ) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body + public abstract Response createUsersWithArrayInput(List<@Valid User> body ) throws NotFoundException; - public abstract Response createUsersWithListInput(List body + public abstract Response createUsersWithListInput(List<@Valid User> body ) throws NotFoundException; public abstract Response deleteUser(String username ) throws NotFoundException; diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/ArrayTest.java index 187da0ad45a3..f807f4daec7a 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/ArrayTest.java @@ -22,7 +22,7 @@ public class ArrayTest { private List> arrayArrayOfInteger = null; @JsonProperty("array_array_of_model") - private List> arrayArrayOfModel = null; + private List> arrayArrayOfModel = null; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -76,12 +76,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = ; } @@ -94,11 +94,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * @return arrayArrayOfModel **/ @ApiModelProperty(value = "") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 216cd400f286..78ae9ae5237e 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -19,7 +19,7 @@ public class FileSchemaTestClass { private ModelFile _file; @JsonProperty("files") - private List files = null; + private List<@Valid ModelFile> files = null; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -39,7 +39,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -57,11 +57,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { * @return files **/ @ApiModelProperty(value = "") - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FormatTest.java index 8937ac052845..90c995e233be 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/FormatTest.java @@ -368,7 +368,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/Pet.java index d918f75324f3..7c7bed08c872 100644 --- a/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/java-msf4j/src/gen/java/org/openapitools/model/Pet.java @@ -33,7 +33,7 @@ public class Pet { private Set photoUrls = new LinkedHashSet<>(); @JsonProperty("tags") - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -149,7 +149,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -167,11 +167,11 @@ public Pet addTagsItem(Tag tagsItem) { * @return tags **/ @ApiModelProperty(value = "") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-msf4j/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/java-msf4j/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 092f5f3a5819..055a942b819d 100644 --- a/samples/server/petstore/java-msf4j/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/java-msf4j/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -27,13 +27,13 @@ public Response createUser(User body return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List body + public Response createUsersWithArrayInput(List<@Valid User> body ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List body + public Response createUsersWithListInput(List<@Valid User> body ) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-api-package-override/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/User.java b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiController.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiController.java index 55ff3e6b7952..bf6da104bd6b 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiController.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImp.java index 99652aa88ba9..3441fea08348 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImpInterface.java index a6863a4d9bc0..b7b5c9d83d88 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiController.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiController.java index 47c5b5c2c341..336a57069cf2 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImp.java index e9f736fadf62..7bfb4863bc10 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImpInterface.java index b18fcb34cc81..9df120612613 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiController.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiController.java index e6a78057b93c..7e5334377601 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiController.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -55,9 +56,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -72,9 +73,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImp.java index cc782eb4c050..c4783f3e0e69 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImpInterface.java index b591a04e9e68..58abb056b58b 100644 --- a/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-api-package-override/app/com/puppies/store/apis/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-async/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-async/app/apimodels/User.java b/samples/server/petstore/java-play-framework-async/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-async/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-async/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java index 093fa1b2a6ce..e24e2d82e838 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiController.java @@ -24,6 +24,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java index b865f46dffd0..0e07789f372d 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImp.java @@ -14,6 +14,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java index 73f7d4c870ba..2bad62696e26 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/PetApiControllerImpInterface.java @@ -24,6 +24,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java index 927c2794470f..3af3ee78dd7f 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiController.java @@ -23,6 +23,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java index 05b9594f9994..13d3d0e33537 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImp.java @@ -13,6 +13,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java index 3afa76d31144..02431b095ca1 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/StoreApiControllerImpInterface.java @@ -23,6 +23,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java index a48e8d6b4374..12c1fb33d95c 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiController.java @@ -23,6 +23,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -58,9 +59,9 @@ public CompletionStage createUser(Http.Request request) throws Exception @ApiAction public CompletionStage createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -75,9 +76,9 @@ public CompletionStage createUsersWithArrayInput(Http.Request request) t @ApiAction public CompletionStage createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java index d91f66b3cf4e..046032de713e 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImp.java @@ -13,6 +13,7 @@ import java.util.concurrent.CompletionStage; import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -21,12 +22,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java index 7c9f9f60346e..21388f030cec 100644 --- a/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-async/app/controllers/UserApiControllerImpInterface.java @@ -23,6 +23,7 @@ import java.util.concurrent.CompletableFuture; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -45,7 +46,7 @@ public CompletionStage createUserHttp(Http.Request request, User body) t public abstract void createUser(Http.Request request, User body) throws Exception; - public CompletionStage createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public CompletionStage createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { CompletableFuture result = CompletableFuture.supplyAsync(() -> { try { createUsersWithArrayInput(request, body); @@ -58,9 +59,9 @@ public CompletionStage createUsersWithArrayInputHttp(Http.Request reques } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public CompletionStage createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public CompletionStage createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { CompletableFuture result = CompletableFuture.supplyAsync(() -> { try { createUsersWithListInput(request, body); @@ -73,7 +74,7 @@ public CompletionStage createUsersWithListInputHttp(Http.Request request } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public CompletionStage deleteUserHttp(Http.Request request, String username) throws Exception { CompletableFuture result = CompletableFuture.supplyAsync(() -> { diff --git a/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-controller-only/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java index a477bbba24ea..15c1739a07d1 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java index f8ac351ae749..f75bc166f38f 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java index 0a862bf9d2c0..91c91a8fa734 100644 --- a/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-controller-only/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -53,9 +54,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -70,9 +71,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/User.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiController.java index d66a24f477c3..20e07a95ad4b 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiController.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImp.java index baaedaae78c9..f429d96bd8b2 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImp.java @@ -10,6 +10,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImpInterface.java index 3c05b7bff361..0a6e22a7af49 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints-with-security/app/controllers/PetApiControllerImpInterface.java @@ -19,6 +19,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-fake-endpoints/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesAnyType.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesAnyType.java index b0a7d76dd743..b596063e22a3 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesAnyType.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesAnyType */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesArray.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesArray.java index 84342b61bd46..8c802c737899 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesArray.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesArray.java @@ -8,6 +8,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesArray */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesBoolean.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesBoolean.java index f6631c053d4f..98b3f22bacd1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesBoolean.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesBoolean */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java index 84ba450c9601..044eaf655d49 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesClass.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesClass */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesInteger.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesInteger.java index 9d1d43a69d83..712afcd8b5fd 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesInteger.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesInteger */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesNumber.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesNumber.java index d87ad137d020..4ee8a083c0ad 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesNumber.java @@ -8,6 +8,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesNumber */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesObject.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesObject.java index c7bf488d2ffd..830315edb27e 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesObject.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesObject.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesObject */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesString.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesString.java index 0c2c8c1ebc4a..746fdd04e47b 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesString.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/AdditionalPropertiesString.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * AdditionalPropertiesString */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java index f7b46fdf15e8..7370e4269721 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Animal.java @@ -8,6 +8,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Animal */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java index c6def2db6ad3..7c930dc6a937 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfArrayOfNumberOnly.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ArrayOfArrayOfNumberOnly */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java index f397215bac15..c6a814c8d18c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayOfNumberOnly.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ArrayOfNumberOnly */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java index b894cfc76b37..5a11d75d9968 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ArrayTest.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ArrayTest */ @@ -27,7 +28,7 @@ public class ArrayTest { @JsonProperty("array_array_of_model") @Valid - private List> arrayArrayOfModel = null; + private List> arrayArrayOfModel = null; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -79,12 +80,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -96,11 +97,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI * Get arrayArrayOfModel * @return arrayArrayOfModel **/ - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/BigCat.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/BigCat.java index 4acdbb7e67aa..fdddc5300d61 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/BigCat.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/BigCat.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * BigCat */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java index adbe5dd10fae..27a669388840 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Capitalization.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Capitalization */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java index 014159adc645..168c9ed651fb 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Cat.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Cat */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java index 453ad7e2a958..dd84fb3e24fa 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Category */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java index a35a880dd0c8..bcf0008f22bc 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ClassModel.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Model for testing model with \"_class\" property */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java index e5792709a198..6c2947efdf72 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Client.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Client */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java index 8887b68658ae..2943b8d6c063 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Dog.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Dog */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java index c2d1b809165b..73f0822af839 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumArrays.java @@ -8,6 +8,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * EnumArrays */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java index 6081f7810492..11d48fee066b 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/EnumTest.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * EnumTest */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FileSchemaTestClass.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FileSchemaTestClass.java index 9a11315dd65c..147456326d4f 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FileSchemaTestClass.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FileSchemaTestClass.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * FileSchemaTestClass */ @@ -23,7 +24,7 @@ public class FileSchemaTestClass { @JsonProperty("files") @Valid - private List files = null; + private List<@Valid ModelFile> files = null; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -42,7 +43,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -59,11 +60,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { * Get files * @return files **/ - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java index 13e3f7e8ba04..24462c23a843 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/FormatTest.java @@ -11,6 +11,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * FormatTest */ @@ -393,7 +394,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java index 697e96681c7d..afdf9b42ffe9 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/HasOnlyReadOnly.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * HasOnlyReadOnly */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java index 230ffa29bc84..a2d839ecda3c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MapTest.java @@ -7,6 +7,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * MapTest */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java index b5ae9f0b47fd..8d5294afa279 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/MixedPropertiesAndAdditionalPropertiesClass.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * MixedPropertiesAndAdditionalPropertiesClass */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java index ebffc7e5dc27..2e560509bac3 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Model200Response.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Model for testing model name starting with number */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java index 0820d45f5def..a7eda644d156 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ModelApiResponse */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelFile.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelFile.java index 9f509226df49..f500767f55fc 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelFile.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelFile.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Must be named `File` for test. */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelList.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelList.java index e31afffb3ac2..99113c60c67a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelList.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelList.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ModelList */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java index e367c3941e94..fb6e7414102c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ModelReturn.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Model for testing reserved words */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java index 232f49c5dceb..e7365ee40ef1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Name.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Model for testing model name same as property name */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java index bbcccc2ebe09..50d14fe892f1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/NumberOnly.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * NumberOnly */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java index ad0b6c1e8617..a49f506d42c0 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Order */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java index 3f19923097ac..ee01312bf163 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/OuterComposite.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * OuterComposite */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java index f58450cb480d..3621b6d35d65 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Pet.java @@ -13,6 +13,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Pet */ @@ -41,7 +42,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -157,7 +158,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -174,11 +175,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java index 55d2816002b8..1ed67fc36637 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/ReadOnlyFirst.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * ReadOnlyFirst */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java index da472606817b..779ca5d74ff3 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/SpecialModelName.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * SpecialModelName */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java index 39bceb93f4ac..e200bcda99de 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Tag */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderDefault.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderDefault.java index 688a80ca22b7..b7fb95fff2cc 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderDefault.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderDefault.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * TypeHolderDefault */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderExample.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderExample.java index 8a713cb754d0..08d86718b51d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderExample.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/TypeHolderExample.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * TypeHolderExample */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java index 72ef978f3dca..3b3c01615e6a 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * User */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/XmlItem.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/XmlItem.java index 09654e3285d1..aa88e14b9a73 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/XmlItem.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/apimodels/XmlItem.java @@ -9,6 +9,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * XmlItem */ diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java index 1583cc31312a..1110f15b03c3 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImp.java index 090cf0e428af..f069c2316cbd 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class AnotherFakeApiControllerImp extends AnotherFakeApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImpInterface.java index 2ab1a36b0d98..cda2b4a8b326 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/AnotherFakeApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class AnotherFakeApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java index 8cc88003ee33..45901365f1b1 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiController.java @@ -28,6 +28,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java index 0d999b3bde66..1fc64b9c08c5 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImp.java @@ -19,6 +19,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class FakeApiControllerImp extends FakeApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java index b7871b677ac6..4625cca51f05 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeApiControllerImpInterface.java @@ -28,6 +28,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class FakeApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java index 8f2ca195120a..4129cedfd8ad 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiController.java @@ -19,6 +19,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImp.java index c3103ee3ec87..51ebec1dd04f 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImp.java @@ -10,6 +10,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class FakeClassnameTags123ApiControllerImp extends FakeClassnameTags123ApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImpInterface.java index 17286d728b85..64c01a9e1eac 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/FakeClassnameTags123ApiControllerImpInterface.java @@ -19,6 +19,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class FakeClassnameTags123ApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java index 700be254347a..bc3848b0e41d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiController.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java index d1c85f1e7fdd..ebc97f08ff73 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImp.java @@ -13,6 +13,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImpInterface.java index e9ab7c1397f8..73b25e32a7c9 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/PetApiControllerImpInterface.java @@ -22,6 +22,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java index 29596d15fb1e..ba0449715144 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java index 0d10b230b617..c42de86818b9 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImpInterface.java index 67780d39c1cf..3111fd7b6c4c 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java index 240f87644886..33d172d7c431 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -55,9 +56,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -72,9 +73,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java index 941e5d9f6ce2..284f8c7f950d 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImpInterface.java index 9737f817f0e2..083eb4d7d02e 100644 --- a/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-fake-endpoints/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-bean-validation/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-exception-handling/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java index e52afb643a2b..0ecbaa0f48eb 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiController.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java index 5a45819711ef..0010fd8ce7e6 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImpInterface.java index 34df059ba94a..34cfbb257d62 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java index 79c7202aaa27..ee129b72004d 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java index ca2f73e6c3a6..ef8464bbc037 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImpInterface.java index 31e5240767ad..e2cb6abf8083 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java index 939a7afdacd9..78e543a3cbdd 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -56,9 +57,9 @@ public Result createUser(Http.Request request) throws IOException { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws IOException { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -73,9 +74,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws IOException @ApiAction public Result createUsersWithListInput(Http.Request request) throws IOException { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java index 79dfd1844648..d5399a889fe2 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImpInterface.java index d26ead9d14da..712cf4ead3a1 100644 --- a/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-exception-handling/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) { public abstract void createUser(Http.Request request, User body) ; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) ; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) ; - public Result createUsersWithListInputHttp(Http.Request request, List body) { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) ; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) ; public Result deleteUserHttp(Http.Request request, String username) { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-interface/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java index f43290fb2124..4db2b07fde99 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiController.java @@ -22,6 +22,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java index 4f6506d0512b..8c1841bfc78f 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp { diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java index 67f0cd4e3023..b20aaec67e16 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java index 753d05ad817a..823d2088ccc9 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp { diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java index 2d1381a31491..e2cab0ec0e45 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -60,9 +61,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -79,9 +80,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java index 870111fdbb88..14c29717b1ee 100644 --- a/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-interface/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp { @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiController.java index 1ddc6c1eecf9..1cfeaacf882c 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImp.java index dc95e25205a7..cf5da3401f4c 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImpInterface.java index 1173b55dbb78..82bc4782ec0c 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiController.java index 29596d15fb1e..ba0449715144 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImp.java index 0d10b230b617..c42de86818b9 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImpInterface.java index 67780d39c1cf..3111fd7b6c4c 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiController.java index 240f87644886..33d172d7c431 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -55,9 +56,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -72,9 +73,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImp.java index 941e5d9f6ce2..284f8c7f950d 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImpInterface.java index 9737f817f0e2..083eb4d7d02e 100644 --- a/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-nullable/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java index 1ddc6c1eecf9..1cfeaacf882c 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java index dc95e25205a7..cf5da3401f4c 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImpInterface.java index 1173b55dbb78..82bc4782ec0c 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java index 29596d15fb1e..ba0449715144 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java index 0d10b230b617..c42de86818b9 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImpInterface.java index 67780d39c1cf..3111fd7b6c4c 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java index 240f87644886..33d172d7c431 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -55,9 +56,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -72,9 +73,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java index 941e5d9f6ce2..284f8c7f950d 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImpInterface.java index 9737f817f0e2..083eb4d7d02e 100644 --- a/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-swagger-ui/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java index 617a9ad9571e..82a0c8974b94 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java index dc95e25205a7..cf5da3401f4c 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImpInterface.java index 1173b55dbb78..82bc4782ec0c 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java index 1b9df86ea06e..bcd6693da91c 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java index 0d10b230b617..c42de86818b9 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImpInterface.java index 67780d39c1cf..3111fd7b6c4c 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java index 75cb3377a176..6ddf0cb13776 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; @@ -54,9 +55,9 @@ public Result createUser(Http.Request request) throws Exception { public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -71,9 +72,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java index 941e5d9f6ce2..284f8c7f950d 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImpInterface.java index 9737f817f0e2..083eb4d7d02e 100644 --- a/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework-no-wrap-calls/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-play-framework/.openapi-generator/VERSION +++ b/samples/server/petstore/java-play-framework/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Category.java b/samples/server/petstore/java-play-framework/app/apimodels/Category.java index afed4d545a99..2c2765d9a802 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Category.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Category.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet */ diff --git a/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java b/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java index 301968462bb4..883865cd5098 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/ModelApiResponse.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource */ diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Order.java b/samples/server/petstore/java-play-framework/app/apimodels/Order.java index d54cba148ad3..29b6e3f6b5cb 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Order.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Order.java @@ -6,6 +6,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store */ diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Pet.java b/samples/server/petstore/java-play-framework/app/apimodels/Pet.java index 2ea68e667f47..b3bcca614be0 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Pet.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Pet.java @@ -10,6 +10,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store */ @@ -38,7 +39,7 @@ public class Pet { @JsonProperty("tags") @Valid - private List tags = null; + private List<@Valid Tag> tags = null; /** * pet status in the store @@ -153,7 +154,7 @@ public void setPhotoUrls(List photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -170,11 +171,11 @@ public Pet addTagsItem(Tag tagsItem) { * Get tags * @return tags **/ - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/java-play-framework/app/apimodels/Tag.java b/samples/server/petstore/java-play-framework/app/apimodels/Tag.java index adac882cd052..e6019d2887d1 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/Tag.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/Tag.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet */ diff --git a/samples/server/petstore/java-play-framework/app/apimodels/User.java b/samples/server/petstore/java-play-framework/app/apimodels/User.java index 4e5d397b990c..1a157887085b 100644 --- a/samples/server/petstore/java-play-framework/app/apimodels/User.java +++ b/samples/server/petstore/java-play-framework/app/apimodels/User.java @@ -5,6 +5,7 @@ import javax.validation.*; import java.util.Objects; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store */ diff --git a/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java b/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java index 1ddc6c1eecf9..1cfeaacf882c 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/PetApiController.java @@ -21,6 +21,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java index dc95e25205a7..cf5da3401f4c 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImp.java @@ -12,6 +12,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class PetApiControllerImp extends PetApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImpInterface.java b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImpInterface.java index 1173b55dbb78..82bc4782ec0c 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework/app/controllers/PetApiControllerImpInterface.java @@ -21,6 +21,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class PetApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java b/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java index 29596d15fb1e..ba0449715144 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/StoreApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; diff --git a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java index 0d10b230b617..c42de86818b9 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class StoreApiControllerImp extends StoreApiControllerImpInterface { @Override diff --git a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImpInterface.java b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImpInterface.java index 67780d39c1cf..3111fd7b6c4c 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework/app/controllers/StoreApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class StoreApiControllerImpInterface { diff --git a/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java b/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java index 240f87644886..33d172d7c431 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java +++ b/samples/server/petstore/java-play-framework/app/controllers/UserApiController.java @@ -20,6 +20,7 @@ import com.fasterxml.jackson.core.type.TypeReference; import javax.validation.constraints.*; +import javax.validation.Valid; import com.typesafe.config.Config; import openapitools.OpenAPIUtils.ApiAction; @@ -55,9 +56,9 @@ public Result createUser(Http.Request request) throws Exception { @ApiAction public Result createUsersWithArrayInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); @@ -72,9 +73,9 @@ public Result createUsersWithArrayInput(Http.Request request) throws Exception { @ApiAction public Result createUsersWithListInput(Http.Request request) throws Exception { JsonNode nodebody = request.body().asJson(); - List body; + List<@Valid User> body; if (nodebody != null) { - body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); + body = mapper.readValue(nodebody.toString(), new TypeReference>(){}); if (configuration.getBoolean("useInputBeanValidation")) { for (User curItem : body) { OpenAPIUtils.validate(curItem); diff --git a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java index 941e5d9f6ce2..284f8c7f950d 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java +++ b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImp.java @@ -11,6 +11,7 @@ import java.io.FileInputStream; import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaPlayFrameworkCodegen") public class UserApiControllerImp extends UserApiControllerImpInterface { @Override @@ -19,12 +20,12 @@ public void createUser(Http.Request request, User body) throws Exception { } @Override - public void createUsersWithArrayInput(Http.Request request, List body) throws Exception { + public void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } @Override - public void createUsersWithListInput(Http.Request request, List body) throws Exception { + public void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception { //Do your magic!!! } diff --git a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImpInterface.java b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImpInterface.java index 9737f817f0e2..083eb4d7d02e 100644 --- a/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImpInterface.java +++ b/samples/server/petstore/java-play-framework/app/controllers/UserApiControllerImpInterface.java @@ -20,6 +20,7 @@ import play.libs.Files.TemporaryFile; import javax.validation.constraints.*; +import javax.validation.Valid; @SuppressWarnings("RedundantThrows") public abstract class UserApiControllerImpInterface { @@ -35,21 +36,21 @@ public Result createUserHttp(Http.Request request, User body) throws Exception { public abstract void createUser(Http.Request request, User body) throws Exception; - public Result createUsersWithArrayInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithArrayInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithArrayInput(request, body); return ok(); } - public abstract void createUsersWithArrayInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithArrayInput(Http.Request request, List<@Valid User> body) throws Exception; - public Result createUsersWithListInputHttp(Http.Request request, List body) throws Exception { + public Result createUsersWithListInputHttp(Http.Request request, List<@Valid User> body) throws Exception { createUsersWithListInput(request, body); return ok(); } - public abstract void createUsersWithListInput(Http.Request request, List body) throws Exception; + public abstract void createUsersWithListInput(Http.Request request, List<@Valid User> body) throws Exception; public Result deleteUserHttp(Http.Request request, String username) throws Exception { deleteUser(request, username); diff --git a/samples/server/petstore/java-undertow/.openapi-generator/VERSION b/samples/server/petstore/java-undertow/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-undertow/.openapi-generator/VERSION +++ b/samples/server/petstore/java-undertow/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/java-undertow/pom.xml b/samples/server/petstore/java-undertow/pom.xml index 4e56b5df7afb..04503f650a6c 100644 --- a/samples/server/petstore/java-undertow/pom.xml +++ b/samples/server/petstore/java-undertow/pom.xml @@ -26,7 +26,7 @@ 1.10 1.2 3.1.2 - 1.2.0 + 1.4.13 4.13.2 2.1.0-beta.124 2.3.5.Final diff --git a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION +++ b/samples/server/petstore/java-vertx-web/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml index 4944745c89b3..943012770159 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/pom.xml @@ -103,6 +103,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -207,7 +215,7 @@ 1.5.22 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 2.0.2 3.3.0 2.15.2 diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/api/UserApi.java index 35c4e018117b..f6adeea7ab07 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/api/UserApi.java @@ -52,7 +52,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithArrayInput(@Valid @NotNull List body); + public void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body); /** * Creates list of users with given input array @@ -63,7 +63,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithListInput(@Valid @NotNull List body); + public void createUsersWithListInput(@Valid @NotNull List<@Valid User> body); /** * Delete user diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Category.java index d0d6a64d5200..0f5f31cb9f40 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Category.java @@ -65,8 +65,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/ModelApiResponse.java index 731e38fc1f10..ec293afce473 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -87,9 +87,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Order.java index 173dc27081e2..434d1626cdaa 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Order.java @@ -190,12 +190,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Pet.java index 56bd1910d8eb..71af8d8a4ced 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Pet.java @@ -37,7 +37,7 @@ public class Pet { @ApiModelProperty(value = "") @Valid - private List tags; + private List<@Valid Tag> tags; public enum StatusEnum { @@ -160,15 +160,15 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * @return tags **/ @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -208,12 +208,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Tag.java index ad06844b599a..9bbfff095da7 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/Tag.java @@ -65,8 +65,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/User.java index 95535c0da6a7..0225ae5d27c0 100644 --- a/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-annotated-base-path/src/gen/java/org/openapitools/model/User.java @@ -194,14 +194,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-cdi/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml index e7e5910ef3c1..39c1a81cd420 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-cdi/pom.xml @@ -65,7 +65,7 @@ javax javaee-api - 7.0 + 8.0 provided diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApi.java index 879c2f794317..5046e290cdbe 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApi.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; @Path("/pet") @RequestScoped diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApiService.java index 4767577be24d..ad1146edb898 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/PetApiService.java @@ -13,6 +13,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApi.java index ea889006e69f..b18ecac10f75 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApi.java @@ -21,6 +21,7 @@ import java.util.Map; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; @Path("/store") @RequestScoped diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApiService.java index e8c6f2e2ad0c..989854df0ca9 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/StoreApiService.java @@ -13,6 +13,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApi.java index be772166c1cb..b3d89a5b5e03 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApi.java @@ -19,6 +19,7 @@ import java.util.Map; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; @Path("/test/upload") @RequestScoped diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApiService.java index a350d5be4bf4..b947eb9d06a9 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/TestApiService.java @@ -11,6 +11,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApi.java index f90f34580e88..57c44827453f 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApi.java @@ -20,6 +20,7 @@ import java.util.Map; import java.util.List; import javax.validation.constraints.*; +import javax.validation.Valid; @Path("/user") @RequestScoped @@ -59,7 +60,7 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru }, tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List user) { + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) List<@Valid User> user) { return delegate.createUsersWithArrayInput(user, securityContext); } @@ -73,7 +74,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object }, tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List user) { + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) List<@Valid User> user) { return delegate.createUsersWithListInput(user, securityContext); } diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApiService.java index 2d99b1eecfc9..78c66c155fd8 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/api/UserApiService.java @@ -12,14 +12,17 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSCXFCDIServerCodegen") public interface UserApiService { public Response createUser(User user, SecurityContext securityContext); - public Response createUsersWithArrayInput(List user, SecurityContext securityContext); - public Response createUsersWithListInput(List user, SecurityContext securityContext); + public Response createUsersWithArrayInput(List<@Valid User> user, SecurityContext securityContext); + public Response createUsersWithListInput(List<@Valid User> user, SecurityContext securityContext); public Response deleteUser(String username, SecurityContext securityContext); public Response getUserByName(String username, SecurityContext securityContext); public Response loginUser(String username, String password, SecurityContext securityContext); diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Category.java index 752df95b6578..a1177cbf5c9d 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Category.java @@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A category for a pet @@ -67,8 +68,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/ModelApiResponse.java index 697741620fd6..ab73f11f8e8a 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -6,6 +6,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; /** * Describes the result of uploading an image resource @@ -88,9 +89,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Order.java index 37bd6dcf3493..db304e3912fe 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Order.java @@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; /** * An order for a pets from the pet store @@ -179,12 +180,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Pet.java index e53c72149284..19625cc472b3 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Pet.java @@ -10,6 +10,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A pet for sale in the pet store @@ -30,7 +31,7 @@ public class Pet { private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; public enum StatusEnum { @@ -149,7 +150,7 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -157,10 +158,10 @@ public Pet tags(List tags) { @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -202,12 +203,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Tag.java index d5c0ffcc1351..62cb384efea7 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/Tag.java @@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A tag for a pet @@ -67,8 +68,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/User.java index 2c527c2f733e..8c95fc5ddd94 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/gen/java/org/openapitools/model/User.java @@ -5,6 +5,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; /** * A User who is purchasing from the pet store @@ -188,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 687f684ffb7a..eb7d8aab1f2b 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -12,6 +12,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 3fd4ebe823e3..63332da1163f 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -12,6 +12,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/TestApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/TestApiServiceImpl.java index 5b8432c47172..5a044826f374 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/TestApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/TestApiServiceImpl.java @@ -10,6 +10,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 53c6d6384d81..e54b81552c43 100644 --- a/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-cdi/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -11,6 +11,9 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; + import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -24,12 +27,12 @@ public Response createUser(User user, SecurityContext securityContext) { return Response.ok().entity("magic!").build(); } @Override - public Response createUsersWithArrayInput(List user, SecurityContext securityContext) { + public Response createUsersWithArrayInput(List<@Valid User> user, SecurityContext securityContext) { // do some magic! return Response.ok().entity("magic!").build(); } @Override - public Response createUsersWithListInput(List user, SecurityContext securityContext) { + public Response createUsersWithListInput(List<@Valid User> user, SecurityContext securityContext) { // do some magic! return Response.ok().entity("magic!").build(); } diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml index 9300cf77e568..3b93fa950404 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/pom.xml @@ -103,6 +103,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -207,7 +215,7 @@ 1.5.22 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 2.0.2 3.3.0 2.15.2 diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/api/UserApi.java index 7076d234ffec..654b752edcf2 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/api/UserApi.java @@ -52,7 +52,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithArrayInput(@Valid @NotNull List body); + public void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body); /** * Creates list of users with given input array @@ -63,7 +63,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithListInput(@Valid @NotNull List body); + public void createUsersWithListInput(@Valid @NotNull List<@Valid User> body); /** * Delete user diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Category.java index d0d6a64d5200..0f5f31cb9f40 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Category.java @@ -65,8 +65,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/ModelApiResponse.java index 731e38fc1f10..ec293afce473 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -87,9 +87,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Order.java index 173dc27081e2..434d1626cdaa 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Order.java @@ -190,12 +190,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Pet.java index 56bd1910d8eb..71af8d8a4ced 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Pet.java @@ -37,7 +37,7 @@ public class Pet { @ApiModelProperty(value = "") @Valid - private List tags; + private List<@Valid Tag> tags; public enum StatusEnum { @@ -160,15 +160,15 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * @return tags **/ @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -208,12 +208,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Tag.java index ad06844b599a..9bbfff095da7 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/Tag.java @@ -65,8 +65,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/User.java index 95535c0da6a7..0225ae5d27c0 100644 --- a/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-non-spring-app/src/gen/java/org/openapitools/model/User.java @@ -194,14 +194,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/FILES b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/FILES index f62583682996..ddb9b249cd98 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/FILES @@ -21,15 +21,12 @@ src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java src/gen/java/org/openapitools/model/ArrayTest.java src/gen/java/org/openapitools/model/BigCat.java -src/gen/java/org/openapitools/model/BigCatAllOf.java src/gen/java/org/openapitools/model/Capitalization.java src/gen/java/org/openapitools/model/Cat.java -src/gen/java/org/openapitools/model/CatAllOf.java src/gen/java/org/openapitools/model/Category.java src/gen/java/org/openapitools/model/ClassModel.java src/gen/java/org/openapitools/model/Client.java src/gen/java/org/openapitools/model/Dog.java -src/gen/java/org/openapitools/model/DogAllOf.java src/gen/java/org/openapitools/model/EnumArrays.java src/gen/java/org/openapitools/model/EnumClass.java src/gen/java/org/openapitools/model/EnumTest.java diff --git a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION index 0984c4c1ad21..0f78c31cdc77 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf-test-data/.openapi-generator/VERSION @@ -1 +1 @@ -5.4.0-SNAPSHOT \ No newline at end of file +7.2.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf-test-data/pom.xml b/samples/server/petstore/jaxrs-cxf-test-data/pom.xml index f42f6e5455e9..7ce4ace8ecec 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/pom.xml +++ b/samples/server/petstore/jaxrs-cxf-test-data/pom.xml @@ -9,7 +9,7 @@ org.springframework.boot spring-boot-starter-parent - 2.0.4.RELEASE + 2.7.15 src/main/java @@ -108,6 +108,12 @@ javax.ws.rs jsr311-api + + + javax.validation + validation-api + @@ -233,7 +239,7 @@ org.openapitools openapi-generator - 5.4.0-SNAPSHOT + 7.2.0-SNAPSHOT @@ -260,7 +266,7 @@ 9.2.9.v20150224 2.0.2 3.3.0 - 2.9.9 + 2.15.2 UTF-8 diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java index badac196113e..75994bd3788f 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/api/AnotherFakeApi.java @@ -3,6 +3,7 @@ import org.openapitools.model.Client; import java.util.List; import java.util.Map; +import java.util.UUID; import java.io.InputStream; import java.io.OutputStream; @@ -44,5 +45,5 @@ public interface AnotherFakeApi { @ApiOperation(value = "To test special tags", tags={ "$another-fake?" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - public Client call123testSpecialTags(@Valid Client body); + public Client call123testSpecialTags(@HeaderParam("uuid_test") @NotNull UUID uuidTest, @Valid Client body); } diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index c1d4b3d903f2..1f85e8457692 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -39,6 +39,23 @@ public AdditionalPropertiesAnyType name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesAnyType.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 2fd3e00c4fbd..028fd7255af8 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -40,6 +40,23 @@ public AdditionalPropertiesArray name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesArray.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index ea7308bdf40e..67cf122c4f32 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -39,6 +39,23 @@ public AdditionalPropertiesBoolean name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesBoolean.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 37a48a09e271..4c44488f6e79 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -15,33 +15,33 @@ public class AdditionalPropertiesClass { @ApiModelProperty(value = "") - private Map mapString = null; + private Map mapString = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private Map mapNumber = null; + private Map mapNumber = new HashMap<>(); @ApiModelProperty(value = "") - private Map mapInteger = null; + private Map mapInteger = new HashMap<>(); @ApiModelProperty(value = "") - private Map mapBoolean = null; + private Map mapBoolean = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private Map> mapArrayInteger = null; + private Map> mapArrayInteger = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private Map> mapArrayAnytype = null; + private Map> mapArrayAnytype = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private Map> mapMapString = null; + private Map> mapMapString = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private Map> mapMapAnytype = null; + private Map> mapMapAnytype = new HashMap<>(); @ApiModelProperty(value = "") private Object anytype1; @@ -380,6 +380,33 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; + return Objects.equals(mapString, additionalPropertiesClass.mapString) && + Objects.equals(mapNumber, additionalPropertiesClass.mapNumber) && + Objects.equals(mapInteger, additionalPropertiesClass.mapInteger) && + Objects.equals(mapBoolean, additionalPropertiesClass.mapBoolean) && + Objects.equals(mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && + Objects.equals(mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && + Objects.equals(mapMapString, additionalPropertiesClass.mapMapString) && + Objects.equals(mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && + Objects.equals(anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(anytype2, additionalPropertiesClass.anytype2) && + Objects.equals(anytype3, additionalPropertiesClass.anytype3); + } + + @Override + public int hashCode() { + return Objects.hash(mapString, mapNumber, mapInteger, mapBoolean, mapArrayInteger, mapArrayAnytype, mapMapString, mapMapAnytype, anytype1, anytype2, anytype3); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index d60a4749cf9a..02e6ecb993d2 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -39,6 +39,23 @@ public AdditionalPropertiesInteger name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesInteger.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 5f57ca61b26c..fca05dc1b400 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -40,6 +40,23 @@ public AdditionalPropertiesNumber name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesNumber.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index 3e611db1e414..dec4938f8f53 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -39,6 +39,23 @@ public AdditionalPropertiesObject name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesObject.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index e7a00d4d4530..699bb416970f 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -39,6 +39,23 @@ public AdditionalPropertiesString name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; + return super.equals(o) && Objects.equals(name, additionalPropertiesString.name); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java index 8941bea38971..3c837308f0eb 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Animal.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonIgnoreProperties; import com.fasterxml.jackson.annotation.JsonSubTypes; import com.fasterxml.jackson.annotation.JsonTypeInfo; import javax.validation.constraints.*; @@ -73,6 +74,24 @@ public Animal color(String color) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Animal animal = (Animal) o; + return Objects.equals(className, animal.className) && + Objects.equals(color, animal.color); + } + + @Override + public int hashCode() { + return Objects.hash(className, color); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java index 109ba6835022..57f41245c0a8 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/AnimalFarm.java @@ -13,6 +13,22 @@ public class AnimalFarm extends ArrayList { + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + AnimalFarm animalFarm = (AnimalFarm) o;return super.equals(o); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 1e7c179b8d44..8fe5f74d946a 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -15,7 +16,7 @@ public class ArrayOfArrayOfNumberOnly { @ApiModelProperty(value = "") @Valid - private List> arrayArrayNumber = null; + private List> arrayArrayNumber; /** * Get arrayArrayNumber * @return arrayArrayNumber @@ -49,6 +50,23 @@ public ArrayOfArrayOfNumberOnly addArrayArrayNumberItem(List arrayAr } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; + return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayArrayNumber); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 43545d844ecf..26b6e2ca31c3 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -15,7 +16,7 @@ public class ArrayOfNumberOnly { @ApiModelProperty(value = "") @Valid - private List arrayNumber = null; + private List arrayNumber; /** * Get arrayNumber * @return arrayNumber @@ -49,6 +50,23 @@ public ArrayOfNumberOnly addArrayNumberItem(BigDecimal arrayNumberItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; + return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + } + + @Override + public int hashCode() { + return Objects.hash(arrayNumber); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java index 7c7828df4239..a5a43ed6f175 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ArrayTest.java @@ -1,6 +1,7 @@ package org.openapitools.model; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.ReadOnlyFirst; import javax.validation.constraints.*; @@ -14,15 +15,15 @@ public class ArrayTest { @ApiModelProperty(value = "") - private List arrayOfString = null; + private List arrayOfString; @ApiModelProperty(value = "") @Valid - private List> arrayArrayOfInteger = null; + private List> arrayArrayOfInteger; @ApiModelProperty(value = "") @Valid - private List> arrayArrayOfModel = null; + private List> arrayArrayOfModel; /** * Get arrayOfString * @return arrayOfString @@ -120,6 +121,25 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ArrayTest arrayTest = (ArrayTest) o; + return Objects.equals(arrayOfString, arrayTest.arrayOfString) && + Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + } + + @Override + public int hashCode() { + return Objects.hash(arrayOfString, arrayArrayOfInteger, arrayArrayOfModel); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCat.java index fc95ae92e645..3221b45ed6d0 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/BigCat.java @@ -2,7 +2,6 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; -import org.openapitools.model.BigCatAllOf; import org.openapitools.model.Cat; import javax.validation.constraints.*; import javax.validation.Valid; @@ -73,6 +72,23 @@ public BigCat kind(KindEnum kind) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + BigCat bigCat = (BigCat) o; + return super.equals(o) && Objects.equals(kind, bigCat.kind); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), kind); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java index 7daf25fc151a..94ba38dc1940 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Capitalization.java @@ -175,6 +175,28 @@ public Capitalization ATT_NAME(String ATT_NAME) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Capitalization capitalization = (Capitalization) o; + return Objects.equals(smallCamel, capitalization.smallCamel) && + Objects.equals(capitalCamel, capitalization.capitalCamel) && + Objects.equals(smallSnake, capitalization.smallSnake) && + Objects.equals(capitalSnake, capitalization.capitalSnake) && + Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(ATT_NAME, capitalization.ATT_NAME); + } + + @Override + public int hashCode() { + return Objects.hash(smallCamel, capitalCamel, smallSnake, capitalSnake, scAETHFlowPoints, ATT_NAME); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java index 4b01acfec7d6..5242ad8bf495 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Cat.java @@ -1,7 +1,6 @@ package org.openapitools.model; import org.openapitools.model.Animal; -import org.openapitools.model.CatAllOf; import javax.validation.constraints.*; import javax.validation.Valid; @@ -39,6 +38,23 @@ public Cat declawed(Boolean declawed) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Cat cat = (Cat) o; + return super.equals(o) && Objects.equals(declawed, cat.declawed); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), declawed); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java index 135a4aef97a9..beb5a2b1cbfa 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Category.java @@ -65,6 +65,24 @@ public Category name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Category category = (Category) o; + return Objects.equals(id, category.id) && + Objects.equals(name, category.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java index 8a6af0e1b1c0..4e660c56c8ee 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ClassModel.java @@ -43,6 +43,23 @@ public ClassModel propertyClass(String propertyClass) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ClassModel classModel = (ClassModel) o; + return Objects.equals(propertyClass, classModel.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(propertyClass); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java index 72c016206fe4..2b3afa79f9f8 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Client.java @@ -37,6 +37,23 @@ public Client client(String client) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Client client = (Client) o; + return Objects.equals(client, client.client); + } + + @Override + public int hashCode() { + return Objects.hash(client); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java index 67d8fe5ef88d..d0f8a8ff3030 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Dog.java @@ -1,7 +1,6 @@ package org.openapitools.model; import org.openapitools.model.Animal; -import org.openapitools.model.DogAllOf; import javax.validation.constraints.*; import javax.validation.Valid; @@ -39,6 +38,23 @@ public Dog breed(String breed) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Dog dog = (Dog) o; + return super.equals(o) && Objects.equals(breed, dog.breed); + } + + @Override + public int hashCode() { + return Objects.hash(super.hashCode(), breed); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java index 2ebeea81137f..a48e76476d40 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumArrays.java @@ -3,6 +3,7 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -78,7 +79,7 @@ public static ArrayEnumEnum fromValue(String value) { } @ApiModelProperty(value = "") - private List arrayEnum = null; + private List arrayEnum; /** * Get justSymbol * @return justSymbol @@ -136,6 +137,24 @@ public EnumArrays addArrayEnumItem(ArrayEnumEnum arrayEnumItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumArrays enumArrays = (EnumArrays) o; + return Objects.equals(justSymbol, enumArrays.justSymbol) && + Objects.equals(arrayEnum, enumArrays.arrayEnum); + } + + @Override + public int hashCode() { + return Objects.hash(justSymbol, arrayEnum); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java index 3f0ae1b7bc5f..c21ef60f661f 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/EnumTest.java @@ -1,6 +1,7 @@ package org.openapitools.model; import com.fasterxml.jackson.annotation.JsonCreator; +import com.fasterxml.jackson.annotation.JsonTypeName; import com.fasterxml.jackson.annotation.JsonValue; import org.openapitools.model.OuterEnum; import javax.validation.constraints.*; @@ -272,6 +273,27 @@ public EnumTest outerEnum(OuterEnum outerEnum) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + EnumTest enumTest = (EnumTest) o; + return Objects.equals(enumString, enumTest.enumString) && + Objects.equals(enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(enumInteger, enumTest.enumInteger) && + Objects.equals(enumNumber, enumTest.enumNumber) && + Objects.equals(outerEnum, enumTest.outerEnum); + } + + @Override + public int hashCode() { + return Objects.hash(enumString, enumStringRequired, enumInteger, enumNumber, outerEnum); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 3a908d1ccddc..19868e6fc4e9 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -1,6 +1,7 @@ package org.openapitools.model; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.ModelFile; import javax.validation.constraints.*; @@ -19,7 +20,7 @@ public class FileSchemaTestClass { @ApiModelProperty(value = "") @Valid - private List files = null; + private List files; /** * Get _file * @return _file @@ -77,6 +78,24 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; + return Objects.equals(_file, fileSchemaTestClass._file) && + Objects.equals(files, fileSchemaTestClass.files); + } + + @Override + public int hashCode() { + return Objects.hash(_file, files); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java index c83a4b540f6e..9582266d5ab9 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/FormatTest.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import java.io.File; import java.math.BigDecimal; import java.util.Date; @@ -411,6 +412,36 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + FormatTest formatTest = (FormatTest) o; + return Objects.equals(integer, formatTest.integer) && + Objects.equals(int32, formatTest.int32) && + Objects.equals(int64, formatTest.int64) && + Objects.equals(number, formatTest.number) && + Objects.equals(_float, formatTest._float) && + Objects.equals(_double, formatTest._double) && + Objects.equals(string, formatTest.string) && + Objects.equals(_byte, formatTest._byte) && + Objects.equals(binary, formatTest.binary) && + Objects.equals(date, formatTest.date) && + Objects.equals(dateTime, formatTest.dateTime) && + Objects.equals(uuid, formatTest.uuid) && + Objects.equals(password, formatTest.password) && + Objects.equals(bigDecimal, formatTest.bigDecimal); + } + + @Override + public int hashCode() { + return Objects.hash(integer, int32, int64, number, _float, _double, string, _byte, binary, date, dateTime, uuid, password, bigDecimal); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); @@ -428,7 +459,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 30939047b1ad..dd6bbe4b86da 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import javax.validation.constraints.*; import javax.validation.Valid; @@ -68,6 +69,24 @@ public HasOnlyReadOnly foo(String foo) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; + return Objects.equals(bar, hasOnlyReadOnly.bar) && + Objects.equals(foo, hasOnlyReadOnly.foo); + } + + @Override + public int hashCode() { + return Objects.hash(bar, foo); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java index f9815b0c9ba5..297d793d9e28 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MapTest.java @@ -3,7 +3,6 @@ import com.fasterxml.jackson.annotation.JsonCreator; import com.fasterxml.jackson.annotation.JsonValue; import java.util.HashMap; -import java.util.List; import java.util.Map; import org.openapitools.model.StringBooleanMap; import javax.validation.constraints.*; @@ -18,7 +17,7 @@ public class MapTest { @ApiModelProperty(value = "") @Valid - private Map> mapMapOfString = null; + private Map> mapMapOfString = new HashMap<>(); public enum InnerEnum { @@ -51,14 +50,14 @@ public static InnerEnum fromValue(String value) { } @ApiModelProperty(value = "") - private Map mapOfEnumString = null; + private Map mapOfEnumString = new HashMap<>(); @ApiModelProperty(value = "") - private Map directMap = null; + private Map directMap = new HashMap<>(); @ApiModelProperty(value = "") @Valid - private StringBooleanMap indirectMap = new StringBooleanMap(); + private StringBooleanMap indirectMap = new HashMap<>(); /** * Get mapMapOfString * @return mapMapOfString @@ -180,6 +179,26 @@ public MapTest indirectMap(StringBooleanMap indirectMap) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MapTest mapTest = (MapTest) o; + return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(directMap, mapTest.directMap) && + Objects.equals(indirectMap, mapTest.indirectMap); + } + + @Override + public int hashCode() { + return Objects.hash(mapMapOfString, mapOfEnumString, directMap, indirectMap); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 350ea5fdb62b..f59f0e89b464 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -2,7 +2,6 @@ import java.util.Date; import java.util.HashMap; -import java.util.List; import java.util.Map; import java.util.UUID; import org.openapitools.model.Animal; @@ -25,7 +24,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass { @ApiModelProperty(value = "") @Valid - private Map map = null; + private Map map = new HashMap<>(); /** * Get uuid * @return uuid @@ -107,6 +106,25 @@ public MixedPropertiesAndAdditionalPropertiesClass putMapItem(String key, Animal } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; + return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + } + + @Override + public int hashCode() { + return Objects.hash(uuid, dateTime, map); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java index 81c5628d325f..991ff3c86e87 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Model200Response.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; import javax.validation.Valid; @@ -70,6 +71,24 @@ public Model200Response propertyClass(String propertyClass) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Model200Response _200response = (Model200Response) o; + return Objects.equals(name, _200response.name) && + Objects.equals(propertyClass, _200response.propertyClass); + } + + @Override + public int hashCode() { + return Objects.hash(name, propertyClass); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java index 2b92d32f17d9..4ffaf99d9a67 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import javax.validation.constraints.*; import javax.validation.Valid; @@ -91,6 +92,25 @@ public ModelApiResponse message(String message) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelApiResponse _apiResponse = (ModelApiResponse) o; + return Objects.equals(code, _apiResponse.code) && + Objects.equals(type, _apiResponse.type) && + Objects.equals(message, _apiResponse.message); + } + + @Override + public int hashCode() { + return Objects.hash(code, type, message); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelFile.java index abe8a12ce30d..39ddf901a29b 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelFile.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; import javax.validation.Valid; @@ -46,6 +47,23 @@ public ModelFile sourceURI(String sourceURI) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelFile _file = (ModelFile) o; + return Objects.equals(sourceURI, _file.sourceURI); + } + + @Override + public int hashCode() { + return Objects.hash(sourceURI); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelList.java index 50aff7d791a6..0bd8b090173e 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelList.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import javax.validation.constraints.*; import javax.validation.Valid; @@ -37,6 +38,23 @@ public ModelList _123list(String _123list) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelList _list = (ModelList) o; + return Objects.equals(_123list, _list._123list); + } + + @Override + public int hashCode() { + return Objects.hash(_123list); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java index 5e3badeb563e..c447e004df55 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ModelReturn.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import io.swagger.annotations.ApiModel; import javax.validation.constraints.*; import javax.validation.Valid; @@ -43,6 +44,23 @@ public ModelReturn _return(Integer _return) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ModelReturn _return = (ModelReturn) o; + return Objects.equals(_return, _return._return); + } + + @Override + public int hashCode() { + return Objects.hash(_return); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java index 1f487b2f5c43..0395a2ff2e76 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Name.java @@ -129,6 +129,26 @@ public Name _123number(Integer _123number) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Name name = (Name) o; + return Objects.equals(name, name.name) && + Objects.equals(snakeCase, name.snakeCase) && + Objects.equals(property, name.property) && + Objects.equals(_123number, name._123number); + } + + @Override + public int hashCode() { + return Objects.hash(name, snakeCase, property, _123number); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java index 39a9ffb278b6..d303cdd6aee5 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/NumberOnly.java @@ -39,6 +39,23 @@ public NumberOnly justNumber(BigDecimal justNumber) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + NumberOnly numberOnly = (NumberOnly) o; + return Objects.equals(justNumber, numberOnly.justNumber); + } + + @Override + public int hashCode() { + return Objects.hash(justNumber); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java index 721bdb2e23c8..b3934175cd8e 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Order.java @@ -210,6 +210,28 @@ public Order complete(Boolean complete) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Order order = (Order) o; + return Objects.equals(id, order.id) && + Objects.equals(petId, order.petId) && + Objects.equals(quantity, order.quantity) && + Objects.equals(shipDate, order.shipDate) && + Objects.equals(status, order.status) && + Objects.equals(complete, order.complete); + } + + @Override + public int hashCode() { + return Objects.hash(id, petId, quantity, shipDate, status, complete); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java index 3b1e1d66ca04..f08a10c53772 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/OuterComposite.java @@ -93,6 +93,25 @@ public OuterComposite myBoolean(Boolean myBoolean) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + OuterComposite outerComposite = (OuterComposite) o; + return Objects.equals(myNumber, outerComposite.myNumber) && + Objects.equals(myString, outerComposite.myString) && + Objects.equals(myBoolean, outerComposite.myBoolean); + } + + @Override + public int hashCode() { + return Objects.hash(myNumber, myString, myBoolean); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java index 79af5b818e96..b621983b0725 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Pet.java @@ -4,6 +4,7 @@ import com.fasterxml.jackson.annotation.JsonValue; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -34,7 +35,7 @@ public class Pet { @ApiModelProperty(value = "") @Valid - private List tags = null; + private List tags; public enum StatusEnum { @@ -236,6 +237,28 @@ public Pet status(StatusEnum status) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Pet pet = (Pet) o; + return Objects.equals(id, pet.id) && + Objects.equals(category, pet.category) && + Objects.equals(name, pet.name) && + Objects.equals(photoUrls, pet.photoUrls) && + Objects.equals(tags, pet.tags) && + Objects.equals(status, pet.status); + } + + @Override + public int hashCode() { + return Objects.hash(id, category, name, photoUrls, tags, status); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index af5aee76deca..2c6dac2dea35 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -66,6 +66,24 @@ public ReadOnlyFirst baz(String baz) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; + return Objects.equals(bar, readOnlyFirst.bar) && + Objects.equals(baz, readOnlyFirst.baz); + } + + @Override + public int hashCode() { + return Objects.hash(bar, baz); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java index 8f9d57bd14aa..1d89f44f9c5e 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -1,5 +1,6 @@ package org.openapitools.model; +import com.fasterxml.jackson.annotation.JsonTypeName; import javax.validation.constraints.*; import javax.validation.Valid; @@ -37,6 +38,23 @@ public class SpecialModelName { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + SpecialModelName $specialModelName = (SpecialModelName) o; + return Objects.equals($specialPropertyName, $specialModelName.$specialPropertyName); + } + + @Override + public int hashCode() { + return Objects.hash($specialPropertyName); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java index 904d5b9bc7cf..997a4145180e 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/StringBooleanMap.java @@ -12,6 +12,22 @@ public class StringBooleanMap extends HashMap { + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + StringBooleanMap stringBooleanMap = (StringBooleanMap) o;return super.equals(o); + } + + @Override + public int hashCode() { + return super.hashCode(); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java index fc47777ce1f5..838de2fa1775 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/Tag.java @@ -64,6 +64,24 @@ public Tag name(String name) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + Tag tag = (Tag) o; + return Objects.equals(id, tag.id) && + Objects.equals(name, tag.name); + } + + @Override + public int hashCode() { + return Objects.hash(id, name); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java index e6ce5057542c..3e0d4ea3e6a1 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -162,6 +163,27 @@ public TypeHolderDefault addArrayItemItem(Integer arrayItemItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o; + return Objects.equals(stringItem, typeHolderDefault.stringItem) && + Objects.equals(numberItem, typeHolderDefault.numberItem) && + Objects.equals(integerItem, typeHolderDefault.integerItem) && + Objects.equals(boolItem, typeHolderDefault.boolItem) && + Objects.equals(arrayItem, typeHolderDefault.arrayItem); + } + + @Override + public int hashCode() { + return Objects.hash(stringItem, numberItem, integerItem, boolItem, arrayItem); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java index 734f422fde20..387956243c47 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -190,6 +191,28 @@ public TypeHolderExample addArrayItemItem(Integer arrayItemItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + TypeHolderExample typeHolderExample = (TypeHolderExample) o; + return Objects.equals(stringItem, typeHolderExample.stringItem) && + Objects.equals(numberItem, typeHolderExample.numberItem) && + Objects.equals(floatItem, typeHolderExample.floatItem) && + Objects.equals(integerItem, typeHolderExample.integerItem) && + Objects.equals(boolItem, typeHolderExample.boolItem) && + Objects.equals(arrayItem, typeHolderExample.arrayItem); + } + + @Override + public int hashCode() { + return Objects.hash(stringItem, numberItem, floatItem, integerItem, boolItem, arrayItem); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java index 65baf8e2b9d5..5b252e7bfff5 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/User.java @@ -229,6 +229,30 @@ public User userStatus(Integer userStatus) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + User user = (User) o; + return Objects.equals(id, user.id) && + Objects.equals(username, user.username) && + Objects.equals(firstName, user.firstName) && + Objects.equals(lastName, user.lastName) && + Objects.equals(email, user.email) && + Objects.equals(password, user.password) && + Objects.equals(phone, user.phone) && + Objects.equals(userStatus, user.userStatus); + } + + @Override + public int hashCode() { + return Objects.hash(id, username, firstName, lastName, email, password, phone, userStatus); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java index 0650d220afef..fae714014707 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/gen/java/org/openapitools/model/XmlItem.java @@ -2,6 +2,7 @@ import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import javax.validation.constraints.*; import javax.validation.Valid; @@ -27,7 +28,7 @@ public class XmlItem { private Boolean attributeBoolean; @ApiModelProperty(value = "") - private List wrappedArray = null; + private List wrappedArray; @ApiModelProperty(example = "string", value = "") private String nameString; @@ -43,10 +44,10 @@ public class XmlItem { private Boolean nameBoolean; @ApiModelProperty(value = "") - private List nameArray = null; + private List nameArray; @ApiModelProperty(value = "") - private List nameWrappedArray = null; + private List nameWrappedArray; @ApiModelProperty(example = "string", value = "") private String prefixString; @@ -62,10 +63,10 @@ public class XmlItem { private Boolean prefixBoolean; @ApiModelProperty(value = "") - private List prefixArray = null; + private List prefixArray; @ApiModelProperty(value = "") - private List prefixWrappedArray = null; + private List prefixWrappedArray; @ApiModelProperty(example = "string", value = "") private String namespaceString; @@ -81,10 +82,10 @@ public class XmlItem { private Boolean namespaceBoolean; @ApiModelProperty(value = "") - private List namespaceArray = null; + private List namespaceArray; @ApiModelProperty(value = "") - private List namespaceWrappedArray = null; + private List namespaceWrappedArray; @ApiModelProperty(example = "string", value = "") private String prefixNsString; @@ -100,10 +101,10 @@ public class XmlItem { private Boolean prefixNsBoolean; @ApiModelProperty(value = "") - private List prefixNsArray = null; + private List prefixNsArray; @ApiModelProperty(value = "") - private List prefixNsWrappedArray = null; + private List prefixNsWrappedArray; /** * Get attributeString * @return attributeString @@ -873,6 +874,51 @@ public XmlItem addPrefixNsWrappedArrayItem(Integer prefixNsWrappedArrayItem) { } + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + XmlItem xmlItem = (XmlItem) o; + return Objects.equals(attributeString, xmlItem.attributeString) && + Objects.equals(attributeNumber, xmlItem.attributeNumber) && + Objects.equals(attributeInteger, xmlItem.attributeInteger) && + Objects.equals(attributeBoolean, xmlItem.attributeBoolean) && + Objects.equals(wrappedArray, xmlItem.wrappedArray) && + Objects.equals(nameString, xmlItem.nameString) && + Objects.equals(nameNumber, xmlItem.nameNumber) && + Objects.equals(nameInteger, xmlItem.nameInteger) && + Objects.equals(nameBoolean, xmlItem.nameBoolean) && + Objects.equals(nameArray, xmlItem.nameArray) && + Objects.equals(nameWrappedArray, xmlItem.nameWrappedArray) && + Objects.equals(prefixString, xmlItem.prefixString) && + Objects.equals(prefixNumber, xmlItem.prefixNumber) && + Objects.equals(prefixInteger, xmlItem.prefixInteger) && + Objects.equals(prefixBoolean, xmlItem.prefixBoolean) && + Objects.equals(prefixArray, xmlItem.prefixArray) && + Objects.equals(prefixWrappedArray, xmlItem.prefixWrappedArray) && + Objects.equals(namespaceString, xmlItem.namespaceString) && + Objects.equals(namespaceNumber, xmlItem.namespaceNumber) && + Objects.equals(namespaceInteger, xmlItem.namespaceInteger) && + Objects.equals(namespaceBoolean, xmlItem.namespaceBoolean) && + Objects.equals(namespaceArray, xmlItem.namespaceArray) && + Objects.equals(namespaceWrappedArray, xmlItem.namespaceWrappedArray) && + Objects.equals(prefixNsString, xmlItem.prefixNsString) && + Objects.equals(prefixNsNumber, xmlItem.prefixNsNumber) && + Objects.equals(prefixNsInteger, xmlItem.prefixNsInteger) && + Objects.equals(prefixNsBoolean, xmlItem.prefixNsBoolean) && + Objects.equals(prefixNsArray, xmlItem.prefixNsArray) && + Objects.equals(prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); + } + + @Override + public int hashCode() { + return Objects.hash(attributeString, attributeNumber, attributeInteger, attributeBoolean, wrappedArray, nameString, nameNumber, nameInteger, nameBoolean, nameArray, nameWrappedArray, prefixString, prefixNumber, prefixInteger, prefixBoolean, prefixArray, prefixWrappedArray, namespaceString, namespaceNumber, namespaceInteger, namespaceBoolean, namespaceArray, namespaceWrappedArray, prefixNsString, prefixNsNumber, prefixNsInteger, prefixNsBoolean, prefixNsArray, prefixNsWrappedArray); + } + @Override public String toString() { StringBuilder sb = new StringBuilder(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index 29a7d7c101ed..8c8301e85b9b 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -4,6 +4,7 @@ import org.openapitools.model.Client; import java.util.List; import java.util.Map; +import java.util.UUID; import java.io.InputStream; import java.io.OutputStream; @@ -35,7 +36,7 @@ public class AnotherFakeApiServiceImpl implements AnotherFakeApi { { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/AnotherFakeApi"); } catch (CacheException e) { e.printStackTrace(); @@ -49,7 +50,7 @@ public class AnotherFakeApiServiceImpl implements AnotherFakeApi { * */ @Override - public Client call123testSpecialTags(Client body) { + public Client call123testSpecialTags(UUID uuidTest, Client body) { try { Client response = cache.getObject("/call123testSpecialTags/response", Client.class); return response; diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index 2fa5d618e5a6..b9169fefcfe7 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -44,7 +44,7 @@ public class FakeApiServiceImpl implements FakeApi { { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeApi"); } catch (CacheException e) { e.printStackTrace(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java index a91ea641651f..a9afa4f35436 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java @@ -35,7 +35,7 @@ public class FakeClassnameTags123ApiServiceImpl implements FakeClassnameTags123A { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/FakeClassnameTags123Api"); } catch (CacheException e) { e.printStackTrace(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 40cd3502fbdc..3147c7fe35de 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -39,7 +39,7 @@ public class PetApiServiceImpl implements PetApi { { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/PetApi"); } catch (CacheException e) { e.printStackTrace(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 06d50eaabdd1..264b4ad4c225 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -35,7 +35,7 @@ public class StoreApiServiceImpl implements StoreApi { { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/StoreApi"); } catch (CacheException e) { e.printStackTrace(); diff --git a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 23d653171ef3..376382a67c48 100644 --- a/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-cxf-test-data/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -36,7 +36,7 @@ public class UserApiServiceImpl implements UserApi { { try { File cacheFile = new File(System.getProperty("jaxrs.test.server.json", - "/Users/williamcheng/Code/openapi-generator2/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); + "/Users/williamcheng/Code/openapi-generator7/samples/server/petstore/jaxrs-cxf-test-data/src/main/resources/test-data.json")); cache = JsonCache.Factory.instance.get("test-data").load(cacheFile).child("/org.openapitools.api/UserApi"); } catch (CacheException e) { e.printStackTrace(); diff --git a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-cxf/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-cxf/pom.xml b/samples/server/petstore/jaxrs-cxf/pom.xml index 09df71b73a95..338e801642db 100644 --- a/samples/server/petstore/jaxrs-cxf/pom.xml +++ b/samples/server/petstore/jaxrs-cxf/pom.xml @@ -103,6 +103,14 @@ swagger-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -207,7 +215,7 @@ 1.5.22 9.2.9.v20150224 4.13.2 - 1.2.12 + 1.4.14 2.0.2 3.3.0 2.15.2 diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/api/UserApi.java index 4af8b1db4fb2..6485b2345f41 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/api/UserApi.java @@ -52,7 +52,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithArrayInput(@Valid @NotNull List body); + public void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body); /** * Creates list of users with given input array @@ -63,7 +63,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation") }) - public void createUsersWithListInput(@Valid @NotNull List body); + public void createUsersWithListInput(@Valid @NotNull List<@Valid User> body); /** * Delete user diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index b3cf3df8d46a..fa1f1664982e 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return Objects.equals(name, additionalPropertiesAnyType.name) && + return Objects.equals(this.name, additionalPropertiesAnyType.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 9159cc710652..7b6df75d5996 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -42,7 +42,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return Objects.equals(name, additionalPropertiesArray.name) && + return Objects.equals(this.name, additionalPropertiesArray.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 6234531ab049..521452f796a7 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return Objects.equals(name, additionalPropertiesBoolean.name) && + return Objects.equals(this.name, additionalPropertiesBoolean.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index dc2c9f535145..3a8a99907b67 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -298,17 +298,17 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapString, additionalPropertiesClass.mapString) && - Objects.equals(mapNumber, additionalPropertiesClass.mapNumber) && - Objects.equals(mapInteger, additionalPropertiesClass.mapInteger) && - Objects.equals(mapBoolean, additionalPropertiesClass.mapBoolean) && - Objects.equals(mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && - Objects.equals(mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && - Objects.equals(mapMapString, additionalPropertiesClass.mapMapString) && - Objects.equals(mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && - Objects.equals(anytype1, additionalPropertiesClass.anytype1) && - Objects.equals(anytype2, additionalPropertiesClass.anytype2) && - Objects.equals(anytype3, additionalPropertiesClass.anytype3); + return Objects.equals(this.mapString, additionalPropertiesClass.mapString) && + Objects.equals(this.mapNumber, additionalPropertiesClass.mapNumber) && + Objects.equals(this.mapInteger, additionalPropertiesClass.mapInteger) && + Objects.equals(this.mapBoolean, additionalPropertiesClass.mapBoolean) && + Objects.equals(this.mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && + Objects.equals(this.mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && + Objects.equals(this.mapMapString, additionalPropertiesClass.mapMapString) && + Objects.equals(this.mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.anytype2, additionalPropertiesClass.anytype2) && + Objects.equals(this.anytype3, additionalPropertiesClass.anytype3); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 8c9bc00682eb..d3a9c5bc078f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return Objects.equals(name, additionalPropertiesInteger.name) && + return Objects.equals(this.name, additionalPropertiesInteger.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 8cfba20b44af..9323fb33b1ba 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -42,7 +42,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return Objects.equals(name, additionalPropertiesNumber.name) && + return Objects.equals(this.name, additionalPropertiesNumber.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index cb523f0de591..9b18e93bcdde 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return Objects.equals(name, additionalPropertiesObject.name) && + return Objects.equals(this.name, additionalPropertiesObject.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 45d39bbd9be3..9011af6958e5 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return Objects.equals(name, additionalPropertiesString.name) && + return Objects.equals(this.name, additionalPropertiesString.name) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Animal.java index 62ec5a93960a..f4aa77c5ebf4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Animal.java @@ -70,8 +70,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 0090ba1f89f3..3e877b82d549 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -49,7 +49,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 7a04b822450a..6261829241c1 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -49,7 +49,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayTest.java index c30cf9634080..8ff058a6d4cf 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ArrayTest.java @@ -23,7 +23,7 @@ public class ArrayTest { @ApiModelProperty(value = "") @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; /** * Get arrayOfString * @return arrayOfString @@ -75,20 +75,20 @@ public ArrayTest addArrayArrayOfIntegerItem(List arrayArrayOfIntegerItem) * @return arrayArrayOfModel **/ @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { this.arrayArrayOfModel.add(arrayArrayOfModelItem); return this; } @@ -102,9 +102,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/BigCat.java index 8e95a2cbbd26..bc9fb8209a8c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/BigCat.java @@ -77,7 +77,7 @@ public boolean equals(Object o) { return false; } BigCat bigCat = (BigCat) o; - return Objects.equals(kind, bigCat.kind) && + return Objects.equals(this.kind, bigCat.kind) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Capitalization.java index 255957a7b28c..a18160eef0ce 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Capitalization.java @@ -147,12 +147,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Cat.java index b149b6fb5dc0..92827966e811 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Cat.java @@ -40,7 +40,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return Objects.equals(declawed, cat.declawed) && + return Objects.equals(this.declawed, cat.declawed) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Category.java index f958bc9cd3c3..a16c3ffd45f0 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Category.java @@ -61,8 +61,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ClassModel.java index 137c3b81f599..234e1f14a3b5 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ClassModel.java @@ -44,7 +44,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Client.java index 07383bf7c838..c80c3ebb4814 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Client.java @@ -39,7 +39,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Dog.java index 91478805d14e..4047607c00f8 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Dog.java @@ -40,7 +40,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return Objects.equals(breed, dog.breed) && + return Objects.equals(this.breed, dog.breed) && super.equals(o); } diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumArrays.java index 41a8653ab824..10ec68c1a808 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumArrays.java @@ -137,8 +137,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumTest.java index f92851793956..7f90af814ecc 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/EnumTest.java @@ -269,11 +269,11 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index d86de866b0a3..14c7478308fa 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -20,7 +20,7 @@ public class FileSchemaTestClass { @ApiModelProperty(value = "") @Valid - private List files; + private List<@Valid ModelFile> files; /** * Get _file * @return _file @@ -44,15 +44,15 @@ public FileSchemaTestClass _file(ModelFile _file) { * @return files **/ @JsonProperty("files") - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -71,8 +71,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FormatTest.java index dfd0ae304bf4..976d985f42b9 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/FormatTest.java @@ -334,20 +334,20 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(bigDecimal, formatTest.bigDecimal); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.bigDecimal, formatTest.bigDecimal); } @Override @@ -372,7 +372,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index c99fc7cacbe4..da75bd675d9f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -45,8 +45,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MapTest.java index 81de01c1ecba..3e56ff41c90c 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MapTest.java @@ -159,10 +159,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 8e290019422a..6b4c41db1c19 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -92,9 +92,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Model200Response.java index 30da65fc1686..92bfe32725f4 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Model200Response.java @@ -66,8 +66,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelApiResponse.java index 06fd6b1f1135..4358dffbccaa 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -82,9 +82,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelFile.java index f11410e57634..2b81e049d786 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelFile.java @@ -48,7 +48,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelList.java index b419eaab64c4..b3bada4f240f 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelList.java @@ -40,7 +40,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelReturn.java index bdfc8d8b9c2d..67c0fc5d96d5 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ModelReturn.java @@ -45,7 +45,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Name.java index 4f5a55f2c9d5..6f474dac56bd 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Name.java @@ -92,10 +92,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/NumberOnly.java index d73e204beb48..52c94fde2346 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/NumberOnly.java @@ -41,7 +41,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Order.java index 5b325259347e..2ce1523b5070 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Order.java @@ -185,12 +185,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/OuterComposite.java index 874caa1e7c3e..ee28549b3ea6 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/OuterComposite.java @@ -83,9 +83,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Pet.java index d094965a17c4..f18417662b84 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Pet.java @@ -35,7 +35,7 @@ public class Pet { @ApiModelProperty(value = "") @Valid - private List tags; + private List<@Valid Tag> tags; public enum StatusEnum { @@ -159,15 +159,15 @@ public Pet addPhotoUrlsItem(String photoUrlsItem) { * @return tags **/ @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -207,12 +207,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index b07b95e2530b..48870cd6e5b8 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -52,8 +52,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/SpecialModelName.java index d4a59f1ccfcb..63b78c36a6ae 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -40,7 +40,7 @@ public boolean equals(Object o) { return false; } SpecialModelName $specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, $specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, $specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Tag.java index 2cf3779e3020..da552b1ec331 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/Tag.java @@ -60,8 +60,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 2faf95b2e3bc..d85f401a6716 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -138,11 +138,11 @@ public boolean equals(Object o) { return false; } TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o; - return Objects.equals(stringItem, typeHolderDefault.stringItem) && - Objects.equals(numberItem, typeHolderDefault.numberItem) && - Objects.equals(integerItem, typeHolderDefault.integerItem) && - Objects.equals(boolItem, typeHolderDefault.boolItem) && - Objects.equals(arrayItem, typeHolderDefault.arrayItem); + return Objects.equals(this.stringItem, typeHolderDefault.stringItem) && + Objects.equals(this.numberItem, typeHolderDefault.numberItem) && + Objects.equals(this.integerItem, typeHolderDefault.integerItem) && + Objects.equals(this.boolItem, typeHolderDefault.boolItem) && + Objects.equals(this.arrayItem, typeHolderDefault.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderExample.java index 26955d28f6f3..0f25d81ac331 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -160,12 +160,12 @@ public boolean equals(Object o) { return false; } TypeHolderExample typeHolderExample = (TypeHolderExample) o; - return Objects.equals(stringItem, typeHolderExample.stringItem) && - Objects.equals(numberItem, typeHolderExample.numberItem) && - Objects.equals(floatItem, typeHolderExample.floatItem) && - Objects.equals(integerItem, typeHolderExample.integerItem) && - Objects.equals(boolItem, typeHolderExample.boolItem) && - Objects.equals(arrayItem, typeHolderExample.arrayItem); + return Objects.equals(this.stringItem, typeHolderExample.stringItem) && + Objects.equals(this.numberItem, typeHolderExample.numberItem) && + Objects.equals(this.floatItem, typeHolderExample.floatItem) && + Objects.equals(this.integerItem, typeHolderExample.integerItem) && + Objects.equals(this.boolItem, typeHolderExample.boolItem) && + Objects.equals(this.arrayItem, typeHolderExample.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/User.java index 5df878d36558..83633445d073 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/User.java @@ -189,14 +189,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/XmlItem.java index 0565b58f729e..09909e884079 100644 --- a/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-cxf/src/gen/java/org/openapitools/model/XmlItem.java @@ -681,35 +681,35 @@ public boolean equals(Object o) { return false; } XmlItem xmlItem = (XmlItem) o; - return Objects.equals(attributeString, xmlItem.attributeString) && - Objects.equals(attributeNumber, xmlItem.attributeNumber) && - Objects.equals(attributeInteger, xmlItem.attributeInteger) && - Objects.equals(attributeBoolean, xmlItem.attributeBoolean) && - Objects.equals(wrappedArray, xmlItem.wrappedArray) && - Objects.equals(nameString, xmlItem.nameString) && - Objects.equals(nameNumber, xmlItem.nameNumber) && - Objects.equals(nameInteger, xmlItem.nameInteger) && - Objects.equals(nameBoolean, xmlItem.nameBoolean) && - Objects.equals(nameArray, xmlItem.nameArray) && - Objects.equals(nameWrappedArray, xmlItem.nameWrappedArray) && - Objects.equals(prefixString, xmlItem.prefixString) && - Objects.equals(prefixNumber, xmlItem.prefixNumber) && - Objects.equals(prefixInteger, xmlItem.prefixInteger) && - Objects.equals(prefixBoolean, xmlItem.prefixBoolean) && - Objects.equals(prefixArray, xmlItem.prefixArray) && - Objects.equals(prefixWrappedArray, xmlItem.prefixWrappedArray) && - Objects.equals(namespaceString, xmlItem.namespaceString) && - Objects.equals(namespaceNumber, xmlItem.namespaceNumber) && - Objects.equals(namespaceInteger, xmlItem.namespaceInteger) && - Objects.equals(namespaceBoolean, xmlItem.namespaceBoolean) && - Objects.equals(namespaceArray, xmlItem.namespaceArray) && - Objects.equals(namespaceWrappedArray, xmlItem.namespaceWrappedArray) && - Objects.equals(prefixNsString, xmlItem.prefixNsString) && - Objects.equals(prefixNsNumber, xmlItem.prefixNsNumber) && - Objects.equals(prefixNsInteger, xmlItem.prefixNsInteger) && - Objects.equals(prefixNsBoolean, xmlItem.prefixNsBoolean) && - Objects.equals(prefixNsArray, xmlItem.prefixNsArray) && - Objects.equals(prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); + return Objects.equals(this.attributeString, xmlItem.attributeString) && + Objects.equals(this.attributeNumber, xmlItem.attributeNumber) && + Objects.equals(this.attributeInteger, xmlItem.attributeInteger) && + Objects.equals(this.attributeBoolean, xmlItem.attributeBoolean) && + Objects.equals(this.wrappedArray, xmlItem.wrappedArray) && + Objects.equals(this.nameString, xmlItem.nameString) && + Objects.equals(this.nameNumber, xmlItem.nameNumber) && + Objects.equals(this.nameInteger, xmlItem.nameInteger) && + Objects.equals(this.nameBoolean, xmlItem.nameBoolean) && + Objects.equals(this.nameArray, xmlItem.nameArray) && + Objects.equals(this.nameWrappedArray, xmlItem.nameWrappedArray) && + Objects.equals(this.prefixString, xmlItem.prefixString) && + Objects.equals(this.prefixNumber, xmlItem.prefixNumber) && + Objects.equals(this.prefixInteger, xmlItem.prefixInteger) && + Objects.equals(this.prefixBoolean, xmlItem.prefixBoolean) && + Objects.equals(this.prefixArray, xmlItem.prefixArray) && + Objects.equals(this.prefixWrappedArray, xmlItem.prefixWrappedArray) && + Objects.equals(this.namespaceString, xmlItem.namespaceString) && + Objects.equals(this.namespaceNumber, xmlItem.namespaceNumber) && + Objects.equals(this.namespaceInteger, xmlItem.namespaceInteger) && + Objects.equals(this.namespaceBoolean, xmlItem.namespaceBoolean) && + Objects.equals(this.namespaceArray, xmlItem.namespaceArray) && + Objects.equals(this.namespaceWrappedArray, xmlItem.namespaceWrappedArray) && + Objects.equals(this.prefixNsString, xmlItem.prefixNsString) && + Objects.equals(this.prefixNsNumber, xmlItem.prefixNsNumber) && + Objects.equals(this.prefixNsInteger, xmlItem.prefixNsInteger) && + Objects.equals(this.prefixNsBoolean, xmlItem.prefixNsBoolean) && + Objects.equals(this.prefixNsArray, xmlItem.prefixNsArray) && + Objects.equals(this.prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-datelib-j8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-datelib-j8/pom.xml b/samples/server/petstore/jaxrs-datelib-j8/pom.xml index 5b9bbbdc406e..acda23ce006d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/pom.xml +++ b/samples/server/petstore/jaxrs-datelib-j8/pom.xml @@ -107,6 +107,14 @@ swagger-jersey2-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -201,7 +209,7 @@ 2.35 2.15.2 4.13.2 - 1.2.12 + 1.4.14 4.0.4 UTF-8 diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/AnotherFakeApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/AnotherFakeApiService.java index 3991f29fa8a7..c678cc557a24 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/AnotherFakeApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/AnotherFakeApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class AnotherFakeApiService { public abstract Response call123testSpecialTags( @NotNull UUID uuidTest,Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeApiService.java index 3cc65be92b99..164d95a75b9a 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeApiService.java @@ -24,6 +24,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeApiService { public abstract Response createXmlItem(XmlItem xmlItem,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java index 9b9724797dfc..a155a1ae0351 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeClassnameTestApiService { public abstract Response testClassname(Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/PetApiService.java index 5a082c27fd48..a82fd652bc3f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/StoreApiService.java index 679dae579bf0..ba613f2eb7a2 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/StoreApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApi.java index 7e617b8d5c7f..ea55ad81c44f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApi.java @@ -75,7 +75,7 @@ public Response createUser(@ApiParam(value = "Created user object", required = t @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body, securityContext); } @@ -87,7 +87,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body, securityContext); } diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApiService.java index e77f749c52c7..46e99f6e59b3 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/api/UserApiService.java @@ -15,11 +15,12 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index b6a8163a0a0e..051517350752 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesAnyType.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesAnyType.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 5d4cf69e2c03..d8acd71a5d65 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -68,7 +68,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesArray.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesArray.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 6916bfcac1de..247ade6e1804 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesBoolean.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesBoolean.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 6622a72bdad4..46092077c935 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -383,17 +383,17 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapString, additionalPropertiesClass.mapString) && - Objects.equals(mapNumber, additionalPropertiesClass.mapNumber) && - Objects.equals(mapInteger, additionalPropertiesClass.mapInteger) && - Objects.equals(mapBoolean, additionalPropertiesClass.mapBoolean) && - Objects.equals(mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && - Objects.equals(mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && - Objects.equals(mapMapString, additionalPropertiesClass.mapMapString) && - Objects.equals(mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && - Objects.equals(anytype1, additionalPropertiesClass.anytype1) && - Objects.equals(anytype2, additionalPropertiesClass.anytype2) && - Objects.equals(anytype3, additionalPropertiesClass.anytype3); + return Objects.equals(this.mapString, additionalPropertiesClass.mapString) && + Objects.equals(this.mapNumber, additionalPropertiesClass.mapNumber) && + Objects.equals(this.mapInteger, additionalPropertiesClass.mapInteger) && + Objects.equals(this.mapBoolean, additionalPropertiesClass.mapBoolean) && + Objects.equals(this.mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && + Objects.equals(this.mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && + Objects.equals(this.mapMapString, additionalPropertiesClass.mapMapString) && + Objects.equals(this.mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.anytype2, additionalPropertiesClass.anytype2) && + Objects.equals(this.anytype3, additionalPropertiesClass.anytype3); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index 907e6c4af5c0..51dc8773d319 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesInteger.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesInteger.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index 70109e66f5f1..92dbb13744ec 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -68,7 +68,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesNumber.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesNumber.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index dcabb93d1739..8e79e710b0cb 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesObject.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesObject.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index cd500c5d054f..3c9eb3d31138 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesString.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesString.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java index 3fc39ea76f23..d0d617470f91 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Animal.java @@ -99,8 +99,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 693d63f76080..363d8da4f5f6 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -77,7 +77,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index e8b6da11ff73..bbb59624f234 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -77,7 +77,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java index 11909ea810d9..a603c6e083c5 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ArrayTest.java @@ -47,7 +47,7 @@ public class ArrayTest implements Serializable { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -105,12 +105,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -125,11 +125,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @@ -143,9 +143,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java index 470990a7b4d3..07baf1294215 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/BigCat.java @@ -102,7 +102,7 @@ public boolean equals(Object o) { return false; } BigCat bigCat = (BigCat) o; - return super.equals(o) && Objects.equals(kind, bigCat.kind); + return super.equals(o) && Objects.equals(this.kind, bigCat.kind); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java index 839472717be3..a88e44d4856d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Capitalization.java @@ -190,12 +190,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java index f76fcca8107e..32e6b6cc673d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Cat.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return super.equals(o) && Objects.equals(declawed, cat.declawed); + return super.equals(o) && Objects.equals(this.declawed, cat.declawed); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java index 3ecccabdec18..0c9610f86020 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Category.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java index 285723346874..8283b93db44a 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ClassModel.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java index b7d2fc08e3bb..d457c92d8ad8 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Client.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java index 7434bb72aceb..2fe79000cb92 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Dog.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return super.equals(o) && Objects.equals(breed, dog.breed); + return super.equals(o) && Objects.equals(this.breed, dog.breed); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java index 2c068d4dc2d6..3445ee684c76 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumArrays.java @@ -164,8 +164,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java index fd0b262303f6..4ef56b1cb6e8 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/EnumTest.java @@ -296,11 +296,11 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index b1fadf19faca..a97dc14fe477 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -42,7 +42,7 @@ public class FileSchemaTestClass implements Serializable { public static final String JSON_PROPERTY_FILES = "files"; @JsonProperty(JSON_PROPERTY_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -64,7 +64,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -84,11 +84,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -102,8 +102,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java index 0d0dc03104af..eae1c96aac64 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/FormatTest.java @@ -406,20 +406,20 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(bigDecimal, formatTest.bigDecimal); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.bigDecimal, formatTest.bigDecimal); } @Override @@ -444,7 +444,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index db0c17f073da..684cad64e655 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -91,8 +91,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java index af682e98fa66..4ecfd580bfbb 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MapTest.java @@ -206,10 +206,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 86a0fabb278d..937cf25dcddd 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -128,9 +128,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java index df2202fa9c9f..e5d23723532e 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Model200Response.java @@ -92,8 +92,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java index c30eb549eeb4..1d394d063783 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -116,9 +116,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelFile.java index ece358fa101e..5c2e27cc7989 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelFile.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelList.java index 84947dd8af74..30f0f8748afd 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelList.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java index 621162551a5b..d193b252e217 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ModelReturn.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java index c983341421dc..4dbbd8371e05 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Name.java @@ -141,10 +141,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java index 1e035ecf9fc9..6b55ebcc1efe 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/NumberOnly.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java index 8e8b0e261907..bd319b8a781a 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Order.java @@ -225,12 +225,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java index 8973c6e300a5..5d0f1afcff2d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/OuterComposite.java @@ -116,9 +116,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java index 375ef27db712..d92b30bb634f 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Pet.java @@ -63,7 +63,7 @@ public class Pet implements Serializable { public static final String JSON_PROPERTY_TAGS = "tags"; @JsonProperty(JSON_PROPERTY_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -191,7 +191,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -211,11 +211,11 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -249,12 +249,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index dbc060096832..fbf022ca8352 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java index 4e72d33b4388..3c02b1b693d1 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } SpecialModelName $specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, $specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, $specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java index c5b0e55158b1..1aeee66afd08 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/Tag.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 2bb7467db5d4..1b4a598cbfc3 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -177,11 +177,11 @@ public boolean equals(Object o) { return false; } TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o; - return Objects.equals(stringItem, typeHolderDefault.stringItem) && - Objects.equals(numberItem, typeHolderDefault.numberItem) && - Objects.equals(integerItem, typeHolderDefault.integerItem) && - Objects.equals(boolItem, typeHolderDefault.boolItem) && - Objects.equals(arrayItem, typeHolderDefault.arrayItem); + return Objects.equals(this.stringItem, typeHolderDefault.stringItem) && + Objects.equals(this.numberItem, typeHolderDefault.numberItem) && + Objects.equals(this.integerItem, typeHolderDefault.integerItem) && + Objects.equals(this.boolItem, typeHolderDefault.boolItem) && + Objects.equals(this.arrayItem, typeHolderDefault.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java index 8416ff31515f..34487c3bb31b 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -202,12 +202,12 @@ public boolean equals(Object o) { return false; } TypeHolderExample typeHolderExample = (TypeHolderExample) o; - return Objects.equals(stringItem, typeHolderExample.stringItem) && - Objects.equals(numberItem, typeHolderExample.numberItem) && - Objects.equals(floatItem, typeHolderExample.floatItem) && - Objects.equals(integerItem, typeHolderExample.integerItem) && - Objects.equals(boolItem, typeHolderExample.boolItem) && - Objects.equals(arrayItem, typeHolderExample.arrayItem); + return Objects.equals(this.stringItem, typeHolderExample.stringItem) && + Objects.equals(this.numberItem, typeHolderExample.numberItem) && + Objects.equals(this.floatItem, typeHolderExample.floatItem) && + Objects.equals(this.integerItem, typeHolderExample.integerItem) && + Objects.equals(this.boolItem, typeHolderExample.boolItem) && + Objects.equals(this.arrayItem, typeHolderExample.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java index 7bdb74393515..75b3feb1480d 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/User.java @@ -240,14 +240,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java index 859d389bd685..c8f11a74cfa2 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/gen/java/org/openapitools/model/XmlItem.java @@ -841,35 +841,35 @@ public boolean equals(Object o) { return false; } XmlItem xmlItem = (XmlItem) o; - return Objects.equals(attributeString, xmlItem.attributeString) && - Objects.equals(attributeNumber, xmlItem.attributeNumber) && - Objects.equals(attributeInteger, xmlItem.attributeInteger) && - Objects.equals(attributeBoolean, xmlItem.attributeBoolean) && - Objects.equals(wrappedArray, xmlItem.wrappedArray) && - Objects.equals(nameString, xmlItem.nameString) && - Objects.equals(nameNumber, xmlItem.nameNumber) && - Objects.equals(nameInteger, xmlItem.nameInteger) && - Objects.equals(nameBoolean, xmlItem.nameBoolean) && - Objects.equals(nameArray, xmlItem.nameArray) && - Objects.equals(nameWrappedArray, xmlItem.nameWrappedArray) && - Objects.equals(prefixString, xmlItem.prefixString) && - Objects.equals(prefixNumber, xmlItem.prefixNumber) && - Objects.equals(prefixInteger, xmlItem.prefixInteger) && - Objects.equals(prefixBoolean, xmlItem.prefixBoolean) && - Objects.equals(prefixArray, xmlItem.prefixArray) && - Objects.equals(prefixWrappedArray, xmlItem.prefixWrappedArray) && - Objects.equals(namespaceString, xmlItem.namespaceString) && - Objects.equals(namespaceNumber, xmlItem.namespaceNumber) && - Objects.equals(namespaceInteger, xmlItem.namespaceInteger) && - Objects.equals(namespaceBoolean, xmlItem.namespaceBoolean) && - Objects.equals(namespaceArray, xmlItem.namespaceArray) && - Objects.equals(namespaceWrappedArray, xmlItem.namespaceWrappedArray) && - Objects.equals(prefixNsString, xmlItem.prefixNsString) && - Objects.equals(prefixNsNumber, xmlItem.prefixNsNumber) && - Objects.equals(prefixNsInteger, xmlItem.prefixNsInteger) && - Objects.equals(prefixNsBoolean, xmlItem.prefixNsBoolean) && - Objects.equals(prefixNsArray, xmlItem.prefixNsArray) && - Objects.equals(prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); + return Objects.equals(this.attributeString, xmlItem.attributeString) && + Objects.equals(this.attributeNumber, xmlItem.attributeNumber) && + Objects.equals(this.attributeInteger, xmlItem.attributeInteger) && + Objects.equals(this.attributeBoolean, xmlItem.attributeBoolean) && + Objects.equals(this.wrappedArray, xmlItem.wrappedArray) && + Objects.equals(this.nameString, xmlItem.nameString) && + Objects.equals(this.nameNumber, xmlItem.nameNumber) && + Objects.equals(this.nameInteger, xmlItem.nameInteger) && + Objects.equals(this.nameBoolean, xmlItem.nameBoolean) && + Objects.equals(this.nameArray, xmlItem.nameArray) && + Objects.equals(this.nameWrappedArray, xmlItem.nameWrappedArray) && + Objects.equals(this.prefixString, xmlItem.prefixString) && + Objects.equals(this.prefixNumber, xmlItem.prefixNumber) && + Objects.equals(this.prefixInteger, xmlItem.prefixInteger) && + Objects.equals(this.prefixBoolean, xmlItem.prefixBoolean) && + Objects.equals(this.prefixArray, xmlItem.prefixArray) && + Objects.equals(this.prefixWrappedArray, xmlItem.prefixWrappedArray) && + Objects.equals(this.namespaceString, xmlItem.namespaceString) && + Objects.equals(this.namespaceNumber, xmlItem.namespaceNumber) && + Objects.equals(this.namespaceInteger, xmlItem.namespaceInteger) && + Objects.equals(this.namespaceBoolean, xmlItem.namespaceBoolean) && + Objects.equals(this.namespaceArray, xmlItem.namespaceArray) && + Objects.equals(this.namespaceWrappedArray, xmlItem.namespaceWrappedArray) && + Objects.equals(this.prefixNsString, xmlItem.prefixNsString) && + Objects.equals(this.prefixNsNumber, xmlItem.prefixNsNumber) && + Objects.equals(this.prefixNsInteger, xmlItem.prefixNsInteger) && + Objects.equals(this.prefixNsBoolean, xmlItem.prefixNsBoolean) && + Objects.equals(this.prefixNsArray, xmlItem.prefixNsArray) && + Objects.equals(this.prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); } @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index 361e57e8167b..edbc664b7303 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class AnotherFakeApiServiceImpl extends AnotherFakeApiService { @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index a0e15051506b..e414cfb1d116 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeApiServiceImpl extends FakeApiService { @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java index 6f681177cb18..7356876a4518 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeClassnameTestApiServiceImpl extends FakeClassnameTestApiService { @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 628d5183e765..7b45a0fd7239 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index b4ec457464ff..c06c4da6d465 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index fd5803901752..28dc27736a46 100644 --- a/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-datelib-j8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class UserApiServiceImpl extends UserApiService { @Override @@ -22,12 +23,12 @@ public Response createUser(User body, SecurityContext securityContext) throws No return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithArrayInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithListInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-jersey/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-jersey/pom.xml b/samples/server/petstore/jaxrs-jersey/pom.xml index 9293b9cb6391..4f38605a7c90 100644 --- a/samples/server/petstore/jaxrs-jersey/pom.xml +++ b/samples/server/petstore/jaxrs-jersey/pom.xml @@ -107,6 +107,14 @@ swagger-jersey2-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -201,7 +209,7 @@ 2.35 2.15.2 4.13.2 - 1.2.12 + 1.4.14 4.0.4 UTF-8 diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/AnotherFakeApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/AnotherFakeApiService.java index ac73af977cfa..4d8fad35e097 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/AnotherFakeApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/AnotherFakeApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class AnotherFakeApiService { public abstract Response call123testSpecialTags(Client client,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java index 32c652a19ee8..e8ad376c9e0b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApi.java @@ -167,6 +167,18 @@ public Response fakePropertyEnumIntegerSerialize(@ApiParam(value = "Input enum ( throws NotFoundException { return delegate.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, securityContext); } + @javax.ws.rs.POST + @Path("/additionalProperties-reference") + @Consumes({ "application/json" }) + + @io.swagger.annotations.ApiOperation(value = "test referenced additionalProperties", notes = "", response = Void.class, tags={ "fake", }) + @io.swagger.annotations.ApiResponses(value = { + @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) + }) + public Response testAdditionalPropertiesReference(@ApiParam(value = "request body", required = true) @NotNull @Valid Map requestBody,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testAdditionalPropertiesReference(requestBody, securityContext); + } @javax.ws.rs.PUT @Path("/body-with-binary") @Consumes({ "image/png" }) @@ -240,7 +252,7 @@ public Response testEndpointParameters(@ApiParam(value = "None", required=true) @io.swagger.annotations.ApiResponse(code = 400, message = "Invalid request", response = Void.class), @io.swagger.annotations.ApiResponse(code = 404, message = "Not found", response = Void.class) }) - public Response testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)") @QueryParam("enum_query_string_array") @Valid List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue = "-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1, -2") @QueryParam("enum_query_integer") Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @QueryParam("enum_query_double") Double enumQueryDouble,@ApiParam(value = "") @QueryParam("enum_query_model_array") @Valid List enumQueryModelArray,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $", defaultValue="$") @DefaultValue("$") @FormParam("enum_form_string_array") List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString,@Context SecurityContext securityContext) + public Response testEnumParameters(@ApiParam(value = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@ApiParam(value = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString,@ApiParam(value = "Query parameter enum test (string array)") @QueryParam("enum_query_string_array") @Valid List enumQueryStringArray,@ApiParam(value = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue = "-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1, -2") @QueryParam("enum_query_integer") Integer enumQueryInteger,@ApiParam(value = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @QueryParam("enum_query_double") Double enumQueryDouble,@ApiParam(value = "") @QueryParam("enum_query_model_array") @Valid List<@Valid EnumClass> enumQueryModelArray,@ApiParam(value = "Form parameter enum test (string array)", allowableValues=">, $", defaultValue="$") @DefaultValue("$") @FormParam("enum_form_string_array") List enumFormStringArray,@ApiParam(value = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @FormParam("enum_form_string") String enumFormString,@Context SecurityContext securityContext) throws NotFoundException { return delegate.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString, securityContext); } diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java index d42edf03a9a0..027b1d38e1c1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeApiService.java @@ -29,6 +29,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeApiService { public abstract Response fakeBigDecimalMap(SecurityContext securityContext) throws NotFoundException; @@ -39,12 +40,13 @@ public abstract class FakeApiService { public abstract Response fakeOuterNumberSerialize(BigDecimal body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakeOuterStringSerialize(String body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty,SecurityContext securityContext) throws NotFoundException; + public abstract Response testAdditionalPropertiesReference(Map requestBody,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithBinary(File body,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithQueryParams( @NotNull String query,User user,SecurityContext securityContext) throws NotFoundException; public abstract Response testClientModel(Client client,SecurityContext securityContext) throws NotFoundException; public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,FormDataBodyPart binaryBodypart,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,Integer enumQueryInteger,Double enumQueryDouble,List enumQueryModelArray,List enumFormStringArray,String enumFormString,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,Integer enumQueryInteger,Double enumQueryDouble,List<@Valid EnumClass> enumQueryModelArray,List enumFormStringArray,String enumFormString,SecurityContext securityContext) throws NotFoundException; public abstract Response testGroupParameters( @NotNull Integer requiredStringGroup, @NotNull Boolean requiredBooleanGroup, @NotNull Long requiredInt64Group,Integer stringGroup,Boolean booleanGroup,Long int64Group,SecurityContext securityContext) throws NotFoundException; public abstract Response testInlineAdditionalProperties(Map requestBody,SecurityContext securityContext) throws NotFoundException; public abstract Response testInlineFreeformAdditionalProperties(TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java index cb5c11254d42..1b8ecd85a062 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeClassnameTestApiService { public abstract Response testClassname(Client client,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FooApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FooApiService.java index dc51a2311da2..c8a56925d0b1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FooApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/FooApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FooApiService { public abstract Response fooGet(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java index c62ed0509980..67234c2527c4 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class PetApiService { public abstract Response addPet(Pet pet,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java index 371e9de5d7b3..dbb4c174f45b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/StoreApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java index ebdd9cabe7f7..a2e5f17da34c 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApi.java @@ -75,7 +75,7 @@ public Response createUser(@ApiParam(value = "Created user object", required = t @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List user,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> user,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(user, securityContext); } @@ -87,7 +87,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List user,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> user,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(user, securityContext); } diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java index 5f9b2873f79b..23feffb5feca 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/api/UserApiService.java @@ -15,11 +15,12 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class UserApiService { public abstract Response createUser(User user,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List user,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List user,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List<@Valid User> user,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List<@Valid User> user,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 3d64a1034c71..a081869eb28e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -107,8 +107,8 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java index 473813750bbc..443173966fec 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java @@ -91,8 +91,8 @@ public boolean equals(Object o) { return false; } AllOfWithSingleRef allOfWithSingleRef = (AllOfWithSingleRef) o; - return Objects.equals(username, allOfWithSingleRef.username) && - Objects.equals(singleRefType, allOfWithSingleRef.singleRefType); + return Objects.equals(this.username, allOfWithSingleRef.username) && + Objects.equals(this.singleRefType, allOfWithSingleRef.singleRefType); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java index 500b36443702..fe6a3f7e6942 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Animal.java @@ -97,8 +97,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 3336f582992d..b6b68808ce39 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 73c9fb09799e..6d33189ca53e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java index 103024acb719..af0831e46be0 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ArrayTest.java @@ -46,7 +46,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -104,12 +104,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -124,11 +124,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @@ -142,9 +142,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java index 31c3ee371963..e952af0fbc98 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Capitalization.java @@ -189,12 +189,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java index fb8b0954a999..0fa048000bd6 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Cat.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return super.equals(o) && Objects.equals(declawed, cat.declawed); + return super.equals(o) && Objects.equals(this.declawed, cat.declawed); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java index 5c5ee2c9b5a4..4a5657942d6b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Category.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ChildWithNullable.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ChildWithNullable.java index 371f22123bc4..136f7dfe7f16 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ChildWithNullable.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ChildWithNullable.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ChildWithNullable childWithNullable = (ChildWithNullable) o; - return super.equals(o) && Objects.equals(otherProperty, childWithNullable.otherProperty); + return super.equals(o) && Objects.equals(this.otherProperty, childWithNullable.otherProperty); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java index b85ca626ded4..080d861f6d3a 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ClassModel.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java index 5d18c048f428..9153a3adf216 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Client.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DeprecatedObject.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DeprecatedObject.java index 75c46150294f..0fd9fc94e2e7 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DeprecatedObject.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/DeprecatedObject.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } DeprecatedObject deprecatedObject = (DeprecatedObject) o; - return Objects.equals(name, deprecatedObject.name); + return Objects.equals(this.name, deprecatedObject.name); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java index 139884e350f8..93e3653ba4da 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Dog.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return super.equals(o) && Objects.equals(breed, dog.breed); + return super.equals(o) && Objects.equals(this.breed, dog.breed); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java index c07029046ac6..4631a7c31f3c 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumArrays.java @@ -163,8 +163,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java index 3812ba5380d7..ef3a079d8f87 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/EnumTest.java @@ -373,14 +373,14 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum) && - Objects.equals(outerEnumInteger, enumTest.outerEnumInteger) && - Objects.equals(outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && - Objects.equals(outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum) && + Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && + Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && + Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java index e7dde1ab8bea..1f2fd614de44 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java @@ -101,8 +101,8 @@ public boolean equals(Object o) { return false; } FakeBigDecimalMap200Response fakeBigDecimalMap200Response = (FakeBigDecimalMap200Response) o; - return Objects.equals(someId, fakeBigDecimalMap200Response.someId) && - Objects.equals(someMap, fakeBigDecimalMap200Response.someMap); + return Objects.equals(this.someId, fakeBigDecimalMap200Response.someId) && + Objects.equals(this.someMap, fakeBigDecimalMap200Response.someMap); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 365006936e34..89e3dc1249f7 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -41,7 +41,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; @JsonProperty(JSON_PROPERTY_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -63,7 +63,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -83,11 +83,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -101,8 +101,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java index d2697a2e2f89..f2e274249f88 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Foo.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Foo foo = (Foo) o; - return Objects.equals(bar, foo.bar); + return Objects.equals(this.bar, foo.bar); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java index 394551fa842c..5ad561923b72 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } FooGetDefaultResponse fooGetDefaultResponse = (FooGetDefaultResponse) o; - return Objects.equals(string, fooGetDefaultResponse.string); + return Objects.equals(this.string, fooGetDefaultResponse.string); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java index a785b2b0f7e2..5bffc06d0eb0 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/FormatTest.java @@ -454,22 +454,22 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(decimal, formatTest.decimal) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(patternWithDigits, formatTest.patternWithDigits) && - Objects.equals(patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.decimal, formatTest.decimal) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && + Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); } @Override @@ -495,7 +495,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 8d8bd67aeb13..69ac562dc6a9 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java index c998c155ce40..30f85ab1078b 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/HealthCheckResult.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(nullableMessage, healthCheckResult.nullableMessage); + return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java index 428a329c83cf..6645c517504e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MapTest.java @@ -205,10 +205,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index dfa842013c5a..cc739934548f 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -127,9 +127,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java index d7ddf004f4d1..ae8f5397738a 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Model200Response.java @@ -91,8 +91,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java index a05c06e91761..28eb65f67817 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelFile.java index 35d3242a106e..135bad167483 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelFile.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelList.java index 4a6bf3fd375a..27e325aba294 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelList.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java index 08dca8ec3604..8f744e457889 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ModelReturn.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java index ac6b9667d605..c5c89ffd43d8 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Name.java @@ -140,10 +140,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java index 9e4136393be5..69fb550cdbb1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NullableClass.java @@ -394,18 +394,18 @@ public boolean equals(Object o) { return false; } NullableClass nullableClass = (NullableClass) o; - return super.equals(o) && Objects.equals(integerProp, nullableClass.integerProp) && - Objects.equals(numberProp, nullableClass.numberProp) && - Objects.equals(booleanProp, nullableClass.booleanProp) && - Objects.equals(stringProp, nullableClass.stringProp) && - Objects.equals(dateProp, nullableClass.dateProp) && - Objects.equals(datetimeProp, nullableClass.datetimeProp) && - Objects.equals(arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && - Objects.equals(arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && - Objects.equals(objectItemsNullable, nullableClass.objectItemsNullable); + return super.equals(o) && Objects.equals(this.integerProp, nullableClass.integerProp) && + Objects.equals(this.numberProp, nullableClass.numberProp) && + Objects.equals(this.booleanProp, nullableClass.booleanProp) && + Objects.equals(this.stringProp, nullableClass.stringProp) && + Objects.equals(this.dateProp, nullableClass.dateProp) && + Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && + Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && + Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && + Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && + Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java index 35fafbc3a139..aceea701ca1e 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/NumberOnly.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java index 456badd43a57..cd7a8697612c 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java @@ -52,7 +52,7 @@ public class ObjectWithDeprecatedFields { public static final String JSON_PROPERTY_BARS = "bars"; @JsonProperty(JSON_PROPERTY_BARS) - private List bars; + private List<@Valid String> bars; public ObjectWithDeprecatedFields uuid(String uuid) { this.uuid = uuid; @@ -114,7 +114,7 @@ public void setDeprecatedRef(DeprecatedObject deprecatedRef) { this.deprecatedRef = deprecatedRef; } - public ObjectWithDeprecatedFields bars(List bars) { + public ObjectWithDeprecatedFields bars(List<@Valid String> bars) { this.bars = bars; return this; } @@ -134,11 +134,11 @@ public ObjectWithDeprecatedFields addBarsItem(String barsItem) { @JsonProperty(value = "bars") @ApiModelProperty(value = "") - public List getBars() { + public List<@Valid String> getBars() { return bars; } - public void setBars(List bars) { + public void setBars(List<@Valid String> bars) { this.bars = bars; } @@ -152,10 +152,10 @@ public boolean equals(Object o) { return false; } ObjectWithDeprecatedFields objectWithDeprecatedFields = (ObjectWithDeprecatedFields) o; - return Objects.equals(uuid, objectWithDeprecatedFields.uuid) && - Objects.equals(id, objectWithDeprecatedFields.id) && - Objects.equals(deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && - Objects.equals(bars, objectWithDeprecatedFields.bars); + return Objects.equals(this.uuid, objectWithDeprecatedFields.uuid) && + Objects.equals(this.id, objectWithDeprecatedFields.id) && + Objects.equals(this.deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && + Objects.equals(this.bars, objectWithDeprecatedFields.bars); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java index 96c4ba5a384e..5a60e9121f40 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Order.java @@ -224,12 +224,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java index e6fef1023ae1..455f52c5ead2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterComposite.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java index 797e87c25de0..9d2f9f0e1071 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } OuterObjectWithEnumProperty outerObjectWithEnumProperty = (OuterObjectWithEnumProperty) o; - return Objects.equals(value, outerObjectWithEnumProperty.value); + return Objects.equals(this.value, outerObjectWithEnumProperty.value); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ParentWithNullable.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ParentWithNullable.java index eedfd014e9c6..4945367253a0 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ParentWithNullable.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ParentWithNullable.java @@ -126,8 +126,8 @@ public boolean equals(Object o) { return false; } ParentWithNullable parentWithNullable = (ParentWithNullable) o; - return Objects.equals(type, parentWithNullable.type) && - Objects.equals(nullableProperty, parentWithNullable.nullableProperty); + return Objects.equals(this.type, parentWithNullable.type) && + Objects.equals(this.nullableProperty, parentWithNullable.nullableProperty); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java index 0de0618f5e99..194a6fc01354 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Pet.java @@ -62,7 +62,7 @@ public class Pet { public static final String JSON_PROPERTY_TAGS = "tags"; @JsonProperty(JSON_PROPERTY_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -190,7 +190,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -210,11 +210,11 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -248,12 +248,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 0650df4c320a..0827ed6b9fe3 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java index e8e0c9a80f40..5f5553bd34b4 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java index b8197646f462..ba07edce8ce1 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/Tag.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java index 1eccc22ee593..ec1f31ec5257 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = (TestInlineFreeformAdditionalPropertiesRequest) o; - return super.equals(o) && Objects.equals(someProperty, testInlineFreeformAdditionalPropertiesRequest.someProperty); + return super.equals(o) && Objects.equals(this.someProperty, testInlineFreeformAdditionalPropertiesRequest.someProperty); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java index 06ab22d0fdc0..26261801d0b2 100644 --- a/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-jersey/src/gen/java/org/openapitools/model/User.java @@ -239,14 +239,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index 840de7f0c320..c730c58f33d6 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class AnotherFakeApiServiceImpl extends AnotherFakeApiService { @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index 4490e6fe4213..7c4cfb0c4aa0 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -28,6 +28,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeApiServiceImpl extends FakeApiService { @Override @@ -71,6 +72,11 @@ public Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty out return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override + public Response testAdditionalPropertiesReference(Map requestBody, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override public Response testBodyWithBinary(File body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); @@ -96,7 +102,7 @@ public Response testEndpointParameters(BigDecimal number, Double _double, String return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString, SecurityContext securityContext) throws NotFoundException { + public Response testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<@Valid EnumClass> enumQueryModelArray, List enumFormStringArray, String enumFormString, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java index 8dae1b59a76a..4b5971a2bf68 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeClassnameTestApiServiceImpl extends FakeClassnameTestApiService { @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java index 344f74d8e830..cf0d9e2fb623 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FooApiServiceImpl extends FooApiService { @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index f7e82817f399..49b1ada77706 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 536e5779d00d..733e474ece9f 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 941d4b82ab0e..e40c07966a77 100644 --- a/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-jersey/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class UserApiServiceImpl extends UserApiService { @Override @@ -22,12 +23,12 @@ public Response createUser(User user, SecurityContext securityContext) throws No return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List user, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithArrayInput(List<@Valid User> user, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List user, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithListInput(List<@Valid User> user, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs-resteasy/default-value/pom.xml b/samples/server/petstore/jaxrs-resteasy/default-value/pom.xml index f73452466702..3676cdf32044 100644 --- a/samples/server/petstore/jaxrs-resteasy/default-value/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/default-value/pom.xml @@ -107,6 +107,14 @@ resteasy-validator-provider-11 3.6.3.SP1 provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -141,6 +149,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/default/build.gradle b/samples/server/petstore/jaxrs-resteasy/default/build.gradle index 623f1efab485..adaf0cce95a0 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/default/build.gradle @@ -10,10 +10,12 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' - providedCompile 'javax:javaee-api:7.0' + providedCompile 'javax:javaee-api:8.0' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' compile 'io.swagger:swagger-annotations:1.5.22' compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final' @@ -21,7 +23,9 @@ dependencies { compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.9.9' compile 'joda-time:joda-time:2.7' //TODO: swaggerFeature - compile 'io.swagger:swagger-jaxrs:1.5.12' + compile('io.swagger:swagger-jaxrs:1.5.12') { + exclude group: "javax.validation", module: "validation-api" + } testCompile 'junit:junit:4.13.2', 'org.hamcrest:hamcrest-core:1.3' diff --git a/samples/server/petstore/jaxrs-resteasy/default/pom.xml b/samples/server/petstore/jaxrs-resteasy/default/pom.xml index 640fdc4dba21..cb7d71acdfde 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/default/pom.xml @@ -63,7 +63,7 @@ javax javaee-api - 7.0 + 8.0 provided @@ -107,6 +107,14 @@ resteasy-validator-provider-11 3.6.3.SP1 provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -135,6 +143,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/PetApiService.java index b357a638a011..4b90ffa4d133 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/PetApiService.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/StoreApiService.java index ed4c8338a600..02b9a047736d 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/StoreApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApi.java index 8ae5e1891d6d..3529dd0c2885 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApi.java @@ -51,7 +51,7 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithArrayInput(body,securityContext); } @@ -62,7 +62,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithListInput(body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApiService.java index 2ab01f3452ed..527b3335433b 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/api/UserApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -19,9 +21,9 @@ public interface UserApiService { Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithArrayInput(List body,SecurityContext securityContext) + Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithListInput(List body,SecurityContext securityContext) + Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Category.java index d2566a81692d..39db901d4e77 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/ModelApiResponse.java index c1a1f5741043..893b8936e17c 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -64,9 +65,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Order.java index 96e47d3b3ba7..4ae91ff954b8 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.Date; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -128,12 +129,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Pet.java index 86e6c57ff162..bb69738a7025 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -23,7 +24,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -106,10 +107,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -136,12 +137,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Tag.java index 1375bf209496..7c03d8c7d5c3 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/User.java index 330a25d8a4a4..9d09c63645f5 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -129,14 +130,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 9b62bb6feb6b..8934773bf509 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 4669635c2590..e0b0ab58cfd8 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 554c147c99f8..9c48ef0c3083 100644 --- a/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/default/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -24,12 +26,12 @@ public Response createUser(User body,SecurityContext securityContext) // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/build.gradle b/samples/server/petstore/jaxrs-resteasy/eap-java8/build.gradle index faea35dd726c..34ec45796e64 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/build.gradle @@ -10,7 +10,9 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/pom.xml b/samples/server/petstore/jaxrs-resteasy/eap-java8/pom.xml index c01897f1b69a..99c9881b888b 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/pom.xml @@ -89,6 +89,14 @@ resteasy-validator-provider-11 ${resteasy-version} provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -113,6 +121,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/api/UserApi.java index 38de4d3547a5..f38af3de1755 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/api/UserApi.java @@ -42,7 +42,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @POST @Path("/createWithList") @@ -50,7 +50,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @DELETE @Path("/{username}") diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Category.java index f5391a0860cc..b808dcd92436 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A category for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/ModelApiResponse.java index b878faeea22b..26a075c67c6f 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="Describes the result of uploading an image resource")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -63,9 +64,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Order.java index d1fe5c4e8108..05554831c121 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="An order for a pets from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -127,12 +128,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Pet.java index 496e43976f09..ddc62ff17a4a 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A pet for sale in the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -22,7 +23,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -103,10 +104,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -133,12 +134,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Tag.java index b2b4142e27e6..30ad4bed5f42 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A tag for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/User.java index cc1cc0d24227..7dff77fbbbb5 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A User who is purchasing from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -128,14 +129,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 7ae1b892f0aa..1db117876a3b 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -13,6 +13,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 262a0fb0005a..8d3ccdd65a08 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index fd3958dae712..82ad2f15c023 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -20,11 +22,11 @@ public Response createUser(User body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) { + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) { + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/build.gradle b/samples/server/petstore/jaxrs-resteasy/eap-joda/build.gradle index faea35dd726c..34ec45796e64 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/build.gradle @@ -10,7 +10,9 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/pom.xml b/samples/server/petstore/jaxrs-resteasy/eap-joda/pom.xml index ff8599c0aab9..2c9e53d49f90 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/pom.xml @@ -89,6 +89,14 @@ resteasy-validator-provider-11 ${resteasy-version} provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -113,6 +121,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/api/UserApi.java index 4b127c222850..a3844ba088ba 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/api/UserApi.java @@ -42,7 +42,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @POST @Path("/createWithList") @@ -50,7 +50,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @DELETE @Path("/{username}") diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Category.java index f5391a0860cc..b808dcd92436 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A category for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/ModelApiResponse.java index b878faeea22b..26a075c67c6f 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="Describes the result of uploading an image resource")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -63,9 +64,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Order.java index c488917d2b39..7084229d0a8d 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="An order for a pets from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -127,12 +128,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Pet.java index 496e43976f09..ddc62ff17a4a 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A pet for sale in the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -22,7 +23,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -103,10 +104,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -133,12 +134,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Tag.java index b2b4142e27e6..30ad4bed5f42 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A tag for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/User.java index cc1cc0d24227..7dff77fbbbb5 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A User who is purchasing from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -128,14 +129,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 50a3d2f99c38..3de5b828e5b9 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -13,6 +13,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 262a0fb0005a..8d3ccdd65a08 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 2806a00e6766..7c29df217c11 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap-joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -20,11 +22,11 @@ public Response createUser(User body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) { + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) { + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } diff --git a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/eap/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/eap/build.gradle b/samples/server/petstore/jaxrs-resteasy/eap/build.gradle index faea35dd726c..34ec45796e64 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/eap/build.gradle @@ -10,7 +10,9 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' diff --git a/samples/server/petstore/jaxrs-resteasy/eap/pom.xml b/samples/server/petstore/jaxrs-resteasy/eap/pom.xml index ab704408339c..13bcbc03e357 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/eap/pom.xml @@ -89,6 +89,14 @@ resteasy-validator-provider-11 ${resteasy-version} provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -113,6 +121,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/api/UserApi.java index a8f524e85942..03400141792a 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/api/UserApi.java @@ -42,7 +42,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @POST @Path("/createWithList") @@ -50,7 +50,7 @@ public interface UserApi { @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext); + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext); @DELETE @Path("/{username}") diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Category.java index f5391a0860cc..b808dcd92436 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A category for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/ModelApiResponse.java index b878faeea22b..26a075c67c6f 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="Describes the result of uploading an image resource")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -63,9 +64,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Order.java index 6129e7561528..1b6db5e78d20 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.util.Date; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="An order for a pets from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -127,12 +128,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Pet.java index 496e43976f09..ddc62ff17a4a 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A pet for sale in the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -22,7 +23,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -103,10 +104,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -133,12 +134,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Tag.java index b2b4142e27e6..30ad4bed5f42 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A tag for a pet")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -49,8 +50,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/User.java index cc1cc0d24227..7dff77fbbbb5 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; @ApiModel(description="A User who is purchasing from the pet store")@javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaResteasyEapServerCodegen") @@ -128,14 +129,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 50a3d2f99c38..3de5b828e5b9 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -13,6 +13,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 262a0fb0005a..8d3ccdd65a08 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index d250cf5c6a2e..cab308b7da84 100644 --- a/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/eap/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -11,6 +11,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -20,11 +22,11 @@ public Response createUser(User body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) { + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) { + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) { // do some magic! return Response.ok().build(); } diff --git a/samples/server/petstore/jaxrs-resteasy/java8/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/java8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/java8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/java8/build.gradle b/samples/server/petstore/jaxrs-resteasy/java8/build.gradle index 623f1efab485..adaf0cce95a0 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/java8/build.gradle @@ -10,10 +10,12 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' - providedCompile 'javax:javaee-api:7.0' + providedCompile 'javax:javaee-api:8.0' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' compile 'io.swagger:swagger-annotations:1.5.22' compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final' @@ -21,7 +23,9 @@ dependencies { compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.9.9' compile 'joda-time:joda-time:2.7' //TODO: swaggerFeature - compile 'io.swagger:swagger-jaxrs:1.5.12' + compile('io.swagger:swagger-jaxrs:1.5.12') { + exclude group: "javax.validation", module: "validation-api" + } testCompile 'junit:junit:4.13.2', 'org.hamcrest:hamcrest-core:1.3' diff --git a/samples/server/petstore/jaxrs-resteasy/java8/pom.xml b/samples/server/petstore/jaxrs-resteasy/java8/pom.xml index 64b584dd9fb5..88e39654293f 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/java8/pom.xml @@ -63,7 +63,7 @@ javax javaee-api - 7.0 + 8.0 provided @@ -107,6 +107,14 @@ resteasy-validator-provider-11 3.6.3.SP1 provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -135,6 +143,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/PetApiService.java index 5415004bc635..3b211fadb8d5 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/PetApiService.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/StoreApiService.java index ed4c8338a600..02b9a047736d 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/StoreApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApi.java index 70a8bc1cf46c..c453e39b9923 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApi.java @@ -51,7 +51,7 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithArrayInput(body,securityContext); } @@ -62,7 +62,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithListInput(body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApiService.java index 5da85d24212c..224be3a1a503 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/api/UserApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -19,9 +21,9 @@ public interface UserApiService { Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithArrayInput(List body,SecurityContext securityContext) + Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithListInput(List body,SecurityContext securityContext) + Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Category.java index d2566a81692d..39db901d4e77 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/ModelApiResponse.java index c1a1f5741043..893b8936e17c 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -64,9 +65,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Order.java index 76fb75a08f96..b4e5c3b3d802 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import java.time.OffsetDateTime; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -128,12 +129,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Pet.java index 86e6c57ff162..bb69738a7025 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -23,7 +24,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -106,10 +107,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -136,12 +137,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Tag.java index 1375bf209496..7c03d8c7d5c3 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/User.java index 330a25d8a4a4..9d09c63645f5 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -129,14 +130,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 0b264cc92ced..afd3438598a0 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 4669635c2590..e0b0ab58cfd8 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index ecc386ffc05e..7818715c89b4 100644 --- a/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/java8/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -24,12 +26,12 @@ public Response createUser(User body,SecurityContext securityContext) // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-resteasy/joda/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-resteasy/joda/build.gradle b/samples/server/petstore/jaxrs-resteasy/joda/build.gradle index 623f1efab485..adaf0cce95a0 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/build.gradle +++ b/samples/server/petstore/jaxrs-resteasy/joda/build.gradle @@ -10,10 +10,12 @@ repositories { dependencies { providedCompile 'org.jboss.resteasy:resteasy-jaxrs:3.0.11.Final' providedCompile 'org.jboss.resteasy:jaxrs-api:3.0.11.Final' - providedCompile 'org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final' + providedCompile('org.jboss.resteasy:resteasy-validator-provider-11:3.0.11.Final') { + exclude group: "javax.validation", module: "validation-api" + } providedCompile 'org.jboss.resteasy:resteasy-multipart-provider:3.0.11.Final' providedCompile 'jakarta.annotation:jakarta.annotation-api:1.3.5' - providedCompile 'javax:javaee-api:7.0' + providedCompile 'javax:javaee-api:8.0' providedCompile 'org.jboss.spec.javax.servlet:jboss-servlet-api_3.0_spec:1.0.0.Final' compile 'io.swagger:swagger-annotations:1.5.22' compile 'org.jboss.resteasy:resteasy-jackson2-provider:3.0.11.Final' @@ -21,7 +23,9 @@ dependencies { compile 'com.fasterxml.jackson.datatype:jackson-datatype-joda:2.9.9' compile 'joda-time:joda-time:2.7' //TODO: swaggerFeature - compile 'io.swagger:swagger-jaxrs:1.5.12' + compile('io.swagger:swagger-jaxrs:1.5.12') { + exclude group: "javax.validation", module: "validation-api" + } testCompile 'junit:junit:4.13.2', 'org.hamcrest:hamcrest-core:1.3' diff --git a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml index 37aeeef8546d..ad8ca97ed485 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/pom.xml +++ b/samples/server/petstore/jaxrs-resteasy/joda/pom.xml @@ -63,7 +63,7 @@ javax javaee-api - 7.0 + 8.0 provided @@ -107,6 +107,14 @@ resteasy-validator-provider-11 3.6.3.SP1 provided + + + + javax.validation + validation-api + + org.jboss.resteasy @@ -135,6 +143,14 @@ io.swagger swagger-jaxrs ${swagger-core-version} + + + + javax.validation + validation-api + + junit diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/PetApiService.java index 5415004bc635..3b211fadb8d5 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/PetApiService.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/StoreApiService.java index ed4c8338a600..02b9a047736d 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/StoreApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApi.java index 4930059c7878..2f7c40e0403a 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApi.java @@ -51,7 +51,7 @@ public Response createUser(@ApiParam(value = "Created user object" ,required=tru @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithArrayInput(body,securityContext); } @@ -62,7 +62,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiOperation(value = "Creates list of users with given input array", notes = "", response = Void.class, tags={ "user", }) @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object" ,required=true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return service.createUsersWithListInput(body,securityContext); } diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApiService.java index 9c059bf7a871..9bb36a882b7b 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/api/UserApiService.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -19,9 +21,9 @@ public interface UserApiService { Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithArrayInput(List body,SecurityContext securityContext) + Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; - Response createUsersWithListInput(List body,SecurityContext securityContext) + Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Category.java index d2566a81692d..39db901d4e77 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Category.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/ModelApiResponse.java index c1a1f5741043..893b8936e17c 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -8,6 +8,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -64,9 +65,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Order.java index ec015fcacaaf..6ef77af7145e 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Order.java @@ -9,6 +9,7 @@ import io.swagger.annotations.ApiModelProperty; import org.joda.time.DateTime; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -128,12 +129,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Pet.java index 86e6c57ff162..bb69738a7025 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Pet.java @@ -13,6 +13,7 @@ import org.openapitools.model.Category; import org.openapitools.model.Tag; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -23,7 +24,7 @@ public class Pet { private Category category; private String name; private List photoUrls = new ArrayList<>(); - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -106,10 +107,10 @@ public void setPhotoUrls(List photoUrls) { @ApiModelProperty(value = "") @JsonProperty("tags") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -136,12 +137,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Tag.java index 1375bf209496..7c03d8c7d5c3 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/Tag.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -50,8 +51,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/User.java index 330a25d8a4a4..9d09c63645f5 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/gen/java/org/openapitools/model/User.java @@ -7,6 +7,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import javax.validation.constraints.*; +import javax.validation.Valid; import io.swagger.annotations.*; import javax.validation.Valid; @@ -129,14 +130,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 0b264cc92ced..afd3438598a0 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -14,6 +14,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 4669635c2590..e0b0ab58cfd8 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; diff --git a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 79b3edebfe71..94be3c2113b0 100644 --- a/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs-resteasy/joda/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -12,6 +12,8 @@ import java.io.InputStream; +import javax.validation.constraints.*; +import javax.validation.Valid; import javax.enterprise.context.RequestScoped; import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; @@ -24,12 +26,12 @@ public Response createUser(User body,SecurityContext securityContext) // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithArrayInput(List body,SecurityContext securityContext) + public Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } - public Response createUsersWithListInput(List body,SecurityContext securityContext) + public Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); diff --git a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES index a5460bdf420e..f7f670f582e6 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES +++ b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/FILES @@ -20,15 +20,12 @@ src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java src/gen/java/org/openapitools/model/ArrayTest.java src/gen/java/org/openapitools/model/BigCat.java -src/gen/java/org/openapitools/model/BigCatAllOf.java src/gen/java/org/openapitools/model/Capitalization.java src/gen/java/org/openapitools/model/Cat.java -src/gen/java/org/openapitools/model/CatAllOf.java src/gen/java/org/openapitools/model/Category.java src/gen/java/org/openapitools/model/ClassModel.java src/gen/java/org/openapitools/model/Client.java src/gen/java/org/openapitools/model/Dog.java -src/gen/java/org/openapitools/model/DogAllOf.java src/gen/java/org/openapitools/model/EnumArrays.java src/gen/java/org/openapitools/model/EnumClass.java src/gen/java/org/openapitools/model/EnumTest.java diff --git a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION index 66672d4e9d31..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-interface-response/.openapi-generator/VERSION @@ -1 +1 @@ -6.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-interface-response/pom.xml b/samples/server/petstore/jaxrs-spec-interface-response/pom.xml index 861b090b321b..becf131d1dec 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/pom.xml +++ b/samples/server/petstore/jaxrs-spec-interface-response/pom.xml @@ -94,7 +94,7 @@ ${java.version} ${java.version} UTF-8 - 2.9.9 + 2.15.2 4.13.2 2.10.13 1.3.2 diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java index 6107529c094e..0cce14c767ad 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/AnotherFakeApi.java @@ -1,6 +1,7 @@ package org.openapitools.api; import org.openapitools.model.Client; +import java.util.UUID; import javax.ws.rs.*; import javax.ws.rs.core.Response; @@ -24,5 +25,6 @@ public interface AnotherFakeApi { @ApiOperation(value = "To test special tags", notes = "To test special tags and operation ID starting with number", tags={ "$another-fake?" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) - Response call123testSpecialTags(@Valid @NotNull Client body); + Response call123testSpecialTags(@HeaderParam("uuid_test") @NotNull @ApiParam("to test uuid example value") UUID uuidTest,@Valid @NotNull Client body); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java index 23a56fbb3702..dba002688897 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeApi.java @@ -36,6 +36,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response createXmlItem(@Valid @NotNull XmlItem xmlItem); + @POST @Path("/outer/boolean") @Produces({ "*/*" }) @@ -44,6 +45,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output boolean", response = Boolean.class) }) Response fakeOuterBooleanSerialize(@Valid Boolean body); + @POST @Path("/outer/composite") @Produces({ "*/*" }) @@ -52,6 +54,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output composite", response = OuterComposite.class) }) Response fakeOuterCompositeSerialize(@Valid OuterComposite body); + @POST @Path("/outer/number") @Produces({ "*/*" }) @@ -60,6 +63,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output number", response = BigDecimal.class) }) Response fakeOuterNumberSerialize(@Valid BigDecimal body); + @POST @Path("/outer/string") @Produces({ "*/*" }) @@ -68,6 +72,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Output string", response = String.class) }) Response fakeOuterStringSerialize(@Valid String body); + @PUT @Path("/body-with-file-schema") @Consumes({ "application/json" }) @@ -76,6 +81,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Success", response = Void.class) }) Response testBodyWithFileSchema(@Valid @NotNull FileSchemaTestClass body); + @PUT @Path("/body-with-query-params") @Consumes({ "application/json" }) @@ -84,6 +90,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Success", response = Void.class) }) Response testBodyWithQueryParams(@QueryParam("query") @NotNull String query,@Valid @NotNull User body); + @PATCH @Consumes({ "application/json" }) @Produces({ "application/json" }) @@ -92,6 +99,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) Response testClientModel(@Valid @NotNull Client body); + @POST @Consumes({ "application/x-www-form-urlencoded" }) @ApiOperation(value = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", notes = "Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트", authorizations = { @@ -103,6 +111,7 @@ public interface FakeApi { @ApiResponse(code = 404, message = "User not found", response = Void.class) }) Response testEndpointParameters(@FormParam(value = "number") BigDecimal number,@FormParam(value = "double") Double _double,@FormParam(value = "pattern_without_delimiter") String patternWithoutDelimiter,@FormParam(value = "byte") byte[] _byte,@FormParam(value = "integer") Integer integer,@FormParam(value = "int32") Integer int32,@FormParam(value = "int64") Long int64,@FormParam(value = "float") Float _float,@FormParam(value = "string") String string, @FormParam(value = "binary") InputStream binaryInputStream,@FormParam(value = "date") LocalDate date,@FormParam(value = "dateTime") Date dateTime,@FormParam(value = "password") String password,@FormParam(value = "callback") String paramCallback); + @GET @Consumes({ "application/x-www-form-urlencoded" }) @ApiOperation(value = "To test enum parameters", notes = "To test enum parameters", tags={ "fake" }) @@ -111,12 +120,14 @@ public interface FakeApi { @ApiResponse(code = 404, message = "Not found", response = Void.class) }) Response testEnumParameters(@HeaderParam("enum_header_string_array") @ApiParam("Header parameter enum test (string array)") List enumHeaderStringArray,@HeaderParam("enum_header_string") @DefaultValue("-efg") @ApiParam("Header parameter enum test (string)") String enumHeaderString,@QueryParam("enum_query_string_array") @ApiParam("Query parameter enum test (string array)") List enumQueryStringArray,@QueryParam("enum_query_string") @DefaultValue("-efg") @ApiParam("Query parameter enum test (string)") String enumQueryString,@QueryParam("enum_query_integer") @ApiParam("Query parameter enum test (double)") Integer enumQueryInteger,@QueryParam("enum_query_double") @ApiParam("Query parameter enum test (double)") Double enumQueryDouble,@FormParam(value = "enum_form_string_array") List enumFormStringArray,@FormParam(value = "enum_form_string") String enumFormString); + @DELETE @ApiOperation(value = "Fake endpoint to test group parameters (optional)", notes = "Fake endpoint to test group parameters (optional)", tags={ "fake" }) @ApiResponses(value = { @ApiResponse(code = 400, message = "Something wrong", response = Void.class) }) Response testGroupParameters(@QueryParam("required_string_group") @NotNull @ApiParam("Required String in group parameters") Integer requiredStringGroup,@HeaderParam("required_boolean_group") @NotNull @ApiParam("Required Boolean in group parameters") Boolean requiredBooleanGroup,@QueryParam("required_int64_group") @NotNull @ApiParam("Required Integer in group parameters") Long requiredInt64Group,@QueryParam("string_group") @ApiParam("String in group parameters") Integer stringGroup,@HeaderParam("boolean_group") @ApiParam("Boolean in group parameters") Boolean booleanGroup,@QueryParam("int64_group") @ApiParam("Integer in group parameters") Long int64Group); + @POST @Path("/inline-additionalProperties") @Consumes({ "application/json" }) @@ -125,6 +136,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response testInlineAdditionalProperties(@Valid @NotNull Map param); + @GET @Path("/jsonFormData") @Consumes({ "application/x-www-form-urlencoded" }) @@ -133,6 +145,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response testJsonFormData(@FormParam(value = "param") String param,@FormParam(value = "param2") String param2); + @PUT @Path("/test-query-parameters") @ApiOperation(value = "", notes = "To test the collection format in query parameters", tags={ "fake" }) @@ -140,6 +153,7 @@ public interface FakeApi { @ApiResponse(code = 200, message = "Success", response = Void.class) }) Response testQueryParameterCollectionFormat(@QueryParam("pipe") @NotNull List pipe,@QueryParam("ioutil") @NotNull List ioutil,@QueryParam("http") @NotNull List http,@QueryParam("url") @NotNull List url,@QueryParam("context") @NotNull List context); + @POST @Path("/{petId}/uploadImageWithRequiredFile") @Consumes({ "multipart/form-data" }) @@ -152,4 +166,5 @@ public interface FakeApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) Response uploadFileWithRequiredFile(@PathParam("petId") @ApiParam("ID of pet to update") Long petId, @FormParam(value = "requiredFile") InputStream requiredFileInputStream,@FormParam(value = "additionalMetadata") String additionalMetadata); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java index e14b0e6205ed..2cfa96236bfc 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/FakeClassnameTestApi.java @@ -28,4 +28,5 @@ public interface FakeClassnameTestApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Client.class) }) Response testClassname(@Valid @NotNull Client body); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java index 5b8958907578..684e7d5e8b60 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/PetApi.java @@ -33,6 +33,7 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) Response addPet(@Valid @NotNull Pet body); + @DELETE @Path("/{petId}") @ApiOperation(value = "Deletes a pet", notes = "", authorizations = { @@ -45,6 +46,7 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid pet value", response = Void.class) }) Response deletePet(@PathParam("petId") @ApiParam("Pet id to delete") Long petId,@HeaderParam("api_key") String apiKey); + @GET @Path("/findByStatus") @Produces({ "application/xml", "application/json" }) @@ -58,6 +60,7 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid status value", response = Void.class, responseContainer = "List") }) Response findPetsByStatus(@QueryParam("status") @NotNull @ApiParam("Status values that need to be considered for filter") List status); + @GET @Path("/findByTags") @Produces({ "application/xml", "application/json" }) @@ -71,6 +74,7 @@ public interface PetApi { @ApiResponse(code = 400, message = "Invalid tag value", response = Void.class, responseContainer = "Set") }) Response findPetsByTags(@QueryParam("tags") @NotNull @ApiParam("Tags to filter by") Set tags); + @GET @Path("/{petId}") @Produces({ "application/xml", "application/json" }) @@ -84,6 +88,7 @@ public interface PetApi { @ApiResponse(code = 404, message = "Pet not found", response = Void.class) }) Response getPetById(@PathParam("petId") @ApiParam("ID of pet to return") Long petId); + @PUT @Consumes({ "application/json", "application/xml" }) @ApiOperation(value = "Update an existing pet", notes = "", authorizations = { @@ -98,6 +103,7 @@ public interface PetApi { @ApiResponse(code = 405, message = "Validation exception", response = Void.class) }) Response updatePet(@Valid @NotNull Pet body); + @POST @Path("/{petId}") @Consumes({ "application/x-www-form-urlencoded" }) @@ -110,6 +116,7 @@ public interface PetApi { @ApiResponse(code = 405, message = "Invalid input", response = Void.class) }) Response updatePetWithForm(@PathParam("petId") @ApiParam("ID of pet that needs to be updated") Long petId,@FormParam(value = "name") String name,@FormParam(value = "status") String status); + @POST @Path("/{petId}/uploadImage") @Consumes({ "multipart/form-data" }) @@ -122,4 +129,5 @@ public interface PetApi { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = ModelApiResponse.class) }) Response uploadFile(@PathParam("petId") @ApiParam("ID of pet to update") Long petId,@FormParam(value = "additionalMetadata") String additionalMetadata, @FormParam(value = "file") InputStream _fileInputStream); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java index b2a8f9c8ee14..c7a53c670fe2 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/StoreApi.java @@ -27,6 +27,7 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) Response deleteOrder(@PathParam("order_id") @ApiParam("ID of the order that needs to be deleted") String orderId); + @GET @Path("/inventory") @Produces({ "application/json" }) @@ -38,6 +39,7 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Map.class, responseContainer = "Map") }) Response getInventory(); + @GET @Path("/order/{order_id}") @Produces({ "application/xml", "application/json" }) @@ -48,6 +50,7 @@ public interface StoreApi { @ApiResponse(code = 404, message = "Order not found", response = Void.class) }) Response getOrderById(@PathParam("order_id") @Min(1L) @Max(5L) @ApiParam("ID of pet that needs to be fetched") Long orderId); + @POST @Path("/order") @Produces({ "application/xml", "application/json" }) @@ -56,4 +59,5 @@ public interface StoreApi { @ApiResponse(code = 200, message = "successful operation", response = Order.class), @ApiResponse(code = 400, message = "Invalid Order", response = Void.class) }) Response placeOrder(@Valid @NotNull Order body); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java index 888b96e8cd02..72d9f7adcaaa 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/api/UserApi.java @@ -1,7 +1,6 @@ package org.openapitools.api; import java.util.Date; -import java.util.List; import org.openapitools.model.User; import javax.ws.rs.*; @@ -26,19 +25,22 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response createUser(@Valid @NotNull User body); + @POST @Path("/createWithArray") @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - Response createUsersWithArrayInput(@Valid @NotNull List body); + Response createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body); + @POST @Path("/createWithList") @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - Response createUsersWithListInput(@Valid @NotNull List body); + Response createUsersWithListInput(@Valid @NotNull List<@Valid User> body); + @DELETE @Path("/{username}") @@ -48,6 +50,7 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found", response = Void.class) }) Response deleteUser(@PathParam("username") @ApiParam("The name that needs to be deleted") String username); + @GET @Path("/{username}") @Produces({ "application/xml", "application/json" }) @@ -58,6 +61,7 @@ public interface UserApi { @ApiResponse(code = 404, message = "User not found", response = Void.class) }) Response getUserByName(@PathParam("username") @ApiParam("The name that needs to be fetched. Use user1 for testing.") String username); + @GET @Path("/login") @Produces({ "application/xml", "application/json" }) @@ -67,6 +71,7 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid username/password supplied", response = Void.class) }) Response loginUser(@QueryParam("username") @NotNull @ApiParam("The user name for login") String username,@QueryParam("password") @NotNull @ApiParam("The password for login in clear text") String password); + @GET @Path("/logout") @ApiOperation(value = "Logs out current logged in user session", notes = "", tags={ "user" }) @@ -74,6 +79,7 @@ public interface UserApi { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) Response logoutUser(); + @PUT @Path("/{username}") @ApiOperation(value = "Updated user", notes = "This can only be done by the logged in user.", tags={ "user" }) @@ -81,4 +87,5 @@ public interface UserApi { @ApiResponse(code = 400, message = "Invalid user supplied", response = Void.class), @ApiResponse(code = 404, message = "User not found", response = Void.class) }) Response updateUser(@PathParam("username") @ApiParam("name that need to be deleted") String username,@Valid @NotNull User body); + } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 31b4b91dfb26..93e1d2fabdd4 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -22,14 +22,14 @@ @JsonTypeName("AdditionalPropertiesClass") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class AdditionalPropertiesClass implements Serializable { - private @Valid Map mapString = null; - private @Valid Map mapNumber = null; - private @Valid Map mapInteger = null; - private @Valid Map mapBoolean = null; - private @Valid Map> mapArrayInteger = null; - private @Valid Map> mapArrayAnytype = null; - private @Valid Map> mapMapString = null; - private @Valid Map> mapMapAnytype = null; + private @Valid Map mapString = new HashMap<>(); + private @Valid Map mapNumber = new HashMap<>(); + private @Valid Map mapInteger = new HashMap<>(); + private @Valid Map mapBoolean = new HashMap<>(); + private @Valid Map> mapArrayInteger = new HashMap<>(); + private @Valid Map> mapArrayAnytype = new HashMap<>(); + private @Valid Map> mapMapString = new HashMap<>(); + private @Valid Map> mapMapAnytype = new HashMap<>(); private @Valid Object anytype1; private @Valid Object anytype2; private @Valid Object anytype3; diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 0385c5e82908..f5305a8ab9ec 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; @@ -21,7 +22,7 @@ @JsonTypeName("ArrayOfArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfArrayOfNumberOnly implements Serializable { - private @Valid List> arrayArrayNumber = null; + private @Valid List> arrayArrayNumber; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index cbfdb520031a..8bb4590441aa 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; @@ -21,7 +22,7 @@ @JsonTypeName("ArrayOfNumberOnly") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayOfNumberOnly implements Serializable { - private @Valid List arrayNumber = null; + private @Valid List arrayNumber; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java index b2043ee09c73..f7900caba932 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/ArrayTest.java @@ -3,6 +3,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.ReadOnlyFirst; import java.io.Serializable; @@ -21,9 +22,9 @@ @JsonTypeName("ArrayTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class ArrayTest implements Serializable { - private @Valid List arrayOfString = null; - private @Valid List> arrayArrayOfInteger = null; - private @Valid List> arrayArrayOfModel = null; + private @Valid List arrayOfString; + private @Valid List> arrayArrayOfInteger; + private @Valid List> arrayArrayOfModel; /** **/ @@ -97,7 +98,7 @@ public ArrayTest removeArrayArrayOfIntegerItem(List arrayArrayOfIntegerIte } /** **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +111,11 @@ public List> getArrayArrayOfModel() { } @JsonProperty("array_array_of_model") - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -123,7 +124,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI return this; } - public ArrayTest removeArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest removeArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (arrayArrayOfModelItem != null && this.arrayArrayOfModel != null) { this.arrayArrayOfModel.remove(arrayArrayOfModelItem); } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java index fb8229016ddf..735ad7c344f3 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/BigCat.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static KindEnum fromString(String s) { + public static KindEnum fromString(String s) { for (KindEnum b : KindEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static KindEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java index 4b2ef0c1c602..408852688ff7 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumArrays.java @@ -3,6 +3,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; @@ -45,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -54,8 +55,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -93,7 +94,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -102,8 +103,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { @@ -115,7 +116,7 @@ public static ArrayEnumEnum fromValue(String value) { } } - private @Valid List arrayEnum = null; + private @Valid List arrayEnum; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java index 778c1dfb9524..089a69da6da5 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumClass.java @@ -28,7 +28,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java index b4692c31c46f..97111084ce86 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/EnumTest.java @@ -45,7 +45,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -54,8 +54,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -93,7 +93,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -102,8 +102,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -141,7 +141,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -150,8 +150,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -189,7 +189,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -198,8 +198,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 8297178d42fc..b038edffbbad 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -3,6 +3,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import org.openapitools.model.ModelFile; import java.io.Serializable; @@ -22,7 +23,7 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files = null; + private @Valid List<@Valid ModelFile> files; /** **/ @@ -45,7 +46,7 @@ public void setFile(ModelFile _file) { /** **/ - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -58,7 +59,7 @@ public List getFiles() { } @JsonProperty("files") - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java index 8d71c957011a..d42555461bcc 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/FormatTest.java @@ -368,7 +368,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java index c45ee600ca2d..aba54bdb3dfa 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MapTest.java @@ -20,7 +20,7 @@ @JsonTypeName("MapTest") @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class MapTest implements Serializable { - private @Valid Map> mapMapOfString = null; + private @Valid Map> mapMapOfString = new HashMap<>(); public enum InnerEnum { UPPER(String.valueOf("UPPER")), LOWER(String.valueOf("lower")); @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { @@ -68,9 +68,9 @@ public static InnerEnum fromValue(String value) { } } - private @Valid Map mapOfEnumString = null; - private @Valid Map directMap = null; - private @Valid Map indirectMap = null; + private @Valid Map mapOfEnumString = new HashMap<>(); + private @Valid Map directMap = new HashMap<>(); + private @Valid Map indirectMap = new HashMap<>(); /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index c5e37deb2390..01d4be09cbfa 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -25,7 +25,7 @@ public class MixedPropertiesAndAdditionalPropertiesClass implements Serializable { private @Valid UUID uuid; private @Valid Date dateTime; - private @Valid Map map = null; + private @Valid Map map = new HashMap<>(); /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java index 5a6d37a5d791..e5575e241d9b 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Order.java @@ -48,7 +48,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -57,8 +57,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java index 131a96d2ceba..a4780a6f6900 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/OuterEnum.java @@ -28,7 +28,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static OuterEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java index 509dc7f912fe..353e952bbbd0 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/Pet.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; +import java.util.Arrays; import java.util.LinkedHashSet; import java.util.List; import java.util.Set; @@ -29,7 +30,7 @@ public class Pet implements Serializable { private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags = null; + private @Valid List<@Valid Tag> tags; public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -55,7 +56,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -64,8 +65,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -176,7 +177,7 @@ public Pet removePhotoUrlsItem(String photoUrlsItem) { } /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -189,7 +190,7 @@ public List getTags() { } @JsonProperty("tags") - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 5a58d2e4a493..147e0422a220 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java index 1c24650e192a..c230c2ce3b0d 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java index eff4ff035ff0..c61b8bd7f096 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/gen/java/org/openapitools/model/XmlItem.java @@ -4,6 +4,7 @@ import io.swagger.annotations.ApiModelProperty; import java.math.BigDecimal; import java.util.ArrayList; +import java.util.Arrays; import java.util.List; import java.io.Serializable; import javax.validation.constraints.*; @@ -25,31 +26,31 @@ public class XmlItem implements Serializable { private @Valid BigDecimal attributeNumber; private @Valid Integer attributeInteger; private @Valid Boolean attributeBoolean; - private @Valid List wrappedArray = null; + private @Valid List wrappedArray; private @Valid String nameString; private @Valid BigDecimal nameNumber; private @Valid Integer nameInteger; private @Valid Boolean nameBoolean; - private @Valid List nameArray = null; - private @Valid List nameWrappedArray = null; + private @Valid List nameArray; + private @Valid List nameWrappedArray; private @Valid String prefixString; private @Valid BigDecimal prefixNumber; private @Valid Integer prefixInteger; private @Valid Boolean prefixBoolean; - private @Valid List prefixArray = null; - private @Valid List prefixWrappedArray = null; + private @Valid List prefixArray; + private @Valid List prefixWrappedArray; private @Valid String namespaceString; private @Valid BigDecimal namespaceNumber; private @Valid Integer namespaceInteger; private @Valid Boolean namespaceBoolean; - private @Valid List namespaceArray = null; - private @Valid List namespaceWrappedArray = null; + private @Valid List namespaceArray; + private @Valid List namespaceWrappedArray; private @Valid String prefixNsString; private @Valid BigDecimal prefixNsNumber; private @Valid Integer prefixNsInteger; private @Valid Boolean prefixNsBoolean; - private @Valid List prefixNsArray = null; - private @Valid List prefixNsWrappedArray = null; + private @Valid List prefixNsArray; + private @Valid List prefixNsWrappedArray; /** **/ diff --git a/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml b/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml index d96b78131c87..c448d48c3deb 100644 --- a/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml +++ b/samples/server/petstore/jaxrs-spec-interface-response/src/main/openapi/openapi.yaml @@ -1079,6 +1079,14 @@ paths: patch: description: To test special tags and operation ID starting with number operationId: 123_test_@#$%_special_tags + parameters: + - description: to test uuid example value + in: header + name: uuid_test + required: true + schema: + format: uuid + type: string requestBody: content: application/json: @@ -1438,15 +1446,29 @@ components: Dog: allOf: - $ref: '#/components/schemas/Animal' - - $ref: '#/components/schemas/Dog_allOf' + - properties: + breed: + type: string + type: object Cat: allOf: - $ref: '#/components/schemas/Animal' - - $ref: '#/components/schemas/Cat_allOf' + - properties: + declawed: + type: boolean + type: object BigCat: allOf: - $ref: '#/components/schemas/Cat' - - $ref: '#/components/schemas/BigCat_allOf' + - properties: + kind: + enum: + - lions + - tigers + - leopards + - jaguars + type: string + type: object Animal: discriminator: propertyName: className @@ -2111,6 +2133,7 @@ components: status: description: Updated status of the pet type: string + type: object uploadFile_request: properties: additionalMetadata: @@ -2120,6 +2143,7 @@ components: description: file to upload format: binary type: string + type: object testEnumParameters_request: properties: enum_form_string_array: @@ -2139,6 +2163,7 @@ components: - -efg - (xyz) type: string + type: object testEndpointParameters_request: properties: integer: @@ -2211,6 +2236,7 @@ components: - double - number - pattern_without_delimiter + type: object testJsonFormData_request: properties: param: @@ -2222,6 +2248,7 @@ components: required: - param - param2 + type: object uploadFileWithRequiredFile_request: properties: additionalMetadata: @@ -2233,25 +2260,6 @@ components: type: string required: - requiredFile - Dog_allOf: - properties: - breed: - type: string - type: object - Cat_allOf: - properties: - declawed: - type: boolean - type: object - BigCat_allOf: - properties: - kind: - enum: - - lions - - tigers - - leopards - - jaguars - type: string type: object securitySchemes: petstore_auth: diff --git a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-interface/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/UserApi.java index ad65de6d7442..79ee197c7440 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/api/UserApi.java @@ -31,7 +31,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - void createUsersWithArrayInput(@Valid @NotNull List body); + void createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body); @POST @@ -39,7 +39,7 @@ public interface UserApi { @ApiOperation(value = "Creates list of users with given input array", notes = "", tags={ "user" }) @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - void createUsersWithListInput(@Valid @NotNull List body); + void createUsersWithListInput(@Valid @NotNull List<@Valid User> body); @DELETE diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java index bb2bfe7261eb..f7900caba932 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/ArrayTest.java @@ -24,7 +24,7 @@ public class ArrayTest implements Serializable { private @Valid List arrayOfString; private @Valid List> arrayArrayOfInteger; - private @Valid List> arrayArrayOfModel; + private @Valid List> arrayArrayOfModel; /** **/ @@ -98,7 +98,7 @@ public ArrayTest removeArrayArrayOfIntegerItem(List arrayArrayOfIntegerIte } /** **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public List> getArrayArrayOfModel() { } @JsonProperty("array_array_of_model") - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -124,7 +124,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI return this; } - public ArrayTest removeArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest removeArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (arrayArrayOfModelItem != null && this.arrayArrayOfModel != null) { this.arrayArrayOfModel.remove(arrayArrayOfModelItem); } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java index fb8229016ddf..735ad7c344f3 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/BigCat.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static KindEnum fromString(String s) { + public static KindEnum fromString(String s) { for (KindEnum b : KindEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static KindEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java index 9ea32a1b4c1a..408852688ff7 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumArrays.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -94,7 +94,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -103,8 +103,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumClass.java index 778c1dfb9524..089a69da6da5 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumClass.java @@ -28,7 +28,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java index b4692c31c46f..97111084ce86 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/EnumTest.java @@ -45,7 +45,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -54,8 +54,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -93,7 +93,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -102,8 +102,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -141,7 +141,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -150,8 +150,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -189,7 +189,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -198,8 +198,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 40bc01d32c7e..b038edffbbad 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -23,7 +23,7 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files; + private @Valid List<@Valid ModelFile> files; /** **/ @@ -46,7 +46,7 @@ public void setFile(ModelFile _file) { /** **/ - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -59,7 +59,7 @@ public List getFiles() { } @JsonProperty("files") - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java index 8d71c957011a..d42555461bcc 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/FormatTest.java @@ -368,7 +368,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java index f45569a171d0..aba54bdb3dfa 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/MapTest.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java index 5a6d37a5d791..e5575e241d9b 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Order.java @@ -48,7 +48,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -57,8 +57,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterEnum.java index 131a96d2ceba..a4780a6f6900 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/OuterEnum.java @@ -28,7 +28,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static OuterEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java index 474f7cd13dfb..353e952bbbd0 100644 --- a/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-interface/src/gen/java/org/openapitools/model/Pet.java @@ -30,7 +30,7 @@ public class Pet implements Serializable { private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags; + private @Valid List<@Valid Tag> tags; public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -56,7 +56,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -65,8 +65,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -177,7 +177,7 @@ public Pet removePhotoUrlsItem(String photoUrlsItem) { } /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -190,7 +190,7 @@ public List getTags() { } @JsonProperty("tags") - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } diff --git a/samples/server/petstore/jaxrs-spec-jakarta/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-jakarta/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-jakarta/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/api/UserApi.java index 91d89f433d8e..25b6530270d4 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/api/UserApi.java @@ -34,7 +34,7 @@ public Response createUser(@Valid @NotNull User body) { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@Valid @NotNull List body) { + public Response createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } @@ -44,7 +44,7 @@ public Response createUsersWithArrayInput(@Valid @NotNull List body) { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@Valid @NotNull List body) { + public Response createUsersWithListInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/ArrayTest.java index 215c289e57eb..50eed4ef013a 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/ArrayTest.java @@ -24,7 +24,7 @@ public class ArrayTest implements Serializable { private @Valid List arrayOfString; private @Valid List> arrayArrayOfInteger; - private @Valid List> arrayArrayOfModel; + private @Valid List> arrayArrayOfModel; protected ArrayTest(ArrayTestBuilder b) { this.arrayOfString = b.arrayOfString; @@ -107,7 +107,7 @@ public ArrayTest removeArrayArrayOfIntegerItem(List arrayArrayOfIntegerIte } /** **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -120,11 +120,11 @@ public List> getArrayArrayOfModel() { } @JsonProperty("array_array_of_model") - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -133,7 +133,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI return this; } - public ArrayTest removeArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest removeArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (arrayArrayOfModelItem != null && this.arrayArrayOfModel != null) { this.arrayArrayOfModel.remove(arrayArrayOfModelItem); } @@ -204,7 +204,7 @@ public ArrayTest build() { public static abstract class ArrayTestBuilder> { private List arrayOfString; private List> arrayArrayOfInteger; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; protected abstract B self(); public abstract C build(); @@ -217,7 +217,7 @@ public B arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return self(); } - public B arrayArrayOfModel(List> arrayArrayOfModel) { + public B arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/BigCat.java index c0fcf7337a07..5a3af224c8f8 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/BigCat.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static KindEnum fromString(String s) { + public static KindEnum fromString(String s) { for (KindEnum b : KindEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static KindEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumArrays.java index d6236bafdc94..19065b41a0a1 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumArrays.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -94,7 +94,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -103,8 +103,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumClass.java index 119fa9414f9c..67abab2ebdfc 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumClass.java @@ -28,7 +28,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumTest.java index 67ceaaa44502..51cad7143d92 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/EnumTest.java @@ -45,7 +45,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -54,8 +54,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -93,7 +93,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -102,8 +102,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -141,7 +141,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -150,8 +150,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -189,7 +189,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -198,8 +198,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 5eb4437f8ddf..5056d5b341de 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -23,7 +23,7 @@ @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files; + private @Valid List<@Valid ModelFile> files; protected FileSchemaTestClass(FileSchemaTestClassBuilder b) { this._file = b._file; @@ -54,7 +54,7 @@ public void setFile(ModelFile _file) { /** **/ - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -67,7 +67,7 @@ public List getFiles() { } @JsonProperty("files") - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -148,7 +148,7 @@ public FileSchemaTestClass build() { public static abstract class FileSchemaTestClassBuilder> { private ModelFile _file; - private List files; + private List<@Valid ModelFile> files; protected abstract B self(); public abstract C build(); @@ -157,7 +157,7 @@ public B _file(ModelFile _file) { this._file = _file; return self(); } - public B files(List files) { + public B files(List<@Valid ModelFile> files) { this.files = files; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FormatTest.java index 8baa28ee4312..2ca118175cac 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/FormatTest.java @@ -388,7 +388,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/MapTest.java index 96271afa1ce9..2d8f92178497 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/MapTest.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Order.java index 9ab2881c6fae..82de8ae71719 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Order.java @@ -48,7 +48,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -57,8 +57,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/OuterEnum.java index 0ae8000e4550..8549f2f1dd90 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/OuterEnum.java @@ -28,7 +28,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static OuterEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Pet.java index b5d45fe47ddd..fd9f1aa9f1eb 100644 --- a/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-jakarta/src/gen/java/org/openapitools/model/Pet.java @@ -30,7 +30,7 @@ public class Pet implements Serializable { private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags; + private @Valid List<@Valid Tag> tags; public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -56,7 +56,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -65,8 +65,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -189,7 +189,7 @@ public Pet removePhotoUrlsItem(String photoUrlsItem) { } /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -202,7 +202,7 @@ public List getTags() { } @JsonProperty("tags") - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -314,7 +314,7 @@ public static abstract class PetBuilder photoUrls = new LinkedHashSet<>(); - private List tags; + private List<@Valid Tag> tags; private StatusEnum status; protected abstract B self(); @@ -336,7 +336,7 @@ public B photoUrls(Set photoUrls) { this.photoUrls = photoUrls; return self(); } - public B tags(List tags) { + public B tags(List<@Valid Tag> tags) { this.tags = tags; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java index cf63562ad52d..b26523f57740 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/api/UserApi.java @@ -82,7 +82,7 @@ public Response createUser(@Valid @NotNull User body) { }) }) - public Response createUsersWithArrayInput(@Valid @NotNull List body) { + public Response createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } @@ -96,7 +96,7 @@ public Response createUsersWithArrayInput(@Valid @NotNull List body) { }) }) - public Response createUsersWithListInput(@Valid @NotNull List body) { + public Response createUsersWithListInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java index d8b7ce08af1b..f8e695b0e815 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/ArrayTest.java @@ -22,7 +22,7 @@ public class ArrayTest implements Serializable { private @Valid List arrayOfString; private @Valid List> arrayArrayOfInteger; - private @Valid List> arrayArrayOfModel; + private @Valid List> arrayArrayOfModel; protected ArrayTest(ArrayTestBuilder b) { this.arrayOfString = b.arrayOfString; @@ -105,7 +105,7 @@ public ArrayTest removeArrayArrayOfIntegerItem(List arrayArrayOfIntegerIte } /** **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -118,11 +118,11 @@ public List> getArrayArrayOfModel() { } @JsonProperty("array_array_of_model") - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -131,7 +131,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI return this; } - public ArrayTest removeArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest removeArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (arrayArrayOfModelItem != null && this.arrayArrayOfModel != null) { this.arrayArrayOfModel.remove(arrayArrayOfModelItem); } @@ -202,7 +202,7 @@ public ArrayTest build() { public static abstract class ArrayTestBuilder> { private List arrayOfString; private List> arrayArrayOfInteger; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; protected abstract B self(); public abstract C build(); @@ -215,7 +215,7 @@ public B arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return self(); } - public B arrayArrayOfModel(List> arrayArrayOfModel) { + public B arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java index 6579d5bf287a..5054009bb8b0 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/BigCat.java @@ -42,7 +42,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static KindEnum fromString(String s) { + public static KindEnum fromString(String s) { for (KindEnum b : KindEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -51,8 +51,8 @@ public static KindEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java index bf1e1cd3b919..69c235797f24 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumArrays.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -92,7 +92,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -101,8 +101,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumClass.java index 778c1dfb9524..089a69da6da5 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumClass.java @@ -28,7 +28,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java index c929ea4d07e3..2c396d0e34a6 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/EnumTest.java @@ -43,7 +43,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -52,8 +52,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -91,7 +91,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -100,8 +100,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -139,7 +139,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -148,8 +148,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -187,7 +187,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -196,8 +196,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index ee28ea1b3654..851b6ae0b00b 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -21,7 +21,7 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files; + private @Valid List<@Valid ModelFile> files; protected FileSchemaTestClass(FileSchemaTestClassBuilder b) { this._file = b._file; @@ -52,7 +52,7 @@ public void setFile(ModelFile _file) { /** **/ - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -65,7 +65,7 @@ public List getFiles() { } @JsonProperty("files") - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -146,7 +146,7 @@ public FileSchemaTestClass build() { public static abstract class FileSchemaTestClassBuilder> { private ModelFile _file; - private List files; + private List<@Valid ModelFile> files; protected abstract B self(); public abstract C build(); @@ -155,7 +155,7 @@ public B _file(ModelFile _file) { this._file = _file; return self(); } - public B files(List files) { + public B files(List<@Valid ModelFile> files) { this.files = files; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java index 4bf137765e8e..83eb1e6a7503 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/FormatTest.java @@ -386,7 +386,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java index 6dcb32d2662a..3a330bd44fbf 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/MapTest.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java index 325a1392d1b5..fe0a79b8fb99 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Order.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterEnum.java index 131a96d2ceba..a4780a6f6900 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/OuterEnum.java @@ -28,7 +28,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static OuterEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java index 73441c26ee95..bad9f6f2258f 100644 --- a/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec-microprofile-openapi-annotations/src/gen/java/org/openapitools/model/Pet.java @@ -28,7 +28,7 @@ public class Pet implements Serializable { private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags; + private @Valid List<@Valid Tag> tags; public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -54,7 +54,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -63,8 +63,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -187,7 +187,7 @@ public Pet removePhotoUrlsItem(String photoUrlsItem) { } /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -200,7 +200,7 @@ public List getTags() { } @JsonProperty("tags") - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -312,7 +312,7 @@ public static abstract class PetBuilder photoUrls = new LinkedHashSet<>(); - private List tags; + private List<@Valid Tag> tags; private StatusEnum status; protected abstract B self(); @@ -334,7 +334,7 @@ public B photoUrls(Set photoUrls) { this.photoUrls = photoUrls; return self(); } - public B tags(List tags) { + public B tags(List<@Valid Tag> tags) { this.tags = tags; return self(); } diff --git a/samples/server/petstore/jaxrs-spec-required-and-readonly-property/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec-required-and-readonly-property/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec-required-and-readonly-property/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec-required-and-readonly-property/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs-spec/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/UserApi.java index 89238abb07f4..0bbd6d9f6cfd 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/api/UserApi.java @@ -34,7 +34,7 @@ public Response createUser(@Valid @NotNull User body) { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@Valid @NotNull List body) { + public Response createUsersWithArrayInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } @@ -44,7 +44,7 @@ public Response createUsersWithArrayInput(@Valid @NotNull List body) { @ApiResponses(value = { @ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@Valid @NotNull List body) { + public Response createUsersWithListInput(@Valid @NotNull List<@Valid User> body) { return Response.ok().entity("magic!").build(); } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java index 63e560ec3436..552d26e4628a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/ArrayTest.java @@ -24,7 +24,7 @@ public class ArrayTest implements Serializable { private @Valid List arrayOfString; private @Valid List> arrayArrayOfInteger; - private @Valid List> arrayArrayOfModel; + private @Valid List> arrayArrayOfModel; protected ArrayTest(ArrayTestBuilder b) { this.arrayOfString = b.arrayOfString; @@ -107,7 +107,7 @@ public ArrayTest removeArrayArrayOfIntegerItem(List arrayArrayOfIntegerIte } /** **/ - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -120,11 +120,11 @@ public List> getArrayArrayOfModel() { } @JsonProperty("array_array_of_model") - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -133,7 +133,7 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI return this; } - public ArrayTest removeArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest removeArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (arrayArrayOfModelItem != null && this.arrayArrayOfModel != null) { this.arrayArrayOfModel.remove(arrayArrayOfModelItem); } @@ -204,7 +204,7 @@ public ArrayTest build() { public static abstract class ArrayTestBuilder> { private List arrayOfString; private List> arrayArrayOfInteger; - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; protected abstract B self(); public abstract C build(); @@ -217,7 +217,7 @@ public B arrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; return self(); } - public B arrayArrayOfModel(List> arrayArrayOfModel) { + public B arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return self(); } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java index 48dcefd8bdef..594c35d9542e 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/BigCat.java @@ -44,7 +44,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static KindEnum fromString(String s) { + public static KindEnum fromString(String s) { for (KindEnum b : KindEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -53,8 +53,8 @@ public static KindEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static KindEnum fromValue(String value) { for (KindEnum b : KindEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java index 8fcde1b1193b..852e14daa22a 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumArrays.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static JustSymbolEnum fromString(String s) { + public static JustSymbolEnum fromString(String s) { for (JustSymbolEnum b : JustSymbolEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static JustSymbolEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static JustSymbolEnum fromValue(String value) { for (JustSymbolEnum b : JustSymbolEnum.values()) { @@ -94,7 +94,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static ArrayEnumEnum fromString(String s) { + public static ArrayEnumEnum fromString(String s) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -103,8 +103,8 @@ public static ArrayEnumEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static ArrayEnumEnum fromValue(String value) { for (ArrayEnumEnum b : ArrayEnumEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumClass.java index 778c1dfb9524..089a69da6da5 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumClass.java @@ -28,7 +28,7 @@ public enum EnumClass { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumClass fromString(String s) { + public static EnumClass fromString(String s) { for (EnumClass b : EnumClass.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static EnumClass fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java index a5a94a0d35f6..4b1a6734e883 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/EnumTest.java @@ -45,7 +45,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringEnum fromString(String s) { + public static EnumStringEnum fromString(String s) { for (EnumStringEnum b : EnumStringEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -54,8 +54,8 @@ public static EnumStringEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringEnum fromValue(String value) { for (EnumStringEnum b : EnumStringEnum.values()) { @@ -93,7 +93,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumStringRequiredEnum fromString(String s) { + public static EnumStringRequiredEnum fromString(String s) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -102,8 +102,8 @@ public static EnumStringRequiredEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumStringRequiredEnum fromValue(String value) { for (EnumStringRequiredEnum b : EnumStringRequiredEnum.values()) { @@ -141,7 +141,7 @@ public String toString() { * Convert a String into Integer, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumIntegerEnum fromString(String s) { + public static EnumIntegerEnum fromString(String s) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -150,8 +150,8 @@ public static EnumIntegerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumIntegerEnum fromValue(Integer value) { for (EnumIntegerEnum b : EnumIntegerEnum.values()) { @@ -189,7 +189,7 @@ public String toString() { * Convert a String into Double, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static EnumNumberEnum fromString(String s) { + public static EnumNumberEnum fromString(String s) { for (EnumNumberEnum b : EnumNumberEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -198,8 +198,8 @@ public static EnumNumberEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static EnumNumberEnum fromValue(Double value) { for (EnumNumberEnum b : EnumNumberEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 167bd8acdbf3..fec6ea060efc 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -23,7 +23,7 @@ @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJAXRSSpecServerCodegen") public class FileSchemaTestClass implements Serializable { private @Valid ModelFile _file; - private @Valid List files; + private @Valid List<@Valid ModelFile> files; protected FileSchemaTestClass(FileSchemaTestClassBuilder b) { this._file = b._file; @@ -54,7 +54,7 @@ public void setFile(ModelFile _file) { /** **/ - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -67,7 +67,7 @@ public List getFiles() { } @JsonProperty("files") - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -148,7 +148,7 @@ public FileSchemaTestClass build() { public static abstract class FileSchemaTestClassBuilder> { private ModelFile _file; - private List files; + private List<@Valid ModelFile> files; protected abstract B self(); public abstract C build(); @@ -157,7 +157,7 @@ public B _file(ModelFile _file) { this._file = _file; return self(); } - public B files(List files) { + public B files(List<@Valid ModelFile> files) { this.files = files; return self(); } diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java index f64ed7b22ce5..6035953441e6 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/FormatTest.java @@ -388,7 +388,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java index a2aa74202115..30dab601b0ed 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/MapTest.java @@ -46,7 +46,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static InnerEnum fromString(String s) { + public static InnerEnum fromString(String s) { for (InnerEnum b : InnerEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -55,8 +55,8 @@ public static InnerEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static InnerEnum fromValue(String value) { for (InnerEnum b : InnerEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java index 4df554866043..d6a8c717b045 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Order.java @@ -48,7 +48,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -57,8 +57,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterEnum.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterEnum.java index 131a96d2ceba..a4780a6f6900 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterEnum.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/OuterEnum.java @@ -28,7 +28,7 @@ public enum OuterEnum { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static OuterEnum fromString(String s) { + public static OuterEnum fromString(String s) { for (OuterEnum b : OuterEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -37,8 +37,8 @@ public static OuterEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @Override @JsonValue public String toString() { diff --git a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java index 85121d7aab37..6318ca6cc029 100644 --- a/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs-spec/src/gen/java/org/openapitools/model/Pet.java @@ -30,7 +30,7 @@ public class Pet implements Serializable { private @Valid Category category; private @Valid String name; private @Valid Set photoUrls = new LinkedHashSet<>(); - private @Valid List tags; + private @Valid List<@Valid Tag> tags; public enum StatusEnum { AVAILABLE(String.valueOf("available")), PENDING(String.valueOf("pending")), SOLD(String.valueOf("sold")); @@ -56,7 +56,7 @@ public String toString() { * Convert a String into String, as specified in the * See JAX RS 2.0 Specification, section 3.2, p. 12 */ - public static StatusEnum fromString(String s) { + public static StatusEnum fromString(String s) { for (StatusEnum b : StatusEnum.values()) { // using Objects.toString() to be safe if value type non-object type // because types like 'int' etc. will be auto-boxed @@ -65,8 +65,8 @@ public static StatusEnum fromString(String s) { } } throw new IllegalArgumentException("Unexpected string value '" + s + "'"); - } - + } + @JsonCreator public static StatusEnum fromValue(String value) { for (StatusEnum b : StatusEnum.values()) { @@ -189,7 +189,7 @@ public Pet removePhotoUrlsItem(String photoUrlsItem) { } /** **/ - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -202,7 +202,7 @@ public List getTags() { } @JsonProperty("tags") - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -314,7 +314,7 @@ public static abstract class PetBuilder photoUrls = new LinkedHashSet<>(); - private List tags; + private List<@Valid Tag> tags; private StatusEnum status; protected abstract B self(); @@ -336,7 +336,7 @@ public B photoUrls(Set photoUrls) { this.photoUrls = photoUrls; return self(); } - public B tags(List tags) { + public B tags(List<@Valid Tag> tags) { this.tags = tags; return self(); } diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2-useTags/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml b/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml index 6741628a3254..e159ebf7ec11 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2-useTags/pom.xml @@ -107,6 +107,14 @@ swagger-jersey2-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -201,7 +209,7 @@ 2.35 2.15.2 4.13.2 - 1.2.12 + 1.4.14 4.0.4 UTF-8 diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/AnotherFakeApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/AnotherFakeApiService.java index 3991f29fa8a7..c678cc557a24 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/AnotherFakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/AnotherFakeApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class AnotherFakeApiService { public abstract Response call123testSpecialTags( @NotNull UUID uuidTest,Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeApiService.java index 119c6a70f68f..6ef9633ac4fd 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeApiService.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeApiService { public abstract Response createXmlItem(XmlItem xmlItem,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeClassnameTags123ApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeClassnameTags123ApiService.java index e0d896f73c8a..1969974563d7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeClassnameTags123ApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/FakeClassnameTags123ApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeClassnameTags123ApiService { public abstract Response testClassname(Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/PetApiService.java index d4b7f595e625..8796ef203573 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/StoreApiService.java index 679dae579bf0..ba613f2eb7a2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/StoreApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApi.java index bbee29b94add..33d87832a625 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApi.java @@ -75,7 +75,7 @@ public Response createUser(@ApiParam(value = "Created user object", required = t @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body, securityContext); } @@ -87,7 +87,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body, securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApiService.java index f555584d0d69..2de8377d5f78 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/api/UserApiService.java @@ -15,11 +15,12 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 82318a601030..5842e032e837 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesAnyType.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesAnyType.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 44dac88de844..cdb30d5cff12 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesArray.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesArray.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 4762975e9f8e..4c51cfbdf926 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesBoolean.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesBoolean.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index b048fa83ac54..183ee49cf312 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -382,17 +382,17 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapString, additionalPropertiesClass.mapString) && - Objects.equals(mapNumber, additionalPropertiesClass.mapNumber) && - Objects.equals(mapInteger, additionalPropertiesClass.mapInteger) && - Objects.equals(mapBoolean, additionalPropertiesClass.mapBoolean) && - Objects.equals(mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && - Objects.equals(mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && - Objects.equals(mapMapString, additionalPropertiesClass.mapMapString) && - Objects.equals(mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && - Objects.equals(anytype1, additionalPropertiesClass.anytype1) && - Objects.equals(anytype2, additionalPropertiesClass.anytype2) && - Objects.equals(anytype3, additionalPropertiesClass.anytype3); + return Objects.equals(this.mapString, additionalPropertiesClass.mapString) && + Objects.equals(this.mapNumber, additionalPropertiesClass.mapNumber) && + Objects.equals(this.mapInteger, additionalPropertiesClass.mapInteger) && + Objects.equals(this.mapBoolean, additionalPropertiesClass.mapBoolean) && + Objects.equals(this.mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && + Objects.equals(this.mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && + Objects.equals(this.mapMapString, additionalPropertiesClass.mapMapString) && + Objects.equals(this.mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.anytype2, additionalPropertiesClass.anytype2) && + Objects.equals(this.anytype3, additionalPropertiesClass.anytype3); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index e05c2898a345..3bd85ca3323a 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesInteger.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesInteger.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d87c35544d0d..63722f79dca2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesNumber.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesNumber.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index fe8dd7d00566..96f5517ea6a3 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesObject.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesObject.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 067b56ba2aaa..8f11a9793722 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesString.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesString.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java index 88fdd4ea06f6..e2f2504d8689 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Animal.java @@ -98,8 +98,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 3336f582992d..b6b68808ce39 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 73c9fb09799e..6d33189ca53e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java index 99c4a0f5e81b..109fb4ab1986 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ArrayTest.java @@ -46,7 +46,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -104,12 +104,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -124,11 +124,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @@ -142,9 +142,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java index 55095ac953c6..0171e3296200 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/BigCat.java @@ -101,7 +101,7 @@ public boolean equals(Object o) { return false; } BigCat bigCat = (BigCat) o; - return super.equals(o) && Objects.equals(kind, bigCat.kind); + return super.equals(o) && Objects.equals(this.kind, bigCat.kind); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java index 31c3ee371963..e952af0fbc98 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Capitalization.java @@ -189,12 +189,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java index fb8b0954a999..0fa048000bd6 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Cat.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return super.equals(o) && Objects.equals(declawed, cat.declawed); + return super.equals(o) && Objects.equals(this.declawed, cat.declawed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java index 5c5ee2c9b5a4..4a5657942d6b 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Category.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java index b85ca626ded4..080d861f6d3a 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ClassModel.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java index 5d18c048f428..9153a3adf216 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Client.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java index 139884e350f8..93e3653ba4da 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Dog.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return super.equals(o) && Objects.equals(breed, dog.breed); + return super.equals(o) && Objects.equals(this.breed, dog.breed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java index c07029046ac6..4631a7c31f3c 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumArrays.java @@ -163,8 +163,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java index e3aadb63bc2b..a9cb994ddaa8 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/EnumTest.java @@ -295,11 +295,11 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 365006936e34..89e3dc1249f7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -41,7 +41,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; @JsonProperty(JSON_PROPERTY_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -63,7 +63,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -83,11 +83,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -101,8 +101,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java index 114a70310b10..9035779e0239 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/FormatTest.java @@ -404,20 +404,20 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(bigDecimal, formatTest.bigDecimal); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.bigDecimal, formatTest.bigDecimal); } @Override @@ -442,7 +442,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 8d8bd67aeb13..69ac562dc6a9 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java index 428a329c83cf..6645c517504e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MapTest.java @@ -205,10 +205,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index dfa842013c5a..cc739934548f 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -127,9 +127,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java index d7ddf004f4d1..ae8f5397738a 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Model200Response.java @@ -91,8 +91,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java index a05c06e91761..28eb65f67817 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelFile.java index 35d3242a106e..135bad167483 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelFile.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelList.java index 4a6bf3fd375a..27e325aba294 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelList.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java index 08dca8ec3604..8f744e457889 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ModelReturn.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java index ac6b9667d605..c5c89ffd43d8 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Name.java @@ -140,10 +140,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java index 35fafbc3a139..aceea701ca1e 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/NumberOnly.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java index 96c4ba5a384e..5a60e9121f40 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Order.java @@ -224,12 +224,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java index e6fef1023ae1..455f52c5ead2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/OuterComposite.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java index 0de0618f5e99..194a6fc01354 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Pet.java @@ -62,7 +62,7 @@ public class Pet { public static final String JSON_PROPERTY_TAGS = "tags"; @JsonProperty(JSON_PROPERTY_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -190,7 +190,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -210,11 +210,11 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -248,12 +248,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 0650df4c320a..0827ed6b9fe3 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java index f80332c68555..0d539a83fd98 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } SpecialModelName $specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, $specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, $specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java index b8197646f462..ba07edce8ce1 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/Tag.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 9a82ca05053c..c11fbaf766be 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -176,11 +176,11 @@ public boolean equals(Object o) { return false; } TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o; - return Objects.equals(stringItem, typeHolderDefault.stringItem) && - Objects.equals(numberItem, typeHolderDefault.numberItem) && - Objects.equals(integerItem, typeHolderDefault.integerItem) && - Objects.equals(boolItem, typeHolderDefault.boolItem) && - Objects.equals(arrayItem, typeHolderDefault.arrayItem); + return Objects.equals(this.stringItem, typeHolderDefault.stringItem) && + Objects.equals(this.numberItem, typeHolderDefault.numberItem) && + Objects.equals(this.integerItem, typeHolderDefault.integerItem) && + Objects.equals(this.boolItem, typeHolderDefault.boolItem) && + Objects.equals(this.arrayItem, typeHolderDefault.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java index dc7765fb9661..250badaeb99b 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -201,12 +201,12 @@ public boolean equals(Object o) { return false; } TypeHolderExample typeHolderExample = (TypeHolderExample) o; - return Objects.equals(stringItem, typeHolderExample.stringItem) && - Objects.equals(numberItem, typeHolderExample.numberItem) && - Objects.equals(floatItem, typeHolderExample.floatItem) && - Objects.equals(integerItem, typeHolderExample.integerItem) && - Objects.equals(boolItem, typeHolderExample.boolItem) && - Objects.equals(arrayItem, typeHolderExample.arrayItem); + return Objects.equals(this.stringItem, typeHolderExample.stringItem) && + Objects.equals(this.numberItem, typeHolderExample.numberItem) && + Objects.equals(this.floatItem, typeHolderExample.floatItem) && + Objects.equals(this.integerItem, typeHolderExample.integerItem) && + Objects.equals(this.boolItem, typeHolderExample.boolItem) && + Objects.equals(this.arrayItem, typeHolderExample.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java index 06ab22d0fdc0..26261801d0b2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/User.java @@ -239,14 +239,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java index 36419211b3a7..26811e06639d 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/gen/java/org/openapitools/model/XmlItem.java @@ -840,35 +840,35 @@ public boolean equals(Object o) { return false; } XmlItem xmlItem = (XmlItem) o; - return Objects.equals(attributeString, xmlItem.attributeString) && - Objects.equals(attributeNumber, xmlItem.attributeNumber) && - Objects.equals(attributeInteger, xmlItem.attributeInteger) && - Objects.equals(attributeBoolean, xmlItem.attributeBoolean) && - Objects.equals(wrappedArray, xmlItem.wrappedArray) && - Objects.equals(nameString, xmlItem.nameString) && - Objects.equals(nameNumber, xmlItem.nameNumber) && - Objects.equals(nameInteger, xmlItem.nameInteger) && - Objects.equals(nameBoolean, xmlItem.nameBoolean) && - Objects.equals(nameArray, xmlItem.nameArray) && - Objects.equals(nameWrappedArray, xmlItem.nameWrappedArray) && - Objects.equals(prefixString, xmlItem.prefixString) && - Objects.equals(prefixNumber, xmlItem.prefixNumber) && - Objects.equals(prefixInteger, xmlItem.prefixInteger) && - Objects.equals(prefixBoolean, xmlItem.prefixBoolean) && - Objects.equals(prefixArray, xmlItem.prefixArray) && - Objects.equals(prefixWrappedArray, xmlItem.prefixWrappedArray) && - Objects.equals(namespaceString, xmlItem.namespaceString) && - Objects.equals(namespaceNumber, xmlItem.namespaceNumber) && - Objects.equals(namespaceInteger, xmlItem.namespaceInteger) && - Objects.equals(namespaceBoolean, xmlItem.namespaceBoolean) && - Objects.equals(namespaceArray, xmlItem.namespaceArray) && - Objects.equals(namespaceWrappedArray, xmlItem.namespaceWrappedArray) && - Objects.equals(prefixNsString, xmlItem.prefixNsString) && - Objects.equals(prefixNsNumber, xmlItem.prefixNsNumber) && - Objects.equals(prefixNsInteger, xmlItem.prefixNsInteger) && - Objects.equals(prefixNsBoolean, xmlItem.prefixNsBoolean) && - Objects.equals(prefixNsArray, xmlItem.prefixNsArray) && - Objects.equals(prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); + return Objects.equals(this.attributeString, xmlItem.attributeString) && + Objects.equals(this.attributeNumber, xmlItem.attributeNumber) && + Objects.equals(this.attributeInteger, xmlItem.attributeInteger) && + Objects.equals(this.attributeBoolean, xmlItem.attributeBoolean) && + Objects.equals(this.wrappedArray, xmlItem.wrappedArray) && + Objects.equals(this.nameString, xmlItem.nameString) && + Objects.equals(this.nameNumber, xmlItem.nameNumber) && + Objects.equals(this.nameInteger, xmlItem.nameInteger) && + Objects.equals(this.nameBoolean, xmlItem.nameBoolean) && + Objects.equals(this.nameArray, xmlItem.nameArray) && + Objects.equals(this.nameWrappedArray, xmlItem.nameWrappedArray) && + Objects.equals(this.prefixString, xmlItem.prefixString) && + Objects.equals(this.prefixNumber, xmlItem.prefixNumber) && + Objects.equals(this.prefixInteger, xmlItem.prefixInteger) && + Objects.equals(this.prefixBoolean, xmlItem.prefixBoolean) && + Objects.equals(this.prefixArray, xmlItem.prefixArray) && + Objects.equals(this.prefixWrappedArray, xmlItem.prefixWrappedArray) && + Objects.equals(this.namespaceString, xmlItem.namespaceString) && + Objects.equals(this.namespaceNumber, xmlItem.namespaceNumber) && + Objects.equals(this.namespaceInteger, xmlItem.namespaceInteger) && + Objects.equals(this.namespaceBoolean, xmlItem.namespaceBoolean) && + Objects.equals(this.namespaceArray, xmlItem.namespaceArray) && + Objects.equals(this.namespaceWrappedArray, xmlItem.namespaceWrappedArray) && + Objects.equals(this.prefixNsString, xmlItem.prefixNsString) && + Objects.equals(this.prefixNsNumber, xmlItem.prefixNsNumber) && + Objects.equals(this.prefixNsInteger, xmlItem.prefixNsInteger) && + Objects.equals(this.prefixNsBoolean, xmlItem.prefixNsBoolean) && + Objects.equals(this.prefixNsArray, xmlItem.prefixNsArray) && + Objects.equals(this.prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index 361e57e8167b..edbc664b7303 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class AnotherFakeApiServiceImpl extends AnotherFakeApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index aa26da980b8a..195b51a46ec7 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -21,6 +21,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeApiServiceImpl extends FakeApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java index 27c7eb541a75..6e3f0c93e9b2 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/FakeClassnameTags123ApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeClassnameTags123ApiServiceImpl extends FakeClassnameTags123ApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index e2f96dc0f947..bf998e921d7f 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index b4ec457464ff..c06c4da6d465 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index c6018c40f96a..33f057ca766f 100644 --- a/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2-useTags/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class UserApiServiceImpl extends UserApiService { @Override @@ -22,12 +23,12 @@ public Response createUser(User body, SecurityContext securityContext) throws No return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithArrayInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithListInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey2/pom.xml b/samples/server/petstore/jaxrs/jersey2/pom.xml index eeaeeac53383..b6b5755dc5d8 100644 --- a/samples/server/petstore/jaxrs/jersey2/pom.xml +++ b/samples/server/petstore/jaxrs/jersey2/pom.xml @@ -107,6 +107,14 @@ swagger-jersey2-jaxrs compile ${swagger-core-version} + + + + javax.validation + validation-api + + ch.qos.logback @@ -201,7 +209,7 @@ 2.35 2.15.2 4.13.2 - 1.2.12 + 1.4.14 4.0.4 UTF-8 diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/AnotherFakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/AnotherFakeApiService.java index 3991f29fa8a7..c678cc557a24 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/AnotherFakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/AnotherFakeApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class AnotherFakeApiService { public abstract Response call123testSpecialTags( @NotNull UUID uuidTest,Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeApiService.java index c46e98aebc47..d42b6887aea8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeApiService.java @@ -23,6 +23,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeApiService { public abstract Response createXmlItem(XmlItem xmlItem,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java index 9b9724797dfc..a155a1ae0351 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeClassnameTestApiService { public abstract Response testClassname(Client body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/PetApiService.java index 5a082c27fd48..a82fd652bc3f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,6 +17,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class PetApiService { public abstract Response addPet(Pet body,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/StoreApiService.java index 679dae579bf0..ba613f2eb7a2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/StoreApiService.java @@ -15,6 +15,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApi.java index 1e162536427e..7adca8b9709c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApi.java @@ -75,7 +75,7 @@ public Response createUser(@ApiParam(value = "Created user object", required = t @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(body, securityContext); } @@ -87,7 +87,7 @@ public Response createUsersWithArrayInput(@ApiParam(value = "List of user object @io.swagger.annotations.ApiResponses(value = { @io.swagger.annotations.ApiResponse(code = 200, message = "successful operation", response = Void.class) }) - public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List body,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@ApiParam(value = "List of user object", required = true) @NotNull @Valid List<@Valid User> body,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(body, securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApiService.java index f555584d0d69..2de8377d5f78 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/api/UserApiService.java @@ -15,11 +15,12 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class UserApiService { public abstract Response createUser(User body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List body,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List<@Valid User> body,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java index 82318a601030..5842e032e837 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesAnyType additionalPropertiesAnyType = (AdditionalPropertiesAnyType) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesAnyType.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesAnyType.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java index 44dac88de844..cdb30d5cff12 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesArray additionalPropertiesArray = (AdditionalPropertiesArray) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesArray.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesArray.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 4762975e9f8e..4c51cfbdf926 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesBoolean additionalPropertiesBoolean = (AdditionalPropertiesBoolean) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesBoolean.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesBoolean.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index b048fa83ac54..183ee49cf312 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -382,17 +382,17 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapString, additionalPropertiesClass.mapString) && - Objects.equals(mapNumber, additionalPropertiesClass.mapNumber) && - Objects.equals(mapInteger, additionalPropertiesClass.mapInteger) && - Objects.equals(mapBoolean, additionalPropertiesClass.mapBoolean) && - Objects.equals(mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && - Objects.equals(mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && - Objects.equals(mapMapString, additionalPropertiesClass.mapMapString) && - Objects.equals(mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && - Objects.equals(anytype1, additionalPropertiesClass.anytype1) && - Objects.equals(anytype2, additionalPropertiesClass.anytype2) && - Objects.equals(anytype3, additionalPropertiesClass.anytype3); + return Objects.equals(this.mapString, additionalPropertiesClass.mapString) && + Objects.equals(this.mapNumber, additionalPropertiesClass.mapNumber) && + Objects.equals(this.mapInteger, additionalPropertiesClass.mapInteger) && + Objects.equals(this.mapBoolean, additionalPropertiesClass.mapBoolean) && + Objects.equals(this.mapArrayInteger, additionalPropertiesClass.mapArrayInteger) && + Objects.equals(this.mapArrayAnytype, additionalPropertiesClass.mapArrayAnytype) && + Objects.equals(this.mapMapString, additionalPropertiesClass.mapMapString) && + Objects.equals(this.mapMapAnytype, additionalPropertiesClass.mapMapAnytype) && + Objects.equals(this.anytype1, additionalPropertiesClass.anytype1) && + Objects.equals(this.anytype2, additionalPropertiesClass.anytype2) && + Objects.equals(this.anytype3, additionalPropertiesClass.anytype3); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java index e05c2898a345..3bd85ca3323a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesInteger additionalPropertiesInteger = (AdditionalPropertiesInteger) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesInteger.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesInteger.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java index d87c35544d0d..63722f79dca2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -67,7 +67,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesNumber additionalPropertiesNumber = (AdditionalPropertiesNumber) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesNumber.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesNumber.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java index fe8dd7d00566..96f5517ea6a3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesObject additionalPropertiesObject = (AdditionalPropertiesObject) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesObject.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesObject.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java index 067b56ba2aaa..8f11a9793722 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/AdditionalPropertiesString.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesString additionalPropertiesString = (AdditionalPropertiesString) o; - return super.equals(o) && Objects.equals(name, additionalPropertiesString.name); + return super.equals(o) && Objects.equals(this.name, additionalPropertiesString.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java index 88fdd4ea06f6..e2f2504d8689 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Animal.java @@ -98,8 +98,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 3336f582992d..b6b68808ce39 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 73c9fb09799e..6d33189ca53e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -76,7 +76,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java index 99c4a0f5e81b..109fb4ab1986 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ArrayTest.java @@ -46,7 +46,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -104,12 +104,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -124,11 +124,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(value = "array_array_of_model") @ApiModelProperty(value = "") @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @@ -142,9 +142,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java index 55095ac953c6..0171e3296200 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/BigCat.java @@ -101,7 +101,7 @@ public boolean equals(Object o) { return false; } BigCat bigCat = (BigCat) o; - return super.equals(o) && Objects.equals(kind, bigCat.kind); + return super.equals(o) && Objects.equals(this.kind, bigCat.kind); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java index 31c3ee371963..e952af0fbc98 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Capitalization.java @@ -189,12 +189,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java index fb8b0954a999..0fa048000bd6 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Cat.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return super.equals(o) && Objects.equals(declawed, cat.declawed); + return super.equals(o) && Objects.equals(this.declawed, cat.declawed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java index 5c5ee2c9b5a4..4a5657942d6b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Category.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java index b85ca626ded4..080d861f6d3a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ClassModel.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java index 5d18c048f428..9153a3adf216 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Client.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java index 139884e350f8..93e3653ba4da 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Dog.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return super.equals(o) && Objects.equals(breed, dog.breed); + return super.equals(o) && Objects.equals(this.breed, dog.breed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java index c07029046ac6..4631a7c31f3c 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumArrays.java @@ -163,8 +163,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java index e3aadb63bc2b..a9cb994ddaa8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/EnumTest.java @@ -295,11 +295,11 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 365006936e34..89e3dc1249f7 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -41,7 +41,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; @JsonProperty(JSON_PROPERTY_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -63,7 +63,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -83,11 +83,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(value = "files") @ApiModelProperty(value = "") @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -101,8 +101,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java index 114a70310b10..9035779e0239 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/FormatTest.java @@ -404,20 +404,20 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(bigDecimal, formatTest.bigDecimal); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.bigDecimal, formatTest.bigDecimal); } @Override @@ -442,7 +442,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index 8d8bd67aeb13..69ac562dc6a9 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java index 428a329c83cf..6645c517504e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MapTest.java @@ -205,10 +205,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index dfa842013c5a..cc739934548f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -127,9 +127,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java index d7ddf004f4d1..ae8f5397738a 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Model200Response.java @@ -91,8 +91,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java index a05c06e91761..28eb65f67817 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelFile.java index 35d3242a106e..135bad167483 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelFile.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelList.java index 4a6bf3fd375a..27e325aba294 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelList.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java index 08dca8ec3604..8f744e457889 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ModelReturn.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java index ac6b9667d605..c5c89ffd43d8 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Name.java @@ -140,10 +140,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java index 35fafbc3a139..aceea701ca1e 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/NumberOnly.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java index 96c4ba5a384e..5a60e9121f40 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Order.java @@ -224,12 +224,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java index e6fef1023ae1..455f52c5ead2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/OuterComposite.java @@ -115,9 +115,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java index 0de0618f5e99..194a6fc01354 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Pet.java @@ -62,7 +62,7 @@ public class Pet { public static final String JSON_PROPERTY_TAGS = "tags"; @JsonProperty(JSON_PROPERTY_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -190,7 +190,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -210,11 +210,11 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(value = "tags") @ApiModelProperty(value = "") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -248,12 +248,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 0650df4c320a..0827ed6b9fe3 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java index f80332c68555..0d539a83fd98 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } SpecialModelName $specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, $specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, $specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java index b8197646f462..ba07edce8ce1 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/Tag.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java index 9a82ca05053c..c11fbaf766be 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderDefault.java @@ -176,11 +176,11 @@ public boolean equals(Object o) { return false; } TypeHolderDefault typeHolderDefault = (TypeHolderDefault) o; - return Objects.equals(stringItem, typeHolderDefault.stringItem) && - Objects.equals(numberItem, typeHolderDefault.numberItem) && - Objects.equals(integerItem, typeHolderDefault.integerItem) && - Objects.equals(boolItem, typeHolderDefault.boolItem) && - Objects.equals(arrayItem, typeHolderDefault.arrayItem); + return Objects.equals(this.stringItem, typeHolderDefault.stringItem) && + Objects.equals(this.numberItem, typeHolderDefault.numberItem) && + Objects.equals(this.integerItem, typeHolderDefault.integerItem) && + Objects.equals(this.boolItem, typeHolderDefault.boolItem) && + Objects.equals(this.arrayItem, typeHolderDefault.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java index dc7765fb9661..250badaeb99b 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/TypeHolderExample.java @@ -201,12 +201,12 @@ public boolean equals(Object o) { return false; } TypeHolderExample typeHolderExample = (TypeHolderExample) o; - return Objects.equals(stringItem, typeHolderExample.stringItem) && - Objects.equals(numberItem, typeHolderExample.numberItem) && - Objects.equals(floatItem, typeHolderExample.floatItem) && - Objects.equals(integerItem, typeHolderExample.integerItem) && - Objects.equals(boolItem, typeHolderExample.boolItem) && - Objects.equals(arrayItem, typeHolderExample.arrayItem); + return Objects.equals(this.stringItem, typeHolderExample.stringItem) && + Objects.equals(this.numberItem, typeHolderExample.numberItem) && + Objects.equals(this.floatItem, typeHolderExample.floatItem) && + Objects.equals(this.integerItem, typeHolderExample.integerItem) && + Objects.equals(this.boolItem, typeHolderExample.boolItem) && + Objects.equals(this.arrayItem, typeHolderExample.arrayItem); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java index 06ab22d0fdc0..26261801d0b2 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/User.java @@ -239,14 +239,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java index 36419211b3a7..26811e06639d 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/jaxrs/jersey2/src/gen/java/org/openapitools/model/XmlItem.java @@ -840,35 +840,35 @@ public boolean equals(Object o) { return false; } XmlItem xmlItem = (XmlItem) o; - return Objects.equals(attributeString, xmlItem.attributeString) && - Objects.equals(attributeNumber, xmlItem.attributeNumber) && - Objects.equals(attributeInteger, xmlItem.attributeInteger) && - Objects.equals(attributeBoolean, xmlItem.attributeBoolean) && - Objects.equals(wrappedArray, xmlItem.wrappedArray) && - Objects.equals(nameString, xmlItem.nameString) && - Objects.equals(nameNumber, xmlItem.nameNumber) && - Objects.equals(nameInteger, xmlItem.nameInteger) && - Objects.equals(nameBoolean, xmlItem.nameBoolean) && - Objects.equals(nameArray, xmlItem.nameArray) && - Objects.equals(nameWrappedArray, xmlItem.nameWrappedArray) && - Objects.equals(prefixString, xmlItem.prefixString) && - Objects.equals(prefixNumber, xmlItem.prefixNumber) && - Objects.equals(prefixInteger, xmlItem.prefixInteger) && - Objects.equals(prefixBoolean, xmlItem.prefixBoolean) && - Objects.equals(prefixArray, xmlItem.prefixArray) && - Objects.equals(prefixWrappedArray, xmlItem.prefixWrappedArray) && - Objects.equals(namespaceString, xmlItem.namespaceString) && - Objects.equals(namespaceNumber, xmlItem.namespaceNumber) && - Objects.equals(namespaceInteger, xmlItem.namespaceInteger) && - Objects.equals(namespaceBoolean, xmlItem.namespaceBoolean) && - Objects.equals(namespaceArray, xmlItem.namespaceArray) && - Objects.equals(namespaceWrappedArray, xmlItem.namespaceWrappedArray) && - Objects.equals(prefixNsString, xmlItem.prefixNsString) && - Objects.equals(prefixNsNumber, xmlItem.prefixNsNumber) && - Objects.equals(prefixNsInteger, xmlItem.prefixNsInteger) && - Objects.equals(prefixNsBoolean, xmlItem.prefixNsBoolean) && - Objects.equals(prefixNsArray, xmlItem.prefixNsArray) && - Objects.equals(prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); + return Objects.equals(this.attributeString, xmlItem.attributeString) && + Objects.equals(this.attributeNumber, xmlItem.attributeNumber) && + Objects.equals(this.attributeInteger, xmlItem.attributeInteger) && + Objects.equals(this.attributeBoolean, xmlItem.attributeBoolean) && + Objects.equals(this.wrappedArray, xmlItem.wrappedArray) && + Objects.equals(this.nameString, xmlItem.nameString) && + Objects.equals(this.nameNumber, xmlItem.nameNumber) && + Objects.equals(this.nameInteger, xmlItem.nameInteger) && + Objects.equals(this.nameBoolean, xmlItem.nameBoolean) && + Objects.equals(this.nameArray, xmlItem.nameArray) && + Objects.equals(this.nameWrappedArray, xmlItem.nameWrappedArray) && + Objects.equals(this.prefixString, xmlItem.prefixString) && + Objects.equals(this.prefixNumber, xmlItem.prefixNumber) && + Objects.equals(this.prefixInteger, xmlItem.prefixInteger) && + Objects.equals(this.prefixBoolean, xmlItem.prefixBoolean) && + Objects.equals(this.prefixArray, xmlItem.prefixArray) && + Objects.equals(this.prefixWrappedArray, xmlItem.prefixWrappedArray) && + Objects.equals(this.namespaceString, xmlItem.namespaceString) && + Objects.equals(this.namespaceNumber, xmlItem.namespaceNumber) && + Objects.equals(this.namespaceInteger, xmlItem.namespaceInteger) && + Objects.equals(this.namespaceBoolean, xmlItem.namespaceBoolean) && + Objects.equals(this.namespaceArray, xmlItem.namespaceArray) && + Objects.equals(this.namespaceWrappedArray, xmlItem.namespaceWrappedArray) && + Objects.equals(this.prefixNsString, xmlItem.prefixNsString) && + Objects.equals(this.prefixNsNumber, xmlItem.prefixNsNumber) && + Objects.equals(this.prefixNsInteger, xmlItem.prefixNsInteger) && + Objects.equals(this.prefixNsBoolean, xmlItem.prefixNsBoolean) && + Objects.equals(this.prefixNsArray, xmlItem.prefixNsArray) && + Objects.equals(this.prefixNsWrappedArray, xmlItem.prefixNsWrappedArray); } @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index 361e57e8167b..edbc664b7303 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class AnotherFakeApiServiceImpl extends AnotherFakeApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index c73b41f74224..f4dc88c44b73 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -22,6 +22,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeApiServiceImpl extends FakeApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java index 6f681177cb18..7356876a4518 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java @@ -13,6 +13,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeClassnameTestApiServiceImpl extends FakeClassnameTestApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index 628d5183e765..7b45a0fd7239 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -16,6 +16,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index b4ec457464ff..c06c4da6d465 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index c6018c40f96a..33f057ca766f 100644 --- a/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey2/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -14,6 +14,7 @@ import javax.ws.rs.core.Response; import javax.ws.rs.core.SecurityContext; import javax.validation.constraints.*; +import javax.validation.Valid; @javax.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class UserApiServiceImpl extends UserApiService { @Override @@ -22,12 +23,12 @@ public Response createUser(User body, SecurityContext securityContext) throws No return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithArrayInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List body, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithListInput(List<@Valid User> body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey3/.openapi-generator/VERSION b/samples/server/petstore/jaxrs/jersey3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/jaxrs/jersey3/.openapi-generator/VERSION +++ b/samples/server/petstore/jaxrs/jersey3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/jaxrs/jersey3/pom.xml b/samples/server/petstore/jaxrs/jersey3/pom.xml index 5d5fe4957d53..749bdab9d591 100644 --- a/samples/server/petstore/jaxrs/jersey3/pom.xml +++ b/samples/server/petstore/jaxrs/jersey3/pom.xml @@ -209,7 +209,7 @@ 3.1.3 2.15.2 4.13.2 - 1.4.9 + 1.4.14 5.0.0 UTF-8 diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/AnotherFakeApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/AnotherFakeApiService.java index 26d97a10d9b9..333a0a836175 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/AnotherFakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/AnotherFakeApiService.java @@ -14,6 +14,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class AnotherFakeApiService { public abstract Response call123testSpecialTags(Client client,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApi.java index 74445e793666..17fd4690a999 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApi.java @@ -175,6 +175,18 @@ public Response fakePropertyEnumIntegerSerialize(@Schema(description = "Input en return delegate.fakePropertyEnumIntegerSerialize(outerObjectWithEnumProperty, securityContext); } + @jakarta.ws.rs.POST + @Path("/additionalProperties-reference") + @Consumes({ "application/json" }) + @Operation(summary = "test referenced additionalProperties", description = "", responses = { + @ApiResponse(responseCode = "200", description = "successful operation", content = + @Content(schema = @Schema(implementation = Void.class))), + }, tags={ "fake", }) + public Response testAdditionalPropertiesReference(@Schema(description = "request body", required = true) @NotNull @Valid Map requestBody,@Context SecurityContext securityContext) + throws NotFoundException { + return delegate.testAdditionalPropertiesReference(requestBody, securityContext); + } + @jakarta.ws.rs.PUT @Path("/body-with-binary") @Consumes({ "image/png" }) @@ -244,7 +256,7 @@ public Response testEndpointParameters(@Schema(description = "None") @QueryParam @ApiResponse(responseCode = "404", description = "Not found", content = @Content(schema = @Schema(implementation = Void.class))), }, tags={ "fake", }) - public Response testEnumParameters(@Schema(description = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@Schema(description = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString,@Schema(description = "Query parameter enum test (string array)") @QueryParam("enum_query_string_array") @Valid List enumQueryStringArray,@Schema(description = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue = "-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString,@Schema(description = "Query parameter enum test (double)", allowableValues="1, -2") @QueryParam("enum_query_integer") Integer enumQueryInteger,@Schema(description = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @QueryParam("enum_query_double") Double enumQueryDouble,@Schema(description = "") @QueryParam("enum_query_model_array") @Valid List enumQueryModelArray,@Schema(description = "Form parameter enum test (string array)", allowableValues=">, $", defaultValue="$") @DefaultValue("$") @QueryParam("enum_form_string_array") List enumFormStringArray,@Schema(description = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_form_string") String enumFormString,@Context SecurityContext securityContext) + public Response testEnumParameters(@Schema(description = "Header parameter enum test (string array)" , allowableValues=">, $")@HeaderParam("enum_header_string_array") List enumHeaderStringArray,@Schema(description = "Header parameter enum test (string)" , allowableValues="_abc, -efg, (xyz)", defaultValue="-efg")@HeaderParam("enum_header_string") String enumHeaderString,@Schema(description = "Query parameter enum test (string array)") @QueryParam("enum_query_string_array") @Valid List enumQueryStringArray,@Schema(description = "Query parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue = "-efg") @DefaultValue("-efg") @QueryParam("enum_query_string") String enumQueryString,@Schema(description = "Query parameter enum test (double)", allowableValues="1, -2") @QueryParam("enum_query_integer") Integer enumQueryInteger,@Schema(description = "Query parameter enum test (double)", allowableValues="1.1, -1.2") @QueryParam("enum_query_double") Double enumQueryDouble,@Schema(description = "") @QueryParam("enum_query_model_array") @Valid List<@Valid EnumClass> enumQueryModelArray,@Schema(description = "Form parameter enum test (string array)", allowableValues=">, $", defaultValue="$") @DefaultValue("$") @QueryParam("enum_form_string_array") List enumFormStringArray,@Schema(description = "Form parameter enum test (string)", allowableValues="_abc, -efg, (xyz)", defaultValue="-efg") @DefaultValue("-efg") @QueryParam("enum_form_string") String enumFormString,@Context SecurityContext securityContext) throws NotFoundException { return delegate.testEnumParameters(enumHeaderStringArray, enumHeaderString, enumQueryStringArray, enumQueryString, enumQueryInteger, enumQueryDouble, enumQueryModelArray, enumFormStringArray, enumFormString, securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApiService.java index 6d30dde0220d..f267dd5ff687 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeApiService.java @@ -29,6 +29,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeApiService { public abstract Response fakeBigDecimalMap(SecurityContext securityContext) throws NotFoundException; @@ -39,12 +40,13 @@ public abstract class FakeApiService { public abstract Response fakeOuterNumberSerialize(BigDecimal body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakeOuterStringSerialize(String body,SecurityContext securityContext) throws NotFoundException; public abstract Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty outerObjectWithEnumProperty,SecurityContext securityContext) throws NotFoundException; + public abstract Response testAdditionalPropertiesReference(Map requestBody,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithBinary(File body,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithFileSchema(FileSchemaTestClass fileSchemaTestClass,SecurityContext securityContext) throws NotFoundException; public abstract Response testBodyWithQueryParams( @NotNull String query,User user,SecurityContext securityContext) throws NotFoundException; public abstract Response testClientModel(Client client,SecurityContext securityContext) throws NotFoundException; public abstract Response testEndpointParameters(BigDecimal number,Double _double,String patternWithoutDelimiter,byte[] _byte,Integer integer,Integer int32,Long int64,Float _float,String string,FormDataBodyPart binaryBodypart,Date date,Date dateTime,String password,String paramCallback,SecurityContext securityContext) throws NotFoundException; - public abstract Response testEnumParameters(List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,Integer enumQueryInteger,Double enumQueryDouble,List enumQueryModelArray,List enumFormStringArray,String enumFormString,SecurityContext securityContext) throws NotFoundException; + public abstract Response testEnumParameters(List enumHeaderStringArray,String enumHeaderString,List enumQueryStringArray,String enumQueryString,Integer enumQueryInteger,Double enumQueryDouble,List<@Valid EnumClass> enumQueryModelArray,List enumFormStringArray,String enumFormString,SecurityContext securityContext) throws NotFoundException; public abstract Response testGroupParameters( @NotNull Integer requiredStringGroup, @NotNull Boolean requiredBooleanGroup, @NotNull Long requiredInt64Group,Integer stringGroup,Boolean booleanGroup,Long int64Group,SecurityContext securityContext) throws NotFoundException; public abstract Response testInlineAdditionalProperties(Map requestBody,SecurityContext securityContext) throws NotFoundException; public abstract Response testInlineFreeformAdditionalProperties(TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java index e975f1f4cf45..a4aae0efb0c3 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FakeClassnameTestApiService.java @@ -14,6 +14,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FakeClassnameTestApiService { public abstract Response testClassname(Client client,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FooApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FooApiService.java index 8f877f49ac0b..7d573009d175 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FooApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/FooApiService.java @@ -14,6 +14,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class FooApiService { public abstract Response fooGet(SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/PetApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/PetApiService.java index ea6f8dcda048..a30bb5ed9d47 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/PetApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/PetApiService.java @@ -17,6 +17,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class PetApiService { public abstract Response addPet(Pet pet,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/StoreApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/StoreApiService.java index a16b9a9248ec..21a17c14aeb0 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/StoreApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/StoreApiService.java @@ -15,6 +15,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class StoreApiService { public abstract Response deleteOrder(String orderId,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApi.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApi.java index 66b00e1337da..667958ad9c0e 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApi.java @@ -78,7 +78,7 @@ public Response createUser(@Schema(description = "Created user object", required @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = Void.class))), }, tags={ "user", }) - public Response createUsersWithArrayInput(@Schema(description = "List of user object", required = true) @NotNull @Valid List user,@Context SecurityContext securityContext) + public Response createUsersWithArrayInput(@Schema(description = "List of user object", required = true) @NotNull @Valid List<@Valid User> user,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithArrayInput(user, securityContext); } @@ -90,7 +90,7 @@ public Response createUsersWithArrayInput(@Schema(description = "List of user ob @ApiResponse(responseCode = "200", description = "successful operation", content = @Content(schema = @Schema(implementation = Void.class))), }, tags={ "user", }) - public Response createUsersWithListInput(@Schema(description = "List of user object", required = true) @NotNull @Valid List user,@Context SecurityContext securityContext) + public Response createUsersWithListInput(@Schema(description = "List of user object", required = true) @NotNull @Valid List<@Valid User> user,@Context SecurityContext securityContext) throws NotFoundException { return delegate.createUsersWithListInput(user, securityContext); } diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApiService.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApiService.java index 4f965efa40ab..cf0b1c0b0b4e 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApiService.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/api/UserApiService.java @@ -15,11 +15,12 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public abstract class UserApiService { public abstract Response createUser(User user,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithArrayInput(List user,SecurityContext securityContext) throws NotFoundException; - public abstract Response createUsersWithListInput(List user,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithArrayInput(List<@Valid User> user,SecurityContext securityContext) throws NotFoundException; + public abstract Response createUsersWithListInput(List<@Valid User> user,SecurityContext securityContext) throws NotFoundException; public abstract Response deleteUser(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response getUserByName(String username,SecurityContext securityContext) throws NotFoundException; public abstract Response loginUser( @NotNull String username, @NotNull String password,SecurityContext securityContext) throws NotFoundException; diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java index 909c02f62f6f..39dce1858371 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -106,8 +106,8 @@ public boolean equals(Object o) { return false; } AdditionalPropertiesClass additionalPropertiesClass = (AdditionalPropertiesClass) o; - return Objects.equals(mapProperty, additionalPropertiesClass.mapProperty) && - Objects.equals(mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); + return Objects.equals(this.mapProperty, additionalPropertiesClass.mapProperty) && + Objects.equals(this.mapOfMapProperty, additionalPropertiesClass.mapOfMapProperty); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java index eba044e8b867..71d0a38a5f72 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/AllOfWithSingleRef.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } AllOfWithSingleRef allOfWithSingleRef = (AllOfWithSingleRef) o; - return Objects.equals(username, allOfWithSingleRef.username) && - Objects.equals(singleRefType, allOfWithSingleRef.singleRefType); + return Objects.equals(this.username, allOfWithSingleRef.username) && + Objects.equals(this.singleRefType, allOfWithSingleRef.singleRefType); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Animal.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Animal.java index 957b5616f45f..3f7a212e7272 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Animal.java @@ -96,8 +96,8 @@ public boolean equals(Object o) { return false; } Animal animal = (Animal) o; - return Objects.equals(className, animal.className) && - Objects.equals(color, animal.color); + return Objects.equals(this.className, animal.className) && + Objects.equals(this.color, animal.color); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java index 29498c6782ae..f52abc2976bb 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfArrayOfNumberOnly.java @@ -75,7 +75,7 @@ public boolean equals(Object o) { return false; } ArrayOfArrayOfNumberOnly arrayOfArrayOfNumberOnly = (ArrayOfArrayOfNumberOnly) o; - return Objects.equals(arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); + return Objects.equals(this.arrayArrayNumber, arrayOfArrayOfNumberOnly.arrayArrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java index 753ab14b4cf2..a052698ca512 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayOfNumberOnly.java @@ -75,7 +75,7 @@ public boolean equals(Object o) { return false; } ArrayOfNumberOnly arrayOfNumberOnly = (ArrayOfNumberOnly) o; - return Objects.equals(arrayNumber, arrayOfNumberOnly.arrayNumber); + return Objects.equals(this.arrayNumber, arrayOfNumberOnly.arrayNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayTest.java index 8ee21a1fa73d..fcb6b5e0e417 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ArrayTest.java @@ -45,7 +45,7 @@ public class ArrayTest { public static final String JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL = "array_array_of_model"; @JsonProperty(JSON_PROPERTY_ARRAY_ARRAY_OF_MODEL) - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -103,12 +103,12 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } - public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelItem) { + public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayOfModelItem) { if (this.arrayArrayOfModel == null) { this.arrayArrayOfModel = new ArrayList<>(); } @@ -123,11 +123,11 @@ public ArrayTest addArrayArrayOfModelItem(List arrayArrayOfModelI @JsonProperty(value = "array_array_of_model") @Schema(description = "") @Valid - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } @@ -141,9 +141,9 @@ public boolean equals(Object o) { return false; } ArrayTest arrayTest = (ArrayTest) o; - return Objects.equals(arrayOfString, arrayTest.arrayOfString) && - Objects.equals(arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && - Objects.equals(arrayArrayOfModel, arrayTest.arrayArrayOfModel); + return Objects.equals(this.arrayOfString, arrayTest.arrayOfString) && + Objects.equals(this.arrayArrayOfInteger, arrayTest.arrayArrayOfInteger) && + Objects.equals(this.arrayArrayOfModel, arrayTest.arrayArrayOfModel); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Capitalization.java index dff0c680a302..f388dacba018 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Capitalization.java @@ -188,12 +188,12 @@ public boolean equals(Object o) { return false; } Capitalization capitalization = (Capitalization) o; - return Objects.equals(smallCamel, capitalization.smallCamel) && - Objects.equals(capitalCamel, capitalization.capitalCamel) && - Objects.equals(smallSnake, capitalization.smallSnake) && - Objects.equals(capitalSnake, capitalization.capitalSnake) && - Objects.equals(scAETHFlowPoints, capitalization.scAETHFlowPoints) && - Objects.equals(ATT_NAME, capitalization.ATT_NAME); + return Objects.equals(this.smallCamel, capitalization.smallCamel) && + Objects.equals(this.capitalCamel, capitalization.capitalCamel) && + Objects.equals(this.smallSnake, capitalization.smallSnake) && + Objects.equals(this.capitalSnake, capitalization.capitalSnake) && + Objects.equals(this.scAETHFlowPoints, capitalization.scAETHFlowPoints) && + Objects.equals(this.ATT_NAME, capitalization.ATT_NAME); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Cat.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Cat.java index 9028e3e82bad..733bf7262e99 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Cat.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Cat cat = (Cat) o; - return super.equals(o) && Objects.equals(declawed, cat.declawed); + return super.equals(o) && Objects.equals(this.declawed, cat.declawed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Category.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Category.java index 329b7d77e021..a3bf3828414d 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Category.java @@ -88,8 +88,8 @@ public boolean equals(Object o) { return false; } Category category = (Category) o; - return Objects.equals(id, category.id) && - Objects.equals(name, category.name); + return Objects.equals(this.id, category.id) && + Objects.equals(this.name, category.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ChildWithNullable.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ChildWithNullable.java index 20eb1ccb19e9..cf2894bc0e59 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ChildWithNullable.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ChildWithNullable.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ChildWithNullable childWithNullable = (ChildWithNullable) o; - return super.equals(o) && Objects.equals(otherProperty, childWithNullable.otherProperty); + return super.equals(o) && Objects.equals(this.otherProperty, childWithNullable.otherProperty); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ClassModel.java index fe3b40460e8b..d7b3844b230e 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ClassModel.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } ClassModel classModel = (ClassModel) o; - return Objects.equals(propertyClass, classModel.propertyClass); + return Objects.equals(this.propertyClass, classModel.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Client.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Client.java index b69fb43db1ac..799081f5ad3c 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Client.java @@ -63,7 +63,7 @@ public boolean equals(Object o) { return false; } Client client = (Client) o; - return Objects.equals(client, client.client); + return Objects.equals(this.client, client.client); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/DeprecatedObject.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/DeprecatedObject.java index 92a6ac3247f3..dab1a1acef6b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/DeprecatedObject.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/DeprecatedObject.java @@ -63,7 +63,7 @@ public boolean equals(Object o) { return false; } DeprecatedObject deprecatedObject = (DeprecatedObject) o; - return Objects.equals(name, deprecatedObject.name); + return Objects.equals(this.name, deprecatedObject.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Dog.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Dog.java index 24df67f003a5..b08d03833086 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Dog.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } Dog dog = (Dog) o; - return super.equals(o) && Objects.equals(breed, dog.breed); + return super.equals(o) && Objects.equals(this.breed, dog.breed); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumArrays.java index 20b44a98237e..ea7708f3120b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumArrays.java @@ -162,8 +162,8 @@ public boolean equals(Object o) { return false; } EnumArrays enumArrays = (EnumArrays) o; - return Objects.equals(justSymbol, enumArrays.justSymbol) && - Objects.equals(arrayEnum, enumArrays.arrayEnum); + return Objects.equals(this.justSymbol, enumArrays.justSymbol) && + Objects.equals(this.arrayEnum, enumArrays.arrayEnum); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumTest.java index 63b217c3b2a7..4cd0670cc714 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/EnumTest.java @@ -372,14 +372,14 @@ public boolean equals(Object o) { return false; } EnumTest enumTest = (EnumTest) o; - return Objects.equals(enumString, enumTest.enumString) && - Objects.equals(enumStringRequired, enumTest.enumStringRequired) && - Objects.equals(enumInteger, enumTest.enumInteger) && - Objects.equals(enumNumber, enumTest.enumNumber) && - Objects.equals(outerEnum, enumTest.outerEnum) && - Objects.equals(outerEnumInteger, enumTest.outerEnumInteger) && - Objects.equals(outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && - Objects.equals(outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); + return Objects.equals(this.enumString, enumTest.enumString) && + Objects.equals(this.enumStringRequired, enumTest.enumStringRequired) && + Objects.equals(this.enumInteger, enumTest.enumInteger) && + Objects.equals(this.enumNumber, enumTest.enumNumber) && + Objects.equals(this.outerEnum, enumTest.outerEnum) && + Objects.equals(this.outerEnumInteger, enumTest.outerEnumInteger) && + Objects.equals(this.outerEnumDefaultValue, enumTest.outerEnumDefaultValue) && + Objects.equals(this.outerEnumIntegerDefaultValue, enumTest.outerEnumIntegerDefaultValue); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java index fb9d49086909..0ada5544ae8b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FakeBigDecimalMap200Response.java @@ -100,8 +100,8 @@ public boolean equals(Object o) { return false; } FakeBigDecimalMap200Response fakeBigDecimalMap200Response = (FakeBigDecimalMap200Response) o; - return Objects.equals(someId, fakeBigDecimalMap200Response.someId) && - Objects.equals(someMap, fakeBigDecimalMap200Response.someMap); + return Objects.equals(this.someId, fakeBigDecimalMap200Response.someId) && + Objects.equals(this.someMap, fakeBigDecimalMap200Response.someMap); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FileSchemaTestClass.java index 0353d0ca69bf..2d1b68fe685f 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FileSchemaTestClass.java @@ -40,7 +40,7 @@ public class FileSchemaTestClass { public static final String JSON_PROPERTY_FILES = "files"; @JsonProperty(JSON_PROPERTY_FILES) - private List files; + private List<@Valid ModelFile> files; public FileSchemaTestClass _file(ModelFile _file) { this._file = _file; @@ -62,7 +62,7 @@ public void setFile(ModelFile _file) { this._file = _file; } - public FileSchemaTestClass files(List files) { + public FileSchemaTestClass files(List<@Valid ModelFile> files) { this.files = files; return this; } @@ -82,11 +82,11 @@ public FileSchemaTestClass addFilesItem(ModelFile filesItem) { @JsonProperty(value = "files") @Schema(description = "") @Valid - public List getFiles() { + public List<@Valid ModelFile> getFiles() { return files; } - public void setFiles(List files) { + public void setFiles(List<@Valid ModelFile> files) { this.files = files; } @@ -100,8 +100,8 @@ public boolean equals(Object o) { return false; } FileSchemaTestClass fileSchemaTestClass = (FileSchemaTestClass) o; - return Objects.equals(_file, fileSchemaTestClass._file) && - Objects.equals(files, fileSchemaTestClass.files); + return Objects.equals(this._file, fileSchemaTestClass._file) && + Objects.equals(this.files, fileSchemaTestClass.files); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Foo.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Foo.java index 4a2124e76397..f055ae4ad1c8 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Foo.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Foo.java @@ -63,7 +63,7 @@ public boolean equals(Object o) { return false; } Foo foo = (Foo) o; - return Objects.equals(bar, foo.bar); + return Objects.equals(this.bar, foo.bar); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java index f2213b5826b2..7e4f6e67f9ca 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FooGetDefaultResponse.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } FooGetDefaultResponse fooGetDefaultResponse = (FooGetDefaultResponse) o; - return Objects.equals(string, fooGetDefaultResponse.string); + return Objects.equals(this.string, fooGetDefaultResponse.string); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FormatTest.java index 560b251c141c..159ac211795a 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/FormatTest.java @@ -453,22 +453,22 @@ public boolean equals(Object o) { return false; } FormatTest formatTest = (FormatTest) o; - return Objects.equals(integer, formatTest.integer) && - Objects.equals(int32, formatTest.int32) && - Objects.equals(int64, formatTest.int64) && - Objects.equals(number, formatTest.number) && - Objects.equals(_float, formatTest._float) && - Objects.equals(_double, formatTest._double) && - Objects.equals(decimal, formatTest.decimal) && - Objects.equals(string, formatTest.string) && - Objects.equals(_byte, formatTest._byte) && - Objects.equals(binary, formatTest.binary) && - Objects.equals(date, formatTest.date) && - Objects.equals(dateTime, formatTest.dateTime) && - Objects.equals(uuid, formatTest.uuid) && - Objects.equals(password, formatTest.password) && - Objects.equals(patternWithDigits, formatTest.patternWithDigits) && - Objects.equals(patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); + return Objects.equals(this.integer, formatTest.integer) && + Objects.equals(this.int32, formatTest.int32) && + Objects.equals(this.int64, formatTest.int64) && + Objects.equals(this.number, formatTest.number) && + Objects.equals(this._float, formatTest._float) && + Objects.equals(this._double, formatTest._double) && + Objects.equals(this.decimal, formatTest.decimal) && + Objects.equals(this.string, formatTest.string) && + Objects.equals(this._byte, formatTest._byte) && + Objects.equals(this.binary, formatTest.binary) && + Objects.equals(this.date, formatTest.date) && + Objects.equals(this.dateTime, formatTest.dateTime) && + Objects.equals(this.uuid, formatTest.uuid) && + Objects.equals(this.password, formatTest.password) && + Objects.equals(this.patternWithDigits, formatTest.patternWithDigits) && + Objects.equals(this.patternWithDigitsAndDelimiter, formatTest.patternWithDigitsAndDelimiter); } @Override @@ -494,7 +494,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" patternWithDigits: ").append(toIndentedString(patternWithDigits)).append("\n"); sb.append(" patternWithDigitsAndDelimiter: ").append(toIndentedString(patternWithDigitsAndDelimiter)).append("\n"); sb.append("}"); diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java index eac34a18d575..13f67db58985 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HasOnlyReadOnly.java @@ -89,8 +89,8 @@ public boolean equals(Object o) { return false; } HasOnlyReadOnly hasOnlyReadOnly = (HasOnlyReadOnly) o; - return Objects.equals(bar, hasOnlyReadOnly.bar) && - Objects.equals(foo, hasOnlyReadOnly.foo); + return Objects.equals(this.bar, hasOnlyReadOnly.bar) && + Objects.equals(this.foo, hasOnlyReadOnly.foo); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HealthCheckResult.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HealthCheckResult.java index 44b7e4aff03e..385a9f40157d 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HealthCheckResult.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/HealthCheckResult.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } HealthCheckResult healthCheckResult = (HealthCheckResult) o; - return Objects.equals(nullableMessage, healthCheckResult.nullableMessage); + return Objects.equals(this.nullableMessage, healthCheckResult.nullableMessage); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MapTest.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MapTest.java index d55f3abc1954..386c635c0050 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MapTest.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MapTest.java @@ -204,10 +204,10 @@ public boolean equals(Object o) { return false; } MapTest mapTest = (MapTest) o; - return Objects.equals(mapMapOfString, mapTest.mapMapOfString) && - Objects.equals(mapOfEnumString, mapTest.mapOfEnumString) && - Objects.equals(directMap, mapTest.directMap) && - Objects.equals(indirectMap, mapTest.indirectMap); + return Objects.equals(this.mapMapOfString, mapTest.mapMapOfString) && + Objects.equals(this.mapOfEnumString, mapTest.mapOfEnumString) && + Objects.equals(this.directMap, mapTest.directMap) && + Objects.equals(this.indirectMap, mapTest.indirectMap); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 88c988f8aea7..0e08effbb22b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -126,9 +126,9 @@ public boolean equals(Object o) { return false; } MixedPropertiesAndAdditionalPropertiesClass mixedPropertiesAndAdditionalPropertiesClass = (MixedPropertiesAndAdditionalPropertiesClass) o; - return Objects.equals(uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && - Objects.equals(dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && - Objects.equals(map, mixedPropertiesAndAdditionalPropertiesClass.map); + return Objects.equals(this.uuid, mixedPropertiesAndAdditionalPropertiesClass.uuid) && + Objects.equals(this.dateTime, mixedPropertiesAndAdditionalPropertiesClass.dateTime) && + Objects.equals(this.map, mixedPropertiesAndAdditionalPropertiesClass.map); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Model200Response.java index 0d77f06a6968..d5c3502c189c 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Model200Response.java @@ -90,8 +90,8 @@ public boolean equals(Object o) { return false; } Model200Response _200response = (Model200Response) o; - return Objects.equals(name, _200response.name) && - Objects.equals(propertyClass, _200response.propertyClass); + return Objects.equals(this.name, _200response.name) && + Objects.equals(this.propertyClass, _200response.propertyClass); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelApiResponse.java index 86de33090ada..6521c00ff3f5 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelApiResponse.java @@ -114,9 +114,9 @@ public boolean equals(Object o) { return false; } ModelApiResponse _apiResponse = (ModelApiResponse) o; - return Objects.equals(code, _apiResponse.code) && - Objects.equals(type, _apiResponse.type) && - Objects.equals(message, _apiResponse.message); + return Objects.equals(this.code, _apiResponse.code) && + Objects.equals(this.type, _apiResponse.type) && + Objects.equals(this.message, _apiResponse.message); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelFile.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelFile.java index 825d188c0c9d..23064119099e 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelFile.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelFile.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ModelFile _file = (ModelFile) o; - return Objects.equals(sourceURI, _file.sourceURI); + return Objects.equals(this.sourceURI, _file.sourceURI); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelList.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelList.java index c75279f16b4e..67aecceb2e42 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelList.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } ModelList _list = (ModelList) o; - return Objects.equals(_123list, _list._123list); + return Objects.equals(this._123list, _list._123list); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelReturn.java index 8cf6a9ada74f..d2578bfaedef 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ModelReturn.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } ModelReturn _return = (ModelReturn) o; - return Objects.equals(_return, _return._return); + return Objects.equals(this._return, _return._return); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Name.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Name.java index 602b74931bee..7a61eb0f2d55 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Name.java @@ -139,10 +139,10 @@ public boolean equals(Object o) { return false; } Name name = (Name) o; - return Objects.equals(name, name.name) && - Objects.equals(snakeCase, name.snakeCase) && - Objects.equals(property, name.property) && - Objects.equals(_123number, name._123number); + return Objects.equals(this.name, name.name) && + Objects.equals(this.snakeCase, name.snakeCase) && + Objects.equals(this.property, name.property) && + Objects.equals(this._123number, name._123number); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NullableClass.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NullableClass.java index 3e5f8220f286..e52edb152c38 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NullableClass.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NullableClass.java @@ -393,18 +393,18 @@ public boolean equals(Object o) { return false; } NullableClass nullableClass = (NullableClass) o; - return super.equals(o) && Objects.equals(integerProp, nullableClass.integerProp) && - Objects.equals(numberProp, nullableClass.numberProp) && - Objects.equals(booleanProp, nullableClass.booleanProp) && - Objects.equals(stringProp, nullableClass.stringProp) && - Objects.equals(dateProp, nullableClass.dateProp) && - Objects.equals(datetimeProp, nullableClass.datetimeProp) && - Objects.equals(arrayNullableProp, nullableClass.arrayNullableProp) && - Objects.equals(arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && - Objects.equals(arrayItemsNullable, nullableClass.arrayItemsNullable) && - Objects.equals(objectNullableProp, nullableClass.objectNullableProp) && - Objects.equals(objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && - Objects.equals(objectItemsNullable, nullableClass.objectItemsNullable); + return super.equals(o) && Objects.equals(this.integerProp, nullableClass.integerProp) && + Objects.equals(this.numberProp, nullableClass.numberProp) && + Objects.equals(this.booleanProp, nullableClass.booleanProp) && + Objects.equals(this.stringProp, nullableClass.stringProp) && + Objects.equals(this.dateProp, nullableClass.dateProp) && + Objects.equals(this.datetimeProp, nullableClass.datetimeProp) && + Objects.equals(this.arrayNullableProp, nullableClass.arrayNullableProp) && + Objects.equals(this.arrayAndItemsNullableProp, nullableClass.arrayAndItemsNullableProp) && + Objects.equals(this.arrayItemsNullable, nullableClass.arrayItemsNullable) && + Objects.equals(this.objectNullableProp, nullableClass.objectNullableProp) && + Objects.equals(this.objectAndItemsNullableProp, nullableClass.objectAndItemsNullableProp) && + Objects.equals(this.objectItemsNullable, nullableClass.objectItemsNullable); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NumberOnly.java index 57c721e4df1d..7651523fc8b7 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/NumberOnly.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } NumberOnly numberOnly = (NumberOnly) o; - return Objects.equals(justNumber, numberOnly.justNumber); + return Objects.equals(this.justNumber, numberOnly.justNumber); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java index 601f0ea4b0c3..0be00c589363 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ObjectWithDeprecatedFields.java @@ -51,7 +51,7 @@ public class ObjectWithDeprecatedFields { public static final String JSON_PROPERTY_BARS = "bars"; @JsonProperty(JSON_PROPERTY_BARS) - private List bars; + private List<@Valid String> bars; public ObjectWithDeprecatedFields uuid(String uuid) { this.uuid = uuid; @@ -113,7 +113,7 @@ public void setDeprecatedRef(DeprecatedObject deprecatedRef) { this.deprecatedRef = deprecatedRef; } - public ObjectWithDeprecatedFields bars(List bars) { + public ObjectWithDeprecatedFields bars(List<@Valid String> bars) { this.bars = bars; return this; } @@ -133,11 +133,11 @@ public ObjectWithDeprecatedFields addBarsItem(String barsItem) { @JsonProperty(value = "bars") @Schema(description = "") - public List getBars() { + public List<@Valid String> getBars() { return bars; } - public void setBars(List bars) { + public void setBars(List<@Valid String> bars) { this.bars = bars; } @@ -151,10 +151,10 @@ public boolean equals(Object o) { return false; } ObjectWithDeprecatedFields objectWithDeprecatedFields = (ObjectWithDeprecatedFields) o; - return Objects.equals(uuid, objectWithDeprecatedFields.uuid) && - Objects.equals(id, objectWithDeprecatedFields.id) && - Objects.equals(deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && - Objects.equals(bars, objectWithDeprecatedFields.bars); + return Objects.equals(this.uuid, objectWithDeprecatedFields.uuid) && + Objects.equals(this.id, objectWithDeprecatedFields.id) && + Objects.equals(this.deprecatedRef, objectWithDeprecatedFields.deprecatedRef) && + Objects.equals(this.bars, objectWithDeprecatedFields.bars); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Order.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Order.java index 4a6c9a64d23d..95d97257837b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Order.java @@ -223,12 +223,12 @@ public boolean equals(Object o) { return false; } Order order = (Order) o; - return Objects.equals(id, order.id) && - Objects.equals(petId, order.petId) && - Objects.equals(quantity, order.quantity) && - Objects.equals(shipDate, order.shipDate) && - Objects.equals(status, order.status) && - Objects.equals(complete, order.complete); + return Objects.equals(this.id, order.id) && + Objects.equals(this.petId, order.petId) && + Objects.equals(this.quantity, order.quantity) && + Objects.equals(this.shipDate, order.shipDate) && + Objects.equals(this.status, order.status) && + Objects.equals(this.complete, order.complete); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterComposite.java index 598006a4c787..711e501501f0 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterComposite.java @@ -114,9 +114,9 @@ public boolean equals(Object o) { return false; } OuterComposite outerComposite = (OuterComposite) o; - return Objects.equals(myNumber, outerComposite.myNumber) && - Objects.equals(myString, outerComposite.myString) && - Objects.equals(myBoolean, outerComposite.myBoolean); + return Objects.equals(this.myNumber, outerComposite.myNumber) && + Objects.equals(this.myString, outerComposite.myString) && + Objects.equals(this.myBoolean, outerComposite.myBoolean); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java index 18170921c853..3c962c80ab5c 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/OuterObjectWithEnumProperty.java @@ -65,7 +65,7 @@ public boolean equals(Object o) { return false; } OuterObjectWithEnumProperty outerObjectWithEnumProperty = (OuterObjectWithEnumProperty) o; - return Objects.equals(value, outerObjectWithEnumProperty.value); + return Objects.equals(this.value, outerObjectWithEnumProperty.value); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ParentWithNullable.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ParentWithNullable.java index 5cc6567488c6..110d53252de7 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ParentWithNullable.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ParentWithNullable.java @@ -125,8 +125,8 @@ public boolean equals(Object o) { return false; } ParentWithNullable parentWithNullable = (ParentWithNullable) o; - return Objects.equals(type, parentWithNullable.type) && - Objects.equals(nullableProperty, parentWithNullable.nullableProperty); + return Objects.equals(this.type, parentWithNullable.type) && + Objects.equals(this.nullableProperty, parentWithNullable.nullableProperty); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Pet.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Pet.java index 725761d7d040..da45e2275558 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Pet.java @@ -61,7 +61,7 @@ public class Pet { public static final String JSON_PROPERTY_TAGS = "tags"; @JsonProperty(JSON_PROPERTY_TAGS) - private List tags; + private List<@Valid Tag> tags; /** * pet status in the store @@ -189,7 +189,7 @@ public void setPhotoUrls(Set photoUrls) { this.photoUrls = photoUrls; } - public Pet tags(List tags) { + public Pet tags(List<@Valid Tag> tags) { this.tags = tags; return this; } @@ -209,11 +209,11 @@ public Pet addTagsItem(Tag tagsItem) { @JsonProperty(value = "tags") @Schema(description = "") @Valid - public List getTags() { + public List<@Valid Tag> getTags() { return tags; } - public void setTags(List tags) { + public void setTags(List<@Valid Tag> tags) { this.tags = tags; } @@ -247,12 +247,12 @@ public boolean equals(Object o) { return false; } Pet pet = (Pet) o; - return Objects.equals(id, pet.id) && - Objects.equals(category, pet.category) && - Objects.equals(name, pet.name) && - Objects.equals(photoUrls, pet.photoUrls) && - Objects.equals(tags, pet.tags) && - Objects.equals(status, pet.status); + return Objects.equals(this.id, pet.id) && + Objects.equals(this.category, pet.category) && + Objects.equals(this.name, pet.name) && + Objects.equals(this.photoUrls, pet.photoUrls) && + Objects.equals(this.tags, pet.tags) && + Objects.equals(this.status, pet.status); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ReadOnlyFirst.java index 8e1030db1c1a..71f51968b83f 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/ReadOnlyFirst.java @@ -88,8 +88,8 @@ public boolean equals(Object o) { return false; } ReadOnlyFirst readOnlyFirst = (ReadOnlyFirst) o; - return Objects.equals(bar, readOnlyFirst.bar) && - Objects.equals(baz, readOnlyFirst.baz); + return Objects.equals(this.bar, readOnlyFirst.bar) && + Objects.equals(this.baz, readOnlyFirst.baz); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/SpecialModelName.java index b1a919194a55..acb6c840883a 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/SpecialModelName.java @@ -64,7 +64,7 @@ public boolean equals(Object o) { return false; } SpecialModelName specialModelName = (SpecialModelName) o; - return Objects.equals($specialPropertyName, specialModelName.$specialPropertyName); + return Objects.equals(this.$specialPropertyName, specialModelName.$specialPropertyName); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Tag.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Tag.java index 0ec0c94faf9f..3a6cafd36174 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/Tag.java @@ -88,8 +88,8 @@ public boolean equals(Object o) { return false; } Tag tag = (Tag) o; - return Objects.equals(id, tag.id) && - Objects.equals(name, tag.name); + return Objects.equals(this.id, tag.id) && + Objects.equals(this.name, tag.name); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java index 5a2c5f104833..39d1191f67de 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/TestInlineFreeformAdditionalPropertiesRequest.java @@ -66,7 +66,7 @@ public boolean equals(Object o) { return false; } TestInlineFreeformAdditionalPropertiesRequest testInlineFreeformAdditionalPropertiesRequest = (TestInlineFreeformAdditionalPropertiesRequest) o; - return super.equals(o) && Objects.equals(someProperty, testInlineFreeformAdditionalPropertiesRequest.someProperty); + return super.equals(o) && Objects.equals(this.someProperty, testInlineFreeformAdditionalPropertiesRequest.someProperty); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/User.java b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/User.java index c0d7e91e0a91..348341a344c4 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/User.java +++ b/samples/server/petstore/jaxrs/jersey3/src/gen/java/org/openapitools/model/User.java @@ -238,14 +238,14 @@ public boolean equals(Object o) { return false; } User user = (User) o; - return Objects.equals(id, user.id) && - Objects.equals(username, user.username) && - Objects.equals(firstName, user.firstName) && - Objects.equals(lastName, user.lastName) && - Objects.equals(email, user.email) && - Objects.equals(password, user.password) && - Objects.equals(phone, user.phone) && - Objects.equals(userStatus, user.userStatus); + return Objects.equals(this.id, user.id) && + Objects.equals(this.username, user.username) && + Objects.equals(this.firstName, user.firstName) && + Objects.equals(this.lastName, user.lastName) && + Objects.equals(this.email, user.email) && + Objects.equals(this.password, user.password) && + Objects.equals(this.phone, user.phone) && + Objects.equals(this.userStatus, user.userStatus); } @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java index b16c7a4d1bd3..d607a42ef085 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/AnotherFakeApiServiceImpl.java @@ -13,6 +13,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class AnotherFakeApiServiceImpl extends AnotherFakeApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java index 434d5b06e65e..a743e03067f5 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeApiServiceImpl.java @@ -28,6 +28,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeApiServiceImpl extends FakeApiService { @Override @@ -71,6 +72,11 @@ public Response fakePropertyEnumIntegerSerialize(OuterObjectWithEnumProperty out return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override + public Response testAdditionalPropertiesReference(Map requestBody, SecurityContext securityContext) throws NotFoundException { + // do some magic! + return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); + } + @Override public Response testBodyWithBinary(File body, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); @@ -96,7 +102,7 @@ public Response testEndpointParameters(BigDecimal number, Double _double, String return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List enumQueryModelArray, List enumFormStringArray, String enumFormString, SecurityContext securityContext) throws NotFoundException { + public Response testEnumParameters(List enumHeaderStringArray, String enumHeaderString, List enumQueryStringArray, String enumQueryString, Integer enumQueryInteger, Double enumQueryDouble, List<@Valid EnumClass> enumQueryModelArray, List enumFormStringArray, String enumFormString, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java index 677af0c3a2e0..e8c4367e4fd9 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FakeClassnameTestApiServiceImpl.java @@ -13,6 +13,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FakeClassnameTestApiServiceImpl extends FakeClassnameTestApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java index bbf3e3aaf770..30933a3631e8 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/FooApiServiceImpl.java @@ -13,6 +13,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class FooApiServiceImpl extends FooApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java index a005a2b19922..67496341461d 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/PetApiServiceImpl.java @@ -16,6 +16,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class PetApiServiceImpl extends PetApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java index 06db41bac8cf..58eef0046476 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/StoreApiServiceImpl.java @@ -14,6 +14,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class StoreApiServiceImpl extends StoreApiService { @Override diff --git a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java index 62e74c356362..db96ab09036b 100644 --- a/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java +++ b/samples/server/petstore/jaxrs/jersey3/src/main/java/org/openapitools/api/impl/UserApiServiceImpl.java @@ -14,6 +14,7 @@ import jakarta.ws.rs.core.Response; import jakarta.ws.rs.core.SecurityContext; import jakarta.validation.constraints.*; +import jakarta.validation.Valid; @jakarta.annotation.Generated(value = "org.openapitools.codegen.languages.JavaJerseyServerCodegen") public class UserApiServiceImpl extends UserApiService { @Override @@ -22,12 +23,12 @@ public Response createUser(User user, SecurityContext securityContext) throws No return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithArrayInput(List user, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithArrayInput(List<@Valid User> user, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } @Override - public Response createUsersWithListInput(List user, SecurityContext securityContext) throws NotFoundException { + public Response createUsersWithListInput(List<@Valid User> user, SecurityContext securityContext) throws NotFoundException { // do some magic! return Response.ok().entity(new ApiResponseMessage(ApiResponseMessage.OK, "magic!")).build(); } diff --git a/samples/server/petstore/julia/.openapi-generator/VERSION b/samples/server/petstore/julia/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/julia/.openapi-generator/VERSION +++ b/samples/server/petstore/julia/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server-modelMutable/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server-modelMutable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server-modelMutable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server-modelMutable/README.md b/samples/server/petstore/kotlin-server-modelMutable/README.md index 396cfb0211fd..46dc45c856af 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/README.md +++ b/samples/server/petstore/kotlin-server-modelMutable/README.md @@ -2,7 +2,7 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -Generated by OpenAPI Generator 7.1.0-SNAPSHOT. +Generated by OpenAPI Generator 7.3.0-SNAPSHOT. ## Requires diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index 3265da9d1e5a..d95a4b4d0883 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -40,6 +40,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -50,6 +51,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -99,6 +101,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -148,6 +151,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -181,6 +185,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -191,6 +196,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -201,6 +207,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -222,6 +229,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index 29fb8cf022f3..fe780f7feb46 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -34,6 +34,7 @@ fun Route.StoreApi() { delete { call.respond(HttpStatusCode.NotImplemented) + } authenticate("api_key") { @@ -43,6 +44,7 @@ fun Route.StoreApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -62,6 +64,7 @@ fun Route.StoreApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } post { @@ -80,6 +83,7 @@ fun Route.StoreApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } diff --git a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index a180d715fe77..ccf0509fca2e 100644 --- a/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server-modelMutable/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -34,18 +34,22 @@ fun Route.UserApi() { post { call.respond(HttpStatusCode.NotImplemented) + } post { call.respond(HttpStatusCode.NotImplemented) + } post { call.respond(HttpStatusCode.NotImplemented) + } delete { call.respond(HttpStatusCode.NotImplemented) + } get { @@ -66,18 +70,22 @@ fun Route.UserApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } get { call.respond(HttpStatusCode.NotImplemented) + } get { call.respond(HttpStatusCode.NotImplemented) + } put { call.respond(HttpStatusCode.NotImplemented) + } } diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec-mutiny/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server/jaxrs-spec-mutiny/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-server/jaxrs-spec-mutiny/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server/jaxrs-spec-mutiny/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server/jaxrs-spec/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server/jaxrs-spec/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-server/jaxrs-spec/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server/jaxrs-spec/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-server/ktor/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-server/ktor/README.md b/samples/server/petstore/kotlin-server/ktor/README.md index 396cfb0211fd..46dc45c856af 100644 --- a/samples/server/petstore/kotlin-server/ktor/README.md +++ b/samples/server/petstore/kotlin-server/ktor/README.md @@ -2,7 +2,7 @@ This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. -Generated by OpenAPI Generator 7.1.0-SNAPSHOT. +Generated by OpenAPI Generator 7.3.0-SNAPSHOT. ## Requires diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt index 3265da9d1e5a..d95a4b4d0883 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/PetApi.kt @@ -40,6 +40,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -50,6 +51,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -99,6 +101,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -148,6 +151,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -181,6 +185,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } @@ -191,6 +196,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -201,6 +207,7 @@ fun Route.PetApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -222,6 +229,7 @@ fun Route.PetApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt index 29fb8cf022f3..fe780f7feb46 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/StoreApi.kt @@ -34,6 +34,7 @@ fun Route.StoreApi() { delete { call.respond(HttpStatusCode.NotImplemented) + } authenticate("api_key") { @@ -43,6 +44,7 @@ fun Route.StoreApi() { call.respond(HttpStatusCode.NotImplemented) + } } @@ -62,6 +64,7 @@ fun Route.StoreApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } post { @@ -80,6 +83,7 @@ fun Route.StoreApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } } diff --git a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt index a180d715fe77..ccf0509fca2e 100644 --- a/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt +++ b/samples/server/petstore/kotlin-server/ktor/src/main/kotlin/org/openapitools/server/apis/UserApi.kt @@ -34,18 +34,22 @@ fun Route.UserApi() { post { call.respond(HttpStatusCode.NotImplemented) + } post { call.respond(HttpStatusCode.NotImplemented) + } post { call.respond(HttpStatusCode.NotImplemented) + } delete { call.respond(HttpStatusCode.NotImplemented) + } get { @@ -66,18 +70,22 @@ fun Route.UserApi() { "application/xml" -> call.respondText(exampleContentString, ContentType.Text.Xml) else -> call.respondText(exampleContentString) } + } get { call.respond(HttpStatusCode.NotImplemented) + } get { call.respond(HttpStatusCode.NotImplemented) + } put { call.respond(HttpStatusCode.NotImplemented) + } } diff --git a/samples/server/petstore/kotlin-spring-default/.openapi-generator/VERSION b/samples/server/petstore/kotlin-spring-default/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-spring-default/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-spring-default/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-3/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-3/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-delegate/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt index d2987dc569ec..9d118bfe7282 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -41,6 +41,7 @@ interface PetApi { fun getDelegate(): PetApiDelegate = object: PetApiDelegate {} @Operation( + tags = ["pet",], summary = "Add a new pet to the store", operationId = "addPet", description = """""", @@ -61,6 +62,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Deletes a pet", operationId = "deletePet", description = """""", @@ -78,6 +80,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Finds Pets by status", operationId = "findPetsByStatus", description = """Multiple status values can be provided with comma separated strings""", @@ -97,6 +100,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Finds Pets by tags", operationId = "findPetsByTags", description = """Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.""", @@ -116,6 +120,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Find pet by ID", operationId = "getPetById", description = """Returns a single pet""", @@ -136,6 +141,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Update an existing pet", operationId = "updatePet", description = """""", @@ -158,6 +164,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "Updates a pet in the store with form data", operationId = "updatePetWithForm", description = """""", @@ -176,6 +183,7 @@ interface PetApi { } @Operation( + tags = ["pet",], summary = "uploads an image", operationId = "uploadFile", description = """""", diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApiController.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApiController.kt index ac2e8fb60763..931361743fd4 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApiController.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/PetApiController.kt @@ -10,7 +10,7 @@ import java.util.Optional class PetApiController( @org.springframework.beans.factory.annotation.Autowired(required = false) delegate: PetApiDelegate? ) : PetApi { - private val delegate: PetApiDelegate + private lateinit var delegate: PetApiDelegate init { this.delegate = Optional.ofNullable(delegate).orElse(object : PetApiDelegate {}) diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt index 90bfc90caad3..9860548367e0 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -40,6 +40,7 @@ interface StoreApi { fun getDelegate(): StoreApiDelegate = object: StoreApiDelegate {} @Operation( + tags = ["store",], summary = "Delete purchase order by ID", operationId = "deleteOrder", description = """For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors""", @@ -57,6 +58,7 @@ interface StoreApi { } @Operation( + tags = ["store",], summary = "Returns pet inventories by status", operationId = "getInventory", description = """Returns a map of status codes to quantities""", @@ -75,6 +77,7 @@ interface StoreApi { } @Operation( + tags = ["store",], summary = "Find purchase order by ID", operationId = "getOrderById", description = """For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions""", @@ -94,6 +97,7 @@ interface StoreApi { } @Operation( + tags = ["store",], summary = "Place an order for a pet", operationId = "placeOrder", description = """""", diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApiController.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApiController.kt index 3f52082c4c0e..555c2f196fc7 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApiController.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/StoreApiController.kt @@ -10,7 +10,7 @@ import java.util.Optional class StoreApiController( @org.springframework.beans.factory.annotation.Autowired(required = false) delegate: StoreApiDelegate? ) : StoreApi { - private val delegate: StoreApiDelegate + private lateinit var delegate: StoreApiDelegate init { this.delegate = Optional.ofNullable(delegate).orElse(object : StoreApiDelegate {}) diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt index 646c15b6b5e1..a4e957fe019f 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -40,6 +40,7 @@ interface UserApi { fun getDelegate(): UserApiDelegate = object: UserApiDelegate {} @Operation( + tags = ["user",], summary = "Create user", operationId = "createUser", description = """This can only be done by the logged in user.""", @@ -58,6 +59,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Creates list of users with given input array", operationId = "createUsersWithArrayInput", description = """""", @@ -76,6 +78,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Creates list of users with given input array", operationId = "createUsersWithListInput", description = """""", @@ -94,6 +97,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Delete user", operationId = "deleteUser", description = """This can only be done by the logged in user.""", @@ -112,6 +116,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Get user by user name", operationId = "getUserByName", description = """""", @@ -131,6 +136,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Logs user into the system", operationId = "loginUser", description = """""", @@ -149,6 +155,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Logs out current logged in user session", operationId = "logoutUser", description = """""", @@ -166,6 +173,7 @@ interface UserApi { } @Operation( + tags = ["user",], summary = "Updated user", operationId = "updateUser", description = """This can only be done by the logged in user.""", diff --git a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApiController.kt b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApiController.kt index a9b1b3300c02..5c8903538c5c 100644 --- a/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApiController.kt +++ b/samples/server/petstore/kotlin-springboot-delegate/src/main/kotlin/org/openapitools/api/UserApiController.kt @@ -10,7 +10,7 @@ import java.util.Optional class UserApiController( @org.springframework.beans.factory.annotation.Autowired(required = false) delegate: UserApiDelegate? ) : UserApi { - private val delegate: UserApiDelegate + private lateinit var delegate: UserApiDelegate init { this.delegate = Optional.ofNullable(delegate).orElse(object : UserApiDelegate {}) diff --git a/samples/server/petstore/kotlin-springboot-modelMutable/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-modelMutable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-modelMutable/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-modelMutable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-reactive/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-request/.openapi-generator-ignore b/samples/server/petstore/kotlin-springboot-request/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/kotlin-springboot-request/.openapi-generator/FILES b/samples/server/petstore/kotlin-springboot-request/.openapi-generator/FILES new file mode 100644 index 000000000000..6500c2b11cc5 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/.openapi-generator/FILES @@ -0,0 +1,16 @@ +README.md +build.gradle.kts +pom.xml +settings.gradle +src/main/kotlin/org/openapitools/SpringDocConfiguration.kt +src/main/kotlin/org/openapitools/api/ApiUtil.kt +src/main/kotlin/org/openapitools/api/Exceptions.kt +src/main/kotlin/org/openapitools/api/PetApi.kt +src/main/kotlin/org/openapitools/api/StoreApi.kt +src/main/kotlin/org/openapitools/api/UserApi.kt +src/main/kotlin/org/openapitools/model/Category.kt +src/main/kotlin/org/openapitools/model/ModelApiResponse.kt +src/main/kotlin/org/openapitools/model/Order.kt +src/main/kotlin/org/openapitools/model/Pet.kt +src/main/kotlin/org/openapitools/model/Tag.kt +src/main/kotlin/org/openapitools/model/User.kt diff --git a/samples/server/petstore/kotlin-springboot-request/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-request/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-request/README.md b/samples/server/petstore/kotlin-springboot-request/README.md new file mode 100644 index 000000000000..b6865a081135 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/README.md @@ -0,0 +1,21 @@ +# openAPIPetstore + +This Kotlin based [Spring Boot](https://spring.io/projects/spring-boot) application has been generated using the [OpenAPI Generator](https://github.com/OpenAPITools/openapi-generator). + +## Getting Started + +This document assumes you have either maven or gradle available, either via the wrapper or otherwise. This does not come with a gradle / maven wrapper checked in. + +By default a [`pom.xml`](pom.xml) file will be generated. If you specified `gradleBuildFile=true` when generating this project, a `build.gradle.kts` will also be generated. Note this uses [Gradle Kotlin DSL](https://github.com/gradle/kotlin-dsl). + +To build the project using maven, run: +```bash +mvn package && java -jar target/openapi-spring-1.0.0.jar +``` + +To build the project using gradle, run: +```bash +gradle build && java -jar build/libs/openapi-spring-1.0.0.jar +``` + +If all builds successfully, the server should run on [http://localhost:8080/](http://localhost:8080/) diff --git a/samples/server/petstore/kotlin-springboot-request/build.gradle.kts b/samples/server/petstore/kotlin-springboot-request/build.gradle.kts new file mode 100644 index 000000000000..f8ef1123955b --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/build.gradle.kts @@ -0,0 +1,43 @@ +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile + +group = "org.openapitools" +version = "1.0.0" +java.sourceCompatibility = JavaVersion.VERSION_17 + +repositories { + mavenCentral() + maven { url = uri("https://repo.spring.io/milestone") } +} + +tasks.withType { + kotlinOptions.jvmTarget = "17" +} + +plugins { + val kotlinVersion = "1.7.10" + id("org.jetbrains.kotlin.jvm") version kotlinVersion + id("org.jetbrains.kotlin.plugin.jpa") version kotlinVersion + id("org.jetbrains.kotlin.plugin.spring") version kotlinVersion + id("org.springframework.boot") version "3.0.2" + id("io.spring.dependency-management") version "1.0.14.RELEASE" +} + +dependencies { + implementation("org.jetbrains.kotlin:kotlin-stdlib-jdk8") + implementation("org.jetbrains.kotlin:kotlin-reflect") + implementation("org.springframework.boot:spring-boot-starter-web") + implementation("org.springdoc:springdoc-openapi-starter-webmvc-ui:2.0.0-M5") + + implementation("com.google.code.findbugs:jsr305:3.0.2") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-yaml") + implementation("com.fasterxml.jackson.dataformat:jackson-dataformat-xml") + implementation("com.fasterxml.jackson.datatype:jackson-datatype-jsr310") + implementation("com.fasterxml.jackson.module:jackson-module-kotlin") + implementation("jakarta.validation:jakarta.validation-api") + implementation("jakarta.annotation:jakarta.annotation-api:2.1.0") + + testImplementation("org.jetbrains.kotlin:kotlin-test-junit5") + testImplementation("org.springframework.boot:spring-boot-starter-test") { + exclude(module = "junit") + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/pom.xml b/samples/server/petstore/kotlin-springboot-request/pom.xml new file mode 100644 index 000000000000..d3dd81b25a85 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/pom.xml @@ -0,0 +1,138 @@ + + 4.0.0 + org.openapitools + openapi-spring + jar + openapi-spring + 1.0.0 + + 2.2.0 + 3.0.2 + 2.1.0 + 1.7.10 + + 1.7.10 + UTF-8 + + + org.springframework.boot + spring-boot-starter-parent + 3.1.3 + + + + repository.spring.milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + + + + spring-milestones + https://repo.spring.io/milestone + + + + ${project.basedir}/src/main/kotlin + ${project.basedir}/src/test/kotlin + + + kotlin-maven-plugin + org.jetbrains.kotlin + ${kotlin.version} + + + spring + + 17 + + + + compile + compile + + compile + + + + test-compile + test-compile + + test-compile + + + + + + org.jetbrains.kotlin + kotlin-maven-allopen + ${kotlin.version} + + + + + + + + org.jetbrains.kotlin + kotlin-stdlib-jdk8 + ${kotlin.version} + + + org.jetbrains.kotlin + kotlin-reflect + ${kotlin.version} + + + org.springframework.boot + spring-boot-starter-web + + + + + org.springdoc + springdoc-openapi-starter-webmvc-ui + ${springdoc-openapi.version} + + + + + com.google.code.findbugs + jsr305 + ${findbugs-jsr305.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + + + com.fasterxml.jackson.dataformat + jackson-dataformat-xml + + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + + + com.fasterxml.jackson.module + jackson-module-kotlin + + + + jakarta.validation + jakarta.validation-api + + + jakarta.annotation + jakarta.annotation-api + ${jakarta-annotation.version} + provided + + + org.jetbrains.kotlin + kotlin-test-junit5 + ${kotlin-test-junit5.version} + test + + + diff --git a/samples/server/petstore/kotlin-springboot-request/settings.gradle b/samples/server/petstore/kotlin-springboot-request/settings.gradle new file mode 100644 index 000000000000..14844905cd40 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/settings.gradle @@ -0,0 +1,15 @@ +pluginManagement { + repositories { + maven { url = uri("https://repo.spring.io/snapshot") } + maven { url = uri("https://repo.spring.io/milestone") } + gradlePluginPortal() + } + resolutionStrategy { + eachPlugin { + if (requested.id.id == "org.springframework.boot") { + useModule("org.springframework.boot:spring-boot-gradle-plugin:${requested.version}") + } + } + } +} +rootProject.name = "openapi-spring" diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/SpringDocConfiguration.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/SpringDocConfiguration.kt new file mode 100644 index 000000000000..ab4d5eb17b86 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/SpringDocConfiguration.kt @@ -0,0 +1,42 @@ +package org.openapitools + +import org.springframework.context.annotation.Bean +import org.springframework.context.annotation.Configuration + +import io.swagger.v3.oas.models.OpenAPI +import io.swagger.v3.oas.models.info.Info +import io.swagger.v3.oas.models.info.Contact +import io.swagger.v3.oas.models.info.License +import io.swagger.v3.oas.models.Components +import io.swagger.v3.oas.models.security.SecurityScheme + +@Configuration +class SpringDocConfiguration { + + @Bean + fun apiInfo(): OpenAPI { + return OpenAPI() + .info( + Info() + .title("OpenAPI Petstore") + .description("This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters.") + .license( + License() + .name("Apache-2.0") + .url("https://www.apache.org/licenses/LICENSE-2.0.html") + ) + .version("1.0.0") + ) + .components( + Components() + .addSecuritySchemes("petstore_auth", SecurityScheme() + .type(SecurityScheme.Type.OAUTH2) + ) + .addSecuritySchemes("api_key", SecurityScheme() + .type(SecurityScheme.Type.APIKEY) + .`in`(SecurityScheme.In.HEADER) + .name("api_key") + ) + ) + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/ApiUtil.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/ApiUtil.kt new file mode 100644 index 000000000000..03344e13b474 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/ApiUtil.kt @@ -0,0 +1,19 @@ +package org.openapitools.api + +import org.springframework.web.context.request.NativeWebRequest + +import jakarta.servlet.http.HttpServletResponse +import java.io.IOException + +object ApiUtil { + fun setExampleResponse(req: NativeWebRequest, contentType: String, example: String) { + try { + val res = req.getNativeResponse(HttpServletResponse::class.java) + res?.characterEncoding = "UTF-8" + res?.addHeader("Content-Type", contentType) + res?.writer?.print(example) + } catch (e: IOException) { + throw RuntimeException(e) + } + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/Exceptions.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/Exceptions.kt new file mode 100644 index 000000000000..117161bf65b1 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/Exceptions.kt @@ -0,0 +1,29 @@ +package org.openapitools.api + +import org.springframework.http.HttpStatus +import org.springframework.web.bind.annotation.ControllerAdvice +import org.springframework.web.bind.annotation.ExceptionHandler +import jakarta.servlet.http.HttpServletResponse +import jakarta.validation.ConstraintViolationException + +// TODO Extend ApiException for custom exception handling, e.g. the below NotFound exception +sealed class ApiException(msg: String, val code: Int) : Exception(msg) + +class NotFoundException(msg: String, code: Int = HttpStatus.NOT_FOUND.value()) : ApiException(msg, code) + + +@ControllerAdvice +class DefaultExceptionHandler { + + @ExceptionHandler(value = [ApiException::class]) + fun onApiException(ex: ApiException, response: HttpServletResponse): Unit = + response.sendError(ex.code, ex.message) + + @ExceptionHandler(value = [NotImplementedError::class]) + fun onNotImplemented(ex: NotImplementedError, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.NOT_IMPLEMENTED.value()) + + @ExceptionHandler(value = [ConstraintViolationException::class]) + fun onConstraintViolation(ex: ConstraintViolationException, response: HttpServletResponse): Unit = + response.sendError(HttpStatus.BAD_REQUEST.value(), ex.constraintViolations.joinToString(", ") { it.message }) +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/PetApi.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/PetApi.kt new file mode 100644 index 000000000000..999d3317e427 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/PetApi.kt @@ -0,0 +1,199 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. +*/ +package org.openapitools.api + +import org.openapitools.model.ModelApiResponse +import org.openapitools.model.Pet +import io.swagger.v3.oas.annotations.* +import io.swagger.v3.oas.annotations.enums.* +import io.swagger.v3.oas.annotations.media.* +import io.swagger.v3.oas.annotations.responses.* +import io.swagger.v3.oas.annotations.security.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.server.reactive.ServerHttpRequest + +import org.springframework.web.bind.annotation.* +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +import kotlin.collections.List +import kotlin.collections.Map + +@Validated +@RequestMapping("\${api.base-path:/v2}") +interface PetApi { + + @Operation( + tags = ["pet",], + summary = "Add a new pet to the store", + operationId = "addPet", + description = """""", + responses = [ + ApiResponse(responseCode = "405", description = "Invalid input") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/pet"], + consumes = ["application/json", "application/xml"] + ) + fun addPet(@Parameter(description = "Pet object that needs to be added to the store", required = true) @Valid @RequestBody body: Pet, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Deletes a pet", + operationId = "deletePet", + description = """""", + responses = [ + ApiResponse(responseCode = "400", description = "Invalid pet value") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.DELETE], + value = ["/pet/{petId}"] + ) + fun deletePet(@Parameter(description = "Pet id to delete", required = true) @PathVariable("petId") petId: kotlin.Long,@Parameter(description = "", `in` = ParameterIn.HEADER) @RequestHeader(value = "api_key", required = false) apiKey: kotlin.String?, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Finds Pets by status", + operationId = "findPetsByStatus", + description = """Multiple status values can be provided with comma separated strings""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(array = ArraySchema(schema = Schema(implementation = Pet::class)))]), + ApiResponse(responseCode = "400", description = "Invalid status value") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/pet/findByStatus"], + produces = ["application/xml", "application/json"] + ) + fun findPetsByStatus(@NotNull @Parameter(description = "Status values that need to be considered for filter", required = true, schema = Schema(allowableValues = ["available", "pending", "sold"])) @Valid @RequestParam(value = "status", required = true) status: kotlin.collections.List, serverHttpRequest: ServerHttpRequest): ResponseEntity> { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Finds Pets by tags", + operationId = "findPetsByTags", + description = """Multiple tags can be provided with comma separated strings. Use tag1, tag2, tag3 for testing.""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(array = ArraySchema(schema = Schema(implementation = Pet::class)))]), + ApiResponse(responseCode = "400", description = "Invalid tag value") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/pet/findByTags"], + produces = ["application/xml", "application/json"] + ) + fun findPetsByTags(@NotNull @Parameter(description = "Tags to filter by", required = true) @Valid @RequestParam(value = "tags", required = true) tags: kotlin.collections.List, serverHttpRequest: ServerHttpRequest): ResponseEntity> { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Find pet by ID", + operationId = "getPetById", + description = """Returns a single pet""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = Pet::class))]), + ApiResponse(responseCode = "400", description = "Invalid ID supplied"), + ApiResponse(responseCode = "404", description = "Pet not found") + ], + security = [ SecurityRequirement(name = "api_key") ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/pet/{petId}"], + produces = ["application/xml", "application/json"] + ) + fun getPetById(@Parameter(description = "ID of pet to return", required = true) @PathVariable("petId") petId: kotlin.Long, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Update an existing pet", + operationId = "updatePet", + description = """""", + responses = [ + ApiResponse(responseCode = "400", description = "Invalid ID supplied"), + ApiResponse(responseCode = "404", description = "Pet not found"), + ApiResponse(responseCode = "405", description = "Validation exception") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.PUT], + value = ["/pet"], + consumes = ["application/json", "application/xml"] + ) + fun updatePet(@Parameter(description = "Pet object that needs to be added to the store", required = true) @Valid @RequestBody body: Pet, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "Updates a pet in the store with form data", + operationId = "updatePetWithForm", + description = """""", + responses = [ + ApiResponse(responseCode = "405", description = "Invalid input") + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/pet/{petId}"], + consumes = ["application/x-www-form-urlencoded"] + ) + fun updatePetWithForm(@Parameter(description = "ID of pet that needs to be updated", required = true) @PathVariable("petId") petId: kotlin.Long,@Parameter(description = "Updated name of the pet") @RequestParam(value = "name", required = false) name: kotlin.String? ,@Parameter(description = "Updated status of the pet") @RequestParam(value = "status", required = false) status: kotlin.String? , serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["pet",], + summary = "uploads an image", + operationId = "uploadFile", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = ModelApiResponse::class))]) + ], + security = [ SecurityRequirement(name = "petstore_auth", scopes = [ "write:pets", "read:pets" ]) ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/pet/{petId}/uploadImage"], + produces = ["application/json"], + consumes = ["multipart/form-data"] + ) + fun uploadFile(@Parameter(description = "ID of pet to update", required = true) @PathVariable("petId") petId: kotlin.Long,@Parameter(description = "Additional data to pass to server") @RequestParam(value = "additionalMetadata", required = false) additionalMetadata: kotlin.String? ,@Parameter(description = "file detail") @Valid @RequestPart("file") file: org.springframework.core.io.Resource?, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/StoreApi.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/StoreApi.kt new file mode 100644 index 000000000000..59dcb3967f5c --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/StoreApi.kt @@ -0,0 +1,116 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. +*/ +package org.openapitools.api + +import org.openapitools.model.Order +import io.swagger.v3.oas.annotations.* +import io.swagger.v3.oas.annotations.enums.* +import io.swagger.v3.oas.annotations.media.* +import io.swagger.v3.oas.annotations.responses.* +import io.swagger.v3.oas.annotations.security.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.server.reactive.ServerHttpRequest + +import org.springframework.web.bind.annotation.* +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +import kotlin.collections.List +import kotlin.collections.Map + +@Validated +@RequestMapping("\${api.base-path:/v2}") +interface StoreApi { + + @Operation( + tags = ["store",], + summary = "Delete purchase order by ID", + operationId = "deleteOrder", + description = """For valid response try integer IDs with value < 1000. Anything above 1000 or nonintegers will generate API errors""", + responses = [ + ApiResponse(responseCode = "400", description = "Invalid ID supplied"), + ApiResponse(responseCode = "404", description = "Order not found") + ] + ) + @RequestMapping( + method = [RequestMethod.DELETE], + value = ["/store/order/{orderId}"] + ) + fun deleteOrder(@Parameter(description = "ID of the order that needs to be deleted", required = true) @PathVariable("orderId") orderId: kotlin.String, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["store",], + summary = "Returns pet inventories by status", + operationId = "getInventory", + description = """Returns a map of status codes to quantities""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = kotlin.collections.Map::class))]) + ], + security = [ SecurityRequirement(name = "api_key") ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/store/inventory"], + produces = ["application/json"] + ) + fun getInventory(, serverHttpRequest: ServerHttpRequest): ResponseEntity> { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["store",], + summary = "Find purchase order by ID", + operationId = "getOrderById", + description = """For valid response try integer IDs with value <= 5 or > 10. Other values will generate exceptions""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = Order::class))]), + ApiResponse(responseCode = "400", description = "Invalid ID supplied"), + ApiResponse(responseCode = "404", description = "Order not found") + ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/store/order/{orderId}"], + produces = ["application/xml", "application/json"] + ) + fun getOrderById(@Min(1L) @Max(5L) @Parameter(description = "ID of pet that needs to be fetched", required = true) @PathVariable("orderId") orderId: kotlin.Long, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["store",], + summary = "Place an order for a pet", + operationId = "placeOrder", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = Order::class))]), + ApiResponse(responseCode = "400", description = "Invalid Order") + ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/store/order"], + produces = ["application/xml", "application/json"] + ) + fun placeOrder(@Parameter(description = "order placed for purchasing the pet", required = true) @Valid @RequestBody body: Order, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/UserApi.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/UserApi.kt new file mode 100644 index 000000000000..af517bd5f980 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/api/UserApi.kt @@ -0,0 +1,183 @@ +/** + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). + * https://openapi-generator.tech + * Do not edit the class manually. +*/ +package org.openapitools.api + +import org.openapitools.model.User +import io.swagger.v3.oas.annotations.* +import io.swagger.v3.oas.annotations.enums.* +import io.swagger.v3.oas.annotations.media.* +import io.swagger.v3.oas.annotations.responses.* +import io.swagger.v3.oas.annotations.security.* +import org.springframework.http.HttpStatus +import org.springframework.http.MediaType +import org.springframework.http.ResponseEntity +import org.springframework.http.server.reactive.ServerHttpRequest + +import org.springframework.web.bind.annotation.* +import org.springframework.validation.annotation.Validated +import org.springframework.web.context.request.NativeWebRequest +import org.springframework.beans.factory.annotation.Autowired + +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid + +import kotlin.collections.List +import kotlin.collections.Map + +@Validated +@RequestMapping("\${api.base-path:/v2}") +interface UserApi { + + @Operation( + tags = ["user",], + summary = "Create user", + operationId = "createUser", + description = """This can only be done by the logged in user.""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation") + ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/user"] + ) + fun createUser(@Parameter(description = "Created user object", required = true) @Valid @RequestBody body: User, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Creates list of users with given input array", + operationId = "createUsersWithArrayInput", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation") + ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/user/createWithArray"] + ) + fun createUsersWithArrayInput(@Parameter(description = "List of user object", required = true) @Valid @RequestBody body: kotlin.collections.List, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Creates list of users with given input array", + operationId = "createUsersWithListInput", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation") + ] + ) + @RequestMapping( + method = [RequestMethod.POST], + value = ["/user/createWithList"] + ) + fun createUsersWithListInput(@Parameter(description = "List of user object", required = true) @Valid @RequestBody body: kotlin.collections.List, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Delete user", + operationId = "deleteUser", + description = """This can only be done by the logged in user.""", + responses = [ + ApiResponse(responseCode = "400", description = "Invalid username supplied"), + ApiResponse(responseCode = "404", description = "User not found") + ] + ) + @RequestMapping( + method = [RequestMethod.DELETE], + value = ["/user/{username}"] + ) + fun deleteUser(@Parameter(description = "The name that needs to be deleted", required = true) @PathVariable("username") username: kotlin.String, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Get user by user name", + operationId = "getUserByName", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = User::class))]), + ApiResponse(responseCode = "400", description = "Invalid username supplied"), + ApiResponse(responseCode = "404", description = "User not found") + ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/user/{username}"], + produces = ["application/xml", "application/json"] + ) + fun getUserByName(@Parameter(description = "The name that needs to be fetched. Use user1 for testing.", required = true) @PathVariable("username") username: kotlin.String, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Logs user into the system", + operationId = "loginUser", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation", content = [Content(schema = Schema(implementation = kotlin.String::class))]), + ApiResponse(responseCode = "400", description = "Invalid username/password supplied") + ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/user/login"], + produces = ["application/xml", "application/json"] + ) + fun loginUser(@NotNull @Parameter(description = "The user name for login", required = true) @Valid @RequestParam(value = "username", required = true) username: kotlin.String,@NotNull @Parameter(description = "The password for login in clear text", required = true) @Valid @RequestParam(value = "password", required = true) password: kotlin.String, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Logs out current logged in user session", + operationId = "logoutUser", + description = """""", + responses = [ + ApiResponse(responseCode = "200", description = "successful operation") + ] + ) + @RequestMapping( + method = [RequestMethod.GET], + value = ["/user/logout"] + ) + fun logoutUser(, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } + + @Operation( + tags = ["user",], + summary = "Updated user", + operationId = "updateUser", + description = """This can only be done by the logged in user.""", + responses = [ + ApiResponse(responseCode = "400", description = "Invalid user supplied"), + ApiResponse(responseCode = "404", description = "User not found") + ] + ) + @RequestMapping( + method = [RequestMethod.PUT], + value = ["/user/{username}"] + ) + fun updateUser(@Parameter(description = "name that need to be deleted", required = true) @PathVariable("username") username: kotlin.String,@Parameter(description = "Updated user object", required = true) @Valid @RequestBody body: User, serverHttpRequest: ServerHttpRequest): ResponseEntity { + return ResponseEntity(HttpStatus.NOT_IMPLEMENTED) + } +} diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Category.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Category.kt new file mode 100644 index 000000000000..338317ebab8d --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Category.kt @@ -0,0 +1,31 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * A category for a pet + * @param id + * @param name + */ +data class Category( + + @Schema(example = "null", description = "") + @get:JsonProperty("id") val id: kotlin.Long? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt new file mode 100644 index 000000000000..338a2d0f46ec --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/ModelApiResponse.kt @@ -0,0 +1,35 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * Describes the result of uploading an image resource + * @param code + * @param type + * @param message + */ +data class ModelApiResponse( + + @Schema(example = "null", description = "") + @get:JsonProperty("code") val code: kotlin.Int? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("type") val type: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("message") val message: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Order.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Order.kt new file mode 100644 index 000000000000..1ffd604abebd --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Order.kt @@ -0,0 +1,59 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * An order for a pets from the pet store + * @param id + * @param petId + * @param quantity + * @param shipDate + * @param status Order Status + * @param complete + */ +data class Order( + + @Schema(example = "null", description = "") + @get:JsonProperty("id") val id: kotlin.Long? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("petId") val petId: kotlin.Long? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("quantity") val quantity: kotlin.Int? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("shipDate") val shipDate: java.time.OffsetDateTime? = null, + + @Schema(example = "null", description = "Order Status") + @get:JsonProperty("status") val status: Order.Status? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("complete") val complete: kotlin.Boolean? = false +) { + + /** + * Order Status + * Values: placed,approved,delivered + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("placed") placed("placed"), + @JsonProperty("approved") approved("approved"), + @JsonProperty("delivered") delivered("delivered") + } + +} + diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Pet.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Pet.kt new file mode 100644 index 000000000000..267ba7c318f9 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Pet.kt @@ -0,0 +1,63 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import com.fasterxml.jackson.annotation.JsonValue +import org.openapitools.model.Category +import org.openapitools.model.Tag +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * A pet for sale in the pet store + * @param name + * @param photoUrls + * @param id + * @param category + * @param tags + * @param status pet status in the store + */ +data class Pet( + + @Schema(example = "doggie", required = true, description = "") + @get:JsonProperty("name", required = true) val name: kotlin.String, + + @Schema(example = "null", required = true, description = "") + @get:JsonProperty("photoUrls", required = true) val photoUrls: kotlin.collections.List, + + @Schema(example = "null", description = "") + @get:JsonProperty("id") val id: kotlin.Long? = null, + + @field:Valid + @Schema(example = "null", description = "") + @get:JsonProperty("category") val category: Category? = null, + + @field:Valid + @Schema(example = "null", description = "") + @get:JsonProperty("tags") val tags: kotlin.collections.List? = null, + + @Schema(example = "null", description = "pet status in the store") + @get:JsonProperty("status") val status: Pet.Status? = null +) { + + /** + * pet status in the store + * Values: available,pending,sold + */ + enum class Status(val value: kotlin.String) { + + @JsonProperty("available") available("available"), + @JsonProperty("pending") pending("pending"), + @JsonProperty("sold") sold("sold") + } + +} + diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Tag.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Tag.kt new file mode 100644 index 000000000000..a4357f8358e3 --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/Tag.kt @@ -0,0 +1,31 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * A tag for a pet + * @param id + * @param name + */ +data class Tag( + + @Schema(example = "null", description = "") + @get:JsonProperty("id") val id: kotlin.Long? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("name") val name: kotlin.String? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/User.kt b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/User.kt new file mode 100644 index 000000000000..74a1c1056afc --- /dev/null +++ b/samples/server/petstore/kotlin-springboot-request/src/main/kotlin/org/openapitools/model/User.kt @@ -0,0 +1,55 @@ +package org.openapitools.model + +import java.util.Objects +import com.fasterxml.jackson.annotation.JsonProperty +import jakarta.validation.constraints.DecimalMax +import jakarta.validation.constraints.DecimalMin +import jakarta.validation.constraints.Email +import jakarta.validation.constraints.Max +import jakarta.validation.constraints.Min +import jakarta.validation.constraints.NotNull +import jakarta.validation.constraints.Pattern +import jakarta.validation.constraints.Size +import jakarta.validation.Valid +import io.swagger.v3.oas.annotations.media.Schema + +/** + * A User who is purchasing from the pet store + * @param id + * @param username + * @param firstName + * @param lastName + * @param email + * @param password + * @param phone + * @param userStatus User Status + */ +data class User( + + @Schema(example = "null", description = "") + @get:JsonProperty("id") val id: kotlin.Long? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("username") val username: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("firstName") val firstName: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("lastName") val lastName: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("email") val email: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("password") val password: kotlin.String? = null, + + @Schema(example = "null", description = "") + @get:JsonProperty("phone") val phone: kotlin.String? = null, + + @Schema(example = "null", description = "User Status") + @get:JsonProperty("userStatus") val userStatus: kotlin.Int? = null +) { + +} + diff --git a/samples/server/petstore/kotlin-springboot-source-swagger1/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-source-swagger1/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-source-swagger1/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-source-swagger1/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-source-swagger2/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-source-swagger2/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-source-swagger2/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-source-swagger2/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot-springfox/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot-springfox/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot-springfox/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot-springfox/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-springboot/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-vertx-modelMutable/.openapi-generator/VERSION b/samples/server/petstore/kotlin-vertx-modelMutable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin-vertx-modelMutable/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin-vertx-modelMutable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt index 644fc1cee83a..05ca5658f485 100644 --- a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt @@ -20,7 +20,7 @@ import org.openapitools.server.api.model.ModelApiResponse import org.openapitools.server.api.model.Pet class PetApiVertxProxyHandler(private val vertx: Vertx, private val service: PetApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt index 985b9249f56d..a43d60b0619e 100644 --- a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt @@ -19,7 +19,7 @@ import com.google.gson.Gson import org.openapitools.server.api.model.Order class StoreApiVertxProxyHandler(private val vertx: Vertx, private val service: StoreApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt index beee4405bee1..4ed3ed309b5c 100644 --- a/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin-vertx-modelMutable/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt @@ -19,7 +19,7 @@ import com.google.gson.Gson import org.openapitools.server.api.model.User class UserApiVertxProxyHandler(private val vertx: Vertx, private val service: UserApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/kotlin/vertx/.openapi-generator/VERSION b/samples/server/petstore/kotlin/vertx/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/kotlin/vertx/.openapi-generator/VERSION +++ b/samples/server/petstore/kotlin/vertx/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt index 644fc1cee83a..05ca5658f485 100644 --- a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/PetApiVertxProxyHandler.kt @@ -20,7 +20,7 @@ import org.openapitools.server.api.model.ModelApiResponse import org.openapitools.server.api.model.Pet class PetApiVertxProxyHandler(private val vertx: Vertx, private val service: PetApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt index 985b9249f56d..a43d60b0619e 100644 --- a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/StoreApiVertxProxyHandler.kt @@ -19,7 +19,7 @@ import com.google.gson.Gson import org.openapitools.server.api.model.Order class StoreApiVertxProxyHandler(private val vertx: Vertx, private val service: StoreApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt index beee4405bee1..4ed3ed309b5c 100644 --- a/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt +++ b/samples/server/petstore/kotlin/vertx/src/main/kotlin/org/openapitools/server/api/verticle/UserApiVertxProxyHandler.kt @@ -19,7 +19,7 @@ import com.google.gson.Gson import org.openapitools.server.api.model.User class UserApiVertxProxyHandler(private val vertx: Vertx, private val service: UserApi, topLevel: Boolean, private val timeoutSeconds: Long) : ProxyHandler() { - private val timerID: Long + private lateinit var timerID: Long private var lastAccessed: Long = 0 init { try { diff --git a/samples/server/petstore/php-laravel/.openapi-generator/VERSION b/samples/server/petstore/php-laravel/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-laravel/.openapi-generator/VERSION +++ b/samples/server/petstore/php-laravel/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php b/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php index 274d5c8d24c6..39ba64eab6c5 100644 --- a/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php +++ b/samples/server/petstore/php-laravel/lib/app/Http/Controllers/FakeController.php @@ -249,6 +249,30 @@ public function fakeBigDecimalMap() return response('How about implementing fakeBigDecimalMap as a get method ?'); } + /** + * Operation testAdditionalPropertiesReference + * + * test referenced additionalProperties. + * + * + * @return Http response + */ + public function testAdditionalPropertiesReference() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['requestBody'])) { + throw new \InvalidArgumentException('Missing the required parameter $requestBody when calling testAdditionalPropertiesReference'); + } + $requestBody = $input['requestBody']; + + + return response('How about implementing testAdditionalPropertiesReference as a post method ?'); + } /** * Operation testBodyWithBinary * diff --git a/samples/server/petstore/php-laravel/lib/routes/api.php b/samples/server/petstore/php-laravel/lib/routes/api.php index 421e91bff1b0..6dfbb686cec3 100644 --- a/samples/server/petstore/php-laravel/lib/routes/api.php +++ b/samples/server/petstore/php-laravel/lib/routes/api.php @@ -70,6 +70,13 @@ * Output-Formats: [*_/_*] */ Route::get('/v2/fake/BigDecimalMap', 'FakeController@fakeBigDecimalMap'); +/** + * post testAdditionalPropertiesReference + * Summary: test referenced additionalProperties + * Notes: + + */ +Route::post('/v2/fake/additionalProperties-reference', 'FakeController@testAdditionalPropertiesReference'); /** * put testBodyWithBinary * Summary: diff --git a/samples/server/petstore/php-lumen/.openapi-generator/VERSION b/samples/server/petstore/php-lumen/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-lumen/.openapi-generator/VERSION +++ b/samples/server/petstore/php-lumen/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php b/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php index 44c5191fc3da..f1e0ec001d65 100644 --- a/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php +++ b/samples/server/petstore/php-lumen/lib/app/Http/Controllers/FakeApi.php @@ -245,6 +245,30 @@ public function fakeBigDecimalMap() return response('How about implementing fakeBigDecimalMap as a get method ?'); } + /** + * Operation testAdditionalPropertiesReference + * + * test referenced additionalProperties. + * + * + * @return Http response + */ + public function testAdditionalPropertiesReference() + { + $input = Request::all(); + + //path params validation + + + //not path params validation + if (!isset($input['request_body'])) { + throw new \InvalidArgumentException('Missing the required parameter $request_body when calling testAdditionalPropertiesReference'); + } + $request_body = $input['request_body']; + + + return response('How about implementing testAdditionalPropertiesReference as a post method ?'); + } /** * Operation testBodyWithBinary * diff --git a/samples/server/petstore/php-lumen/lib/routes/web.php b/samples/server/petstore/php-lumen/lib/routes/web.php index 36105116319c..59762b6f3810 100644 --- a/samples/server/petstore/php-lumen/lib/routes/web.php +++ b/samples/server/petstore/php-lumen/lib/routes/web.php @@ -86,6 +86,13 @@ */ $router->get('/v2/fake/BigDecimalMap', 'FakeApi@fakeBigDecimalMap'); +/** + * post testAdditionalPropertiesReference + * Summary: test referenced additionalProperties + * Notes: + */ +$router->post('/v2/fake/additionalProperties-reference', 'FakeApi@testAdditionalPropertiesReference'); + /** * put testBodyWithBinary * Summary: diff --git a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION +++ b/samples/server/petstore/php-mezzio-ph-modern/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION +++ b/samples/server/petstore/php-mezzio-ph/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-slim4/.openapi-generator/VERSION b/samples/server/petstore/php-slim4/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-slim4/.openapi-generator/VERSION +++ b/samples/server/petstore/php-slim4/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php index fa0f0bcb450e..9e2c11d8a838 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/PetApiInterface.php @@ -73,8 +73,11 @@ public function setapi_key(?string $value): void; * * @return array|object|null */ - public function addPet(Pet $pet, int &$responseCode, array &$responseHeaders): array|object|null; - + public function addPet( + Pet $pet, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation deletePet @@ -88,8 +91,12 @@ public function addPet(Pet $pet, int &$responseCode, array &$responseHeaders): a * * @return void */ - public function deletePet(int $petId, ?string $apiKey, int &$responseCode, array &$responseHeaders): void; - + public function deletePet( + int $petId, + ?string $apiKey, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation findPetsByStatus @@ -102,8 +109,11 @@ public function deletePet(int $petId, ?string $apiKey, int &$responseCode, array * * @return array|object|null */ - public function findPetsByStatus(array $status, int &$responseCode, array &$responseHeaders): array|object|null; - + public function findPetsByStatus( + array $status, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation findPetsByTags @@ -117,8 +127,11 @@ public function findPetsByStatus(array $status, int &$responseCode, array &$resp * @return array|object|null * @deprecated */ - public function findPetsByTags(array $tags, int &$responseCode, array &$responseHeaders): array|object|null; - + public function findPetsByTags( + array $tags, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation getPetById @@ -131,8 +144,11 @@ public function findPetsByTags(array $tags, int &$responseCode, array &$response * * @return array|object|null */ - public function getPetById(int $petId, int &$responseCode, array &$responseHeaders): array|object|null; - + public function getPetById( + int $petId, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation updatePet @@ -145,8 +161,11 @@ public function getPetById(int $petId, int &$responseCode, array &$responseHeade * * @return array|object|null */ - public function updatePet(Pet $pet, int &$responseCode, array &$responseHeaders): array|object|null; - + public function updatePet( + Pet $pet, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation updatePetWithForm @@ -161,8 +180,13 @@ public function updatePet(Pet $pet, int &$responseCode, array &$responseHeaders) * * @return void */ - public function updatePetWithForm(int $petId, ?string $name, ?string $status, int &$responseCode, array &$responseHeaders): void; - + public function updatePetWithForm( + int $petId, + ?string $name, + ?string $status, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation uploadFile @@ -177,6 +201,11 @@ public function updatePetWithForm(int $petId, ?string $name, ?string $status, in * * @return array|object|null */ - public function uploadFile(int $petId, ?string $additionalMetadata, ?UploadedFile $file, int &$responseCode, array &$responseHeaders): array|object|null; - + public function uploadFile( + int $petId, + ?string $additionalMetadata, + ?UploadedFile $file, + int &$responseCode, + array &$responseHeaders + ): array|object|null; } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php index 89dc4a72a9e8..097275dc0a48 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/StoreApiInterface.php @@ -63,8 +63,11 @@ public function setapi_key(?string $value): void; * * @return void */ - public function deleteOrder(string $orderId, int &$responseCode, array &$responseHeaders): void; - + public function deleteOrder( + string $orderId, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation getInventory @@ -76,8 +79,10 @@ public function deleteOrder(string $orderId, int &$responseCode, array &$respons * * @return array|object|null */ - public function getInventory(int &$responseCode, array &$responseHeaders): array|object|null; - + public function getInventory( + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation getOrderById @@ -90,8 +95,11 @@ public function getInventory(int &$responseCode, array &$responseHeaders): array * * @return array|object|null */ - public function getOrderById(int $orderId, int &$responseCode, array &$responseHeaders): array|object|null; - + public function getOrderById( + int $orderId, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation placeOrder @@ -104,6 +112,9 @@ public function getOrderById(int $orderId, int &$responseCode, array &$responseH * * @return array|object|null */ - public function placeOrder(Order $order, int &$responseCode, array &$responseHeaders): array|object|null; - + public function placeOrder( + Order $order, + int &$responseCode, + array &$responseHeaders + ): array|object|null; } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php index df557493614a..f98deb9fd07d 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Api/UserApiInterface.php @@ -63,8 +63,11 @@ public function setapi_key(?string $value): void; * * @return void */ - public function createUser(User $user, int &$responseCode, array &$responseHeaders): void; - + public function createUser( + User $user, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation createUsersWithArrayInput @@ -77,8 +80,11 @@ public function createUser(User $user, int &$responseCode, array &$responseHeade * * @return void */ - public function createUsersWithArrayInput(array $user, int &$responseCode, array &$responseHeaders): void; - + public function createUsersWithArrayInput( + array $user, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation createUsersWithListInput @@ -91,8 +97,11 @@ public function createUsersWithArrayInput(array $user, int &$responseCode, array * * @return void */ - public function createUsersWithListInput(array $user, int &$responseCode, array &$responseHeaders): void; - + public function createUsersWithListInput( + array $user, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation deleteUser @@ -105,8 +114,11 @@ public function createUsersWithListInput(array $user, int &$responseCode, array * * @return void */ - public function deleteUser(string $username, int &$responseCode, array &$responseHeaders): void; - + public function deleteUser( + string $username, + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation getUserByName @@ -119,8 +131,11 @@ public function deleteUser(string $username, int &$responseCode, array &$respons * * @return array|object|null */ - public function getUserByName(string $username, int &$responseCode, array &$responseHeaders): array|object|null; - + public function getUserByName( + string $username, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation loginUser @@ -134,8 +149,12 @@ public function getUserByName(string $username, int &$responseCode, array &$resp * * @return array|object|null */ - public function loginUser(string $username, string $password, int &$responseCode, array &$responseHeaders): array|object|null; - + public function loginUser( + string $username, + string $password, + int &$responseCode, + array &$responseHeaders + ): array|object|null; /** * Operation logoutUser @@ -147,8 +166,10 @@ public function loginUser(string $username, string $password, int &$responseCode * * @return void */ - public function logoutUser(int &$responseCode, array &$responseHeaders): void; - + public function logoutUser( + int &$responseCode, + array &$responseHeaders + ): void; /** * Operation updateUser @@ -162,6 +183,10 @@ public function logoutUser(int &$responseCode, array &$responseHeaders): void; * * @return void */ - public function updateUser(string $username, User $user, int &$responseCode, array &$responseHeaders): void; - + public function updateUser( + string $username, + User $user, + int &$responseCode, + array &$responseHeaders + ): void; } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php index 218d4f85afb4..69f4ccd2777a 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/ApiResponse.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -91,6 +92,8 @@ public function getCode(): ?int return $this->code; } + + /** * Sets code. * @@ -115,6 +118,8 @@ public function getType(): ?string return $this->type; } + + /** * Sets type. * @@ -139,6 +144,8 @@ public function getMessage(): ?string return $this->message; } + + /** * Sets message. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php index 2ea80a897b63..8cecd5ca1a65 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Category.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -83,6 +84,8 @@ public function getId(): ?int return $this->id; } + + /** * Sets id. * @@ -107,6 +110,8 @@ public function getName(): ?string return $this->name; } + + /** * Sets name. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/EnumStringModel.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/EnumStringModel.php index d637e27af2fb..5cf945fa9b0f 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/EnumStringModel.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/EnumStringModel.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -41,27 +42,11 @@ * @package OpenAPI\Server\Model * @author OpenAPI Generator team */ -class EnumStringModel +enum EnumStringModel: string { - /** - * Possible values of this enum - */ - const AVAILABLE = "available"; - const PENDING = "pending"; - const SOLD = "sold"; - - /** - * Gets allowable values of the enum - * @return string[] - */ - public static function getAllowableEnumValues() - { - return [ - self::AVAILABLE, - self::PENDING, - self::SOLD, - ]; - } + case AVAILABLE = "available"; + case PENDING = "pending"; + case SOLD = "sold"; } diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php index d902d49a2ab3..ae3f8fb0c5d5 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Order.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -71,7 +72,7 @@ class Order /** * @var \DateTime|null * @SerializedName("shipDate") - * @Assert\DateTime() + * @Assert\Type("\DateTime")) * @Type("DateTime") */ protected ?\DateTime $shipDate = null; @@ -121,6 +122,8 @@ public function getId(): ?int return $this->id; } + + /** * Sets id. * @@ -145,6 +148,8 @@ public function getPetId(): ?int return $this->petId; } + + /** * Sets petId. * @@ -169,6 +174,8 @@ public function getQuantity(): ?int return $this->quantity; } + + /** * Sets quantity. * @@ -193,6 +200,8 @@ public function getShipDate(): ?\DateTime return $this->shipDate; } + + /** * Sets shipDate. * @@ -217,6 +226,8 @@ public function getStatus(): ?string return $this->status; } + + /** * Sets status. * @@ -241,6 +252,8 @@ public function isComplete(): ?bool return $this->complete; } + + /** * Sets complete. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php index 0ba0114642f6..2225627acf2c 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Pet.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -70,7 +71,7 @@ class Pet protected ?string $name = null; /** - * @var array|null + * @var string[]|null * @SerializedName("photoUrls") * @Assert\NotNull() * @Assert\All({ @@ -81,7 +82,7 @@ class Pet protected ?array $photoUrls = null; /** - * @var array|null + * @var Tag[]|null * @SerializedName("tags") * @Assert\All({ * @Assert\Type("OpenAPI\Server\Model\Tag") @@ -127,6 +128,8 @@ public function getId(): ?int return $this->id; } + + /** * Sets id. * @@ -151,6 +154,8 @@ public function getCategory(): ?Category return $this->category; } + + /** * Sets category. * @@ -175,6 +180,8 @@ public function getName(): ?string return $this->name; } + + /** * Sets name. * @@ -192,17 +199,19 @@ public function setName(?string $name): self /** * Gets photoUrls. * - * @return array|null + * @return string[]|null */ public function getPhotoUrls(): ?array { return $this->photoUrls; } + + /** * Sets photoUrls. * - * @param array|null $photoUrls + * @param string[]|null $photoUrls * * @return $this */ @@ -216,17 +225,19 @@ public function setPhotoUrls(?array $photoUrls): self /** * Gets tags. * - * @return array|null + * @return Tag[]|null */ public function getTags(): ?array { return $this->tags; } + + /** * Sets tags. * - * @param array|null $tags + * @param Tag[]|null $tags * * @return $this */ @@ -247,6 +258,8 @@ public function getStatus(): ?string return $this->status; } + + /** * Sets status. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php index 08f6550d182a..5c242dff5370 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/Tag.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -82,6 +83,8 @@ public function getId(): ?int return $this->id; } + + /** * Sets id. * @@ -106,6 +109,8 @@ public function getName(): ?string return $this->name; } + + /** * Sets name. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php index 129657df957c..db11613de25e 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Model/User.php @@ -31,6 +31,7 @@ use Symfony\Component\Validator\Constraints as Assert; use JMS\Serializer\Annotation\Type; +use JMS\Serializer\Annotation\Accessor; use JMS\Serializer\Annotation\SerializedName; /** @@ -138,6 +139,8 @@ public function getId(): ?int return $this->id; } + + /** * Sets id. * @@ -162,6 +165,8 @@ public function getUsername(): ?string return $this->username; } + + /** * Sets username. * @@ -186,6 +191,8 @@ public function getFirstName(): ?string return $this->firstName; } + + /** * Sets firstName. * @@ -210,6 +217,8 @@ public function getLastName(): ?string return $this->lastName; } + + /** * Sets lastName. * @@ -234,6 +243,8 @@ public function getEmail(): ?string return $this->email; } + + /** * Sets email. * @@ -258,6 +269,8 @@ public function getPassword(): ?string return $this->password; } + + /** * Sets password. * @@ -282,6 +295,8 @@ public function getPhone(): ?string return $this->phone; } + + /** * Sets phone. * @@ -306,6 +321,8 @@ public function getUserStatus(): ?int return $this->userStatus; } + + /** * Sets userStatus. * diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/JmsSerializer.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/JmsSerializer.php index 379e7faf32a4..34a16b5e7346 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/JmsSerializer.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/JmsSerializer.php @@ -60,7 +60,7 @@ private function convertFormat(string $format): ?string private function deserializeString($data, string $type) { // Figure out if we have an array format - if (1 === preg_match('/array<(csv|ssv|tsv|pipes),(int|string)>/i', $type, $matches)) { + if (1 === preg_match('/array<(csv|ssv|tsv|pipes),(.*)>/i', $type, $matches)) { return $this->deserializeArrayString($matches[1], $matches[2], $data); } @@ -75,6 +75,13 @@ private function deserializeString($data, string $type) return $data + 0; } + break; + case 'double': + case 'float': + if (is_float($data) || is_numeric($data)) { + return (float) $data; + } + break; case 'string': break; @@ -97,7 +104,21 @@ private function deserializeString($data, string $type) case '\DateTime': return is_null($data) ? null :new DateTime($data); default: - throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + if (!class_exists($type)) { + throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + } + + $reflectionClass = new \ReflectionClass($type); + if (!$reflectionClass->implementsInterface('\BackedENum')) { + throw new RuntimeException(sprintf("Type %s is unsupported", $type)); + } + + $enum = $type::tryFrom($data); + if (!$enum) { + throw new RuntimeException(sprintf("Unknown %s value in %s enum", $data, $type)); + } + + return $enum; } // If we end up here, just return data diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php index 5f6b18b59981..4893720e7d11 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Service/SerializerInterface.php @@ -12,7 +12,7 @@ interface SerializerInterface * * @return string */ - public function serialize($data, string $format): string; + public function serialize($data, string $format): string; /** * Deserializes the given data to the specified type. diff --git a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/EnumStringModelTest.php b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/EnumStringModelTest.php index bfaca490cbcd..8ad6dd1b945c 100644 --- a/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/EnumStringModelTest.php +++ b/samples/server/petstore/php-symfony/SymfonyBundle-php/Tests/Model/EnumStringModelTest.php @@ -27,8 +27,9 @@ * Please update the test case below to test the model. */ -namespace OpenAPI\Server\Model; +namespace OpenAPI\Server\Tests\Model; +use OpenAPI\Server\Model\EnumStringModel; use PHPUnit\Framework\MockObject\MockObject; use PHPUnit\Framework\TestCase; @@ -58,7 +59,6 @@ public static function setUpBeforeClass(): void */ public function setUp(): void { - $this->object = $this->getMockBuilder(EnumStringModel::class)->getMockForAbstractClass(); } /** @@ -81,7 +81,6 @@ public static function tearDownAfterClass(): void */ public function testTestClassExists(): void { - $this->assertTrue(class_exists(EnumStringModel::class)); - $this->assertInstanceOf(EnumStringModel::class, $this->object); + $this->assertTrue(enum_exists(EnumStringModel::class)); } } diff --git a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION +++ b/samples/server/petstore/python-aiohttp-srclayout/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-aiohttp-srclayout/requirements.txt b/samples/server/petstore/python-aiohttp-srclayout/requirements.txt index 70c264978d3b..aaaaeb756eac 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/requirements.txt +++ b/samples/server/petstore/python-aiohttp-srclayout/requirements.txt @@ -1,4 +1,4 @@ -connexion[aiohttp,swagger-ui] >= 2.6.0; python_version>="3.6" +connexion[aiohttp,swagger-ui] >= 2.6.0, <3; python_version>="3.6" # 2.3 is the last version that supports python 3.5 connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version=="3.4" # connexion requires werkzeug but connexion < 2.4.0 does not install werkzeug @@ -7,3 +7,4 @@ connexion[aiohttp,swagger-ui] <= 2.3.0; python_version=="3.5" or python_version= werkzeug == 0.16.1; python_version=="3.5" or python_version=="3.4" swagger-ui-bundle == 0.0.9 aiohttp_jinja2 == 1.5.0 +Flask < 2.3 \ No newline at end of file diff --git a/samples/server/petstore/python-aiohttp-srclayout/test_python3.sh b/samples/server/petstore/python-aiohttp-srclayout/test_python3.sh index 43fab931f00f..95b8f7173f00 100755 --- a/samples/server/petstore/python-aiohttp-srclayout/test_python3.sh +++ b/samples/server/petstore/python-aiohttp-srclayout/test_python3.sh @@ -23,7 +23,7 @@ pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT tox || exit 1 ### static analysis of code -flake8 --show-source petstore_api/ +flake8 --show-source ./src ### deactivate virtualenv if [ $DEACTIVE == true ]; then diff --git a/samples/server/petstore/python-aiohttp-srclayout/tests/test_pet_controller.py b/samples/server/petstore/python-aiohttp-srclayout/tests/test_pet_controller.py index 3cac35cc24cb..898181839f42 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/tests/test_pet_controller.py +++ b/samples/server/petstore/python-aiohttp-srclayout/tests/test_pet_controller.py @@ -8,6 +8,7 @@ from openapi_server.models.api_response import ApiResponse from openapi_server.models.pet import Pet +pytestmark = pytest.mark.asyncio @pytest.mark.skip("Connexion does not support multiple consumes. See https://github.com/zalando/connexion/pull/760") async def test_add_pet(client): diff --git a/samples/server/petstore/python-aiohttp-srclayout/tests/test_store_controller.py b/samples/server/petstore/python-aiohttp-srclayout/tests/test_store_controller.py index 9d376a5f7a5b..9cbe796815f9 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/tests/test_store_controller.py +++ b/samples/server/petstore/python-aiohttp-srclayout/tests/test_store_controller.py @@ -6,6 +6,7 @@ from openapi_server.models.order import Order +pytestmark = pytest.mark.asyncio async def test_delete_order(client): """Test case for delete_order diff --git a/samples/server/petstore/python-aiohttp-srclayout/tests/test_user_controller.py b/samples/server/petstore/python-aiohttp-srclayout/tests/test_user_controller.py index 6564329315ed..ae97db8ea413 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/tests/test_user_controller.py +++ b/samples/server/petstore/python-aiohttp-srclayout/tests/test_user_controller.py @@ -6,6 +6,7 @@ from openapi_server.models.user import User +pytestmark = pytest.mark.asyncio @pytest.mark.skip("*/* not supported by Connexion. Use application/json instead. See https://github.com/zalando/connexion/pull/760") async def test_create_user(client): diff --git a/samples/server/petstore/python-aiohttp-srclayout/tox.ini b/samples/server/petstore/python-aiohttp-srclayout/tox.ini index 25d12bb84c0b..7663dfb69e41 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/tox.ini +++ b/samples/server/petstore/python-aiohttp-srclayout/tox.ini @@ -5,7 +5,7 @@ skipsdist=True [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - {toxinidir} + {toxinidir} commands= - pytest --cov=src/openapi_server + pytest --cov=openapi_server diff --git a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION +++ b/samples/server/petstore/python-blueplanet/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/.openapi-generator/VERSION b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/python-fastapi/.openapi-generator/VERSION +++ b/samples/server/petstore/python-fastapi/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-fastapi/openapi.yaml b/samples/server/petstore/python-fastapi/openapi.yaml index 2c6ca420c6a1..1fe20cb00076 100644 --- a/samples/server/petstore/python-fastapi/openapi.yaml +++ b/samples/server/petstore/python-fastapi/openapi.yaml @@ -590,7 +590,7 @@ paths: - description: has default value explode: true in: query - name: has_default + name: hasDefault required: false schema: default: Hello World @@ -599,7 +599,7 @@ paths: - description: no default value explode: true in: query - name: no_default + name: noDefault required: false schema: type: string diff --git a/samples/server/petstore/python-fastapi/pom.xml b/samples/server/petstore/python-fastapi/pom.xml deleted file mode 100644 index cec32c1dc9ac..000000000000 --- a/samples/server/petstore/python-fastapi/pom.xml +++ /dev/null @@ -1,40 +0,0 @@ - - 4.0.0 - org.openapitools - PythonFastAPITests - pom - 1.0-SNAPSHOT - Python FastAPI Server - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - com.spotify - dockerfile-maven-plugin - 1.4.13 - - - test - integration-test - - build - - - - - - - diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/fake_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/fake_api.py index c255fa4774a6..eb90fbbfbb02 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/fake_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/fake_api.py @@ -42,8 +42,8 @@ response_model_by_alias=True, ) async def fake_query_param_default( - has_default: str = Query('Hello World', description="has default value"), - no_default: str = Query(None, description="no default value"), + has_default: str = Query('Hello World', description="has default value", alias="hasDefault"), + no_default: str = Query(None, description="no default value", alias="noDefault"), ) -> None: """""" return BaseFakeApi.subclasses[0]().fake_query_param_default(has_default, no_default) diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py index e07db9a7cc95..cf8ada786d1e 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/pet_api.py @@ -84,7 +84,7 @@ async def delete_pet( response_model_by_alias=True, ) async def find_pets_by_status( - status: List[str] = Query(None, description="Status values that need to be considered for filter"), + status: List[str] = Query(None, description="Status values that need to be considered for filter", alias="status"), token_petstore_auth: TokenModel = Security( get_token_petstore_auth, scopes=["read:pets"] ), @@ -104,7 +104,7 @@ async def find_pets_by_status( response_model_by_alias=True, ) async def find_pets_by_tags( - tags: List[str] = Query(None, description="Tags to filter by"), + tags: List[str] = Query(None, description="Tags to filter by", alias="tags"), token_petstore_auth: TokenModel = Security( get_token_petstore_auth, scopes=["read:pets"] ), diff --git a/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py index 324251767e1e..e57b899c69b6 100644 --- a/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py +++ b/samples/server/petstore/python-fastapi/src/openapi_server/apis/user_api.py @@ -138,8 +138,8 @@ async def get_user_by_name( response_model_by_alias=True, ) async def login_user( - username: str = Query(None, description="The user name for login", regex=r"/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/"), - password: str = Query(None, description="The password for login in clear text"), + username: str = Query(None, description="The user name for login", alias="username", regex=r"/^[a-zA-Z0-9]+[a-zA-Z0-9\.\-_]*[a-zA-Z0-9]+$/"), + password: str = Query(None, description="The password for login in clear text", alias="password"), ) -> str: """""" return BaseUserApi.subclasses[0]().login_user(username, password) diff --git a/samples/server/petstore/python-flask/.openapi-generator/VERSION b/samples/server/petstore/python-flask/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/python-flask/.openapi-generator/VERSION +++ b/samples/server/petstore/python-flask/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/python-flask/Makefile b/samples/server/petstore/python-flask/Makefile deleted file mode 100644 index b32712ef06c3..000000000000 --- a/samples/server/petstore/python-flask/Makefile +++ /dev/null @@ -1,20 +0,0 @@ - #!/bin/bash - -REQUIREMENTS_OUT=test-requirements.txt.log -SETUP_OUT=*.egg-info -VENV=.venv - -clean: - rm -rf $(REQUIREMENTS_OUT) - rm -rf $(SETUP_OUT) - rm -rf $(VENV) - rm -rf .tox - rm -rf .coverage - find . -name "*.py[oc]" -delete - find . -name "__pycache__" -delete - -test: clean - bash ./test_python3.sh - -test-all: clean - bash ./test_python3.sh diff --git a/samples/server/petstore/python-flask/dev-requirements.txt b/samples/server/petstore/python-flask/dev-requirements.txt deleted file mode 100644 index ccdfca629494..000000000000 --- a/samples/server/petstore/python-flask/dev-requirements.txt +++ /dev/null @@ -1,2 +0,0 @@ -tox -flake8 diff --git a/samples/server/petstore/python-flask/pom.xml b/samples/server/petstore/python-flask/pom.xml deleted file mode 100644 index 542458a0e48f..000000000000 --- a/samples/server/petstore/python-flask/pom.xml +++ /dev/null @@ -1,46 +0,0 @@ - - 4.0.0 - org.openapitools - PythonFlaskConnexionTests - pom - 1.0-SNAPSHOT - Python Flask Server - - - - maven-dependency-plugin - - - package - - copy-dependencies - - - ${project.build.directory} - - - - - - org.codehaus.mojo - exec-maven-plugin - 1.2.1 - - - test - integration-test - - exec - - - make - - test-all - - - - - - - - diff --git a/samples/server/petstore/python-flask/test_python3.sh b/samples/server/petstore/python-flask/test_python3.sh deleted file mode 100755 index add0ff0c4f21..000000000000 --- a/samples/server/petstore/python-flask/test_python3.sh +++ /dev/null @@ -1,31 +0,0 @@ -#!/bin/bash - -REQUIREMENTS_FILE=dev-requirements.txt -REQUIREMENTS_OUT=dev-requirements.txt.log -SETUP_OUT=*.egg-info -VENV=.venv -DEACTIVE=false - -export LC_ALL=en_US.UTF-8 -export LANG=en_US.UTF-8 - -### set virtualenv -if [ -z "$VIRTUAL_ENV" ]; then - virtualenv $VENV --always-copy --python python3 - source $VENV/bin/activate - DEACTIVE=true -fi - -### install dependencies -pip install -r $REQUIREMENTS_FILE | tee -a $REQUIREMENTS_OUT - -### run tests -tox || exit 1 - -### static analysis of code -#flake8 --show-source openapi_server/ - -### deactivate virtualenv -# if [ $DEACTIVE == true ]; then -# deactivate -# fi diff --git a/samples/server/petstore/python-flask/tox.ini b/samples/server/petstore/python-flask/tox.ini index f66b2d84cdaa..7663dfb69e41 100644 --- a/samples/server/petstore/python-flask/tox.ini +++ b/samples/server/petstore/python-flask/tox.ini @@ -5,7 +5,7 @@ skipsdist=True [testenv] deps=-r{toxinidir}/requirements.txt -r{toxinidir}/test-requirements.txt - {toxinidir} + {toxinidir} commands= pytest --cov=openapi_server diff --git a/samples/server/petstore/rust-axum/.gitignore b/samples/server/petstore/rust-axum/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/Cargo.toml b/samples/server/petstore/rust-axum/Cargo.toml new file mode 100644 index 000000000000..c086d1f01388 --- /dev/null +++ b/samples/server/petstore/rust-axum/Cargo.toml @@ -0,0 +1,3 @@ +[workspace] +members = ["output/*"] +resolver = "2" diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/.gitignore b/samples/server/petstore/rust-axum/output/multipart-v3/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/Cargo.toml b/samples/server/petstore/rust-axum/output/multipart-v3/Cargo.toml new file mode 100644 index 000000000000..9b554d7ce5fc --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "multipart-v3" +version = "1.0.7" +authors = ["OpenAPI Generator team and contributors"] +description = "API under test" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/README.md b/samples/server/petstore/rust-axum/output/multipart-v3/README.md new file mode 100644 index 000000000000..d7e08f99cb3d --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/README.md @@ -0,0 +1,91 @@ +# Rust API for multipart-v3 + +API under test + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 1.0.7 + + + + +This autogenerated project defines an API crate `multipart-v3` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl multipart-v3::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = multipart-v3::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/src/header.rs b/samples/server/petstore/rust-axum/output/multipart-v3/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/src/lib.rs b/samples/server/petstore/rust-axum/output/multipart-v3/src/lib.rs new file mode 100644 index 000000000000..f0c2fbe49bcb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/src/lib.rs @@ -0,0 +1,85 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0.7"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MultipartRelatedRequestPostResponse { + /// OK + Status201_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MultipartRequestPostResponse { + /// OK + Status201_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MultipleIdenticalMimeTypesPostResponse { + /// OK + Status200_OK +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// MultipartRelatedRequestPost - POST /multipart_related_request + async fn multipart_related_request_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: axum::body::Body, + ) -> Result; + + + /// MultipartRequestPost - POST /multipart_request + async fn multipart_request_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Multipart, + ) -> Result; + + + /// MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types + async fn multiple_identical_mime_types_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: axum::body::Body, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/src/models.rs b/samples/server/petstore/rust-axum/output/multipart-v3/src/models.rs new file mode 100644 index 000000000000..6ccb7d3f84d1 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/src/models.rs @@ -0,0 +1,431 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MultipartRelatedRequest { + #[serde(rename = "object_field")] + #[serde(skip_serializing_if="Option::is_none")] + pub object_field: Option, + + #[serde(rename = "optional_binary_field")] + #[serde(skip_serializing_if="Option::is_none")] + pub optional_binary_field: Option, + + #[serde(rename = "required_binary_field")] + pub required_binary_field: ByteArray, + +} + + +impl MultipartRelatedRequest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_binary_field: ByteArray, ) -> MultipartRelatedRequest { + MultipartRelatedRequest { + object_field: None, + optional_binary_field: None, + required_binary_field, + } + } +} + +/// Converts the MultipartRelatedRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MultipartRelatedRequest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping object_field in query parameter serialization + + // Skipping optional_binary_field in query parameter serialization + // Skipping optional_binary_field in query parameter serialization + + // Skipping required_binary_field in query parameter serialization + // Skipping required_binary_field in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MultipartRelatedRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MultipartRelatedRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub object_field: Vec, + pub optional_binary_field: Vec, + pub required_binary_field: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MultipartRelatedRequest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "object_field" => intermediate_rep.object_field.push(::from_str(val).map_err(|x| x.to_string())?), + "optional_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()), + "required_binary_field" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipartRelatedRequest".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing MultipartRelatedRequest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MultipartRelatedRequest { + object_field: intermediate_rep.object_field.into_iter().next(), + optional_binary_field: intermediate_rep.optional_binary_field.into_iter().next(), + required_binary_field: intermediate_rep.required_binary_field.into_iter().next().ok_or_else(|| "required_binary_field missing in MultipartRelatedRequest".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MultipartRelatedRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MultipartRelatedRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MultipartRequestObjectField { + #[serde(rename = "field_a")] + pub field_a: String, + + #[serde(rename = "field_b")] + #[serde(skip_serializing_if="Option::is_none")] + pub field_b: Option>, + +} + + +impl MultipartRequestObjectField { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(field_a: String, ) -> MultipartRequestObjectField { + MultipartRequestObjectField { + field_a, + field_b: None, + } + } +} + +/// Converts the MultipartRequestObjectField value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MultipartRequestObjectField { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("field_a".to_string()), + Some(self.field_a.to_string()), + + + self.field_b.as_ref().map(|field_b| { + [ + "field_b".to_string(), + field_b.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MultipartRequestObjectField value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MultipartRequestObjectField { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub field_a: Vec, + pub field_b: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MultipartRequestObjectField".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "field_a" => intermediate_rep.field_a.push(::from_str(val).map_err(|x| x.to_string())?), + "field_b" => return std::result::Result::Err("Parsing a container in this style is not supported in MultipartRequestObjectField".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing MultipartRequestObjectField".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MultipartRequestObjectField { + field_a: intermediate_rep.field_a.into_iter().next().ok_or_else(|| "field_a missing in MultipartRequestObjectField".to_string())?, + field_b: intermediate_rep.field_b.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MultipartRequestObjectField - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MultipartRequestObjectField - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MultipleIdenticalMimeTypesPostRequest { + #[serde(rename = "binary1")] + #[serde(skip_serializing_if="Option::is_none")] + pub binary1: Option, + + #[serde(rename = "binary2")] + #[serde(skip_serializing_if="Option::is_none")] + pub binary2: Option, + +} + + +impl MultipleIdenticalMimeTypesPostRequest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> MultipleIdenticalMimeTypesPostRequest { + MultipleIdenticalMimeTypesPostRequest { + binary1: None, + binary2: None, + } + } +} + +/// Converts the MultipleIdenticalMimeTypesPostRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MultipleIdenticalMimeTypesPostRequest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping binary1 in query parameter serialization + // Skipping binary1 in query parameter serialization + + // Skipping binary2 in query parameter serialization + // Skipping binary2 in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MultipleIdenticalMimeTypesPostRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MultipleIdenticalMimeTypesPostRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub binary1: Vec, + pub binary2: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MultipleIdenticalMimeTypesPostRequest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "binary1" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipleIdenticalMimeTypesPostRequest".to_string()), + "binary2" => return std::result::Result::Err("Parsing binary data in this style is not supported in MultipleIdenticalMimeTypesPostRequest".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing MultipleIdenticalMimeTypesPostRequest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MultipleIdenticalMimeTypesPostRequest { + binary1: intermediate_rep.binary1.into_iter().next(), + binary2: intermediate_rep.binary2.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MultipleIdenticalMimeTypesPostRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MultipleIdenticalMimeTypesPostRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/src/server/mod.rs b/samples/server/petstore/rust-axum/output/multipart-v3/src/server/mod.rs new file mode 100644 index 000000000000..a13018a64851 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/src/server/mod.rs @@ -0,0 +1,241 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + MultipartRelatedRequestPostResponse, + MultipartRequestPostResponse, + MultipleIdenticalMimeTypesPostResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/multipart_related_request", + post(multipart_related_request_post::) + ) + .route("/multipart_request", + post(multipart_request_post::) + ) + .route("/multiple-identical-mime-types", + post(multiple_identical_mime_types_post::) + ) + .with_state(api_impl) +} + + +#[tracing::instrument(skip_all)] +fn multipart_related_request_post_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MultipartRelatedRequestPost - POST /multipart_related_request +#[tracing::instrument(skip_all)] +async fn multipart_related_request_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: axum::body::Body, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + multipart_related_request_post_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().multipart_related_request_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MultipartRelatedRequestPostResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn multipart_request_post_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MultipartRequestPost - POST /multipart_request +#[tracing::instrument(skip_all)] +async fn multipart_request_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Multipart, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + multipart_request_post_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().multipart_request_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MultipartRequestPostResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn multiple_identical_mime_types_post_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MultipleIdenticalMimeTypesPost - POST /multiple-identical-mime-types +#[tracing::instrument(skip_all)] +async fn multiple_identical_mime_types_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: axum::body::Body, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + multiple_identical_mime_types_post_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().multiple_identical_mime_types_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MultipleIdenticalMimeTypesPostResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/multipart-v3/src/types.rs b/samples/server/petstore/rust-axum/output/multipart-v3/src/types.rs new file mode 100644 index 000000000000..17faecc35e63 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/multipart-v3/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use multipart_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use multipart_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use multipart_v3::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/.gitignore b/samples/server/petstore/rust-axum/output/openapi-v3/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/Cargo.toml b/samples/server/petstore/rust-axum/output/openapi-v3/Cargo.toml new file mode 100644 index 000000000000..0c2cd9740585 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "openapi-v3" +version = "1.0.7" +authors = ["OpenAPI Generator team and contributors"] +description = "API under test" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/README.md b/samples/server/petstore/rust-axum/output/openapi-v3/README.md new file mode 100644 index 000000000000..7343a6f0ef3b --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/README.md @@ -0,0 +1,91 @@ +# Rust API for openapi-v3 + +API under test + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 1.0.7 + + + + +This autogenerated project defines an API crate `openapi-v3` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl openapi-v3::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = openapi-v3::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/src/header.rs b/samples/server/petstore/rust-axum/output/openapi-v3/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/src/lib.rs b/samples/server/petstore/rust-axum/output/openapi-v3/src/lib.rs new file mode 100644 index 000000000000..b72ebe84cb8d --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/src/lib.rs @@ -0,0 +1,589 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0.7"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum AnyOfGetResponse { + /// Success + Status200_Success + (models::AnyOfObject) + , + /// AlternateSuccess + Status201_AlternateSuccess + (models::Model12345AnyOfObject) + , + /// AnyOfSuccess + Status202_AnyOfSuccess + (models::AnyOfGet202Response) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CallbackWithHeaderPostResponse { + /// OK + Status204_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum ComplexQueryParamGetResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum EnumInPathPathParamGetResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum JsonComplexQueryParamGetResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MandatoryRequestHeaderGetResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MergePatchJsonGetResponse { + /// merge-patch+json-encoded response + Status200_Merge + (models::AnotherXmlObject) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MultigetGetResponse { + /// JSON rsp + Status200_JSONRsp + (models::AnotherXmlObject) + , + /// XML rsp + Status201_XMLRsp + (String) + , + /// octet rsp + Status202_OctetRsp + (ByteArray) + , + /// string rsp + Status203_StringRsp + (String) + , + /// Duplicate Response long text. One. + Status204_DuplicateResponseLongText + (models::AnotherXmlObject) + , + /// Duplicate Response long text. Two. + Status205_DuplicateResponseLongText + (models::AnotherXmlObject) + , + /// Duplicate Response long text. Three. + Status206_DuplicateResponseLongText + (models::AnotherXmlObject) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum MultipleAuthSchemeGetResponse { + /// Check that limiting to multiple required auth schemes works + Status200_CheckThatLimitingToMultipleRequiredAuthSchemesWorks +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum OneOfGetResponse { + /// Success + Status200_Success + (models::OneOfGet200Response) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum OverrideServerGetResponse { + /// Success. + Status204_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum ParamgetGetResponse { + /// JSON rsp + Status200_JSONRsp + (models::AnotherXmlObject) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum ReadonlyAuthSchemeGetResponse { + /// Check that limiting to a single required auth scheme works + Status200_CheckThatLimitingToASingleRequiredAuthSchemeWorks +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum RegisterCallbackPostResponse { + /// OK + Status204_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum RequiredOctetStreamPutResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum ResponsesWithHeadersGetResponse { + /// Success + Status200_Success + { + body: String, + success_info: + String + , + bool_header: + Option< + bool + > + , + object_header: + Option< + models::ObjectHeader + > + } + , + /// Precondition Failed + Status412_PreconditionFailed + { + further_info: + Option< + String + > + , + failure_info: + Option< + String + > + } +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Rfc7807GetResponse { + /// OK + Status204_OK + (models::ObjectWithArrayOfObjects) + , + /// NotFound + Status404_NotFound + (models::ObjectWithArrayOfObjects) + , + /// NotAcceptable + Status406_NotAcceptable + (String) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UntypedPropertyGetResponse { + /// Check that untyped properties works + Status200_CheckThatUntypedPropertiesWorks +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UuidGetResponse { + /// Duplicate Response long text. One. + Status200_DuplicateResponseLongText + (uuid::Uuid) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum XmlExtraPostResponse { + /// OK + Status201_OK + , + /// Bad Request + Status400_BadRequest +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum XmlOtherPostResponse { + /// OK + Status201_OK + (String) + , + /// Bad Request + Status400_BadRequest +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum XmlOtherPutResponse { + /// OK + Status201_OK + , + /// Bad Request + Status400_BadRequest +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum XmlPostResponse { + /// OK + Status201_OK + , + /// Bad Request + Status400_BadRequest +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum XmlPutResponse { + /// OK + Status201_OK + , + /// Bad Request + Status400_BadRequest +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateRepoResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetRepoInfoResponse { + /// OK + Status200_OK + (String) +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// AnyOfGet - GET /any-of + async fn any_of_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::AnyOfGetQueryParams, + ) -> Result; + + + /// CallbackWithHeaderPost - POST /callback-with-header + async fn callback_with_header_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::CallbackWithHeaderPostQueryParams, + ) -> Result; + + + /// ComplexQueryParamGet - GET /complex-query-param + async fn complex_query_param_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::ComplexQueryParamGetQueryParams, + ) -> Result; + + + /// EnumInPathPathParamGet - GET /enum_in_path/{path_param} + async fn enum_in_path_path_param_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::EnumInPathPathParamGetPathParams, + ) -> Result; + + + /// JsonComplexQueryParamGet - GET /json-complex-query-param + async fn json_complex_query_param_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::JsonComplexQueryParamGetQueryParams, + ) -> Result; + + + /// MandatoryRequestHeaderGet - GET /mandatory-request-header + async fn mandatory_request_header_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + header_params: models::MandatoryRequestHeaderGetHeaderParams, + ) -> Result; + + + /// MergePatchJsonGet - GET /merge-patch-json + async fn merge_patch_json_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Get some stuff.. + /// + /// MultigetGet - GET /multiget + async fn multiget_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// MultipleAuthSchemeGet - GET /multiple_auth_scheme + async fn multiple_auth_scheme_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// OneOfGet - GET /one-of + async fn one_of_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// OverrideServerGet - GET /override-server + async fn override_server_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Get some stuff with parameters.. + /// + /// ParamgetGet - GET /paramget + async fn paramget_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::ParamgetGetQueryParams, + ) -> Result; + + + /// ReadonlyAuthSchemeGet - GET /readonly_auth_scheme + async fn readonly_auth_scheme_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// RegisterCallbackPost - POST /register-callback + async fn register_callback_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::RegisterCallbackPostQueryParams, + ) -> Result; + + + /// RequiredOctetStreamPut - PUT /required_octet_stream + async fn required_octet_stream_put( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// ResponsesWithHeadersGet - GET /responses_with_headers + async fn responses_with_headers_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Rfc7807Get - GET /rfc7807 + async fn rfc7807_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// UntypedPropertyGet - GET /untyped_property + async fn untyped_property_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Option, + ) -> Result; + + + /// UuidGet - GET /uuid + async fn uuid_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// XmlExtraPost - POST /xml_extra + async fn xml_extra_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// XmlOtherPost - POST /xml_other + async fn xml_other_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// XmlOtherPut - PUT /xml_other + async fn xml_other_put( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// Post an array. + /// + /// XmlPost - POST /xml + async fn xml_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// XmlPut - PUT /xml + async fn xml_put( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Bytes, + ) -> Result; + + + /// CreateRepo - POST /repos + async fn create_repo( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::ObjectParam, + ) -> Result; + + + /// GetRepoInfo - GET /repos/{repoId} + async fn get_repo_info( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetRepoInfoPathParams, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-axum/output/openapi-v3/src/models.rs new file mode 100644 index 000000000000..cfa2394362e3 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/src/models.rs @@ -0,0 +1,2793 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct AnyOfGetQueryParams { + /// list of any of objects + #[serde(rename = "any-of")] + #[validate( + length(min = 1), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub any_of: Option>, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct CallbackWithHeaderPostQueryParams { + #[serde(rename = "url")] + pub url: String, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct ComplexQueryParamGetQueryParams { + #[serde(rename = "list-of-strings")] + #[serde(skip_serializing_if="Option::is_none")] + pub list_of_strings: Option>, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct EnumInPathPathParamGetPathParams { + pub path_param: models::StringEnum, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct JsonComplexQueryParamGetQueryParams { + #[serde(rename = "list-of-strings")] + #[serde(skip_serializing_if="Option::is_none")] + pub list_of_strings: Option>, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct MandatoryRequestHeaderGetHeaderParams { + pub x_header: String, + } + + + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct ParamgetGetQueryParams { + /// The stuff to get + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + /// Some object to pass as query parameter + #[serde(rename = "someObject")] + #[serde(skip_serializing_if="Option::is_none")] + pub some_object: Option, + /// Some list to pass as query parameter + #[serde(rename = "someList")] + #[serde(skip_serializing_if="Option::is_none")] + pub some_list: Option>, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct RegisterCallbackPostQueryParams { + #[serde(rename = "url")] + pub url: String, + } + + + + + + + + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetRepoInfoPathParams { + pub repo_id: String, + } + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AdditionalPropertiesWithList(std::collections::HashMap>); + +impl validator::Validate for AdditionalPropertiesWithList { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From>> for AdditionalPropertiesWithList { + fn from(x: std::collections::HashMap>) -> Self { + AdditionalPropertiesWithList(x) + } +} + +impl std::convert::From for std::collections::HashMap> { + fn from(x: AdditionalPropertiesWithList) -> Self { + x.0 + } +} + +impl std::ops::Deref for AdditionalPropertiesWithList { + type Target = std::collections::HashMap>; + fn deref(&self) -> &std::collections::HashMap> { + &self.0 + } +} + +impl std::ops::DerefMut for AdditionalPropertiesWithList { + fn deref_mut(&mut self) -> &mut std::collections::HashMap> { + &mut self.0 + } +} + +/// Converts the AdditionalPropertiesWithList value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for AdditionalPropertiesWithList { + fn to_string(&self) -> String { + // Skipping additionalProperties in query parameter serialization + "".to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AdditionalPropertiesWithList value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for AdditionalPropertiesWithList { + type Err = &'static str; + + fn from_str(s: &str) -> std::result::Result { + std::result::Result::Err("Parsing additionalProperties for AdditionalPropertiesWithList is not supported") + } +} + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AnotherXmlArray(Vec); + +impl validator::Validate for AnotherXmlArray { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for AnotherXmlArray { + fn from(x: Vec) -> Self { + AnotherXmlArray(x) + } +} + +impl std::convert::From for Vec { + fn from(x: AnotherXmlArray) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for AnotherXmlArray { + fn from_iter>(u: U) -> Self { + AnotherXmlArray(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for AnotherXmlArray { + type Item = String; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a AnotherXmlArray { + type Item = &'a String; + type IntoIter = std::slice::Iter<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut AnotherXmlArray { + type Item = &'a mut String; + type IntoIter = std::slice::IterMut<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for AnotherXmlArray { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for AnotherXmlArray { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the AnotherXmlArray value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AnotherXmlArray { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnotherXmlArray value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnotherXmlArray { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(AnotherXmlArray(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AnotherXmlArray - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AnotherXmlArray - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AnotherXmlInner(String); + +impl validator::Validate for AnotherXmlInner { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for AnotherXmlInner { + fn from(x: String) -> Self { + AnotherXmlInner(x) + } +} + +impl std::string::ToString for AnotherXmlInner { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for AnotherXmlInner { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(AnotherXmlInner(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: AnotherXmlInner) -> Self { + x.0 + } +} + +impl std::ops::Deref for AnotherXmlInner { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for AnotherXmlInner { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +/// An XML object + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AnotherXmlObject { + #[serde(rename = "inner_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + +} + + +impl AnotherXmlObject { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> AnotherXmlObject { + AnotherXmlObject { + inner_string: None, + } + } +} + +/// Converts the AnotherXmlObject value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AnotherXmlObject { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.inner_string.as_ref().map(|inner_string| { + [ + "inner_string".to_string(), + inner_string.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnotherXmlObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnotherXmlObject { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub inner_string: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing AnotherXmlObject".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing AnotherXmlObject".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(AnotherXmlObject { + inner_string: intermediate_rep.inner_string.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AnotherXmlObject - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AnotherXmlObject - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + +/// Any of: +/// - String +/// - uuid::Uuid +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct AnyOfGet202Response(Box); + +impl validator::Validate for AnyOfGet202Response +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnyOfGet202Response value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnyOfGet202Response { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for AnyOfGet202Response { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} + + + + + + +/// Test a model containing an anyOf + +/// Any of: +/// - String +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct AnyOfObject(Box); + +impl validator::Validate for AnyOfObject +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnyOfObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnyOfObject { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for AnyOfObject { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} + + + + + + +/// Test containing an anyOf object + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AnyOfProperty { + #[serde(rename = "requiredAnyOf")] + pub required_any_of: models::AnyOfObject, + + #[serde(rename = "optionalAnyOf")] + #[serde(skip_serializing_if="Option::is_none")] + pub optional_any_of: Option, + +} + + +impl AnyOfProperty { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_any_of: models::AnyOfObject, ) -> AnyOfProperty { + AnyOfProperty { + required_any_of, + optional_any_of: None, + } + } +} + +/// Converts the AnyOfProperty value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AnyOfProperty { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping requiredAnyOf in query parameter serialization + + // Skipping optionalAnyOf in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnyOfProperty value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnyOfProperty { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub required_any_of: Vec, + pub optional_any_of: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing AnyOfProperty".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "requiredAnyOf" => intermediate_rep.required_any_of.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalAnyOf" => intermediate_rep.optional_any_of.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing AnyOfProperty".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(AnyOfProperty { + required_any_of: intermediate_rep.required_any_of.into_iter().next().ok_or_else(|| "requiredAnyOf missing in AnyOfProperty".to_string())?, + optional_any_of: intermediate_rep.optional_any_of.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AnyOfProperty - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AnyOfProperty - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// An XML object + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct DuplicateXmlObject { + #[serde(rename = "inner_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + + #[serde(rename = "inner_array")] + pub inner_array: models::XmlArray, + +} + + +impl DuplicateXmlObject { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(inner_array: models::XmlArray, ) -> DuplicateXmlObject { + DuplicateXmlObject { + inner_string: None, + inner_array, + } + } +} + +/// Converts the DuplicateXmlObject value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for DuplicateXmlObject { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.inner_string.as_ref().map(|inner_string| { + [ + "inner_string".to_string(), + inner_string.to_string(), + ].join(",") + }), + + // Skipping inner_array in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a DuplicateXmlObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for DuplicateXmlObject { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub inner_string: Vec, + pub inner_array: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing DuplicateXmlObject".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "inner_string" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "inner_array" => intermediate_rep.inner_array.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing DuplicateXmlObject".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(DuplicateXmlObject { + inner_string: intermediate_rep.inner_string.into_iter().next(), + inner_array: intermediate_rep.inner_array.into_iter().next().ok_or_else(|| "inner_array missing in DuplicateXmlObject".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for DuplicateXmlObject - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into DuplicateXmlObject - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Test a model containing a special character in the enum +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum EnumWithStarObject { + #[serde(rename = "FOO")] + Foo, + #[serde(rename = "BAR")] + Bar, + #[serde(rename = "*")] + Star, +} + +impl std::fmt::Display for EnumWithStarObject { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + EnumWithStarObject::Foo => write!(f, "FOO"), + EnumWithStarObject::Bar => write!(f, "BAR"), + EnumWithStarObject::Star => write!(f, "*"), + } + } +} + +impl std::str::FromStr for EnumWithStarObject { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "FOO" => std::result::Result::Ok(EnumWithStarObject::Foo), + "BAR" => std::result::Result::Ok(EnumWithStarObject::Bar), + "*" => std::result::Result::Ok(EnumWithStarObject::Star), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Err(String); + +impl validator::Validate for Err { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for Err { + fn from(x: String) -> Self { + Err(x) + } +} + +impl std::string::ToString for Err { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for Err { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(Err(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: Err) -> Self { + x.0 + } +} + +impl std::ops::Deref for Err { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for Err { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Error(String); + +impl validator::Validate for Error { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for Error { + fn from(x: String) -> Self { + Error(x) + } +} + +impl std::string::ToString for Error { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for Error { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(Error(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: Error) -> Self { + x.0 + } +} + +impl std::ops::Deref for Error { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for Error { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +/// Test a model containing an anyOf that starts with a number + +/// Any of: +/// - String +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct Model12345AnyOfObject(Box); + +impl validator::Validate for Model12345AnyOfObject +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Model12345AnyOfObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Model12345AnyOfObject { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for Model12345AnyOfObject { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} + + + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MultigetGet201Response { + #[serde(rename = "foo")] + #[serde(skip_serializing_if="Option::is_none")] + pub foo: Option, + +} + + +impl MultigetGet201Response { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> MultigetGet201Response { + MultigetGet201Response { + foo: None, + } + } +} + +/// Converts the MultigetGet201Response value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MultigetGet201Response { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.foo.as_ref().map(|foo| { + [ + "foo".to_string(), + foo.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MultigetGet201Response value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MultigetGet201Response { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub foo: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MultigetGet201Response".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing MultigetGet201Response".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MultigetGet201Response { + foo: intermediate_rep.foo.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MultigetGet201Response - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MultigetGet201Response - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MyId(i32); + +impl validator::Validate for MyId { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for MyId { + fn from(x: i32) -> Self { + MyId(x) + } +} + +impl std::convert::From for i32 { + fn from(x: MyId) -> Self { + x.0 + } +} + +impl std::ops::Deref for MyId { + type Target = i32; + fn deref(&self) -> &i32 { + &self.0 + } +} + +impl std::ops::DerefMut for MyId { + fn deref_mut(&mut self) -> &mut i32 { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MyIdList(Vec); + +impl validator::Validate for MyIdList { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for MyIdList { + fn from(x: Vec) -> Self { + MyIdList(x) + } +} + +impl std::convert::From for Vec { + fn from(x: MyIdList) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for MyIdList { + fn from_iter>(u: U) -> Self { + MyIdList(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for MyIdList { + type Item = i32; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a MyIdList { + type Item = &'a i32; + type IntoIter = std::slice::Iter<'a, i32>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut MyIdList { + type Item = &'a mut i32; + type IntoIter = std::slice::IterMut<'a, i32>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for MyIdList { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for MyIdList { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the MyIdList value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MyIdList { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MyIdList value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MyIdList { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(MyIdList(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MyIdList - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MyIdList - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct NullableTest { + #[serde(rename = "nullable")] + pub nullable: Nullable, + + #[serde(rename = "nullableWithNullDefault")] + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub nullable_with_null_default: Option>, + + #[serde(rename = "nullableWithPresentDefault")] + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub nullable_with_present_default: Option>, + + #[serde(rename = "nullableWithNoDefault")] + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub nullable_with_no_default: Option>, + + #[serde(rename = "nullableArray")] + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub nullable_array: Option>>, + + #[serde(rename = "min_item_test")] + #[validate( + length(min = 1), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub min_item_test: Option>, + + #[serde(rename = "max_item_test")] + #[validate( + length(max = 2), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub max_item_test: Option>, + + #[serde(rename = "min_max_item_test")] + #[validate( + length(min = 1, max = 3), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub min_max_item_test: Option>, + +} + + +impl NullableTest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(nullable: Nullable, ) -> NullableTest { + NullableTest { + nullable, + nullable_with_null_default: None, + nullable_with_present_default: Some(Nullable::Present("default".to_string())), + nullable_with_no_default: None, + nullable_array: None, + min_item_test: None, + max_item_test: None, + min_max_item_test: None, + } + } +} + +/// Converts the NullableTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for NullableTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("nullable".to_string()), + Some(self.nullable.as_ref().map_or("null".to_string(), |x| x.to_string())), + + + self.nullable_with_null_default.as_ref().map(|nullable_with_null_default| { + [ + "nullableWithNullDefault".to_string(), + nullable_with_null_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), + + + self.nullable_with_present_default.as_ref().map(|nullable_with_present_default| { + [ + "nullableWithPresentDefault".to_string(), + nullable_with_present_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), + + + self.nullable_with_no_default.as_ref().map(|nullable_with_no_default| { + [ + "nullableWithNoDefault".to_string(), + nullable_with_no_default.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), + + + self.nullable_array.as_ref().map(|nullable_array| { + [ + "nullableArray".to_string(), + nullable_array.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")), + ].join(",") + }), + + + self.min_item_test.as_ref().map(|min_item_test| { + [ + "min_item_test".to_string(), + min_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + + self.max_item_test.as_ref().map(|max_item_test| { + [ + "max_item_test".to_string(), + max_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + + self.min_max_item_test.as_ref().map(|min_max_item_test| { + [ + "min_max_item_test".to_string(), + min_max_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a NullableTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for NullableTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub nullable: Vec, + pub nullable_with_null_default: Vec, + pub nullable_with_present_default: Vec, + pub nullable_with_no_default: Vec, + pub nullable_array: Vec>, + pub min_item_test: Vec>, + pub max_item_test: Vec>, + pub min_max_item_test: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing NullableTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "nullable" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), + "nullableWithNullDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), + "nullableWithPresentDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), + "nullableWithNoDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), + "nullableArray" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "min_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "max_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "min_max_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing NullableTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(NullableTest { + nullable: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + nullable_with_null_default: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + nullable_with_present_default: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + nullable_with_no_default: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + nullable_array: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + min_item_test: intermediate_rep.min_item_test.into_iter().next(), + max_item_test: intermediate_rep.max_item_test.into_iter().next(), + min_max_item_test: intermediate_rep.min_max_item_test.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for NullableTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into NullableTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectHeader { + #[serde(rename = "requiredObjectHeader")] + pub required_object_header: bool, + + #[serde(rename = "optionalObjectHeader")] + #[serde(skip_serializing_if="Option::is_none")] + pub optional_object_header: Option, + +} + + +impl ObjectHeader { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_object_header: bool, ) -> ObjectHeader { + ObjectHeader { + required_object_header, + optional_object_header: None, + } + } +} + +/// Converts the ObjectHeader value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectHeader { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("requiredObjectHeader".to_string()), + Some(self.required_object_header.to_string()), + + + self.optional_object_header.as_ref().map(|optional_object_header| { + [ + "optionalObjectHeader".to_string(), + optional_object_header.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectHeader value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectHeader { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub required_object_header: Vec, + pub optional_object_header: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectHeader".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "requiredObjectHeader" => intermediate_rep.required_object_header.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalObjectHeader" => intermediate_rep.optional_object_header.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectHeader".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectHeader { + required_object_header: intermediate_rep.required_object_header.into_iter().next().ok_or_else(|| "requiredObjectHeader missing in ObjectHeader".to_string())?, + optional_object_header: intermediate_rep.optional_object_header.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectHeader - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectHeader - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectParam { + #[serde(rename = "requiredParam")] + pub required_param: bool, + + #[serde(rename = "optionalParam")] + #[serde(skip_serializing_if="Option::is_none")] + pub optional_param: Option, + +} + + +impl ObjectParam { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_param: bool, ) -> ObjectParam { + ObjectParam { + required_param, + optional_param: None, + } + } +} + +/// Converts the ObjectParam value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectParam { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("requiredParam".to_string()), + Some(self.required_param.to_string()), + + + self.optional_param.as_ref().map(|optional_param| { + [ + "optionalParam".to_string(), + optional_param.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectParam value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectParam { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub required_param: Vec, + pub optional_param: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectParam".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "requiredParam" => intermediate_rep.required_param.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optionalParam" => intermediate_rep.optional_param.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectParam".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectParam { + required_param: intermediate_rep.required_param.into_iter().next().ok_or_else(|| "requiredParam missing in ObjectParam".to_string())?, + optional_param: intermediate_rep.optional_param.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectParam - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectParam - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectUntypedProps { + #[serde(rename = "required_untyped")] + pub required_untyped: crate::types::Object, + + #[serde(rename = "required_untyped_nullable")] + pub required_untyped_nullable: Nullable, + + #[serde(rename = "not_required_untyped")] + #[serde(skip_serializing_if="Option::is_none")] + pub not_required_untyped: Option, + + #[serde(rename = "not_required_untyped_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub not_required_untyped_nullable: Option, + +} + + +impl ObjectUntypedProps { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_untyped: crate::types::Object, required_untyped_nullable: Nullable, ) -> ObjectUntypedProps { + ObjectUntypedProps { + required_untyped, + required_untyped_nullable, + not_required_untyped: None, + not_required_untyped_nullable: None, + } + } +} + +/// Converts the ObjectUntypedProps value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectUntypedProps { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping required_untyped in query parameter serialization + + // Skipping required_untyped_nullable in query parameter serialization + + // Skipping not_required_untyped in query parameter serialization + + // Skipping not_required_untyped_nullable in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectUntypedProps value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectUntypedProps { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub required_untyped: Vec, + pub required_untyped_nullable: Vec, + pub not_required_untyped: Vec, + pub not_required_untyped_nullable: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectUntypedProps".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "required_untyped" => intermediate_rep.required_untyped.push(::from_str(val).map_err(|x| x.to_string())?), + "required_untyped_nullable" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ObjectUntypedProps".to_string()), + #[allow(clippy::redundant_clone)] + "not_required_untyped" => intermediate_rep.not_required_untyped.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "not_required_untyped_nullable" => intermediate_rep.not_required_untyped_nullable.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectUntypedProps".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectUntypedProps { + required_untyped: intermediate_rep.required_untyped.into_iter().next().ok_or_else(|| "required_untyped missing in ObjectUntypedProps".to_string())?, + required_untyped_nullable: std::result::Result::Err("Nullable types not supported in ObjectUntypedProps".to_string())?, + not_required_untyped: intermediate_rep.not_required_untyped.into_iter().next(), + not_required_untyped_nullable: intermediate_rep.not_required_untyped_nullable.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectUntypedProps - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectUntypedProps - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectWithArrayOfObjects { + #[serde(rename = "objectArray")] + #[serde(skip_serializing_if="Option::is_none")] + pub object_array: Option>, + +} + + +impl ObjectWithArrayOfObjects { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ObjectWithArrayOfObjects { + ObjectWithArrayOfObjects { + object_array: None, + } + } +} + +/// Converts the ObjectWithArrayOfObjects value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectWithArrayOfObjects { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.object_array.as_ref().map(|object_array| { + [ + "objectArray".to_string(), + object_array.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectWithArrayOfObjects value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectWithArrayOfObjects { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub object_array: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectWithArrayOfObjects".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "objectArray" => return std::result::Result::Err("Parsing a container in this style is not supported in ObjectWithArrayOfObjects".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectWithArrayOfObjects".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectWithArrayOfObjects { + object_array: intermediate_rep.object_array.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectWithArrayOfObjects - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectWithArrayOfObjects - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Ok(String); + +impl validator::Validate for Ok { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for Ok { + fn from(x: String) -> Self { + Ok(x) + } +} + +impl std::string::ToString for Ok { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for Ok { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(Ok(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: Ok) -> Self { + x.0 + } +} + +impl std::ops::Deref for Ok { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for Ok { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + + + +/// One of: +/// - Vec +/// - i32 +#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)] +pub struct OneOfGet200Response(Box); + +impl validator::Validate for OneOfGet200Response +{ + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a OneOfGet200Response value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for OneOfGet200Response { + type Err = serde_json::Error; + + fn from_str(s: &str) -> std::result::Result { + serde_json::from_str(s) + } +} + +impl PartialEq for OneOfGet200Response { + fn eq(&self, other: &Self) -> bool { + self.0.get().eq(other.0.get()) + } +} + + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct OptionalObjectHeader(i32); + +impl validator::Validate for OptionalObjectHeader { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for OptionalObjectHeader { + fn from(x: i32) -> Self { + OptionalObjectHeader(x) + } +} + +impl std::convert::From for i32 { + fn from(x: OptionalObjectHeader) -> Self { + x.0 + } +} + +impl std::ops::Deref for OptionalObjectHeader { + type Target = i32; + fn deref(&self) -> &i32 { + &self.0 + } +} + +impl std::ops::DerefMut for OptionalObjectHeader { + fn deref_mut(&mut self) -> &mut i32 { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct RequiredObjectHeader(bool); + +impl validator::Validate for RequiredObjectHeader { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for RequiredObjectHeader { + fn from(x: bool) -> Self { + RequiredObjectHeader(x) + } +} + +impl std::convert::From for bool { + fn from(x: RequiredObjectHeader) -> Self { + x.0 + } +} + +impl std::ops::Deref for RequiredObjectHeader { + type Target = bool; + fn deref(&self) -> &bool { + &self.0 + } +} + +impl std::ops::DerefMut for RequiredObjectHeader { + fn deref_mut(&mut self) -> &mut bool { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Result(String); + +impl validator::Validate for Result { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for Result { + fn from(x: String) -> Self { + Result(x) + } +} + +impl std::string::ToString for Result { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for Result { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(Result(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: Result) -> Self { + x.0 + } +} + +impl std::ops::Deref for Result { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for Result { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum StringEnum { + #[serde(rename = "FOO")] + Foo, + #[serde(rename = "BAR")] + Bar, +} + +impl std::fmt::Display for StringEnum { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + StringEnum::Foo => write!(f, "FOO"), + StringEnum::Bar => write!(f, "BAR"), + } + } +} + +impl std::str::FromStr for StringEnum { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "FOO" => std::result::Result::Ok(StringEnum::Foo), + "BAR" => std::result::Result::Ok(StringEnum::Bar), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct StringObject(String); + +impl validator::Validate for StringObject { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for StringObject { + fn from(x: String) -> Self { + StringObject(x) + } +} + +impl std::string::ToString for StringObject { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for StringObject { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(StringObject(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: StringObject) -> Self { + x.0 + } +} + +impl std::ops::Deref for StringObject { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for StringObject { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +/// Test a model containing a UUID +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct UuidObject(uuid::Uuid); + +impl validator::Validate for UuidObject { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for UuidObject { + fn from(x: uuid::Uuid) -> Self { + UuidObject(x) + } +} + +impl std::convert::From for uuid::Uuid { + fn from(x: UuidObject) -> Self { + x.0 + } +} + +impl std::ops::Deref for UuidObject { + type Target = uuid::Uuid; + fn deref(&self) -> &uuid::Uuid { + &self.0 + } +} + +impl std::ops::DerefMut for UuidObject { + fn deref_mut(&mut self) -> &mut uuid::Uuid { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct XmlArray(Vec); + +impl validator::Validate for XmlArray { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for XmlArray { + fn from(x: Vec) -> Self { + XmlArray(x) + } +} + +impl std::convert::From for Vec { + fn from(x: XmlArray) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for XmlArray { + fn from_iter>(u: U) -> Self { + XmlArray(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for XmlArray { + type Item = String; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a XmlArray { + type Item = &'a String; + type IntoIter = std::slice::Iter<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut XmlArray { + type Item = &'a mut String; + type IntoIter = std::slice::IterMut<'a, String>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for XmlArray { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for XmlArray { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the XmlArray value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for XmlArray { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a XmlArray value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for XmlArray { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(XmlArray(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for XmlArray - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into XmlArray - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct XmlInner(String); + +impl validator::Validate for XmlInner { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for XmlInner { + fn from(x: String) -> Self { + XmlInner(x) + } +} + +impl std::string::ToString for XmlInner { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for XmlInner { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(XmlInner(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: XmlInner) -> Self { + x.0 + } +} + +impl std::ops::Deref for XmlInner { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for XmlInner { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + +/// An XML object + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct XmlObject { + #[serde(rename = "innerString")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner_string: Option, + + #[serde(rename = "other_inner_rename")] + #[serde(skip_serializing_if="Option::is_none")] + pub other_inner_rename: Option, + +} + + +impl XmlObject { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> XmlObject { + XmlObject { + inner_string: None, + other_inner_rename: None, + } + } +} + +/// Converts the XmlObject value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for XmlObject { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.inner_string.as_ref().map(|inner_string| { + [ + "innerString".to_string(), + inner_string.to_string(), + ].join(",") + }), + + + self.other_inner_rename.as_ref().map(|other_inner_rename| { + [ + "other_inner_rename".to_string(), + other_inner_rename.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a XmlObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for XmlObject { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub inner_string: Vec, + pub other_inner_rename: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing XmlObject".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "innerString" => intermediate_rep.inner_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "other_inner_rename" => intermediate_rep.other_inner_rename.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing XmlObject".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(XmlObject { + inner_string: intermediate_rep.inner_string.into_iter().next(), + other_inner_rename: intermediate_rep.other_inner_rename.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for XmlObject - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into XmlObject - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-axum/output/openapi-v3/src/server/mod.rs new file mode 100644 index 000000000000..eea66d5a3dd7 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/src/server/mod.rs @@ -0,0 +1,2439 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + AnyOfGetResponse, + CallbackWithHeaderPostResponse, + ComplexQueryParamGetResponse, + EnumInPathPathParamGetResponse, + JsonComplexQueryParamGetResponse, + MandatoryRequestHeaderGetResponse, + MergePatchJsonGetResponse, + MultigetGetResponse, + MultipleAuthSchemeGetResponse, + OneOfGetResponse, + OverrideServerGetResponse, + ParamgetGetResponse, + ReadonlyAuthSchemeGetResponse, + RegisterCallbackPostResponse, + RequiredOctetStreamPutResponse, + ResponsesWithHeadersGetResponse, + Rfc7807GetResponse, + UntypedPropertyGetResponse, + UuidGetResponse, + XmlExtraPostResponse, + XmlOtherPostResponse, + XmlOtherPutResponse, + XmlPostResponse, + XmlPutResponse, + CreateRepoResponse, + GetRepoInfoResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/any-of", + get(any_of_get::) + ) + .route("/callback-with-header", + post(callback_with_header_post::) + ) + .route("/complex-query-param", + get(complex_query_param_get::) + ) + .route("/enum_in_path/:path_param", + get(enum_in_path_path_param_get::) + ) + .route("/json-complex-query-param", + get(json_complex_query_param_get::) + ) + .route("/mandatory-request-header", + get(mandatory_request_header_get::) + ) + .route("/merge-patch-json", + get(merge_patch_json_get::) + ) + .route("/multiget", + get(multiget_get::) + ) + .route("/multiple_auth_scheme", + get(multiple_auth_scheme_get::) + ) + .route("/one-of", + get(one_of_get::) + ) + .route("/override-server", + get(override_server_get::) + ) + .route("/paramget", + get(paramget_get::) + ) + .route("/readonly_auth_scheme", + get(readonly_auth_scheme_get::) + ) + .route("/register-callback", + post(register_callback_post::) + ) + .route("/repos", + post(create_repo::) + ) + .route("/repos/:repo_id", + get(get_repo_info::).get(get_repo_info::) + ) + .route("/required_octet_stream", + put(required_octet_stream_put::) + ) + .route("/responses_with_headers", + get(responses_with_headers_get::) + ) + .route("/rfc7807", + get(rfc7807_get::) + ) + .route("/untyped_property", + get(untyped_property_get::) + ) + .route("/uuid", + get(uuid_get::) + ) + .route("/xml", + post(xml_post::).put(xml_put::) + ) + .route("/xml_extra", + post(xml_extra_post::) + ) + .route("/xml_other", + post(xml_other_post::).put(xml_other_put::) + ) + .with_state(api_impl) +} + + +#[tracing::instrument(skip_all)] +fn any_of_get_validation( + query_params: models::AnyOfGetQueryParams, +) -> std::result::Result<( + models::AnyOfGetQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// AnyOfGet - GET /any-of +#[tracing::instrument(skip_all)] +async fn any_of_get( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + any_of_get_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().any_of_get( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + AnyOfGetResponse::Status200_Success + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + AnyOfGetResponse::Status201_AlternateSuccess + (body) + => { + + let mut response = response.status(201); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + AnyOfGetResponse::Status202_AnyOfSuccess + (body) + => { + + let mut response = response.status(202); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn callback_with_header_post_validation( + query_params: models::CallbackWithHeaderPostQueryParams, +) -> std::result::Result<( + models::CallbackWithHeaderPostQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// CallbackWithHeaderPost - POST /callback-with-header +#[tracing::instrument(skip_all)] +async fn callback_with_header_post( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + callback_with_header_post_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().callback_with_header_post( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CallbackWithHeaderPostResponse::Status204_OK + => { + + let mut response = response.status(204); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn complex_query_param_get_validation( + query_params: models::ComplexQueryParamGetQueryParams, +) -> std::result::Result<( + models::ComplexQueryParamGetQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// ComplexQueryParamGet - GET /complex-query-param +#[tracing::instrument(skip_all)] +async fn complex_query_param_get( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + complex_query_param_get_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().complex_query_param_get( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + ComplexQueryParamGetResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn enum_in_path_path_param_get_validation( + path_params: models::EnumInPathPathParamGetPathParams, +) -> std::result::Result<( + models::EnumInPathPathParamGetPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// EnumInPathPathParamGet - GET /enum_in_path/{path_param} +#[tracing::instrument(skip_all)] +async fn enum_in_path_path_param_get( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + enum_in_path_path_param_get_validation( + path_params, + ) + ; + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().enum_in_path_path_param_get( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + EnumInPathPathParamGetResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn json_complex_query_param_get_validation( + query_params: models::JsonComplexQueryParamGetQueryParams, +) -> std::result::Result<( + models::JsonComplexQueryParamGetQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// JsonComplexQueryParamGet - GET /json-complex-query-param +#[tracing::instrument(skip_all)] +async fn json_complex_query_param_get( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + json_complex_query_param_get_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().json_complex_query_param_get( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + JsonComplexQueryParamGetResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn mandatory_request_header_get_validation( + header_params: models::MandatoryRequestHeaderGetHeaderParams, +) -> std::result::Result<( + models::MandatoryRequestHeaderGetHeaderParams, +), ValidationErrors> +{ + header_params.validate()?; + +Ok(( + header_params, +)) +} + +/// MandatoryRequestHeaderGet - GET /mandatory-request-header +#[tracing::instrument(skip_all)] +async fn mandatory_request_header_get( + method: Method, + host: Host, + cookies: CookieJar, + headers: HeaderMap, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + // Header parameters + let header_params = { + let header_x_header = headers.get(HeaderName::from_static("x-header")); + + let header_x_header = match header_x_header { + Some(v) => match header::IntoHeaderValue::::try_from((*v).clone()) { + Ok(result) => + result.0, + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header X-Header - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from("Missing required header X-Header")).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + models::MandatoryRequestHeaderGetHeaderParams { + x_header: header_x_header, + } + }; + + + let validation = + mandatory_request_header_get_validation( + header_params, + ) + ; + + let Ok(( + header_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().mandatory_request_header_get( + method, + host, + cookies, + header_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MandatoryRequestHeaderGetResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn merge_patch_json_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MergePatchJsonGet - GET /merge-patch-json +#[tracing::instrument(skip_all)] +async fn merge_patch_json_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + merge_patch_json_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().merge_patch_json_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MergePatchJsonGetResponse::Status200_Merge + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/merge-patch+json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn multiget_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MultigetGet - GET /multiget +#[tracing::instrument(skip_all)] +async fn multiget_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + multiget_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().multiget_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MultigetGetResponse::Status200_JSONRsp + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status201_XMLRsp + (body) + => { + + let mut response = response.status(201); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status202_OctetRsp + (body) + => { + + let mut response = response.status(202); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/octet-stream").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body.0; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status203_StringRsp + (body) + => { + + let mut response = response.status(203); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status204_DuplicateResponseLongText + (body) + => { + + let mut response = response.status(204); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status205_DuplicateResponseLongText + (body) + => { + + let mut response = response.status(205); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + MultigetGetResponse::Status206_DuplicateResponseLongText + (body) + => { + + let mut response = response.status(206); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn multiple_auth_scheme_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// MultipleAuthSchemeGet - GET /multiple_auth_scheme +#[tracing::instrument(skip_all)] +async fn multiple_auth_scheme_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + multiple_auth_scheme_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().multiple_auth_scheme_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + MultipleAuthSchemeGetResponse::Status200_CheckThatLimitingToMultipleRequiredAuthSchemesWorks + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn one_of_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// OneOfGet - GET /one-of +#[tracing::instrument(skip_all)] +async fn one_of_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + one_of_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().one_of_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + OneOfGetResponse::Status200_Success + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn override_server_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// OverrideServerGet - GET /override-server +#[tracing::instrument(skip_all)] +async fn override_server_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + override_server_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().override_server_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + OverrideServerGetResponse::Status204_Success + => { + + let mut response = response.status(204); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn paramget_get_validation( + query_params: models::ParamgetGetQueryParams, +) -> std::result::Result<( + models::ParamgetGetQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// ParamgetGet - GET /paramget +#[tracing::instrument(skip_all)] +async fn paramget_get( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + paramget_get_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().paramget_get( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + ParamgetGetResponse::Status200_JSONRsp + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn readonly_auth_scheme_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// ReadonlyAuthSchemeGet - GET /readonly_auth_scheme +#[tracing::instrument(skip_all)] +async fn readonly_auth_scheme_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + readonly_auth_scheme_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().readonly_auth_scheme_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + ReadonlyAuthSchemeGetResponse::Status200_CheckThatLimitingToASingleRequiredAuthSchemeWorks + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn register_callback_post_validation( + query_params: models::RegisterCallbackPostQueryParams, +) -> std::result::Result<( + models::RegisterCallbackPostQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// RegisterCallbackPost - POST /register-callback +#[tracing::instrument(skip_all)] +async fn register_callback_post( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + register_callback_post_validation( + query_params, + ) + ; + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().register_callback_post( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + RegisterCallbackPostResponse::Status204_OK + => { + + let mut response = response.status(204); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct RequiredOctetStreamPutBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn required_octet_stream_put_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// RequiredOctetStreamPut - PUT /required_octet_stream +#[tracing::instrument(skip_all)] +async fn required_octet_stream_put( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + required_octet_stream_put_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().required_octet_stream_put( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + RequiredOctetStreamPutResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn responses_with_headers_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// ResponsesWithHeadersGet - GET /responses_with_headers +#[tracing::instrument(skip_all)] +async fn responses_with_headers_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + responses_with_headers_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().responses_with_headers_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + ResponsesWithHeadersGetResponse::Status200_Success + { + body, + success_info, + bool_header, + object_header + } + => { + let success_info = match header::IntoHeaderValue(success_info).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling success_info header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("success-info"), + success_info + ); + } + if let Some(bool_header) = bool_header { + let bool_header = match header::IntoHeaderValue(bool_header).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling bool_header header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("bool-header"), + bool_header + ); + } + } + if let Some(object_header) = object_header { + let object_header = match header::IntoHeaderValue(object_header).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling object_header header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("object-header"), + object_header + ); + } + } + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + ResponsesWithHeadersGetResponse::Status412_PreconditionFailed + { + further_info, + failure_info + } + => { + if let Some(further_info) = further_info { + let further_info = match header::IntoHeaderValue(further_info).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling further_info header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("further-info"), + further_info + ); + } + } + if let Some(failure_info) = failure_info { + let failure_info = match header::IntoHeaderValue(failure_info).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling failure_info header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("failure-info"), + failure_info + ); + } + } + + let mut response = response.status(412); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn rfc7807_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Rfc7807Get - GET /rfc7807 +#[tracing::instrument(skip_all)] +async fn rfc7807_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + rfc7807_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().rfc7807_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Rfc7807GetResponse::Status204_OK + (body) + => { + + let mut response = response.status(204); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + Rfc7807GetResponse::Status404_NotFound + (body) + => { + + let mut response = response.status(404); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/problem+json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + Rfc7807GetResponse::Status406_NotAcceptable + (body) + => { + + let mut response = response.status(406); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct UntypedPropertyGetBodyValidator<'a> { + #[validate] + body: &'a models::ObjectUntypedProps, + } + + +#[tracing::instrument(skip_all)] +fn untyped_property_get_validation( + body: Option, +) -> std::result::Result<( + Option, +), ValidationErrors> +{ + if let Some(body) = &body { + let b = UntypedPropertyGetBodyValidator { body }; + b.validate()?; + } + +Ok(( + body, +)) +} + +/// UntypedPropertyGet - GET /untyped_property +#[tracing::instrument(skip_all)] +async fn untyped_property_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + untyped_property_get_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().untyped_property_get( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UntypedPropertyGetResponse::Status200_CheckThatUntypedPropertiesWorks + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn uuid_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// UuidGet - GET /uuid +#[tracing::instrument(skip_all)] +async fn uuid_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + uuid_get_validation( + ) + ; + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().uuid_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UuidGetResponse::Status200_DuplicateResponseLongText + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct XmlExtraPostBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn xml_extra_post_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// XmlExtraPost - POST /xml_extra +#[tracing::instrument(skip_all)] +async fn xml_extra_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + xml_extra_post_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().xml_extra_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + XmlExtraPostResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + XmlExtraPostResponse::Status400_BadRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct XmlOtherPostBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn xml_other_post_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// XmlOtherPost - POST /xml_other +#[tracing::instrument(skip_all)] +async fn xml_other_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + xml_other_post_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().xml_other_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + XmlOtherPostResponse::Status201_OK + (body) + => { + + let mut response = response.status(201); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + XmlOtherPostResponse::Status400_BadRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct XmlOtherPutBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn xml_other_put_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// XmlOtherPut - PUT /xml_other +#[tracing::instrument(skip_all)] +async fn xml_other_put( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + xml_other_put_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().xml_other_put( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + XmlOtherPutResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + XmlOtherPutResponse::Status400_BadRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct XmlPostBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn xml_post_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// XmlPost - POST /xml +#[tracing::instrument(skip_all)] +async fn xml_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + xml_post_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().xml_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + XmlPostResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + XmlPostResponse::Status400_BadRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct XmlPutBodyValidator<'a> { + body: &'a [u8], + } + + +#[tracing::instrument(skip_all)] +fn xml_put_validation( + body: Bytes, +) -> std::result::Result<( + Bytes, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// XmlPut - PUT /xml +#[tracing::instrument(skip_all)] +async fn xml_put( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: Bytes, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + xml_put_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().xml_put( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + XmlPutResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + XmlPutResponse::Status400_BadRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateRepoBodyValidator<'a> { + #[validate] + body: &'a models::ObjectParam, + } + + +#[tracing::instrument(skip_all)] +fn create_repo_validation( + body: models::ObjectParam, +) -> std::result::Result<( + models::ObjectParam, +), ValidationErrors> +{ + let b = CreateRepoBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateRepo - POST /repos +#[tracing::instrument(skip_all)] +async fn create_repo( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + create_repo_validation( + body, + ) + ; + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_repo( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateRepoResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_repo_info_validation( + path_params: models::GetRepoInfoPathParams, +) -> std::result::Result<( + models::GetRepoInfoPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetRepoInfo - GET /repos/{repoId} +#[tracing::instrument(skip_all)] +async fn get_repo_info( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + let validation = + get_repo_info_validation( + path_params, + ) + ; + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_repo_info( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetRepoInfoResponse::Status200_OK + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/openapi-v3/src/types.rs b/samples/server/petstore/rust-axum/output/openapi-v3/src/types.rs new file mode 100644 index 000000000000..1c59471ea542 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/openapi-v3/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use openapi_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use openapi_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use openapi_v3::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/ops-v3/.gitignore b/samples/server/petstore/rust-axum/output/ops-v3/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/ops-v3/Cargo.toml b/samples/server/petstore/rust-axum/output/ops-v3/Cargo.toml new file mode 100644 index 000000000000..80a1405875ea --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "ops-v3" +version = "0.0.1" +authors = ["OpenAPI Generator team and contributors"] +description = "No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/ops-v3/README.md b/samples/server/petstore/rust-axum/output/ops-v3/README.md new file mode 100644 index 000000000000..c32fe05320aa --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/README.md @@ -0,0 +1,91 @@ +# Rust API for ops-v3 + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 0.0.1 + + + + +This autogenerated project defines an API crate `ops-v3` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl ops-v3::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = ops-v3::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/ops-v3/src/header.rs b/samples/server/petstore/rust-axum/output/ops-v3/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/ops-v3/src/lib.rs b/samples/server/petstore/rust-axum/output/ops-v3/src/lib.rs new file mode 100644 index 000000000000..59cae7079d4c --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/src/lib.rs @@ -0,0 +1,660 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "0.0.1"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op10GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op11GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op12GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op13GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op14GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op15GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op16GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op17GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op18GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op19GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op1GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op20GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op21GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op22GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op23GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op24GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op25GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op26GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op27GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op28GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op29GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op2GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op30GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op31GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op32GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op33GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op34GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op35GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op36GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op37GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op3GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op4GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op5GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op6GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op7GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op8GetResponse { + /// OK + Status200_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Op9GetResponse { + /// OK + Status200_OK +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// Op10Get - GET /op10 + async fn op10_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op11Get - GET /op11 + async fn op11_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op12Get - GET /op12 + async fn op12_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op13Get - GET /op13 + async fn op13_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op14Get - GET /op14 + async fn op14_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op15Get - GET /op15 + async fn op15_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op16Get - GET /op16 + async fn op16_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op17Get - GET /op17 + async fn op17_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op18Get - GET /op18 + async fn op18_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op19Get - GET /op19 + async fn op19_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op1Get - GET /op1 + async fn op1_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op20Get - GET /op20 + async fn op20_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op21Get - GET /op21 + async fn op21_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op22Get - GET /op22 + async fn op22_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op23Get - GET /op23 + async fn op23_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op24Get - GET /op24 + async fn op24_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op25Get - GET /op25 + async fn op25_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op26Get - GET /op26 + async fn op26_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op27Get - GET /op27 + async fn op27_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op28Get - GET /op28 + async fn op28_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op29Get - GET /op29 + async fn op29_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op2Get - GET /op2 + async fn op2_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op30Get - GET /op30 + async fn op30_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op31Get - GET /op31 + async fn op31_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op32Get - GET /op32 + async fn op32_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op33Get - GET /op33 + async fn op33_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op34Get - GET /op34 + async fn op34_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op35Get - GET /op35 + async fn op35_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op36Get - GET /op36 + async fn op36_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op37Get - GET /op37 + async fn op37_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op3Get - GET /op3 + async fn op3_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op4Get - GET /op4 + async fn op4_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op5Get - GET /op5 + async fn op5_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op6Get - GET /op6 + async fn op6_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op7Get - GET /op7 + async fn op7_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op8Get - GET /op8 + async fn op8_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Op9Get - GET /op9 + async fn op9_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/ops-v3/src/models.rs b/samples/server/petstore/rust-axum/output/ops-v3/src/models.rs new file mode 100644 index 000000000000..3ba24da3c350 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/src/models.rs @@ -0,0 +1,47 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/samples/server/petstore/rust-axum/output/ops-v3/src/server/mod.rs b/samples/server/petstore/rust-axum/output/ops-v3/src/server/mod.rs new file mode 100644 index 000000000000..e484ed2fa75f --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/src/server/mod.rs @@ -0,0 +1,2581 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + Op10GetResponse, + Op11GetResponse, + Op12GetResponse, + Op13GetResponse, + Op14GetResponse, + Op15GetResponse, + Op16GetResponse, + Op17GetResponse, + Op18GetResponse, + Op19GetResponse, + Op1GetResponse, + Op20GetResponse, + Op21GetResponse, + Op22GetResponse, + Op23GetResponse, + Op24GetResponse, + Op25GetResponse, + Op26GetResponse, + Op27GetResponse, + Op28GetResponse, + Op29GetResponse, + Op2GetResponse, + Op30GetResponse, + Op31GetResponse, + Op32GetResponse, + Op33GetResponse, + Op34GetResponse, + Op35GetResponse, + Op36GetResponse, + Op37GetResponse, + Op3GetResponse, + Op4GetResponse, + Op5GetResponse, + Op6GetResponse, + Op7GetResponse, + Op8GetResponse, + Op9GetResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/op1", + get(op1_get::) + ) + .route("/op10", + get(op10_get::) + ) + .route("/op11", + get(op11_get::) + ) + .route("/op12", + get(op12_get::) + ) + .route("/op13", + get(op13_get::) + ) + .route("/op14", + get(op14_get::) + ) + .route("/op15", + get(op15_get::) + ) + .route("/op16", + get(op16_get::) + ) + .route("/op17", + get(op17_get::) + ) + .route("/op18", + get(op18_get::) + ) + .route("/op19", + get(op19_get::) + ) + .route("/op2", + get(op2_get::) + ) + .route("/op20", + get(op20_get::) + ) + .route("/op21", + get(op21_get::) + ) + .route("/op22", + get(op22_get::) + ) + .route("/op23", + get(op23_get::) + ) + .route("/op24", + get(op24_get::) + ) + .route("/op25", + get(op25_get::) + ) + .route("/op26", + get(op26_get::) + ) + .route("/op27", + get(op27_get::) + ) + .route("/op28", + get(op28_get::) + ) + .route("/op29", + get(op29_get::) + ) + .route("/op3", + get(op3_get::) + ) + .route("/op30", + get(op30_get::) + ) + .route("/op31", + get(op31_get::) + ) + .route("/op32", + get(op32_get::) + ) + .route("/op33", + get(op33_get::) + ) + .route("/op34", + get(op34_get::) + ) + .route("/op35", + get(op35_get::) + ) + .route("/op36", + get(op36_get::) + ) + .route("/op37", + get(op37_get::) + ) + .route("/op4", + get(op4_get::) + ) + .route("/op5", + get(op5_get::) + ) + .route("/op6", + get(op6_get::) + ) + .route("/op7", + get(op7_get::) + ) + .route("/op8", + get(op8_get::) + ) + .route("/op9", + get(op9_get::) + ) + .with_state(api_impl) +} + + +#[tracing::instrument(skip_all)] +fn op10_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op10Get - GET /op10 +#[tracing::instrument(skip_all)] +async fn op10_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op10_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op10_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op10GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op11_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op11Get - GET /op11 +#[tracing::instrument(skip_all)] +async fn op11_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op11_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op11_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op11GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op12_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op12Get - GET /op12 +#[tracing::instrument(skip_all)] +async fn op12_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op12_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op12_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op12GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op13_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op13Get - GET /op13 +#[tracing::instrument(skip_all)] +async fn op13_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op13_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op13_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op13GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op14_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op14Get - GET /op14 +#[tracing::instrument(skip_all)] +async fn op14_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op14_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op14_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op14GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op15_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op15Get - GET /op15 +#[tracing::instrument(skip_all)] +async fn op15_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op15_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op15_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op15GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op16_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op16Get - GET /op16 +#[tracing::instrument(skip_all)] +async fn op16_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op16_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op16_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op16GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op17_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op17Get - GET /op17 +#[tracing::instrument(skip_all)] +async fn op17_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op17_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op17_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op17GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op18_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op18Get - GET /op18 +#[tracing::instrument(skip_all)] +async fn op18_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op18_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op18_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op18GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op19_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op19Get - GET /op19 +#[tracing::instrument(skip_all)] +async fn op19_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op19_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op19_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op19GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op1_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op1Get - GET /op1 +#[tracing::instrument(skip_all)] +async fn op1_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op1_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op1_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op1GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op20_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op20Get - GET /op20 +#[tracing::instrument(skip_all)] +async fn op20_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op20_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op20_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op20GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op21_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op21Get - GET /op21 +#[tracing::instrument(skip_all)] +async fn op21_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op21_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op21_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op21GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op22_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op22Get - GET /op22 +#[tracing::instrument(skip_all)] +async fn op22_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op22_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op22_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op22GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op23_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op23Get - GET /op23 +#[tracing::instrument(skip_all)] +async fn op23_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op23_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op23_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op23GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op24_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op24Get - GET /op24 +#[tracing::instrument(skip_all)] +async fn op24_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op24_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op24_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op24GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op25_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op25Get - GET /op25 +#[tracing::instrument(skip_all)] +async fn op25_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op25_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op25_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op25GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op26_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op26Get - GET /op26 +#[tracing::instrument(skip_all)] +async fn op26_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op26_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op26_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op26GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op27_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op27Get - GET /op27 +#[tracing::instrument(skip_all)] +async fn op27_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op27_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op27_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op27GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op28_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op28Get - GET /op28 +#[tracing::instrument(skip_all)] +async fn op28_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op28_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op28_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op28GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op29_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op29Get - GET /op29 +#[tracing::instrument(skip_all)] +async fn op29_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op29_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op29_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op29GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op2_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op2Get - GET /op2 +#[tracing::instrument(skip_all)] +async fn op2_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op2_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op2_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op2GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op30_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op30Get - GET /op30 +#[tracing::instrument(skip_all)] +async fn op30_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op30_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op30_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op30GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op31_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op31Get - GET /op31 +#[tracing::instrument(skip_all)] +async fn op31_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op31_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op31_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op31GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op32_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op32Get - GET /op32 +#[tracing::instrument(skip_all)] +async fn op32_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op32_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op32_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op32GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op33_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op33Get - GET /op33 +#[tracing::instrument(skip_all)] +async fn op33_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op33_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op33_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op33GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op34_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op34Get - GET /op34 +#[tracing::instrument(skip_all)] +async fn op34_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op34_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op34_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op34GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op35_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op35Get - GET /op35 +#[tracing::instrument(skip_all)] +async fn op35_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op35_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op35_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op35GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op36_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op36Get - GET /op36 +#[tracing::instrument(skip_all)] +async fn op36_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op36_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op36_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op36GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op37_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op37Get - GET /op37 +#[tracing::instrument(skip_all)] +async fn op37_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op37_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op37_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op37GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op3_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op3Get - GET /op3 +#[tracing::instrument(skip_all)] +async fn op3_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op3_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op3_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op3GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op4_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op4Get - GET /op4 +#[tracing::instrument(skip_all)] +async fn op4_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op4_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op4_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op4GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op5_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op5Get - GET /op5 +#[tracing::instrument(skip_all)] +async fn op5_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op5_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op5_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op5GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op6_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op6Get - GET /op6 +#[tracing::instrument(skip_all)] +async fn op6_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op6_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op6_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op6GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op7_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op7Get - GET /op7 +#[tracing::instrument(skip_all)] +async fn op7_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op7_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op7_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op7GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op8_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op8Get - GET /op8 +#[tracing::instrument(skip_all)] +async fn op8_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op8_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op8_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op8GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn op9_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Op9Get - GET /op9 +#[tracing::instrument(skip_all)] +async fn op9_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + op9_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().op9_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Op9GetResponse::Status200_OK + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/ops-v3/src/types.rs b/samples/server/petstore/rust-axum/output/ops-v3/src/types.rs new file mode 100644 index 000000000000..98c3d7a00cd2 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ops-v3/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use ops_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use ops_v3::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use ops_v3::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.gitignore b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml new file mode 100644 index 000000000000..42f579e8e992 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/Cargo.toml @@ -0,0 +1,48 @@ +[package] +name = "petstore-with-fake-endpoints-models-for-testing" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\" +license = "Apache-2.0" +edition = "2021" +publish = ["crates-io"] + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/README.md b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/README.md new file mode 100644 index 000000000000..66718aba409f --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/README.md @@ -0,0 +1,91 @@ +# Rust API for petstore-with-fake-endpoints-models-for-testing + +This spec is mainly for testing Petstore server and contains fake endpoints, models. Please do not use this for any other purpose. Special characters: \" \\ + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 1.0.0 + + + + +This autogenerated project defines an API crate `petstore-with-fake-endpoints-models-for-testing` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl petstore-with-fake-endpoints-models-for-testing::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = petstore-with-fake-endpoints-models-for-testing::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/header.rs b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs new file mode 100644 index 000000000000..a19cbbbba29e --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs @@ -0,0 +1,792 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = "/v2"; +pub const API_VERSION: &str = "1.0.0"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestSpecialTagsResponse { + /// successful operation + Status200_SuccessfulOperation + (models::Client) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum Call123exampleResponse { + /// success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FakeOuterBooleanSerializeResponse { + /// Output boolean + Status200_OutputBoolean + (bool) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FakeOuterCompositeSerializeResponse { + /// Output composite + Status200_OutputComposite + (models::OuterComposite) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FakeOuterNumberSerializeResponse { + /// Output number + Status200_OutputNumber + (f64) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FakeOuterStringSerializeResponse { + /// Output string + Status200_OutputString + (String) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FakeResponseWithNumericalDescriptionResponse { + /// 1234 + Status200 +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum HyphenParamResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestBodyWithQueryParamsResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestClientModelResponse { + /// successful operation + Status200_SuccessfulOperation + (models::Client) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestEndpointParametersResponse { + /// Invalid username supplied + Status400_InvalidUsernameSupplied + , + /// User not found + Status404_UserNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestEnumParametersResponse { + /// Invalid request + Status400_InvalidRequest + , + /// Not found + Status404_NotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestInlineAdditionalPropertiesResponse { + /// successful operation + Status200_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestJsonFormDataResponse { + /// successful operation + Status200_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum TestClassnameResponse { + /// successful operation + Status200_SuccessfulOperation + (models::Client) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum AddPetResponse { + /// Invalid input + Status405_InvalidInput +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeletePetResponse { + /// Invalid pet value + Status400_InvalidPetValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FindPetsByStatusResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid status value + Status400_InvalidStatusValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FindPetsByTagsResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid tag value + Status400_InvalidTagValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetPetByIdResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Pet not found + Status404_PetNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdatePetResponse { + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Pet not found + Status404_PetNotFound + , + /// Validation exception + Status405_ValidationException +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdatePetWithFormResponse { + /// Invalid input + Status405_InvalidInput +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UploadFileResponse { + /// successful operation + Status200_SuccessfulOperation + (models::ApiResponse) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeleteOrderResponse { + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Order not found + Status404_OrderNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetInventoryResponse { + /// successful operation + Status200_SuccessfulOperation + (std::collections::HashMap) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetOrderByIdResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Order not found + Status404_OrderNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum PlaceOrderResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid Order + Status400_InvalidOrder +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUserResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUsersWithArrayInputResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUsersWithListInputResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeleteUserResponse { + /// Invalid username supplied + Status400_InvalidUsernameSupplied + , + /// User not found + Status404_UserNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetUserByNameResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid username supplied + Status400_InvalidUsernameSupplied + , + /// User not found + Status404_UserNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum LoginUserResponse { + /// successful operation + Status200_SuccessfulOperation + { + body: String, + x_rate_limit: + Option< + i32 + > + , + x_expires_after: + Option< + chrono::DateTime:: + > + } + , + /// Invalid username/password supplied + Status400_InvalidUsername +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum LogoutUserResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdateUserResponse { + /// Invalid user supplied + Status400_InvalidUserSupplied + , + /// User not found + Status404_UserNotFound +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// To test special tags. + /// + /// TestSpecialTags - PATCH /v2/another-fake/dummy + async fn test_special_tags( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Client, + ) -> Result; + + + /// Call123example - GET /v2/fake/operation-with-numeric-id + async fn call123example( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// FakeOuterBooleanSerialize - POST /v2/fake/outer/boolean + async fn fake_outer_boolean_serialize( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Option, + ) -> Result; + + + /// FakeOuterCompositeSerialize - POST /v2/fake/outer/composite + async fn fake_outer_composite_serialize( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Option, + ) -> Result; + + + /// FakeOuterNumberSerialize - POST /v2/fake/outer/number + async fn fake_outer_number_serialize( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Option, + ) -> Result; + + + /// FakeOuterStringSerialize - POST /v2/fake/outer/string + async fn fake_outer_string_serialize( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Option, + ) -> Result; + + + /// FakeResponseWithNumericalDescription - GET /v2/fake/response-with-numerical-description + async fn fake_response_with_numerical_description( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// HyphenParam - GET /v2/fake/hyphenParam/{hyphen-param} + async fn hyphen_param( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::HyphenParamPathParams, + ) -> Result; + + + /// TestBodyWithQueryParams - PUT /v2/fake/body-with-query-params + async fn test_body_with_query_params( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::TestBodyWithQueryParamsQueryParams, + body: models::User, + ) -> Result; + + + /// To test \"client\" model. + /// + /// TestClientModel - PATCH /v2/fake + async fn test_client_model( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Client, + ) -> Result; + + + /// Fake endpoint for testing various parameters 假端點 偽のエンドポイント 가짜 엔드 포인트. + /// + /// TestEndpointParameters - POST /v2/fake + async fn test_endpoint_parameters( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// To test enum parameters. + /// + /// TestEnumParameters - GET /v2/fake + async fn test_enum_parameters( + &self, + method: Method, + host: Host, + cookies: CookieJar, + header_params: models::TestEnumParametersHeaderParams, + query_params: models::TestEnumParametersQueryParams, + ) -> Result; + + + /// test inline additionalProperties. + /// + /// TestInlineAdditionalProperties - POST /v2/fake/inline-additionalProperties + async fn test_inline_additional_properties( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: std::collections::HashMap, + ) -> Result; + + + /// test json serialization of form data. + /// + /// TestJsonFormData - GET /v2/fake/jsonFormData + async fn test_json_form_data( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// To test class name in snake case. + /// + /// TestClassname - PATCH /v2/fake_classname_test + async fn test_classname( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Client, + ) -> Result; + + + /// Add a new pet to the store. + /// + /// AddPet - POST /v2/pet + async fn add_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Pet, + ) -> Result; + + + /// Deletes a pet. + /// + /// DeletePet - DELETE /v2/pet/{petId} + async fn delete_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + header_params: models::DeletePetHeaderParams, + path_params: models::DeletePetPathParams, + ) -> Result; + + + /// Finds Pets by status. + /// + /// FindPetsByStatus - GET /v2/pet/findByStatus + async fn find_pets_by_status( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::FindPetsByStatusQueryParams, + ) -> Result; + + + /// Finds Pets by tags. + /// + /// FindPetsByTags - GET /v2/pet/findByTags + async fn find_pets_by_tags( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::FindPetsByTagsQueryParams, + ) -> Result; + + + /// Find pet by ID. + /// + /// GetPetById - GET /v2/pet/{petId} + async fn get_pet_by_id( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetPetByIdPathParams, + ) -> Result; + + + /// Update an existing pet. + /// + /// UpdatePet - PUT /v2/pet + async fn update_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Pet, + ) -> Result; + + + /// Updates a pet in the store with form data. + /// + /// UpdatePetWithForm - POST /v2/pet/{petId} + async fn update_pet_with_form( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UpdatePetWithFormPathParams, + ) -> Result; + + + /// uploads an image. + /// + /// UploadFile - POST /v2/pet/{petId}/uploadImage + async fn upload_file( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UploadFilePathParams, + body: Multipart, + ) -> Result; + + + /// Delete purchase order by ID. + /// + /// DeleteOrder - DELETE /v2/store/order/{order_id} + async fn delete_order( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::DeleteOrderPathParams, + ) -> Result; + + + /// Returns pet inventories by status. + /// + /// GetInventory - GET /v2/store/inventory + async fn get_inventory( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Find purchase order by ID. + /// + /// GetOrderById - GET /v2/store/order/{order_id} + async fn get_order_by_id( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetOrderByIdPathParams, + ) -> Result; + + + /// Place an order for a pet. + /// + /// PlaceOrder - POST /v2/store/order + async fn place_order( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Order, + ) -> Result; + + + /// Create user. + /// + /// CreateUser - POST /v2/user + async fn create_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::User, + ) -> Result; + + + /// Creates list of users with given input array. + /// + /// CreateUsersWithArrayInput - POST /v2/user/createWithArray + async fn create_users_with_array_input( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Vec, + ) -> Result; + + + /// Creates list of users with given input array. + /// + /// CreateUsersWithListInput - POST /v2/user/createWithList + async fn create_users_with_list_input( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Vec, + ) -> Result; + + + /// Delete user. + /// + /// DeleteUser - DELETE /v2/user/{username} + async fn delete_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::DeleteUserPathParams, + ) -> Result; + + + /// Get user by user name. + /// + /// GetUserByName - GET /v2/user/{username} + async fn get_user_by_name( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetUserByNamePathParams, + ) -> Result; + + + /// Logs user into the system. + /// + /// LoginUser - GET /v2/user/login + async fn login_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::LoginUserQueryParams, + ) -> Result; + + + /// Logs out current logged in user session. + /// + /// LogoutUser - GET /v2/user/logout + async fn logout_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Updated user. + /// + /// UpdateUser - PUT /v2/user/{username} + async fn update_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UpdateUserPathParams, + body: models::User, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs new file mode 100644 index 000000000000..3ba9efc9eb7a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs @@ -0,0 +1,5570 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct HyphenParamPathParams { + /// Parameter with hyphen in name + pub hyphen_param: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct TestBodyWithQueryParamsQueryParams { + #[serde(rename = "query")] + pub query: String, + } + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct TestEnumParametersHeaderParams { + pub enum_header_string_array: Option>, + pub enum_header_string: Option, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct TestEnumParametersQueryParams { + /// Query parameter enum test (string array) + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_query_string_array")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_query_string_array: Option>, + /// Query parameter enum test (string) + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_query_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_query_string: Option, + /// Query parameter enum test (double) + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_query_integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_query_integer: Option, + /// Query parameter enum test (double) + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_query_double")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_query_double: Option, + } + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeletePetHeaderParams { + pub api_key: Option, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeletePetPathParams { + /// Pet id to delete + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct FindPetsByStatusQueryParams { + /// Status values that need to be considered for filter + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + pub status: Vec, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct FindPetsByTagsQueryParams { + /// Tags to filter by + #[serde(rename = "tags")] + pub tags: Vec, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetPetByIdPathParams { + /// ID of pet to return + pub pet_id: i64, + } + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UpdatePetWithFormPathParams { + /// ID of pet that needs to be updated + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UploadFilePathParams { + /// ID of pet to update + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeleteOrderPathParams { + /// ID of the order that needs to be deleted + pub order_id: String, + } + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetOrderByIdPathParams { + /// ID of pet that needs to be fetched + #[validate( + range(min = 1, max = 5), + )] + pub order_id: i64, + } + + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeleteUserPathParams { + /// The name that needs to be deleted + pub username: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetUserByNamePathParams { + /// The name that needs to be fetched. Use user1 for testing. + pub username: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct LoginUserQueryParams { + /// The user name for login + #[serde(rename = "username")] + pub username: String, + /// The password for login in clear text + #[serde(rename = "password")] + pub password: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UpdateUserPathParams { + /// name that need to be deleted + pub username: String, + } + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AdditionalPropertiesClass { + #[serde(rename = "map_property")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_property: Option>, + + #[serde(rename = "map_of_map_property")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_of_map_property: Option>>, + +} + + +impl AdditionalPropertiesClass { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> AdditionalPropertiesClass { + AdditionalPropertiesClass { + map_property: None, + map_of_map_property: None, + } + } +} + +/// Converts the AdditionalPropertiesClass value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AdditionalPropertiesClass { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping map_property in query parameter serialization + + // Skipping map_of_map_property in query parameter serialization + // Skipping map_of_map_property in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AdditionalPropertiesClass value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AdditionalPropertiesClass { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub map_property: Vec>, + pub map_of_map_property: Vec>>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing AdditionalPropertiesClass".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "map_property" => return std::result::Result::Err("Parsing a container in this style is not supported in AdditionalPropertiesClass".to_string()), + "map_of_map_property" => return std::result::Result::Err("Parsing a container in this style is not supported in AdditionalPropertiesClass".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing AdditionalPropertiesClass".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(AdditionalPropertiesClass { + map_property: intermediate_rep.map_property.into_iter().next(), + map_of_map_property: intermediate_rep.map_of_map_property.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AdditionalPropertiesClass - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AdditionalPropertiesClass - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Animal { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + +} + + +impl Animal { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(class_name: String, ) -> Animal { + Animal { + class_name, + color: Some("red".to_string()), + } + } +} + +/// Converts the Animal value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Animal { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("className".to_string()), + Some(self.class_name.to_string()), + + + self.color.as_ref().map(|color| { + [ + "color".to_string(), + color.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Animal value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Animal { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub class_name: Vec, + pub color: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Animal".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Animal".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Animal { + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Animal".to_string())?, + color: intermediate_rep.color.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Animal - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Animal - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AnimalFarm(Vec); + +impl validator::Validate for AnimalFarm { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for AnimalFarm { + fn from(x: Vec) -> Self { + AnimalFarm(x) + } +} + +impl std::convert::From for Vec { + fn from(x: AnimalFarm) -> Self { + x.0 + } +} + +impl std::iter::FromIterator for AnimalFarm { + fn from_iter>(u: U) -> Self { + AnimalFarm(Vec::::from_iter(u)) + } +} + +impl std::iter::IntoIterator for AnimalFarm { + type Item = Animal; + type IntoIter = std::vec::IntoIter; + + fn into_iter(self) -> Self::IntoIter { + self.0.into_iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a AnimalFarm { + type Item = &'a Animal; + type IntoIter = std::slice::Iter<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter() + } +} + +impl<'a> std::iter::IntoIterator for &'a mut AnimalFarm { + type Item = &'a mut Animal; + type IntoIter = std::slice::IterMut<'a, Animal>; + + fn into_iter(self) -> Self::IntoIter { + self.0.iter_mut() + } +} + +impl std::ops::Deref for AnimalFarm { + type Target = Vec; + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl std::ops::DerefMut for AnimalFarm { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +/// Converts the AnimalFarm value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AnimalFarm { + fn to_string(&self) -> String { + self.iter().map(|x| x.to_string()).collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AnimalFarm value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AnimalFarm { + type Err = ::Err; + + fn from_str(s: &str) -> std::result::Result { + let mut items = vec![]; + for item in s.split(',') + { + items.push(item.parse()?); + } + std::result::Result::Ok(AnimalFarm(items)) + } +} + + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AnimalFarm - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AnimalFarm - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ApiResponse { + #[serde(rename = "code")] + #[serde(skip_serializing_if="Option::is_none")] + pub code: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if="Option::is_none")] + pub r#type: Option, + + #[serde(rename = "message")] + #[serde(skip_serializing_if="Option::is_none")] + pub message: Option, + +} + + +impl ApiResponse { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ApiResponse { + ApiResponse { + code: None, + r#type: None, + message: None, + } + } +} + +/// Converts the ApiResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ApiResponse { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.code.as_ref().map(|code| { + [ + "code".to_string(), + code.to_string(), + ].join(",") + }), + + + self.r#type.as_ref().map(|r#type| { + [ + "type".to_string(), + r#type.to_string(), + ].join(",") + }), + + + self.message.as_ref().map(|message| { + [ + "message".to_string(), + message.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ApiResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ApiResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub code: Vec, + pub r#type: Vec, + pub message: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ApiResponse".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "type" => intermediate_rep.r#type.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ApiResponse".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ApiResponse { + code: intermediate_rep.code.into_iter().next(), + r#type: intermediate_rep.r#type.into_iter().next(), + message: intermediate_rep.message.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ApiResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ApiResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ArrayOfArrayOfNumberOnly { + #[serde(rename = "ArrayArrayNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_number: Option>>, + +} + + +impl ArrayOfArrayOfNumberOnly { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ArrayOfArrayOfNumberOnly { + ArrayOfArrayOfNumberOnly { + array_array_number: None, + } + } +} + +/// Converts the ArrayOfArrayOfNumberOnly value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ArrayOfArrayOfNumberOnly { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping ArrayArrayNumber in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ArrayOfArrayOfNumberOnly value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ArrayOfArrayOfNumberOnly { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub array_array_number: Vec>>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ArrayOfArrayOfNumberOnly".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "ArrayArrayNumber" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayOfArrayOfNumberOnly".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing ArrayOfArrayOfNumberOnly".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ArrayOfArrayOfNumberOnly { + array_array_number: intermediate_rep.array_array_number.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ArrayOfArrayOfNumberOnly - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ArrayOfArrayOfNumberOnly - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ArrayOfNumberOnly { + #[serde(rename = "ArrayNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_number: Option>, + +} + + +impl ArrayOfNumberOnly { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ArrayOfNumberOnly { + ArrayOfNumberOnly { + array_number: None, + } + } +} + +/// Converts the ArrayOfNumberOnly value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ArrayOfNumberOnly { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.array_number.as_ref().map(|array_number| { + [ + "ArrayNumber".to_string(), + array_number.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ArrayOfNumberOnly value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ArrayOfNumberOnly { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub array_number: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ArrayOfNumberOnly".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "ArrayNumber" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayOfNumberOnly".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing ArrayOfNumberOnly".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ArrayOfNumberOnly { + array_number: intermediate_rep.array_number.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ArrayOfNumberOnly - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ArrayOfNumberOnly - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ArrayTest { + #[serde(rename = "array_of_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_of_string: Option>, + + #[serde(rename = "array_array_of_integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_of_integer: Option>>, + + #[serde(rename = "array_array_of_model")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_of_model: Option>>, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "array_of_enum")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_of_enum: Option>, + +} + + +impl ArrayTest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ArrayTest { + ArrayTest { + array_of_string: None, + array_array_of_integer: None, + array_array_of_model: None, + array_of_enum: None, + } + } +} + +/// Converts the ArrayTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ArrayTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.array_of_string.as_ref().map(|array_of_string| { + [ + "array_of_string".to_string(), + array_of_string.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + // Skipping array_array_of_integer in query parameter serialization + + // Skipping array_array_of_model in query parameter serialization + + + self.array_of_enum.as_ref().map(|array_of_enum| { + [ + "array_of_enum".to_string(), + array_of_enum.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ArrayTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ArrayTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub array_of_string: Vec>, + pub array_array_of_integer: Vec>>, + pub array_array_of_model: Vec>>, + pub array_of_enum: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ArrayTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "array_of_string" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), + "array_array_of_integer" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), + "array_array_of_model" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), + "array_of_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in ArrayTest".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing ArrayTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ArrayTest { + array_of_string: intermediate_rep.array_of_string.into_iter().next(), + array_array_of_integer: intermediate_rep.array_array_of_integer.into_iter().next(), + array_array_of_model: intermediate_rep.array_array_of_model.into_iter().next(), + array_of_enum: intermediate_rep.array_of_enum.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ArrayTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ArrayTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Capitalization { + #[serde(rename = "smallCamel")] + #[serde(skip_serializing_if="Option::is_none")] + pub small_camel: Option, + + #[serde(rename = "CapitalCamel")] + #[serde(skip_serializing_if="Option::is_none")] + pub capital_camel: Option, + + #[serde(rename = "small_Snake")] + #[serde(skip_serializing_if="Option::is_none")] + pub small_snake: Option, + + #[serde(rename = "Capital_Snake")] + #[serde(skip_serializing_if="Option::is_none")] + pub capital_snake: Option, + + #[serde(rename = "SCA_ETH_Flow_Points")] + #[serde(skip_serializing_if="Option::is_none")] + pub sca_eth_flow_points: Option, + +/// Name of the pet + #[serde(rename = "ATT_NAME")] + #[serde(skip_serializing_if="Option::is_none")] + pub att_name: Option, + +} + + +impl Capitalization { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Capitalization { + Capitalization { + small_camel: None, + capital_camel: None, + small_snake: None, + capital_snake: None, + sca_eth_flow_points: None, + att_name: None, + } + } +} + +/// Converts the Capitalization value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Capitalization { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.small_camel.as_ref().map(|small_camel| { + [ + "smallCamel".to_string(), + small_camel.to_string(), + ].join(",") + }), + + + self.capital_camel.as_ref().map(|capital_camel| { + [ + "CapitalCamel".to_string(), + capital_camel.to_string(), + ].join(",") + }), + + + self.small_snake.as_ref().map(|small_snake| { + [ + "small_Snake".to_string(), + small_snake.to_string(), + ].join(",") + }), + + + self.capital_snake.as_ref().map(|capital_snake| { + [ + "Capital_Snake".to_string(), + capital_snake.to_string(), + ].join(",") + }), + + + self.sca_eth_flow_points.as_ref().map(|sca_eth_flow_points| { + [ + "SCA_ETH_Flow_Points".to_string(), + sca_eth_flow_points.to_string(), + ].join(",") + }), + + + self.att_name.as_ref().map(|att_name| { + [ + "ATT_NAME".to_string(), + att_name.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Capitalization value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Capitalization { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub small_camel: Vec, + pub capital_camel: Vec, + pub small_snake: Vec, + pub capital_snake: Vec, + pub sca_eth_flow_points: Vec, + pub att_name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Capitalization".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "smallCamel" => intermediate_rep.small_camel.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "CapitalCamel" => intermediate_rep.capital_camel.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "small_Snake" => intermediate_rep.small_snake.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "Capital_Snake" => intermediate_rep.capital_snake.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "SCA_ETH_Flow_Points" => intermediate_rep.sca_eth_flow_points.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "ATT_NAME" => intermediate_rep.att_name.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Capitalization".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Capitalization { + small_camel: intermediate_rep.small_camel.into_iter().next(), + capital_camel: intermediate_rep.capital_camel.into_iter().next(), + small_snake: intermediate_rep.small_snake.into_iter().next(), + capital_snake: intermediate_rep.capital_snake.into_iter().next(), + sca_eth_flow_points: intermediate_rep.sca_eth_flow_points.into_iter().next(), + att_name: intermediate_rep.att_name.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Capitalization - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Capitalization - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Cat { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + + #[serde(rename = "declawed")] + #[serde(skip_serializing_if="Option::is_none")] + pub declawed: Option, + +} + + +impl Cat { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(class_name: String, ) -> Cat { + Cat { + class_name, + color: Some("red".to_string()), + declawed: None, + } + } +} + +/// Converts the Cat value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Cat { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("className".to_string()), + Some(self.class_name.to_string()), + + + self.color.as_ref().map(|color| { + [ + "color".to_string(), + color.to_string(), + ].join(",") + }), + + + self.declawed.as_ref().map(|declawed| { + [ + "declawed".to_string(), + declawed.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Cat value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Cat { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub class_name: Vec, + pub color: Vec, + pub declawed: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Cat".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "declawed" => intermediate_rep.declawed.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Cat".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Cat { + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Cat".to_string())?, + color: intermediate_rep.color.into_iter().next(), + declawed: intermediate_rep.declawed.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Cat - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Cat - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Category { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + + +impl Category { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Category { + Category { + id: None, + name: None, + } + } +} + +/// Converts the Category value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Category { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.name.as_ref().map(|name| { + [ + "name".to_string(), + name.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Category value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Category { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Category".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Category".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Category { + id: intermediate_rep.id.into_iter().next(), + name: intermediate_rep.name.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Category - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Category - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Model for testing model with \"_class\" property + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ClassModel { + #[serde(rename = "_class")] + #[serde(skip_serializing_if="Option::is_none")] + pub _class: Option, + +} + + +impl ClassModel { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ClassModel { + ClassModel { + _class: None, + } + } +} + +/// Converts the ClassModel value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ClassModel { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self._class.as_ref().map(|_class| { + [ + "_class".to_string(), + _class.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ClassModel value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ClassModel { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub _class: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ClassModel".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "_class" => intermediate_rep._class.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ClassModel".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ClassModel { + _class: intermediate_rep._class.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ClassModel - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ClassModel - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Client { + #[serde(rename = "client")] + #[serde(skip_serializing_if="Option::is_none")] + pub client: Option, + +} + + +impl Client { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Client { + Client { + client: None, + } + } +} + +/// Converts the Client value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Client { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.client.as_ref().map(|client| { + [ + "client".to_string(), + client.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Client value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Client { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub client: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Client".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "client" => intermediate_rep.client.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Client".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Client { + client: intermediate_rep.client.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Client - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Client - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Dog { + #[serde(rename = "className")] + pub class_name: String, + + #[serde(rename = "color")] + #[serde(skip_serializing_if="Option::is_none")] + pub color: Option, + + #[serde(rename = "breed")] + #[serde(skip_serializing_if="Option::is_none")] + pub breed: Option, + +} + + +impl Dog { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(class_name: String, ) -> Dog { + Dog { + class_name, + color: Some("red".to_string()), + breed: None, + } + } +} + +/// Converts the Dog value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Dog { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("className".to_string()), + Some(self.class_name.to_string()), + + + self.color.as_ref().map(|color| { + [ + "color".to_string(), + color.to_string(), + ].join(",") + }), + + + self.breed.as_ref().map(|breed| { + [ + "breed".to_string(), + breed.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Dog value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Dog { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub class_name: Vec, + pub color: Vec, + pub breed: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Dog".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "className" => intermediate_rep.class_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "color" => intermediate_rep.color.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "breed" => intermediate_rep.breed.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Dog".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Dog { + class_name: intermediate_rep.class_name.into_iter().next().ok_or_else(|| "className missing in Dog".to_string())?, + color: intermediate_rep.color.into_iter().next(), + breed: intermediate_rep.breed.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Dog - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Dog - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + #[serde(rename = "$special[property.name]")] + #[serde(skip_serializing_if="Option::is_none")] + pub dollar_special_left_square_bracket_property_period_name_right_square_bracket: Option, + +} + + +impl DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + dollar_special_left_square_bracket_property_period_name_right_square_bracket: None, + } + } +} + +/// Converts the DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.dollar_special_left_square_bracket_property_period_name_right_square_bracket.as_ref().map(|dollar_special_left_square_bracket_property_period_name_right_square_bracket| { + [ + "$special[property.name]".to_string(), + dollar_special_left_square_bracket_property_period_name_right_square_bracket.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub dollar_special_left_square_bracket_property_period_name_right_square_bracket: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "$special[property.name]" => intermediate_rep.dollar_special_left_square_bracket_property_period_name_right_square_bracket.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket { + dollar_special_left_square_bracket_property_period_name_right_square_bracket: intermediate_rep.dollar_special_left_square_bracket_property_period_name_right_square_bracket.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into DollarSpecialLeftSquareBracketModelPeriodNameRightSquareBracket - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct EnumArrays { +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "just_symbol")] + #[serde(skip_serializing_if="Option::is_none")] + pub just_symbol: Option, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "array_enum")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_enum: Option>, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "array_array_enum")] + #[serde(skip_serializing_if="Option::is_none")] + pub array_array_enum: Option>>, + +} + + +impl EnumArrays { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> EnumArrays { + EnumArrays { + just_symbol: None, + array_enum: None, + array_array_enum: None, + } + } +} + +/// Converts the EnumArrays value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for EnumArrays { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.just_symbol.as_ref().map(|just_symbol| { + [ + "just_symbol".to_string(), + just_symbol.to_string(), + ].join(",") + }), + + + self.array_enum.as_ref().map(|array_enum| { + [ + "array_enum".to_string(), + array_enum.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + // Skipping array_array_enum in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a EnumArrays value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for EnumArrays { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub just_symbol: Vec, + pub array_enum: Vec>, + pub array_array_enum: Vec>>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing EnumArrays".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "just_symbol" => intermediate_rep.just_symbol.push(::from_str(val).map_err(|x| x.to_string())?), + "array_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in EnumArrays".to_string()), + "array_array_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in EnumArrays".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing EnumArrays".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(EnumArrays { + just_symbol: intermediate_rep.just_symbol.into_iter().next(), + array_enum: intermediate_rep.array_enum.into_iter().next(), + array_array_enum: intermediate_rep.array_array_enum.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for EnumArrays - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into EnumArrays - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum EnumClass { + #[serde(rename = "_abc")] + Abc, + #[serde(rename = "-efg")] + Efg, + #[serde(rename = "(xyz)")] + LeftParenthesisXyzRightParenthesis, +} + +impl std::fmt::Display for EnumClass { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + EnumClass::Abc => write!(f, "_abc"), + EnumClass::Efg => write!(f, "-efg"), + EnumClass::LeftParenthesisXyzRightParenthesis => write!(f, "(xyz)"), + } + } +} + +impl std::str::FromStr for EnumClass { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "_abc" => std::result::Result::Ok(EnumClass::Abc), + "-efg" => std::result::Result::Ok(EnumClass::Efg), + "(xyz)" => std::result::Result::Ok(EnumClass::LeftParenthesisXyzRightParenthesis), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct EnumTest { +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_string: Option, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_string_required")] + pub enum_string_required: String, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_integer")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_integer: Option, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "enum_number")] + #[serde(skip_serializing_if="Option::is_none")] + pub enum_number: Option, + + #[serde(rename = "outerEnum")] + #[serde(skip_serializing_if="Option::is_none")] + pub outer_enum: Option, + +} + + +impl EnumTest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(enum_string_required: String, ) -> EnumTest { + EnumTest { + enum_string: None, + enum_string_required, + enum_integer: None, + enum_number: None, + outer_enum: None, + } + } +} + +/// Converts the EnumTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for EnumTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.enum_string.as_ref().map(|enum_string| { + [ + "enum_string".to_string(), + enum_string.to_string(), + ].join(",") + }), + + + Some("enum_string_required".to_string()), + Some(self.enum_string_required.to_string()), + + + self.enum_integer.as_ref().map(|enum_integer| { + [ + "enum_integer".to_string(), + enum_integer.to_string(), + ].join(",") + }), + + + self.enum_number.as_ref().map(|enum_number| { + [ + "enum_number".to_string(), + enum_number.to_string(), + ].join(",") + }), + + // Skipping outerEnum in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a EnumTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for EnumTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub enum_string: Vec, + pub enum_string_required: Vec, + pub enum_integer: Vec, + pub enum_number: Vec, + pub outer_enum: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing EnumTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "enum_string" => intermediate_rep.enum_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_string_required" => intermediate_rep.enum_string_required.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_integer" => intermediate_rep.enum_integer.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "enum_number" => intermediate_rep.enum_number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "outerEnum" => intermediate_rep.outer_enum.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing EnumTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(EnumTest { + enum_string: intermediate_rep.enum_string.into_iter().next(), + enum_string_required: intermediate_rep.enum_string_required.into_iter().next().ok_or_else(|| "enum_string_required missing in EnumTest".to_string())?, + enum_integer: intermediate_rep.enum_integer.into_iter().next(), + enum_number: intermediate_rep.enum_number.into_iter().next(), + outer_enum: intermediate_rep.outer_enum.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for EnumTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into EnumTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct FormatTest { + #[serde(rename = "integer")] + #[validate( + range(min = 10, max = 100), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub integer: Option, + + #[serde(rename = "int32")] + #[validate( + range(min = 20, max = 200), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub int32: Option, + + #[serde(rename = "int64")] + #[serde(skip_serializing_if="Option::is_none")] + pub int64: Option, + + #[serde(rename = "number")] + #[validate( + range(min = 32.1, max = 543.2), + )] + pub number: f64, + + #[serde(rename = "float")] + #[validate( + range(min = 54.3, max = 987.6), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub float: Option, + + #[serde(rename = "double")] + #[validate( + range(min = 67.8, max = 123.4), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub double: Option, + + #[serde(rename = "string")] + #[validate( + regex = "RE_FORMATTEST_STRING", + )] + #[serde(skip_serializing_if="Option::is_none")] + pub string: Option, + + #[serde(rename = "byte")] + #[validate( + custom ="validate_byte_formattest_byte" + )] + pub byte: ByteArray, + + #[serde(rename = "binary")] + #[serde(skip_serializing_if="Option::is_none")] + pub binary: Option, + + #[serde(rename = "date")] + pub date: chrono::naive::NaiveDate, + + #[serde(rename = "dateTime")] + #[serde(skip_serializing_if="Option::is_none")] + pub date_time: Option>, + + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + + #[serde(rename = "password")] + #[validate( + length(min = 10, max = 64), + )] + pub password: String, + +} + +lazy_static::lazy_static! { + static ref RE_FORMATTEST_STRING: regex::Regex = regex::Regex::new(r"/[a-z]/i").unwrap(); +} +lazy_static::lazy_static! { + static ref RE_FORMATTEST_BYTE: regex::bytes::Regex = regex::bytes::Regex::new(r"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$").unwrap(); +} +fn validate_byte_formattest_byte( + b: &ByteArray +) -> std::result::Result<(), validator::ValidationError> { + if !RE_FORMATTEST_BYTE.is_match(&b.0) { + return Err(validator::ValidationError::new("Character not allowed")); + } + std::result::Result::Ok(()) +} + +impl FormatTest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(number: f64, byte: ByteArray, date: chrono::naive::NaiveDate, password: String, ) -> FormatTest { + FormatTest { + integer: None, + int32: None, + int64: None, + number, + float: None, + double: None, + string: None, + byte, + binary: None, + date, + date_time: None, + uuid: None, + password, + } + } +} + +/// Converts the FormatTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for FormatTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.integer.as_ref().map(|integer| { + [ + "integer".to_string(), + integer.to_string(), + ].join(",") + }), + + + self.int32.as_ref().map(|int32| { + [ + "int32".to_string(), + int32.to_string(), + ].join(",") + }), + + + self.int64.as_ref().map(|int64| { + [ + "int64".to_string(), + int64.to_string(), + ].join(",") + }), + + + Some("number".to_string()), + Some(self.number.to_string()), + + + self.float.as_ref().map(|float| { + [ + "float".to_string(), + float.to_string(), + ].join(",") + }), + + + self.double.as_ref().map(|double| { + [ + "double".to_string(), + double.to_string(), + ].join(",") + }), + + + self.string.as_ref().map(|string| { + [ + "string".to_string(), + string.to_string(), + ].join(",") + }), + + // Skipping byte in query parameter serialization + // Skipping byte in query parameter serialization + + // Skipping binary in query parameter serialization + // Skipping binary in query parameter serialization + + // Skipping date in query parameter serialization + + // Skipping dateTime in query parameter serialization + + // Skipping uuid in query parameter serialization + + + Some("password".to_string()), + Some(self.password.to_string()), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a FormatTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for FormatTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub integer: Vec, + pub int32: Vec, + pub int64: Vec, + pub number: Vec, + pub float: Vec, + pub double: Vec, + pub string: Vec, + pub byte: Vec, + pub binary: Vec, + pub date: Vec, + pub date_time: Vec>, + pub uuid: Vec, + pub password: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing FormatTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "integer" => intermediate_rep.integer.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int32" => intermediate_rep.int32.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "int64" => intermediate_rep.int64.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "number" => intermediate_rep.number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "float" => intermediate_rep.float.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "double" => intermediate_rep.double.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "string" => intermediate_rep.string.push(::from_str(val).map_err(|x| x.to_string())?), + "byte" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), + "binary" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), + #[allow(clippy::redundant_clone)] + "date" => intermediate_rep.date.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing FormatTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(FormatTest { + integer: intermediate_rep.integer.into_iter().next(), + int32: intermediate_rep.int32.into_iter().next(), + int64: intermediate_rep.int64.into_iter().next(), + number: intermediate_rep.number.into_iter().next().ok_or_else(|| "number missing in FormatTest".to_string())?, + float: intermediate_rep.float.into_iter().next(), + double: intermediate_rep.double.into_iter().next(), + string: intermediate_rep.string.into_iter().next(), + byte: intermediate_rep.byte.into_iter().next().ok_or_else(|| "byte missing in FormatTest".to_string())?, + binary: intermediate_rep.binary.into_iter().next(), + date: intermediate_rep.date.into_iter().next().ok_or_else(|| "date missing in FormatTest".to_string())?, + date_time: intermediate_rep.date_time.into_iter().next(), + uuid: intermediate_rep.uuid.into_iter().next(), + password: intermediate_rep.password.into_iter().next().ok_or_else(|| "password missing in FormatTest".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for FormatTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into FormatTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct HasOnlyReadOnly { + #[serde(rename = "bar")] + #[serde(skip_serializing_if="Option::is_none")] + pub bar: Option, + + #[serde(rename = "foo")] + #[serde(skip_serializing_if="Option::is_none")] + pub foo: Option, + +} + + +impl HasOnlyReadOnly { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> HasOnlyReadOnly { + HasOnlyReadOnly { + bar: None, + foo: None, + } + } +} + +/// Converts the HasOnlyReadOnly value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for HasOnlyReadOnly { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.bar.as_ref().map(|bar| { + [ + "bar".to_string(), + bar.to_string(), + ].join(",") + }), + + + self.foo.as_ref().map(|foo| { + [ + "foo".to_string(), + foo.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a HasOnlyReadOnly value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for HasOnlyReadOnly { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub bar: Vec, + pub foo: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing HasOnlyReadOnly".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "foo" => intermediate_rep.foo.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing HasOnlyReadOnly".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(HasOnlyReadOnly { + bar: intermediate_rep.bar.into_iter().next(), + foo: intermediate_rep.foo.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for HasOnlyReadOnly - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into HasOnlyReadOnly - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct List { + #[serde(rename = "123-list")] + #[serde(skip_serializing_if="Option::is_none")] + pub param_123_list: Option, + +} + + +impl List { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> List { + List { + param_123_list: None, + } + } +} + +/// Converts the List value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for List { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.param_123_list.as_ref().map(|param_123_list| { + [ + "123-list".to_string(), + param_123_list.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a List value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for List { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub param_123_list: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing List".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "123-list" => intermediate_rep.param_123_list.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing List".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(List { + param_123_list: intermediate_rep.param_123_list.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for List - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into List - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MapTest { + #[serde(rename = "map_map_of_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_map_of_string: Option>>, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "map_map_of_enum")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_map_of_enum: Option>>, + +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "map_of_enum_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub map_of_enum_string: Option>, + +} + + +impl MapTest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> MapTest { + MapTest { + map_map_of_string: None, + map_map_of_enum: None, + map_of_enum_string: None, + } + } +} + +/// Converts the MapTest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MapTest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping map_map_of_string in query parameter serialization + // Skipping map_map_of_string in query parameter serialization + + // Skipping map_map_of_enum in query parameter serialization + // Skipping map_map_of_enum in query parameter serialization + + // Skipping map_of_enum_string in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MapTest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MapTest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub map_map_of_string: Vec>>, + pub map_map_of_enum: Vec>>, + pub map_of_enum_string: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MapTest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "map_map_of_string" => return std::result::Result::Err("Parsing a container in this style is not supported in MapTest".to_string()), + "map_map_of_enum" => return std::result::Result::Err("Parsing a container in this style is not supported in MapTest".to_string()), + "map_of_enum_string" => return std::result::Result::Err("Parsing a container in this style is not supported in MapTest".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing MapTest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MapTest { + map_map_of_string: intermediate_rep.map_map_of_string.into_iter().next(), + map_map_of_enum: intermediate_rep.map_map_of_enum.into_iter().next(), + map_of_enum_string: intermediate_rep.map_of_enum_string.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MapTest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MapTest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct MixedPropertiesAndAdditionalPropertiesClass { + #[serde(rename = "uuid")] + #[serde(skip_serializing_if="Option::is_none")] + pub uuid: Option, + + #[serde(rename = "dateTime")] + #[serde(skip_serializing_if="Option::is_none")] + pub date_time: Option>, + + #[serde(rename = "map")] + #[serde(skip_serializing_if="Option::is_none")] + pub map: Option>, + +} + + +impl MixedPropertiesAndAdditionalPropertiesClass { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> MixedPropertiesAndAdditionalPropertiesClass { + MixedPropertiesAndAdditionalPropertiesClass { + uuid: None, + date_time: None, + map: None, + } + } +} + +/// Converts the MixedPropertiesAndAdditionalPropertiesClass value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for MixedPropertiesAndAdditionalPropertiesClass { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping uuid in query parameter serialization + + // Skipping dateTime in query parameter serialization + + // Skipping map in query parameter serialization + // Skipping map in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a MixedPropertiesAndAdditionalPropertiesClass value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for MixedPropertiesAndAdditionalPropertiesClass { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub uuid: Vec, + pub date_time: Vec>, + pub map: Vec>, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing MixedPropertiesAndAdditionalPropertiesClass".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "uuid" => intermediate_rep.uuid.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + "map" => return std::result::Result::Err("Parsing a container in this style is not supported in MixedPropertiesAndAdditionalPropertiesClass".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing MixedPropertiesAndAdditionalPropertiesClass".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(MixedPropertiesAndAdditionalPropertiesClass { + uuid: intermediate_rep.uuid.into_iter().next(), + date_time: intermediate_rep.date_time.into_iter().next(), + map: intermediate_rep.map.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for MixedPropertiesAndAdditionalPropertiesClass - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into MixedPropertiesAndAdditionalPropertiesClass - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Model for testing model name starting with number + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Model200Response { + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + + #[serde(rename = "class")] + #[serde(skip_serializing_if="Option::is_none")] + pub class: Option, + +} + + +impl Model200Response { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Model200Response { + Model200Response { + name: None, + class: None, + } + } +} + +/// Converts the Model200Response value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Model200Response { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.name.as_ref().map(|name| { + [ + "name".to_string(), + name.to_string(), + ].join(",") + }), + + + self.class.as_ref().map(|class| { + [ + "class".to_string(), + class.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Model200Response value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Model200Response { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub name: Vec, + pub class: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Model200Response".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "class" => intermediate_rep.class.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Model200Response".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Model200Response { + name: intermediate_rep.name.into_iter().next(), + class: intermediate_rep.class.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Model200Response - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Model200Response - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Model for testing model name same as property name + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Name { + #[serde(rename = "name")] + pub name: i32, + + #[serde(rename = "snake_case")] + #[serde(skip_serializing_if="Option::is_none")] + pub snake_case: Option, + + #[serde(rename = "property")] + #[serde(skip_serializing_if="Option::is_none")] + pub property: Option, + + #[serde(rename = "123Number")] + #[serde(skip_serializing_if="Option::is_none")] + pub param_123_number: Option, + +} + + +impl Name { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(name: i32, ) -> Name { + Name { + name, + snake_case: None, + property: None, + param_123_number: None, + } + } +} + +/// Converts the Name value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Name { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("name".to_string()), + Some(self.name.to_string()), + + + self.snake_case.as_ref().map(|snake_case| { + [ + "snake_case".to_string(), + snake_case.to_string(), + ].join(",") + }), + + + self.property.as_ref().map(|property| { + [ + "property".to_string(), + property.to_string(), + ].join(",") + }), + + + self.param_123_number.as_ref().map(|param_123_number| { + [ + "123Number".to_string(), + param_123_number.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Name value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Name { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub name: Vec, + pub snake_case: Vec, + pub property: Vec, + pub param_123_number: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Name".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "snake_case" => intermediate_rep.snake_case.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "property" => intermediate_rep.property.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "123Number" => intermediate_rep.param_123_number.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Name".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Name { + name: intermediate_rep.name.into_iter().next().ok_or_else(|| "name missing in Name".to_string())?, + snake_case: intermediate_rep.snake_case.into_iter().next(), + property: intermediate_rep.property.into_iter().next(), + param_123_number: intermediate_rep.param_123_number.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Name - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Name - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct NumberOnly { + #[serde(rename = "JustNumber")] + #[serde(skip_serializing_if="Option::is_none")] + pub just_number: Option, + +} + + +impl NumberOnly { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> NumberOnly { + NumberOnly { + just_number: None, + } + } +} + +/// Converts the NumberOnly value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for NumberOnly { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.just_number.as_ref().map(|just_number| { + [ + "JustNumber".to_string(), + just_number.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a NumberOnly value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for NumberOnly { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub just_number: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing NumberOnly".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "JustNumber" => intermediate_rep.just_number.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing NumberOnly".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(NumberOnly { + just_number: intermediate_rep.just_number.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for NumberOnly - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into NumberOnly - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectContainingObjectWithOnlyAdditionalProperties { + #[serde(rename = "inner")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner: Option, + +} + + +impl ObjectContainingObjectWithOnlyAdditionalProperties { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ObjectContainingObjectWithOnlyAdditionalProperties { + ObjectContainingObjectWithOnlyAdditionalProperties { + inner: None, + } + } +} + +/// Converts the ObjectContainingObjectWithOnlyAdditionalProperties value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectContainingObjectWithOnlyAdditionalProperties { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping inner in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectContainingObjectWithOnlyAdditionalProperties value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectContainingObjectWithOnlyAdditionalProperties { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub inner: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectContainingObjectWithOnlyAdditionalProperties".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectContainingObjectWithOnlyAdditionalProperties".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectContainingObjectWithOnlyAdditionalProperties { + inner: intermediate_rep.inner.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectContainingObjectWithOnlyAdditionalProperties - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectContainingObjectWithOnlyAdditionalProperties - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectWithOnlyAdditionalProperties(std::collections::HashMap); + +impl validator::Validate for ObjectWithOnlyAdditionalProperties { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for ObjectWithOnlyAdditionalProperties { + fn from(x: std::collections::HashMap) -> Self { + ObjectWithOnlyAdditionalProperties(x) + } +} + +impl std::convert::From for std::collections::HashMap { + fn from(x: ObjectWithOnlyAdditionalProperties) -> Self { + x.0 + } +} + +impl std::ops::Deref for ObjectWithOnlyAdditionalProperties { + type Target = std::collections::HashMap; + fn deref(&self) -> &std::collections::HashMap { + &self.0 + } +} + +impl std::ops::DerefMut for ObjectWithOnlyAdditionalProperties { + fn deref_mut(&mut self) -> &mut std::collections::HashMap { + &mut self.0 + } +} + +/// Converts the ObjectWithOnlyAdditionalProperties value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for ObjectWithOnlyAdditionalProperties { + fn to_string(&self) -> String { + // Skipping additionalProperties in query parameter serialization + "".to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectWithOnlyAdditionalProperties value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for ObjectWithOnlyAdditionalProperties { + type Err = &'static str; + + fn from_str(s: &str) -> std::result::Result { + std::result::Result::Err("Parsing additionalProperties for ObjectWithOnlyAdditionalProperties is not supported") + } +} + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Order { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "petId")] + #[serde(skip_serializing_if="Option::is_none")] + pub pet_id: Option, + + #[serde(rename = "quantity")] + #[serde(skip_serializing_if="Option::is_none")] + pub quantity: Option, + + #[serde(rename = "shipDate")] + #[serde(skip_serializing_if="Option::is_none")] + pub ship_date: Option>, + +/// Order Status +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + + #[serde(rename = "complete")] + #[serde(skip_serializing_if="Option::is_none")] + pub complete: Option, + +} + + +impl Order { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Order { + Order { + id: None, + pet_id: None, + quantity: None, + ship_date: None, + status: None, + complete: Some(false), + } + } +} + +/// Converts the Order value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Order { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.pet_id.as_ref().map(|pet_id| { + [ + "petId".to_string(), + pet_id.to_string(), + ].join(",") + }), + + + self.quantity.as_ref().map(|quantity| { + [ + "quantity".to_string(), + quantity.to_string(), + ].join(",") + }), + + // Skipping shipDate in query parameter serialization + + + self.status.as_ref().map(|status| { + [ + "status".to_string(), + status.to_string(), + ].join(",") + }), + + + self.complete.as_ref().map(|complete| { + [ + "complete".to_string(), + complete.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Order value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Order { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub pet_id: Vec, + pub quantity: Vec, + pub ship_date: Vec>, + pub status: Vec, + pub complete: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Order".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "petId" => intermediate_rep.pet_id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "quantity" => intermediate_rep.quantity.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "shipDate" => intermediate_rep.ship_date.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "complete" => intermediate_rep.complete.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Order".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Order { + id: intermediate_rep.id.into_iter().next(), + pet_id: intermediate_rep.pet_id.into_iter().next(), + quantity: intermediate_rep.quantity.into_iter().next(), + ship_date: intermediate_rep.ship_date.into_iter().next(), + status: intermediate_rep.status.into_iter().next(), + complete: intermediate_rep.complete.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Order - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Order - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct OuterBoolean(bool); + +impl validator::Validate for OuterBoolean { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for OuterBoolean { + fn from(x: bool) -> Self { + OuterBoolean(x) + } +} + +impl std::convert::From for bool { + fn from(x: OuterBoolean) -> Self { + x.0 + } +} + +impl std::ops::Deref for OuterBoolean { + type Target = bool; + fn deref(&self) -> &bool { + &self.0 + } +} + +impl std::ops::DerefMut for OuterBoolean { + fn deref_mut(&mut self) -> &mut bool { + &mut self.0 + } +} + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct OuterComposite { + #[serde(rename = "my_number")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_number: Option, + + #[serde(rename = "my_string")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_string: Option, + + #[serde(rename = "my_boolean")] + #[serde(skip_serializing_if="Option::is_none")] + pub my_boolean: Option, + +} + + +impl OuterComposite { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> OuterComposite { + OuterComposite { + my_number: None, + my_string: None, + my_boolean: None, + } + } +} + +/// Converts the OuterComposite value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for OuterComposite { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.my_number.as_ref().map(|my_number| { + [ + "my_number".to_string(), + my_number.to_string(), + ].join(",") + }), + + + self.my_string.as_ref().map(|my_string| { + [ + "my_string".to_string(), + my_string.to_string(), + ].join(",") + }), + + + self.my_boolean.as_ref().map(|my_boolean| { + [ + "my_boolean".to_string(), + my_boolean.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a OuterComposite value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for OuterComposite { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub my_number: Vec, + pub my_string: Vec, + pub my_boolean: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing OuterComposite".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "my_number" => intermediate_rep.my_number.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "my_string" => intermediate_rep.my_string.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "my_boolean" => intermediate_rep.my_boolean.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing OuterComposite".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(OuterComposite { + my_number: intermediate_rep.my_number.into_iter().next(), + my_string: intermediate_rep.my_string.into_iter().next(), + my_boolean: intermediate_rep.my_boolean.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for OuterComposite - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into OuterComposite - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Enumeration of values. +/// Since this enum's variants do not hold data, we can easily define them as `#[repr(C)]` +/// which helps with FFI. +#[allow(non_camel_case_types)] +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk_enum_derive::LabelledGenericEnum))] +pub enum OuterEnum { + #[serde(rename = "placed")] + Placed, + #[serde(rename = "approved")] + Approved, + #[serde(rename = "delivered")] + Delivered, +} + +impl std::fmt::Display for OuterEnum { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match *self { + OuterEnum::Placed => write!(f, "placed"), + OuterEnum::Approved => write!(f, "approved"), + OuterEnum::Delivered => write!(f, "delivered"), + } + } +} + +impl std::str::FromStr for OuterEnum { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + match s { + "placed" => std::result::Result::Ok(OuterEnum::Placed), + "approved" => std::result::Result::Ok(OuterEnum::Approved), + "delivered" => std::result::Result::Ok(OuterEnum::Delivered), + _ => std::result::Result::Err(format!("Value not valid: {}", s)), + } + } +} + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct OuterNumber(f64); + +impl validator::Validate for OuterNumber { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for OuterNumber { + fn from(x: f64) -> Self { + OuterNumber(x) + } +} + +impl std::convert::From for f64 { + fn from(x: OuterNumber) -> Self { + x.0 + } +} + +impl std::ops::Deref for OuterNumber { + type Target = f64; + fn deref(&self) -> &f64 { + &self.0 + } +} + +impl std::ops::DerefMut for OuterNumber { + fn deref_mut(&mut self) -> &mut f64 { + &mut self.0 + } +} + + + +#[derive(Debug, Clone, PartialEq, PartialOrd, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct OuterString(String); + +impl validator::Validate for OuterString { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From for OuterString { + fn from(x: String) -> Self { + OuterString(x) + } +} + +impl std::string::ToString for OuterString { + fn to_string(&self) -> String { + self.0.to_string() + } +} + +impl std::str::FromStr for OuterString { + type Err = std::string::ParseError; + fn from_str(x: &str) -> std::result::Result { + std::result::Result::Ok(OuterString(x.to_string())) + } +} + +impl std::convert::From for String { + fn from(x: OuterString) -> Self { + x.0 + } +} + +impl std::ops::Deref for OuterString { + type Target = String; + fn deref(&self) -> &String { + &self.0 + } +} + +impl std::ops::DerefMut for OuterString { + fn deref_mut(&mut self) -> &mut String { + &mut self.0 + } +} + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Pet { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "category")] + #[serde(skip_serializing_if="Option::is_none")] + pub category: Option, + + #[serde(rename = "name")] + pub name: String, + + #[serde(rename = "photoUrls")] + pub photo_urls: Vec, + + #[serde(rename = "tags")] + #[serde(skip_serializing_if="Option::is_none")] + pub tags: Option>, + +/// pet status in the store +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + +} + + +impl Pet { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(name: String, photo_urls: Vec, ) -> Pet { + Pet { + id: None, + category: None, + name, + photo_urls, + tags: None, + status: None, + } + } +} + +/// Converts the Pet value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Pet { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + // Skipping category in query parameter serialization + + + Some("name".to_string()), + Some(self.name.to_string()), + + + Some("photoUrls".to_string()), + Some(self.photo_urls.iter().map(|x| x.to_string()).collect::>().join(",")), + + // Skipping tags in query parameter serialization + + + self.status.as_ref().map(|status| { + [ + "status".to_string(), + status.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Pet value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Pet { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub category: Vec, + pub name: Vec, + pub photo_urls: Vec>, + pub tags: Vec>, + pub status: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Pet".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "category" => intermediate_rep.category.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + "photoUrls" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), + "tags" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Pet".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Pet { + id: intermediate_rep.id.into_iter().next(), + category: intermediate_rep.category.into_iter().next(), + name: intermediate_rep.name.into_iter().next().ok_or_else(|| "name missing in Pet".to_string())?, + photo_urls: intermediate_rep.photo_urls.into_iter().next().ok_or_else(|| "photoUrls missing in Pet".to_string())?, + tags: intermediate_rep.tags.into_iter().next(), + status: intermediate_rep.status.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Pet - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Pet - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ReadOnlyFirst { + #[serde(rename = "bar")] + #[serde(skip_serializing_if="Option::is_none")] + pub bar: Option, + + #[serde(rename = "baz")] + #[serde(skip_serializing_if="Option::is_none")] + pub baz: Option, + +} + + +impl ReadOnlyFirst { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ReadOnlyFirst { + ReadOnlyFirst { + bar: None, + baz: None, + } + } +} + +/// Converts the ReadOnlyFirst value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ReadOnlyFirst { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.bar.as_ref().map(|bar| { + [ + "bar".to_string(), + bar.to_string(), + ].join(",") + }), + + + self.baz.as_ref().map(|baz| { + [ + "baz".to_string(), + baz.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ReadOnlyFirst value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ReadOnlyFirst { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub bar: Vec, + pub baz: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ReadOnlyFirst".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "bar" => intermediate_rep.bar.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "baz" => intermediate_rep.baz.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ReadOnlyFirst".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ReadOnlyFirst { + bar: intermediate_rep.bar.into_iter().next(), + baz: intermediate_rep.baz.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ReadOnlyFirst - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ReadOnlyFirst - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// Model for testing reserved words + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Return { + #[serde(rename = "return")] + #[serde(skip_serializing_if="Option::is_none")] + pub r#return: Option, + +} + + +impl Return { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Return { + Return { + r#return: None, + } + } +} + +/// Converts the Return value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Return { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.r#return.as_ref().map(|r#return| { + [ + "return".to_string(), + r#return.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Return value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Return { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub r#return: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Return".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "return" => intermediate_rep.r#return.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Return".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Return { + r#return: intermediate_rep.r#return.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Return - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Return - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Tag { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + + +impl Tag { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Tag { + Tag { + id: None, + name: None, + } + } +} + +/// Converts the Tag value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Tag { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.name.as_ref().map(|name| { + [ + "name".to_string(), + name.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Tag value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Tag { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Tag".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Tag".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Tag { + id: intermediate_rep.id.into_iter().next(), + name: intermediate_rep.name.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Tag - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Tag - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct User { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "username")] + #[serde(skip_serializing_if="Option::is_none")] + pub username: Option, + + #[serde(rename = "firstName")] + #[serde(skip_serializing_if="Option::is_none")] + pub first_name: Option, + + #[serde(rename = "lastName")] + #[serde(skip_serializing_if="Option::is_none")] + pub last_name: Option, + + #[serde(rename = "email")] + #[serde(skip_serializing_if="Option::is_none")] + pub email: Option, + + #[serde(rename = "password")] + #[serde(skip_serializing_if="Option::is_none")] + pub password: Option, + + #[serde(rename = "phone")] + #[serde(skip_serializing_if="Option::is_none")] + pub phone: Option, + +/// User Status + #[serde(rename = "userStatus")] + #[serde(skip_serializing_if="Option::is_none")] + pub user_status: Option, + +} + + +impl User { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> User { + User { + id: None, + username: None, + first_name: None, + last_name: None, + email: None, + password: None, + phone: None, + user_status: None, + } + } +} + +/// Converts the User value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for User { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.username.as_ref().map(|username| { + [ + "username".to_string(), + username.to_string(), + ].join(",") + }), + + + self.first_name.as_ref().map(|first_name| { + [ + "firstName".to_string(), + first_name.to_string(), + ].join(",") + }), + + + self.last_name.as_ref().map(|last_name| { + [ + "lastName".to_string(), + last_name.to_string(), + ].join(",") + }), + + + self.email.as_ref().map(|email| { + [ + "email".to_string(), + email.to_string(), + ].join(",") + }), + + + self.password.as_ref().map(|password| { + [ + "password".to_string(), + password.to_string(), + ].join(",") + }), + + + self.phone.as_ref().map(|phone| { + [ + "phone".to_string(), + phone.to_string(), + ].join(",") + }), + + + self.user_status.as_ref().map(|user_status| { + [ + "userStatus".to_string(), + user_status.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a User value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for User { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub username: Vec, + pub first_name: Vec, + pub last_name: Vec, + pub email: Vec, + pub password: Vec, + pub phone: Vec, + pub user_status: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing User".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "username" => intermediate_rep.username.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "firstName" => intermediate_rep.first_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "lastName" => intermediate_rep.last_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "email" => intermediate_rep.email.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "phone" => intermediate_rep.phone.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "userStatus" => intermediate_rep.user_status.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing User".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(User { + id: intermediate_rep.id.into_iter().next(), + username: intermediate_rep.username.into_iter().next(), + first_name: intermediate_rep.first_name.into_iter().next(), + last_name: intermediate_rep.last_name.into_iter().next(), + email: intermediate_rep.email.into_iter().next(), + password: intermediate_rep.password.into_iter().next(), + phone: intermediate_rep.phone.into_iter().next(), + user_status: intermediate_rep.user_status.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for User - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into User - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs new file mode 100644 index 000000000000..2657be589088 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs @@ -0,0 +1,3212 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + TestSpecialTagsResponse, + Call123exampleResponse, + FakeOuterBooleanSerializeResponse, + FakeOuterCompositeSerializeResponse, + FakeOuterNumberSerializeResponse, + FakeOuterStringSerializeResponse, + FakeResponseWithNumericalDescriptionResponse, + HyphenParamResponse, + TestBodyWithQueryParamsResponse, + TestClientModelResponse, + TestEndpointParametersResponse, + TestEnumParametersResponse, + TestInlineAdditionalPropertiesResponse, + TestJsonFormDataResponse, + TestClassnameResponse, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/v2/another-fake/dummy", + patch(test_special_tags::) + ) + .route("/v2/fake", + get(test_enum_parameters::).patch(test_client_model::).post(test_endpoint_parameters::) + ) + .route("/v2/fake/body-with-query-params", + put(test_body_with_query_params::) + ) + .route("/v2/fake/hyphenParam/:hyphen_param", + get(hyphen_param::) + ) + .route("/v2/fake/inline-additionalProperties", + post(test_inline_additional_properties::) + ) + .route("/v2/fake/jsonFormData", + get(test_json_form_data::) + ) + .route("/v2/fake/operation-with-numeric-id", + get(call123example::) + ) + .route("/v2/fake/outer/boolean", + post(fake_outer_boolean_serialize::) + ) + .route("/v2/fake/outer/composite", + post(fake_outer_composite_serialize::) + ) + .route("/v2/fake/outer/number", + post(fake_outer_number_serialize::) + ) + .route("/v2/fake/outer/string", + post(fake_outer_string_serialize::) + ) + .route("/v2/fake/response-with-numerical-description", + get(fake_response_with_numerical_description::) + ) + .route("/v2/fake_classname_test", + patch(test_classname::) + ) + .route("/v2/pet", + post(add_pet::).put(update_pet::) + ) + .route("/v2/pet/:pet_id", + delete(delete_pet::).get(get_pet_by_id::).post(update_pet_with_form::) + ) + .route("/v2/pet/:pet_id/uploadImage", + post(upload_file::) + ) + .route("/v2/pet/findByStatus", + get(find_pets_by_status::) + ) + .route("/v2/pet/findByTags", + get(find_pets_by_tags::) + ) + .route("/v2/store/inventory", + get(get_inventory::) + ) + .route("/v2/store/order", + post(place_order::) + ) + .route("/v2/store/order/:order_id", + delete(delete_order::).get(get_order_by_id::) + ) + .route("/v2/user", + post(create_user::) + ) + .route("/v2/user/:username", + delete(delete_user::).get(get_user_by_name::).put(update_user::) + ) + .route("/v2/user/createWithArray", + post(create_users_with_array_input::) + ) + .route("/v2/user/createWithList", + post(create_users_with_list_input::) + ) + .route("/v2/user/login", + get(login_user::) + ) + .route("/v2/user/logout", + get(logout_user::) + ) + .with_state(api_impl) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct TestSpecialTagsBodyValidator<'a> { + #[validate] + body: &'a models::Client, + } + + +#[tracing::instrument(skip_all)] +fn test_special_tags_validation( + body: models::Client, +) -> std::result::Result<( + models::Client, +), ValidationErrors> +{ + let b = TestSpecialTagsBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// TestSpecialTags - PATCH /v2/another-fake/dummy +#[tracing::instrument(skip_all)] +async fn test_special_tags( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_special_tags_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_special_tags( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestSpecialTagsResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn call123example_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// Call123example - GET /v2/fake/operation-with-numeric-id +#[tracing::instrument(skip_all)] +async fn call123example( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + call123example_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().call123example( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + Call123exampleResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct FakeOuterBooleanSerializeBodyValidator<'a> { + #[validate] + body: &'a models::OuterBoolean, + } + + +#[tracing::instrument(skip_all)] +fn fake_outer_boolean_serialize_validation( + body: Option, +) -> std::result::Result<( + Option, +), ValidationErrors> +{ + if let Some(body) = &body { + let b = FakeOuterBooleanSerializeBodyValidator { body }; + b.validate()?; + } + +Ok(( + body, +)) +} + +/// FakeOuterBooleanSerialize - POST /v2/fake/outer/boolean +#[tracing::instrument(skip_all)] +async fn fake_outer_boolean_serialize( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + fake_outer_boolean_serialize_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().fake_outer_boolean_serialize( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FakeOuterBooleanSerializeResponse::Status200_OutputBoolean + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct FakeOuterCompositeSerializeBodyValidator<'a> { + #[validate] + body: &'a models::OuterComposite, + } + + +#[tracing::instrument(skip_all)] +fn fake_outer_composite_serialize_validation( + body: Option, +) -> std::result::Result<( + Option, +), ValidationErrors> +{ + if let Some(body) = &body { + let b = FakeOuterCompositeSerializeBodyValidator { body }; + b.validate()?; + } + +Ok(( + body, +)) +} + +/// FakeOuterCompositeSerialize - POST /v2/fake/outer/composite +#[tracing::instrument(skip_all)] +async fn fake_outer_composite_serialize( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + fake_outer_composite_serialize_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().fake_outer_composite_serialize( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FakeOuterCompositeSerializeResponse::Status200_OutputComposite + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct FakeOuterNumberSerializeBodyValidator<'a> { + #[validate] + body: &'a models::OuterNumber, + } + + +#[tracing::instrument(skip_all)] +fn fake_outer_number_serialize_validation( + body: Option, +) -> std::result::Result<( + Option, +), ValidationErrors> +{ + if let Some(body) = &body { + let b = FakeOuterNumberSerializeBodyValidator { body }; + b.validate()?; + } + +Ok(( + body, +)) +} + +/// FakeOuterNumberSerialize - POST /v2/fake/outer/number +#[tracing::instrument(skip_all)] +async fn fake_outer_number_serialize( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + fake_outer_number_serialize_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().fake_outer_number_serialize( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FakeOuterNumberSerializeResponse::Status200_OutputNumber + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct FakeOuterStringSerializeBodyValidator<'a> { + #[validate] + body: &'a models::OuterString, + } + + +#[tracing::instrument(skip_all)] +fn fake_outer_string_serialize_validation( + body: Option, +) -> std::result::Result<( + Option, +), ValidationErrors> +{ + if let Some(body) = &body { + let b = FakeOuterStringSerializeBodyValidator { body }; + b.validate()?; + } + +Ok(( + body, +)) +} + +/// FakeOuterStringSerialize - POST /v2/fake/outer/string +#[tracing::instrument(skip_all)] +async fn fake_outer_string_serialize( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + fake_outer_string_serialize_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().fake_outer_string_serialize( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FakeOuterStringSerializeResponse::Status200_OutputString + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn fake_response_with_numerical_description_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// FakeResponseWithNumericalDescription - GET /v2/fake/response-with-numerical-description +#[tracing::instrument(skip_all)] +async fn fake_response_with_numerical_description( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + fake_response_with_numerical_description_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().fake_response_with_numerical_description( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FakeResponseWithNumericalDescriptionResponse::Status200 + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn hyphen_param_validation( + path_params: models::HyphenParamPathParams, +) -> std::result::Result<( + models::HyphenParamPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// HyphenParam - GET /v2/fake/hyphenParam/{hyphen-param} +#[tracing::instrument(skip_all)] +async fn hyphen_param( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + hyphen_param_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().hyphen_param( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + HyphenParamResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct TestBodyWithQueryParamsBodyValidator<'a> { + #[validate] + body: &'a models::User, + } + + +#[tracing::instrument(skip_all)] +fn test_body_with_query_params_validation( + query_params: models::TestBodyWithQueryParamsQueryParams, + body: models::User, +) -> std::result::Result<( + models::TestBodyWithQueryParamsQueryParams, + models::User, +), ValidationErrors> +{ + query_params.validate()?; + let b = TestBodyWithQueryParamsBodyValidator { body: &body }; + b.validate()?; + +Ok(( + query_params, + body, +)) +} + +/// TestBodyWithQueryParams - PUT /v2/fake/body-with-query-params +#[tracing::instrument(skip_all)] +async fn test_body_with_query_params( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_body_with_query_params_validation( + query_params, + body, + ) + ).await.unwrap(); + + let Ok(( + query_params, + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_body_with_query_params( + method, + host, + cookies, + query_params, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestBodyWithQueryParamsResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct TestClientModelBodyValidator<'a> { + #[validate] + body: &'a models::Client, + } + + +#[tracing::instrument(skip_all)] +fn test_client_model_validation( + body: models::Client, +) -> std::result::Result<( + models::Client, +), ValidationErrors> +{ + let b = TestClientModelBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// TestClientModel - PATCH /v2/fake +#[tracing::instrument(skip_all)] +async fn test_client_model( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_client_model_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_client_model( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestClientModelResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn test_endpoint_parameters_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// TestEndpointParameters - POST /v2/fake +#[tracing::instrument(skip_all)] +async fn test_endpoint_parameters( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_endpoint_parameters_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_endpoint_parameters( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestEndpointParametersResponse::Status400_InvalidUsernameSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + TestEndpointParametersResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn test_enum_parameters_validation( + header_params: models::TestEnumParametersHeaderParams, + query_params: models::TestEnumParametersQueryParams, +) -> std::result::Result<( + models::TestEnumParametersHeaderParams, + models::TestEnumParametersQueryParams, +), ValidationErrors> +{ + header_params.validate()?; + query_params.validate()?; + +Ok(( + header_params, + query_params, +)) +} + +/// TestEnumParameters - GET /v2/fake +#[tracing::instrument(skip_all)] +async fn test_enum_parameters( + method: Method, + host: Host, + cookies: CookieJar, + headers: HeaderMap, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + // Header parameters + let header_params = { + let header_enum_header_string_array = headers.get(HeaderName::from_static("enum_header_string_array")); + + let header_enum_header_string_array = match header_enum_header_string_array { + Some(v) => match header::IntoHeaderValue::>::try_from((*v).clone()) { + Ok(result) => + Some(result.0), + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header enum_header_string_array - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { + None + } + }; + let header_enum_header_string = headers.get(HeaderName::from_static("enum_header_string")); + + let header_enum_header_string = match header_enum_header_string { + Some(v) => match header::IntoHeaderValue::::try_from((*v).clone()) { + Ok(result) => + Some(result.0), + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header enum_header_string - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { + None + } + }; + + models::TestEnumParametersHeaderParams { + enum_header_string_array: header_enum_header_string_array, + enum_header_string: header_enum_header_string, + } + }; + + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_enum_parameters_validation( + header_params, + query_params, + ) + ).await.unwrap(); + + let Ok(( + header_params, + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_enum_parameters( + method, + host, + cookies, + header_params, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestEnumParametersResponse::Status400_InvalidRequest + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + TestEnumParametersResponse::Status404_NotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct TestInlineAdditionalPropertiesBodyValidator<'a> { + body: &'a std::collections::HashMap, + } + + +#[tracing::instrument(skip_all)] +fn test_inline_additional_properties_validation( + body: std::collections::HashMap, +) -> std::result::Result<( + std::collections::HashMap, +), ValidationErrors> +{ + let b = TestInlineAdditionalPropertiesBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// TestInlineAdditionalProperties - POST /v2/fake/inline-additionalProperties +#[tracing::instrument(skip_all)] +async fn test_inline_additional_properties( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_inline_additional_properties_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_inline_additional_properties( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestInlineAdditionalPropertiesResponse::Status200_SuccessfulOperation + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn test_json_form_data_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// TestJsonFormData - GET /v2/fake/jsonFormData +#[tracing::instrument(skip_all)] +async fn test_json_form_data( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_json_form_data_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_json_form_data( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestJsonFormDataResponse::Status200_SuccessfulOperation + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct TestClassnameBodyValidator<'a> { + #[validate] + body: &'a models::Client, + } + + +#[tracing::instrument(skip_all)] +fn test_classname_validation( + body: models::Client, +) -> std::result::Result<( + models::Client, +), ValidationErrors> +{ + let b = TestClassnameBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// TestClassname - PATCH /v2/fake_classname_test +#[tracing::instrument(skip_all)] +async fn test_classname( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + test_classname_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().test_classname( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + TestClassnameResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct AddPetBodyValidator<'a> { + #[validate] + body: &'a models::Pet, + } + + +#[tracing::instrument(skip_all)] +fn add_pet_validation( + body: models::Pet, +) -> std::result::Result<( + models::Pet, +), ValidationErrors> +{ + let b = AddPetBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// AddPet - POST /v2/pet +#[tracing::instrument(skip_all)] +async fn add_pet( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + add_pet_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().add_pet( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + AddPetResponse::Status405_InvalidInput + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_pet_validation( + header_params: models::DeletePetHeaderParams, + path_params: models::DeletePetPathParams, +) -> std::result::Result<( + models::DeletePetHeaderParams, + models::DeletePetPathParams, +), ValidationErrors> +{ + header_params.validate()?; + path_params.validate()?; + +Ok(( + header_params, + path_params, +)) +} + +/// DeletePet - DELETE /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn delete_pet( + method: Method, + host: Host, + cookies: CookieJar, + headers: HeaderMap, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + // Header parameters + let header_params = { + let header_api_key = headers.get(HeaderName::from_static("api_key")); + + let header_api_key = match header_api_key { + Some(v) => match header::IntoHeaderValue::::try_from((*v).clone()) { + Ok(result) => + Some(result.0), + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header api_key - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { + None + } + }; + + models::DeletePetHeaderParams { + api_key: header_api_key, + } + }; + + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_pet_validation( + header_params, + path_params, + ) + ).await.unwrap(); + + let Ok(( + header_params, + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_pet( + method, + host, + cookies, + header_params, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeletePetResponse::Status400_InvalidPetValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn find_pets_by_status_validation( + query_params: models::FindPetsByStatusQueryParams, +) -> std::result::Result<( + models::FindPetsByStatusQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// FindPetsByStatus - GET /v2/pet/findByStatus +#[tracing::instrument(skip_all)] +async fn find_pets_by_status( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + find_pets_by_status_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().find_pets_by_status( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FindPetsByStatusResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + FindPetsByStatusResponse::Status400_InvalidStatusValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn find_pets_by_tags_validation( + query_params: models::FindPetsByTagsQueryParams, +) -> std::result::Result<( + models::FindPetsByTagsQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// FindPetsByTags - GET /v2/pet/findByTags +#[tracing::instrument(skip_all)] +async fn find_pets_by_tags( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + find_pets_by_tags_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().find_pets_by_tags( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FindPetsByTagsResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + FindPetsByTagsResponse::Status400_InvalidTagValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_pet_by_id_validation( + path_params: models::GetPetByIdPathParams, +) -> std::result::Result<( + models::GetPetByIdPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetPetById - GET /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn get_pet_by_id( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_pet_by_id_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_pet_by_id( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetPetByIdResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetPetByIdResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetPetByIdResponse::Status404_PetNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct UpdatePetBodyValidator<'a> { + #[validate] + body: &'a models::Pet, + } + + +#[tracing::instrument(skip_all)] +fn update_pet_validation( + body: models::Pet, +) -> std::result::Result<( + models::Pet, +), ValidationErrors> +{ + let b = UpdatePetBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// UpdatePet - PUT /v2/pet +#[tracing::instrument(skip_all)] +async fn update_pet( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_pet_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_pet( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdatePetResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + UpdatePetResponse::Status404_PetNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + UpdatePetResponse::Status405_ValidationException + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn update_pet_with_form_validation( + path_params: models::UpdatePetWithFormPathParams, +) -> std::result::Result<( + models::UpdatePetWithFormPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// UpdatePetWithForm - POST /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn update_pet_with_form( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_pet_with_form_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_pet_with_form( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdatePetWithFormResponse::Status405_InvalidInput + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn upload_file_validation( + path_params: models::UploadFilePathParams, +) -> std::result::Result<( + models::UploadFilePathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// UploadFile - POST /v2/pet/{petId}/uploadImage +#[tracing::instrument(skip_all)] +async fn upload_file( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, + body: Multipart, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + upload_file_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().upload_file( + method, + host, + cookies, + path_params, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UploadFileResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_order_validation( + path_params: models::DeleteOrderPathParams, +) -> std::result::Result<( + models::DeleteOrderPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// DeleteOrder - DELETE /v2/store/order/{order_id} +#[tracing::instrument(skip_all)] +async fn delete_order( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_order_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_order( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeleteOrderResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + DeleteOrderResponse::Status404_OrderNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_inventory_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// GetInventory - GET /v2/store/inventory +#[tracing::instrument(skip_all)] +async fn get_inventory( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_inventory_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_inventory( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetInventoryResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_order_by_id_validation( + path_params: models::GetOrderByIdPathParams, +) -> std::result::Result<( + models::GetOrderByIdPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetOrderById - GET /v2/store/order/{order_id} +#[tracing::instrument(skip_all)] +async fn get_order_by_id( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_order_by_id_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_order_by_id( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetOrderByIdResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetOrderByIdResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetOrderByIdResponse::Status404_OrderNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct PlaceOrderBodyValidator<'a> { + #[validate] + body: &'a models::Order, + } + + +#[tracing::instrument(skip_all)] +fn place_order_validation( + body: models::Order, +) -> std::result::Result<( + models::Order, +), ValidationErrors> +{ + let b = PlaceOrderBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// PlaceOrder - POST /v2/store/order +#[tracing::instrument(skip_all)] +async fn place_order( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + place_order_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().place_order( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + PlaceOrderResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + PlaceOrderResponse::Status400_InvalidOrder + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUserBodyValidator<'a> { + #[validate] + body: &'a models::User, + } + + +#[tracing::instrument(skip_all)] +fn create_user_validation( + body: models::User, +) -> std::result::Result<( + models::User, +), ValidationErrors> +{ + let b = CreateUserBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUser - POST /v2/user +#[tracing::instrument(skip_all)] +async fn create_user( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_user_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_user( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUserResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUsersWithArrayInputBodyValidator<'a> { + #[validate] + body: &'a Vec, + } + + +#[tracing::instrument(skip_all)] +fn create_users_with_array_input_validation( + body: Vec, +) -> std::result::Result<( + Vec, +), ValidationErrors> +{ + let b = CreateUsersWithArrayInputBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUsersWithArrayInput - POST /v2/user/createWithArray +#[tracing::instrument(skip_all)] +async fn create_users_with_array_input( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_users_with_array_input_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_users_with_array_input( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUsersWithArrayInputResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUsersWithListInputBodyValidator<'a> { + #[validate] + body: &'a Vec, + } + + +#[tracing::instrument(skip_all)] +fn create_users_with_list_input_validation( + body: Vec, +) -> std::result::Result<( + Vec, +), ValidationErrors> +{ + let b = CreateUsersWithListInputBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUsersWithListInput - POST /v2/user/createWithList +#[tracing::instrument(skip_all)] +async fn create_users_with_list_input( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_users_with_list_input_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_users_with_list_input( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUsersWithListInputResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_user_validation( + path_params: models::DeleteUserPathParams, +) -> std::result::Result<( + models::DeleteUserPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// DeleteUser - DELETE /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn delete_user( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_user_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_user( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeleteUserResponse::Status400_InvalidUsernameSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + DeleteUserResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_user_by_name_validation( + path_params: models::GetUserByNamePathParams, +) -> std::result::Result<( + models::GetUserByNamePathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetUserByName - GET /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn get_user_by_name( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_user_by_name_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_user_by_name( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetUserByNameResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetUserByNameResponse::Status400_InvalidUsernameSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetUserByNameResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn login_user_validation( + query_params: models::LoginUserQueryParams, +) -> std::result::Result<( + models::LoginUserQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// LoginUser - GET /v2/user/login +#[tracing::instrument(skip_all)] +async fn login_user( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + login_user_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().login_user( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + LoginUserResponse::Status200_SuccessfulOperation + { + body, + x_rate_limit, + x_expires_after + } + => { + if let Some(x_rate_limit) = x_rate_limit { + let x_rate_limit = match header::IntoHeaderValue(x_rate_limit).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling x_rate_limit header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("x-rate-limit"), + x_rate_limit + ); + } + } + if let Some(x_expires_after) = x_expires_after { + let x_expires_after = match header::IntoHeaderValue(x_expires_after).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling x_expires_after header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("x-expires-after"), + x_expires_after + ); + } + } + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + LoginUserResponse::Status400_InvalidUsername + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn logout_user_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// LogoutUser - GET /v2/user/logout +#[tracing::instrument(skip_all)] +async fn logout_user( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + logout_user_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().logout_user( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + LogoutUserResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct UpdateUserBodyValidator<'a> { + #[validate] + body: &'a models::User, + } + + +#[tracing::instrument(skip_all)] +fn update_user_validation( + path_params: models::UpdateUserPathParams, + body: models::User, +) -> std::result::Result<( + models::UpdateUserPathParams, + models::User, +), ValidationErrors> +{ + path_params.validate()?; + let b = UpdateUserBodyValidator { body: &body }; + b.validate()?; + +Ok(( + path_params, + body, +)) +} + +/// UpdateUser - PUT /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn update_user( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_user_validation( + path_params, + body, + ) + ).await.unwrap(); + + let Ok(( + path_params, + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_user( + method, + host, + cookies, + path_params, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdateUserResponse::Status400_InvalidUserSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + UpdateUserResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/types.rs b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/types.rs new file mode 100644 index 000000000000..c17c655d720d --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore-with-fake-endpoints-models-for-testing/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use petstore_with_fake_endpoints_models_for_testing::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/petstore/.gitignore b/samples/server/petstore/rust-axum/output/petstore/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/petstore/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/petstore/Cargo.toml b/samples/server/petstore/rust-axum/output/petstore/Cargo.toml new file mode 100644 index 000000000000..bdc5cf7766cf --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/Cargo.toml @@ -0,0 +1,47 @@ +[package] +name = "petstore" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters." +license = "Apache-2.0" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/petstore/README.md b/samples/server/petstore/rust-axum/output/petstore/README.md new file mode 100644 index 000000000000..3a9a839d794b --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/README.md @@ -0,0 +1,91 @@ +# Rust API for petstore + +This is a sample server Petstore server. For this sample, you can use the api key `special-key` to test the authorization filters. + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 1.0.0 + + + + +This autogenerated project defines an API crate `petstore` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl petstore::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = petstore::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/petstore/src/header.rs b/samples/server/petstore/rust-axum/output/petstore/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/petstore/src/lib.rs b/samples/server/petstore/rust-axum/output/petstore/src/lib.rs new file mode 100644 index 000000000000..287ff425af9c --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/src/lib.rs @@ -0,0 +1,510 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = "/v2"; +pub const API_VERSION: &str = "1.0.0"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum AddPetResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid input + Status405_InvalidInput +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeletePetResponse { + /// Invalid pet value + Status400_InvalidPetValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FindPetsByStatusResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid status value + Status400_InvalidStatusValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FindPetsByTagsResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid tag value + Status400_InvalidTagValue +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetPetByIdResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Pet not found + Status404_PetNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdatePetResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Pet not found + Status404_PetNotFound + , + /// Validation exception + Status405_ValidationException +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdatePetWithFormResponse { + /// Invalid input + Status405_InvalidInput +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UploadFileResponse { + /// successful operation + Status200_SuccessfulOperation + (models::ApiResponse) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeleteOrderResponse { + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Order not found + Status404_OrderNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetInventoryResponse { + /// successful operation + Status200_SuccessfulOperation + (std::collections::HashMap) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetOrderByIdResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid ID supplied + Status400_InvalidIDSupplied + , + /// Order not found + Status404_OrderNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum PlaceOrderResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid Order + Status400_InvalidOrder +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUserResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUsersWithArrayInputResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum CreateUsersWithListInputResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DeleteUserResponse { + /// Invalid username supplied + Status400_InvalidUsernameSupplied + , + /// User not found + Status404_UserNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetUserByNameResponse { + /// successful operation + Status200_SuccessfulOperation + (String) + , + /// Invalid username supplied + Status400_InvalidUsernameSupplied + , + /// User not found + Status404_UserNotFound +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum LoginUserResponse { + /// successful operation + Status200_SuccessfulOperation + { + body: String, + set_cookie: + Option< + String + > + , + x_rate_limit: + Option< + i32 + > + , + x_expires_after: + Option< + chrono::DateTime:: + > + } + , + /// Invalid username/password supplied + Status400_InvalidUsername +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum LogoutUserResponse { + /// successful operation + Status0_SuccessfulOperation +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum UpdateUserResponse { + /// Invalid user supplied + Status400_InvalidUserSupplied + , + /// User not found + Status404_UserNotFound +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// Add a new pet to the store. + /// + /// AddPet - POST /v2/pet + async fn add_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Pet, + ) -> Result; + + + /// Deletes a pet. + /// + /// DeletePet - DELETE /v2/pet/{petId} + async fn delete_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + header_params: models::DeletePetHeaderParams, + path_params: models::DeletePetPathParams, + ) -> Result; + + + /// Finds Pets by status. + /// + /// FindPetsByStatus - GET /v2/pet/findByStatus + async fn find_pets_by_status( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::FindPetsByStatusQueryParams, + ) -> Result; + + + /// Finds Pets by tags. + /// + /// FindPetsByTags - GET /v2/pet/findByTags + async fn find_pets_by_tags( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::FindPetsByTagsQueryParams, + ) -> Result; + + + /// Find pet by ID. + /// + /// GetPetById - GET /v2/pet/{petId} + async fn get_pet_by_id( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetPetByIdPathParams, + ) -> Result; + + + /// Update an existing pet. + /// + /// UpdatePet - PUT /v2/pet + async fn update_pet( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Pet, + ) -> Result; + + + /// Updates a pet in the store with form data. + /// + /// UpdatePetWithForm - POST /v2/pet/{petId} + async fn update_pet_with_form( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UpdatePetWithFormPathParams, + ) -> Result; + + + /// uploads an image. + /// + /// UploadFile - POST /v2/pet/{petId}/uploadImage + async fn upload_file( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UploadFilePathParams, + body: Multipart, + ) -> Result; + + + /// Delete purchase order by ID. + /// + /// DeleteOrder - DELETE /v2/store/order/{orderId} + async fn delete_order( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::DeleteOrderPathParams, + ) -> Result; + + + /// Returns pet inventories by status. + /// + /// GetInventory - GET /v2/store/inventory + async fn get_inventory( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Find purchase order by ID. + /// + /// GetOrderById - GET /v2/store/order/{orderId} + async fn get_order_by_id( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetOrderByIdPathParams, + ) -> Result; + + + /// Place an order for a pet. + /// + /// PlaceOrder - POST /v2/store/order + async fn place_order( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::Order, + ) -> Result; + + + /// Create user. + /// + /// CreateUser - POST /v2/user + async fn create_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::User, + ) -> Result; + + + /// Creates list of users with given input array. + /// + /// CreateUsersWithArrayInput - POST /v2/user/createWithArray + async fn create_users_with_array_input( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Vec, + ) -> Result; + + + /// Creates list of users with given input array. + /// + /// CreateUsersWithListInput - POST /v2/user/createWithList + async fn create_users_with_list_input( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: Vec, + ) -> Result; + + + /// Delete user. + /// + /// DeleteUser - DELETE /v2/user/{username} + async fn delete_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::DeleteUserPathParams, + ) -> Result; + + + /// Get user by user name. + /// + /// GetUserByName - GET /v2/user/{username} + async fn get_user_by_name( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::GetUserByNamePathParams, + ) -> Result; + + + /// Logs user into the system. + /// + /// LoginUser - GET /v2/user/login + async fn login_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + query_params: models::LoginUserQueryParams, + ) -> Result; + + + /// Logs out current logged in user session. + /// + /// LogoutUser - GET /v2/user/logout + async fn logout_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Updated user. + /// + /// UpdateUser - PUT /v2/user/{username} + async fn update_user( + &self, + method: Method, + host: Host, + cookies: CookieJar, + path_params: models::UpdateUserPathParams, + body: models::User, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/petstore/src/models.rs b/samples/server/petstore/rust-axum/output/petstore/src/models.rs new file mode 100644 index 000000000000..1199eeb54f04 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/src/models.rs @@ -0,0 +1,1264 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeletePetHeaderParams { + pub api_key: Option, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeletePetPathParams { + /// Pet id to delete + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct FindPetsByStatusQueryParams { + /// Status values that need to be considered for filter + /// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + pub status: Vec, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct FindPetsByTagsQueryParams { + /// Tags to filter by + #[serde(rename = "tags")] + pub tags: Vec, + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetPetByIdPathParams { + /// ID of pet to return + pub pet_id: i64, + } + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UpdatePetWithFormPathParams { + /// ID of pet that needs to be updated + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UploadFilePathParams { + /// ID of pet to update + pub pet_id: i64, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeleteOrderPathParams { + /// ID of the order that needs to be deleted + pub order_id: String, + } + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetOrderByIdPathParams { + /// ID of pet that needs to be fetched + #[validate( + range(min = 1, max = 5), + )] + pub order_id: i64, + } + + + + + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct DeleteUserPathParams { + /// The name that needs to be deleted + pub username: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct GetUserByNamePathParams { + /// The name that needs to be fetched. Use user1 for testing. + pub username: String, + } + + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct LoginUserQueryParams { + /// The user name for login + #[serde(rename = "username")] + #[validate( + regex = "RE_LOGINUSERQUERYPARAMS_USERNAME", + )] + pub username: String, + /// The password for login in clear text + #[serde(rename = "password")] + pub password: String, + } + + lazy_static::lazy_static! { + static ref RE_LOGINUSERQUERYPARAMS_USERNAME: regex::Regex = regex::Regex::new(r"^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$").unwrap(); + } + + + #[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] + #[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] + pub struct UpdateUserPathParams { + /// name that need to be deleted + pub username: String, + } + + + + +/// Describes the result of uploading an image resource + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ApiResponse { + #[serde(rename = "code")] + #[serde(skip_serializing_if="Option::is_none")] + pub code: Option, + + #[serde(rename = "type")] + #[serde(skip_serializing_if="Option::is_none")] + pub r#type: Option, + + #[serde(rename = "message")] + #[serde(skip_serializing_if="Option::is_none")] + pub message: Option, + +} + + +impl ApiResponse { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ApiResponse { + ApiResponse { + code: None, + r#type: None, + message: None, + } + } +} + +/// Converts the ApiResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ApiResponse { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.code.as_ref().map(|code| { + [ + "code".to_string(), + code.to_string(), + ].join(",") + }), + + + self.r#type.as_ref().map(|r#type| { + [ + "type".to_string(), + r#type.to_string(), + ].join(",") + }), + + + self.message.as_ref().map(|message| { + [ + "message".to_string(), + message.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ApiResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ApiResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub code: Vec, + pub r#type: Vec, + pub message: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ApiResponse".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "code" => intermediate_rep.code.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "type" => intermediate_rep.r#type.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "message" => intermediate_rep.message.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ApiResponse".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ApiResponse { + code: intermediate_rep.code.into_iter().next(), + r#type: intermediate_rep.r#type.into_iter().next(), + message: intermediate_rep.message.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ApiResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ApiResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// A category for a pet + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Category { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[validate( + regex = "RE_CATEGORY_NAME", + )] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + +lazy_static::lazy_static! { + static ref RE_CATEGORY_NAME: regex::Regex = regex::Regex::new(r"^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$").unwrap(); +} + +impl Category { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Category { + Category { + id: None, + name: None, + } + } +} + +/// Converts the Category value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Category { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.name.as_ref().map(|name| { + [ + "name".to_string(), + name.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Category value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Category { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Category".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Category".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Category { + id: intermediate_rep.id.into_iter().next(), + name: intermediate_rep.name.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Category - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Category - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// An order for a pets from the pet store + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Order { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "petId")] + #[serde(skip_serializing_if="Option::is_none")] + pub pet_id: Option, + + #[serde(rename = "quantity")] + #[serde(skip_serializing_if="Option::is_none")] + pub quantity: Option, + + #[serde(rename = "shipDate")] + #[serde(skip_serializing_if="Option::is_none")] + pub ship_date: Option>, + +/// Order Status +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + + #[serde(rename = "complete")] + #[serde(skip_serializing_if="Option::is_none")] + pub complete: Option, + +} + + +impl Order { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Order { + Order { + id: None, + pet_id: None, + quantity: None, + ship_date: None, + status: None, + complete: Some(false), + } + } +} + +/// Converts the Order value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Order { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.pet_id.as_ref().map(|pet_id| { + [ + "petId".to_string(), + pet_id.to_string(), + ].join(",") + }), + + + self.quantity.as_ref().map(|quantity| { + [ + "quantity".to_string(), + quantity.to_string(), + ].join(",") + }), + + // Skipping shipDate in query parameter serialization + + + self.status.as_ref().map(|status| { + [ + "status".to_string(), + status.to_string(), + ].join(",") + }), + + + self.complete.as_ref().map(|complete| { + [ + "complete".to_string(), + complete.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Order value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Order { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub pet_id: Vec, + pub quantity: Vec, + pub ship_date: Vec>, + pub status: Vec, + pub complete: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Order".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "petId" => intermediate_rep.pet_id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "quantity" => intermediate_rep.quantity.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "shipDate" => intermediate_rep.ship_date.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "complete" => intermediate_rep.complete.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Order".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Order { + id: intermediate_rep.id.into_iter().next(), + pet_id: intermediate_rep.pet_id.into_iter().next(), + quantity: intermediate_rep.quantity.into_iter().next(), + ship_date: intermediate_rep.ship_date.into_iter().next(), + status: intermediate_rep.status.into_iter().next(), + complete: intermediate_rep.complete.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Order - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Order - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// A pet for sale in the pet store + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Pet { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "category")] + #[serde(skip_serializing_if="Option::is_none")] + pub category: Option, + + #[serde(rename = "name")] + pub name: String, + + #[serde(rename = "photoUrls")] + pub photo_urls: Vec, + + #[serde(rename = "tags")] + #[serde(skip_serializing_if="Option::is_none")] + pub tags: Option>, + +/// pet status in the store +/// Note: inline enums are not fully supported by openapi-generator + #[serde(rename = "status")] + #[serde(skip_serializing_if="Option::is_none")] + pub status: Option, + +} + + +impl Pet { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(name: String, photo_urls: Vec, ) -> Pet { + Pet { + id: None, + category: None, + name, + photo_urls, + tags: None, + status: None, + } + } +} + +/// Converts the Pet value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Pet { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + // Skipping category in query parameter serialization + + + Some("name".to_string()), + Some(self.name.to_string()), + + + Some("photoUrls".to_string()), + Some(self.photo_urls.iter().map(|x| x.to_string()).collect::>().join(",")), + + // Skipping tags in query parameter serialization + + + self.status.as_ref().map(|status| { + [ + "status".to_string(), + status.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Pet value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Pet { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub category: Vec, + pub name: Vec, + pub photo_urls: Vec>, + pub tags: Vec>, + pub status: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Pet".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "category" => intermediate_rep.category.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + "photoUrls" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), + "tags" => return std::result::Result::Err("Parsing a container in this style is not supported in Pet".to_string()), + #[allow(clippy::redundant_clone)] + "status" => intermediate_rep.status.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Pet".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Pet { + id: intermediate_rep.id.into_iter().next(), + category: intermediate_rep.category.into_iter().next(), + name: intermediate_rep.name.into_iter().next().ok_or_else(|| "name missing in Pet".to_string())?, + photo_urls: intermediate_rep.photo_urls.into_iter().next().ok_or_else(|| "photoUrls missing in Pet".to_string())?, + tags: intermediate_rep.tags.into_iter().next(), + status: intermediate_rep.status.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Pet - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Pet - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// A tag for a pet + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct Tag { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "name")] + #[serde(skip_serializing_if="Option::is_none")] + pub name: Option, + +} + + +impl Tag { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> Tag { + Tag { + id: None, + name: None, + } + } +} + +/// Converts the Tag value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for Tag { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.name.as_ref().map(|name| { + [ + "name".to_string(), + name.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a Tag value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for Tag { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub name: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing Tag".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "name" => intermediate_rep.name.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing Tag".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(Tag { + id: intermediate_rep.id.into_iter().next(), + name: intermediate_rep.name.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for Tag - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into Tag - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// A User who is purchasing from the pet store + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct User { + #[serde(rename = "id")] + #[serde(skip_serializing_if="Option::is_none")] + pub id: Option, + + #[serde(rename = "username")] + #[serde(skip_serializing_if="Option::is_none")] + pub username: Option, + + #[serde(rename = "firstName")] + #[serde(skip_serializing_if="Option::is_none")] + pub first_name: Option, + + #[serde(rename = "lastName")] + #[serde(skip_serializing_if="Option::is_none")] + pub last_name: Option, + + #[serde(rename = "email")] + #[serde(skip_serializing_if="Option::is_none")] + pub email: Option, + + #[serde(rename = "password")] + #[serde(skip_serializing_if="Option::is_none")] + pub password: Option, + + #[serde(rename = "phone")] + #[serde(skip_serializing_if="Option::is_none")] + pub phone: Option, + +/// User Status + #[serde(rename = "userStatus")] + #[serde(skip_serializing_if="Option::is_none")] + pub user_status: Option, + +} + + +impl User { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> User { + User { + id: None, + username: None, + first_name: None, + last_name: None, + email: None, + password: None, + phone: None, + user_status: None, + } + } +} + +/// Converts the User value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for User { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.id.as_ref().map(|id| { + [ + "id".to_string(), + id.to_string(), + ].join(",") + }), + + + self.username.as_ref().map(|username| { + [ + "username".to_string(), + username.to_string(), + ].join(",") + }), + + + self.first_name.as_ref().map(|first_name| { + [ + "firstName".to_string(), + first_name.to_string(), + ].join(",") + }), + + + self.last_name.as_ref().map(|last_name| { + [ + "lastName".to_string(), + last_name.to_string(), + ].join(",") + }), + + + self.email.as_ref().map(|email| { + [ + "email".to_string(), + email.to_string(), + ].join(",") + }), + + + self.password.as_ref().map(|password| { + [ + "password".to_string(), + password.to_string(), + ].join(",") + }), + + + self.phone.as_ref().map(|phone| { + [ + "phone".to_string(), + phone.to_string(), + ].join(",") + }), + + + self.user_status.as_ref().map(|user_status| { + [ + "userStatus".to_string(), + user_status.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a User value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for User { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub username: Vec, + pub first_name: Vec, + pub last_name: Vec, + pub email: Vec, + pub password: Vec, + pub phone: Vec, + pub user_status: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing User".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "username" => intermediate_rep.username.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "firstName" => intermediate_rep.first_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "lastName" => intermediate_rep.last_name.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "email" => intermediate_rep.email.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "phone" => intermediate_rep.phone.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "userStatus" => intermediate_rep.user_status.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing User".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(User { + id: intermediate_rep.id.into_iter().next(), + username: intermediate_rep.username.into_iter().next(), + first_name: intermediate_rep.first_name.into_iter().next(), + last_name: intermediate_rep.last_name.into_iter().next(), + email: intermediate_rep.email.into_iter().next(), + password: intermediate_rep.password.into_iter().next(), + phone: intermediate_rep.phone.into_iter().next(), + user_status: intermediate_rep.user_status.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for User - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into User - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + diff --git a/samples/server/petstore/rust-axum/output/petstore/src/server/mod.rs b/samples/server/petstore/rust-axum/output/petstore/src/server/mod.rs new file mode 100644 index 000000000000..89007f8055b9 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/src/server/mod.rs @@ -0,0 +1,1904 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + AddPetResponse, + DeletePetResponse, + FindPetsByStatusResponse, + FindPetsByTagsResponse, + GetPetByIdResponse, + UpdatePetResponse, + UpdatePetWithFormResponse, + UploadFileResponse, + DeleteOrderResponse, + GetInventoryResponse, + GetOrderByIdResponse, + PlaceOrderResponse, + CreateUserResponse, + CreateUsersWithArrayInputResponse, + CreateUsersWithListInputResponse, + DeleteUserResponse, + GetUserByNameResponse, + LoginUserResponse, + LogoutUserResponse, + UpdateUserResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/v2/pet", + post(add_pet::).put(update_pet::) + ) + .route("/v2/pet/:pet_id", + delete(delete_pet::).get(get_pet_by_id::).post(update_pet_with_form::) + ) + .route("/v2/pet/:pet_id/uploadImage", + post(upload_file::) + ) + .route("/v2/pet/findByStatus", + get(find_pets_by_status::) + ) + .route("/v2/pet/findByTags", + get(find_pets_by_tags::) + ) + .route("/v2/store/inventory", + get(get_inventory::) + ) + .route("/v2/store/order", + post(place_order::) + ) + .route("/v2/store/order/:order_id", + delete(delete_order::).get(get_order_by_id::) + ) + .route("/v2/user", + post(create_user::) + ) + .route("/v2/user/:username", + delete(delete_user::).get(get_user_by_name::).put(update_user::) + ) + .route("/v2/user/createWithArray", + post(create_users_with_array_input::) + ) + .route("/v2/user/createWithList", + post(create_users_with_list_input::) + ) + .route("/v2/user/login", + get(login_user::) + ) + .route("/v2/user/logout", + get(logout_user::) + ) + .with_state(api_impl) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct AddPetBodyValidator<'a> { + #[validate] + body: &'a models::Pet, + } + + +#[tracing::instrument(skip_all)] +fn add_pet_validation( + body: models::Pet, +) -> std::result::Result<( + models::Pet, +), ValidationErrors> +{ + let b = AddPetBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// AddPet - POST /v2/pet +#[tracing::instrument(skip_all)] +async fn add_pet( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + add_pet_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().add_pet( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + AddPetResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + AddPetResponse::Status405_InvalidInput + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_pet_validation( + header_params: models::DeletePetHeaderParams, + path_params: models::DeletePetPathParams, +) -> std::result::Result<( + models::DeletePetHeaderParams, + models::DeletePetPathParams, +), ValidationErrors> +{ + header_params.validate()?; + path_params.validate()?; + +Ok(( + header_params, + path_params, +)) +} + +/// DeletePet - DELETE /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn delete_pet( + method: Method, + host: Host, + cookies: CookieJar, + headers: HeaderMap, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + // Header parameters + let header_params = { + let header_api_key = headers.get(HeaderName::from_static("api_key")); + + let header_api_key = match header_api_key { + Some(v) => match header::IntoHeaderValue::::try_from((*v).clone()) { + Ok(result) => + Some(result.0), + Err(err) => { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(format!("Invalid header api_key - {}", err))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + + }, + }, + None => { + None + } + }; + + models::DeletePetHeaderParams { + api_key: header_api_key, + } + }; + + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_pet_validation( + header_params, + path_params, + ) + ).await.unwrap(); + + let Ok(( + header_params, + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_pet( + method, + host, + cookies, + header_params, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeletePetResponse::Status400_InvalidPetValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn find_pets_by_status_validation( + query_params: models::FindPetsByStatusQueryParams, +) -> std::result::Result<( + models::FindPetsByStatusQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// FindPetsByStatus - GET /v2/pet/findByStatus +#[tracing::instrument(skip_all)] +async fn find_pets_by_status( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + find_pets_by_status_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().find_pets_by_status( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FindPetsByStatusResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + FindPetsByStatusResponse::Status400_InvalidStatusValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn find_pets_by_tags_validation( + query_params: models::FindPetsByTagsQueryParams, +) -> std::result::Result<( + models::FindPetsByTagsQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// FindPetsByTags - GET /v2/pet/findByTags +#[tracing::instrument(skip_all)] +async fn find_pets_by_tags( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + find_pets_by_tags_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().find_pets_by_tags( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FindPetsByTagsResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + FindPetsByTagsResponse::Status400_InvalidTagValue + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_pet_by_id_validation( + path_params: models::GetPetByIdPathParams, +) -> std::result::Result<( + models::GetPetByIdPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetPetById - GET /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn get_pet_by_id( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_pet_by_id_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_pet_by_id( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetPetByIdResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetPetByIdResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetPetByIdResponse::Status404_PetNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct UpdatePetBodyValidator<'a> { + #[validate] + body: &'a models::Pet, + } + + +#[tracing::instrument(skip_all)] +fn update_pet_validation( + body: models::Pet, +) -> std::result::Result<( + models::Pet, +), ValidationErrors> +{ + let b = UpdatePetBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// UpdatePet - PUT /v2/pet +#[tracing::instrument(skip_all)] +async fn update_pet( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_pet_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_pet( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdatePetResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + UpdatePetResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + UpdatePetResponse::Status404_PetNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + UpdatePetResponse::Status405_ValidationException + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn update_pet_with_form_validation( + path_params: models::UpdatePetWithFormPathParams, +) -> std::result::Result<( + models::UpdatePetWithFormPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// UpdatePetWithForm - POST /v2/pet/{petId} +#[tracing::instrument(skip_all)] +async fn update_pet_with_form( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_pet_with_form_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_pet_with_form( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdatePetWithFormResponse::Status405_InvalidInput + => { + + let mut response = response.status(405); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn upload_file_validation( + path_params: models::UploadFilePathParams, +) -> std::result::Result<( + models::UploadFilePathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// UploadFile - POST /v2/pet/{petId}/uploadImage +#[tracing::instrument(skip_all)] +async fn upload_file( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, + body: Multipart, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + upload_file_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().upload_file( + method, + host, + cookies, + path_params, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UploadFileResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_order_validation( + path_params: models::DeleteOrderPathParams, +) -> std::result::Result<( + models::DeleteOrderPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// DeleteOrder - DELETE /v2/store/order/{orderId} +#[tracing::instrument(skip_all)] +async fn delete_order( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_order_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_order( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeleteOrderResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + DeleteOrderResponse::Status404_OrderNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_inventory_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// GetInventory - GET /v2/store/inventory +#[tracing::instrument(skip_all)] +async fn get_inventory( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_inventory_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_inventory( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetInventoryResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_order_by_id_validation( + path_params: models::GetOrderByIdPathParams, +) -> std::result::Result<( + models::GetOrderByIdPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetOrderById - GET /v2/store/order/{orderId} +#[tracing::instrument(skip_all)] +async fn get_order_by_id( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_order_by_id_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_order_by_id( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetOrderByIdResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetOrderByIdResponse::Status400_InvalidIDSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetOrderByIdResponse::Status404_OrderNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct PlaceOrderBodyValidator<'a> { + #[validate] + body: &'a models::Order, + } + + +#[tracing::instrument(skip_all)] +fn place_order_validation( + body: models::Order, +) -> std::result::Result<( + models::Order, +), ValidationErrors> +{ + let b = PlaceOrderBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// PlaceOrder - POST /v2/store/order +#[tracing::instrument(skip_all)] +async fn place_order( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + place_order_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().place_order( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + PlaceOrderResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + PlaceOrderResponse::Status400_InvalidOrder + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUserBodyValidator<'a> { + #[validate] + body: &'a models::User, + } + + +#[tracing::instrument(skip_all)] +fn create_user_validation( + body: models::User, +) -> std::result::Result<( + models::User, +), ValidationErrors> +{ + let b = CreateUserBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUser - POST /v2/user +#[tracing::instrument(skip_all)] +async fn create_user( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_user_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_user( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUserResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUsersWithArrayInputBodyValidator<'a> { + #[validate] + body: &'a Vec, + } + + +#[tracing::instrument(skip_all)] +fn create_users_with_array_input_validation( + body: Vec, +) -> std::result::Result<( + Vec, +), ValidationErrors> +{ + let b = CreateUsersWithArrayInputBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUsersWithArrayInput - POST /v2/user/createWithArray +#[tracing::instrument(skip_all)] +async fn create_users_with_array_input( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_users_with_array_input_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_users_with_array_input( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUsersWithArrayInputResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct CreateUsersWithListInputBodyValidator<'a> { + #[validate] + body: &'a Vec, + } + + +#[tracing::instrument(skip_all)] +fn create_users_with_list_input_validation( + body: Vec, +) -> std::result::Result<( + Vec, +), ValidationErrors> +{ + let b = CreateUsersWithListInputBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// CreateUsersWithListInput - POST /v2/user/createWithList +#[tracing::instrument(skip_all)] +async fn create_users_with_list_input( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json>, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + create_users_with_list_input_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().create_users_with_list_input( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + CreateUsersWithListInputResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn delete_user_validation( + path_params: models::DeleteUserPathParams, +) -> std::result::Result<( + models::DeleteUserPathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// DeleteUser - DELETE /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn delete_user( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + delete_user_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().delete_user( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DeleteUserResponse::Status400_InvalidUsernameSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + DeleteUserResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_user_by_name_validation( + path_params: models::GetUserByNamePathParams, +) -> std::result::Result<( + models::GetUserByNamePathParams, +), ValidationErrors> +{ + path_params.validate()?; + +Ok(( + path_params, +)) +} + +/// GetUserByName - GET /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn get_user_by_name( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_user_by_name_validation( + path_params, + ) + ).await.unwrap(); + + let Ok(( + path_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_user_by_name( + method, + host, + cookies, + path_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetUserByNameResponse::Status200_SuccessfulOperation + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + GetUserByNameResponse::Status400_InvalidUsernameSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + GetUserByNameResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn login_user_validation( + query_params: models::LoginUserQueryParams, +) -> std::result::Result<( + models::LoginUserQueryParams, +), ValidationErrors> +{ + query_params.validate()?; + +Ok(( + query_params, +)) +} + +/// LoginUser - GET /v2/user/login +#[tracing::instrument(skip_all)] +async fn login_user( + method: Method, + host: Host, + cookies: CookieJar, + Query(query_params): Query, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + login_user_validation( + query_params, + ) + ).await.unwrap(); + + let Ok(( + query_params, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().login_user( + method, + host, + cookies, + query_params, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + LoginUserResponse::Status200_SuccessfulOperation + { + body, + set_cookie, + x_rate_limit, + x_expires_after + } + => { + if let Some(set_cookie) = set_cookie { + let set_cookie = match header::IntoHeaderValue(set_cookie).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling set_cookie header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("set-cookie"), + set_cookie + ); + } + } + if let Some(x_rate_limit) = x_rate_limit { + let x_rate_limit = match header::IntoHeaderValue(x_rate_limit).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling x_rate_limit header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("x-rate-limit"), + x_rate_limit + ); + } + } + if let Some(x_expires_after) = x_expires_after { + let x_expires_after = match header::IntoHeaderValue(x_expires_after).try_into() { + Ok(val) => val, + Err(e) => { + return Response::builder() + .status(StatusCode::INTERNAL_SERVER_ERROR) + .body(Body::from(format!("An internal server error occurred handling x_expires_after header - {}", e))).map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }); + } + }; + + + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + HeaderName::from_static("x-expires-after"), + x_expires_after + ); + } + } + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/plain").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + LoginUserResponse::Status400_InvalidUsername + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn logout_user_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// LogoutUser - GET /v2/user/logout +#[tracing::instrument(skip_all)] +async fn logout_user( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + logout_user_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().logout_user( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + LogoutUserResponse::Status0_SuccessfulOperation + => { + + let mut response = response.status(0); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct UpdateUserBodyValidator<'a> { + #[validate] + body: &'a models::User, + } + + +#[tracing::instrument(skip_all)] +fn update_user_validation( + path_params: models::UpdateUserPathParams, + body: models::User, +) -> std::result::Result<( + models::UpdateUserPathParams, + models::User, +), ValidationErrors> +{ + path_params.validate()?; + let b = UpdateUserBodyValidator { body: &body }; + b.validate()?; + +Ok(( + path_params, + body, +)) +} + +/// UpdateUser - PUT /v2/user/{username} +#[tracing::instrument(skip_all)] +async fn update_user( + method: Method, + host: Host, + cookies: CookieJar, + Path(path_params): Path, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + update_user_validation( + path_params, + body, + ) + ).await.unwrap(); + + let Ok(( + path_params, + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().update_user( + method, + host, + cookies, + path_params, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + UpdateUserResponse::Status400_InvalidUserSupplied + => { + + let mut response = response.status(400); + response.body(Body::empty()) + }, + UpdateUserResponse::Status404_UserNotFound + => { + + let mut response = response.status(404); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/petstore/src/types.rs b/samples/server/petstore/rust-axum/output/petstore/src/types.rs new file mode 100644 index 000000000000..eca60521b9a6 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/petstore/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use petstore::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use petstore::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use petstore::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/.gitignore b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/Cargo.toml b/samples/server/petstore/rust-axum/output/ping-bearer-auth/Cargo.toml new file mode 100644 index 000000000000..fa0a6c1f3ed6 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "ping-bearer-auth" +version = "1.0.0" +authors = ["OpenAPI Generator team and contributors"] +description = "No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator)" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/README.md b/samples/server/petstore/rust-axum/output/ping-bearer-auth/README.md new file mode 100644 index 000000000000..46a6534028db --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/README.md @@ -0,0 +1,91 @@ +# Rust API for ping-bearer-auth + +No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 1.0 + + + + +This autogenerated project defines an API crate `ping-bearer-auth` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl ping-bearer-auth::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = ping-bearer-auth::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/header.rs b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/lib.rs b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/lib.rs new file mode 100644 index 000000000000..f99c0799ecf7 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/lib.rs @@ -0,0 +1,48 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "1.0"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum PingGetResponse { + /// OK + Status201_OK +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// PingGet - GET /ping + async fn ping_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/models.rs b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/models.rs new file mode 100644 index 000000000000..34696c0ab8ae --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/models.rs @@ -0,0 +1,11 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/server/mod.rs b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/server/mod.rs new file mode 100644 index 000000000000..76578d0a4ec6 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/server/mod.rs @@ -0,0 +1,97 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + PingGetResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/ping", + get(ping_get::) + ) + .with_state(api_impl) +} + + +#[tracing::instrument(skip_all)] +fn ping_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// PingGet - GET /ping +#[tracing::instrument(skip_all)] +async fn ping_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + ping_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().ping_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + PingGetResponse::Status201_OK + => { + + let mut response = response.status(201); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/types.rs b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/types.rs new file mode 100644 index 000000000000..391471861d0c --- /dev/null +++ b/samples/server/petstore/rust-axum/output/ping-bearer-auth/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use ping_bearer_auth::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/.gitignore b/samples/server/petstore/rust-axum/output/rust-axum-test/.gitignore new file mode 100644 index 000000000000..a9d37c560c6a --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/.gitignore @@ -0,0 +1,2 @@ +target +Cargo.lock diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator-ignore b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/FILES b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/FILES new file mode 100644 index 000000000000..ea1c5b8c5beb --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/FILES @@ -0,0 +1,8 @@ +.gitignore +Cargo.toml +README.md +src/header.rs +src/lib.rs +src/models.rs +src/server/mod.rs +src/types.rs diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/VERSION b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/Cargo.toml b/samples/server/petstore/rust-axum/output/rust-axum-test/Cargo.toml new file mode 100644 index 000000000000..347c1aad2d7c --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/Cargo.toml @@ -0,0 +1,46 @@ +[package] +name = "rust-server-test" +version = "2.3.4" +authors = ["OpenAPI Generator team and contributors"] +description = "This spec is for testing rust-server-specific things" +edition = "2021" + +[features] +default = ["server"] +server = [] +conversion = [ + "frunk", + "frunk_derives", + "frunk_core", + "frunk-enum-core", + "frunk-enum-derive", +] + +[dependencies] +async-trait = "0.1" +axum = { version = "0.7" } +axum-extra = { version = "0.9", features = ["cookie", "multipart"] } +base64 = "0.21" +bytes = "1" +chrono = { version = "0.4", features = ["serde"] } +frunk = { version = "0.4", optional = true } +frunk-enum-core = { version = "0.3", optional = true } +frunk-enum-derive = { version = "0.3", optional = true } +frunk_core = { version = "0.4", optional = true } +frunk_derives = { version = "0.4", optional = true } +http = "1" +lazy_static = "1" +regex = "1" +serde = { version = "1", features = ["derive"] } +serde_json = { version = "1", features = ["raw_value"] } +serde_urlencoded = "0.7" +tokio = { version = "1", default-features = false, features = [ + "signal", + "rt-multi-thread", +] } +tracing = { version = "0.1", features = ["attributes"] } +uuid = { version = "1", features = ["serde"] } +validator = { version = "0.16", features = ["derive"] } + +[dev-dependencies] +tracing-subscriber = "0.3" diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/README.md b/samples/server/petstore/rust-axum/output/rust-axum-test/README.md new file mode 100644 index 000000000000..b71f8cde2164 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/README.md @@ -0,0 +1,91 @@ +# Rust API for rust-server-test + +This spec is for testing rust-server-specific things + +## Overview + +This server was generated by the [openapi-generator] +(https://openapi-generator.tech) project. By using the +[OpenAPI-Spec](https://github.com/OAI/OpenAPI-Specification) from a remote +server, you can easily generate a server stub. + +To see how to make this your own, look here: [README]((https://openapi-generator.tech)) + +- API version: 2.3.4 + + + + +This autogenerated project defines an API crate `rust-server-test` which contains: +* An `Api` trait defining the API in Rust. +* Data types representing the underlying data model. +* Axum router which accepts HTTP requests and invokes the appropriate `Api` method for each operation. + * Request validations (path, query, body params) are included. + +## Using the generated library + +The generated library has a few optional features that can be activated through Cargo. + +* `server` + * This defaults to enabled and creates the basic skeleton of a server implementation based on Axum. + * To create the server stack you'll need to provide an implementation of the API trait to provide the server function. +* `conversions` + * This defaults to disabled and creates extra derives on models to allow "transmogrification" between objects of structurally similar types. + +See https://doc.rust-lang.org/cargo/reference/manifest.html#the-features-section for how to use features in your `Cargo.toml`. + +### Example + +```rust +struct ServerImpl { + // database: sea_orm::DbConn, +} + +#[allow(unused_variables)] +#[async_trait] +impl rust-server-test::Api for ServerImpl { + // API implementation goes here +} + +pub async fn start_server(addr: &str) { + // initialize tracing + tracing_subscriber::fmt::init(); + + // Init Axum router + let app = rust-server-test::server::new(Arc::new(ServerImpl)); + + // Add layers to the router + let app = app.layer(...); + + // Run the server with graceful shutdown + let listener = TcpListener::bind(addr).await.unwrap(); + axum::serve(listener, app) + .with_graceful_shutdown(shutdown_signal()) + .await + .unwrap(); +} + +async fn shutdown_signal() { + let ctrl_c = async { + signal::ctrl_c() + .await + .expect("failed to install Ctrl+C handler"); + }; + + #[cfg(unix)] + let terminate = async { + signal::unix::signal(signal::unix::SignalKind::terminate()) + .expect("failed to install signal handler") + .recv() + .await; + }; + + #[cfg(not(unix))] + let terminate = std::future::pending::<()>(); + + tokio::select! { + _ = ctrl_c => {}, + _ = terminate => {}, + } +} +``` diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/src/header.rs b/samples/server/petstore/rust-axum/output/rust-axum-test/src/header.rs new file mode 100644 index 000000000000..4d1cc4c6dccd --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/src/header.rs @@ -0,0 +1,180 @@ +use std::{convert::TryFrom, fmt, ops::Deref}; + +use chrono::{DateTime, Utc}; +use http::HeaderValue; + +/// A struct to allow homogeneous conversion into a HeaderValue. We can't +/// implement the From/Into trait on HeaderValue because we don't own +/// either of the types. +#[derive(Debug, Clone)] +pub(crate) struct IntoHeaderValue(pub T); + +// Generic implementations + +impl Deref for IntoHeaderValue { + type Target = T; + + fn deref(&self) -> &T { + &self.0 + } +} + +// Derive for each TryFrom in http::HeaderValue + +macro_rules! ihv_generate { + ($t:ident) => { + impl TryFrom for IntoHeaderValue<$t> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse::<$t>() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse {} as a string: {}", + stringify!($t), e)), + }, + Err(e) => Err(format!("Unable to parse header {:?} as a string - {}", + hdr_value, e)), + } + } + } + + impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue<$t>) -> Result { + Ok(hdr_value.0.into()) + } + } + }; +} + +ihv_generate!(u64); +ihv_generate!(i64); +ihv_generate!(i16); +ihv_generate!(u16); +ihv_generate!(u32); +ihv_generate!(usize); +ihv_generate!(isize); +ihv_generate!(i32); + +// Custom derivations + +// Vec + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue( + hdr_value + .split(',') + .filter_map(|x| match x.trim() { + "" => None, + y => Some(y.to_string()), + }) + .collect())), + Err(e) => Err(format!("Unable to parse header: {:?} as a string - {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(&hdr_value.0.join(", ")) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} into a header - {}", + hdr_value, e)) + } + } +} + +// String + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value.to_string())), + Err(e) => Err(format!("Unable to convert header {:?} to {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)) + } + } +} + +// Bool + +impl TryFrom for IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match hdr_value.parse() { + Ok(hdr_value) => Ok(IntoHeaderValue(hdr_value)), + Err(e) => Err(format!("Unable to parse bool from {} - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert {:?} from a header {}", + hdr_value, e)), + } + } +} + +impl TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue) -> Result { + match HeaderValue::from_str(&hdr_value.0.to_string()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert: {:?} into a header: {}", + hdr_value, e)) + } + } +} + +// DateTime + +impl TryFrom for IntoHeaderValue> { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> Result { + match hdr_value.to_str() { + Ok(hdr_value) => match DateTime::parse_from_rfc3339(hdr_value) { + Ok(date) => Ok(IntoHeaderValue(date.with_timezone(&Utc))), + Err(e) => Err(format!("Unable to parse: {} as date - {}", + hdr_value, e)), + }, + Err(e) => Err(format!("Unable to convert header {:?} to string {}", + hdr_value, e)), + } + } +} + +impl TryFrom>> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: IntoHeaderValue>) -> Result { + match HeaderValue::from_str(hdr_value.0.to_rfc3339().as_str()) { + Ok(hdr_value) => Ok(hdr_value), + Err(e) => Err(format!("Unable to convert {:?} to a header: {}", + hdr_value, e)), + } + } +} diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/src/lib.rs b/samples/server/petstore/rust-axum/output/rust-axum-test/src/lib.rs new file mode 100644 index 000000000000..41f3a2ace3f0 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/src/lib.rs @@ -0,0 +1,203 @@ +#![allow(missing_docs, trivial_casts, unused_variables, unused_mut, unused_imports, unused_extern_crates, non_camel_case_types)] +#![allow(unused_imports, unused_attributes)] +#![allow(clippy::derive_partial_eq_without_eq, clippy::disallowed_names)] + +use async_trait::async_trait; +use axum::extract::*; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::Method; +use serde::{Deserialize, Serialize}; + +use types::*; + +pub const BASE_PATH: &str = ""; +pub const API_VERSION: &str = "2.3.4"; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum AllOfGetResponse { + /// OK + Status200_OK + (models::AllOfObject) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DummyGetResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum DummyPutResponse { + /// Success + Status200_Success +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum FileResponseGetResponse { + /// Success + Status200_Success + (ByteArray) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum GetStructuredYamlResponse { + /// OK + Status200_OK + (String) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum HtmlPostResponse { + /// Success + Status200_Success + (String) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum PostYamlResponse { + /// OK + Status204_OK +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum RawJsonGetResponse { + /// Success + Status200_Success + (crate::types::Object) +} + + #[derive(Debug, PartialEq, Serialize, Deserialize)] +#[must_use] +#[allow(clippy::large_enum_variant)] +pub enum SoloObjectPostResponse { + /// OK + Status204_OK +} + + +/// API +#[async_trait] +#[allow(clippy::ptr_arg)] +pub trait Api { + + /// AllOfGet - GET /allOf + async fn all_of_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// A dummy endpoint to make the spec valid.. + /// + /// DummyGet - GET /dummy + async fn dummy_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// DummyPut - PUT /dummy + async fn dummy_put( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: models::DummyPutRequest, + ) -> Result; + + + /// Get a file. + /// + /// FileResponseGet - GET /file_response + async fn file_response_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// GetStructuredYaml - GET /get-structured-yaml + async fn get_structured_yaml( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Test HTML handling. + /// + /// HtmlPost - POST /html + async fn html_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: String, + ) -> Result; + + + /// PostYaml - POST /post-yaml + async fn post_yaml( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: String, + ) -> Result; + + + /// Get an arbitrary JSON blob.. + /// + /// RawJsonGet - GET /raw_json + async fn raw_json_get( + &self, + method: Method, + host: Host, + cookies: CookieJar, + ) -> Result; + + + /// Send an arbitrary JSON blob. + /// + /// SoloObjectPost - POST /solo-object + async fn solo_object_post( + &self, + method: Method, + host: Host, + cookies: CookieJar, + body: crate::types::Object, + ) -> Result; + +} + +#[cfg(feature = "server")] +pub mod server; + +pub mod models; +pub mod types; + +#[cfg(feature = "server")] +pub(crate) mod header; diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/src/models.rs b/samples/server/petstore/rust-axum/output/rust-axum-test/src/models.rs new file mode 100644 index 000000000000..e8afc229ad87 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/src/models.rs @@ -0,0 +1,1030 @@ +#![allow(unused_qualifications)] + +use http::HeaderValue; +use validator::Validate; + +#[cfg(feature = "server")] +use crate::header; +use crate::{models, types::*}; + + + + + + + + + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ANullableContainer { + #[serde(rename = "NullableThing")] + #[serde(deserialize_with = "deserialize_optional_nullable")] + #[serde(default = "default_optional_nullable")] + #[serde(skip_serializing_if="Option::is_none")] + pub nullable_thing: Option>, + + #[serde(rename = "RequiredNullableThing")] + pub required_nullable_thing: Nullable, + +} + + +impl ANullableContainer { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_nullable_thing: Nullable, ) -> ANullableContainer { + ANullableContainer { + nullable_thing: None, + required_nullable_thing, + } + } +} + +/// Converts the ANullableContainer value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ANullableContainer { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.nullable_thing.as_ref().map(|nullable_thing| { + [ + "NullableThing".to_string(), + nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string()), + ].join(",") + }), + + + Some("RequiredNullableThing".to_string()), + Some(self.required_nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string())), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ANullableContainer value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ANullableContainer { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub nullable_thing: Vec, + pub required_nullable_thing: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ANullableContainer".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + "NullableThing" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ANullableContainer".to_string()), + "RequiredNullableThing" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in ANullableContainer".to_string()), + _ => return std::result::Result::Err("Unexpected key while parsing ANullableContainer".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ANullableContainer { + nullable_thing: std::result::Result::Err("Nullable types not supported in ANullableContainer".to_string())?, + required_nullable_thing: std::result::Result::Err("Nullable types not supported in ANullableContainer".to_string())?, + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ANullableContainer - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ANullableContainer - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// An additionalPropertiesObject +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AdditionalPropertiesObject(std::collections::HashMap); + +impl validator::Validate for AdditionalPropertiesObject { + fn validate(&self) -> std::result::Result<(), validator::ValidationErrors> { + std::result::Result::Ok(()) + } +} + +impl std::convert::From> for AdditionalPropertiesObject { + fn from(x: std::collections::HashMap) -> Self { + AdditionalPropertiesObject(x) + } +} + +impl std::convert::From for std::collections::HashMap { + fn from(x: AdditionalPropertiesObject) -> Self { + x.0 + } +} + +impl std::ops::Deref for AdditionalPropertiesObject { + type Target = std::collections::HashMap; + fn deref(&self) -> &std::collections::HashMap { + &self.0 + } +} + +impl std::ops::DerefMut for AdditionalPropertiesObject { + fn deref_mut(&mut self) -> &mut std::collections::HashMap { + &mut self.0 + } +} + +/// Converts the AdditionalPropertiesObject value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl ::std::string::ToString for AdditionalPropertiesObject { + fn to_string(&self) -> String { + // Skipping additionalProperties in query parameter serialization + "".to_string() + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AdditionalPropertiesObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl ::std::str::FromStr for AdditionalPropertiesObject { + type Err = &'static str; + + fn from_str(s: &str) -> std::result::Result { + std::result::Result::Err("Parsing additionalProperties for AdditionalPropertiesObject is not supported") + } +} + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct AllOfObject { + #[serde(rename = "sampleProperty")] + #[serde(skip_serializing_if="Option::is_none")] + pub sample_property: Option, + + #[serde(rename = "sampleBaseProperty")] + #[serde(skip_serializing_if="Option::is_none")] + pub sample_base_property: Option, + +} + + +impl AllOfObject { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> AllOfObject { + AllOfObject { + sample_property: None, + sample_base_property: None, + } + } +} + +/// Converts the AllOfObject value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for AllOfObject { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.sample_property.as_ref().map(|sample_property| { + [ + "sampleProperty".to_string(), + sample_property.to_string(), + ].join(",") + }), + + + self.sample_base_property.as_ref().map(|sample_base_property| { + [ + "sampleBaseProperty".to_string(), + sample_base_property.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a AllOfObject value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for AllOfObject { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub sample_property: Vec, + pub sample_base_property: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing AllOfObject".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "sampleProperty" => intermediate_rep.sample_property.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "sampleBaseProperty" => intermediate_rep.sample_base_property.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing AllOfObject".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(AllOfObject { + sample_property: intermediate_rep.sample_property.into_iter().next(), + sample_base_property: intermediate_rep.sample_base_property.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for AllOfObject - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into AllOfObject - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct BaseAllOf { + #[serde(rename = "sampleBaseProperty")] + #[serde(skip_serializing_if="Option::is_none")] + pub sample_base_property: Option, + +} + + +impl BaseAllOf { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> BaseAllOf { + BaseAllOf { + sample_base_property: None, + } + } +} + +/// Converts the BaseAllOf value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for BaseAllOf { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.sample_base_property.as_ref().map(|sample_base_property| { + [ + "sampleBaseProperty".to_string(), + sample_base_property.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a BaseAllOf value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for BaseAllOf { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub sample_base_property: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing BaseAllOf".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "sampleBaseProperty" => intermediate_rep.sample_base_property.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing BaseAllOf".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(BaseAllOf { + sample_base_property: intermediate_rep.sample_base_property.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for BaseAllOf - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into BaseAllOf - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct DummyPutRequest { + #[serde(rename = "id")] + pub id: String, + + #[serde(rename = "password")] + #[serde(skip_serializing_if="Option::is_none")] + pub password: Option, + +} + + +impl DummyPutRequest { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(id: String, ) -> DummyPutRequest { + DummyPutRequest { + id, + password: None, + } + } +} + +/// Converts the DummyPutRequest value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for DummyPutRequest { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("id".to_string()), + Some(self.id.to_string()), + + + self.password.as_ref().map(|password| { + [ + "password".to_string(), + password.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a DummyPutRequest value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for DummyPutRequest { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub id: Vec, + pub password: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing DummyPutRequest".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "id" => intermediate_rep.id.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "password" => intermediate_rep.password.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing DummyPutRequest".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(DummyPutRequest { + id: intermediate_rep.id.into_iter().next().ok_or_else(|| "id missing in DummyPutRequest".to_string())?, + password: intermediate_rep.password.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for DummyPutRequest - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into DummyPutRequest - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// structured response + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct GetYamlResponse { +/// Inner string + #[serde(rename = "value")] + #[serde(skip_serializing_if="Option::is_none")] + pub value: Option, + +} + + +impl GetYamlResponse { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> GetYamlResponse { + GetYamlResponse { + value: None, + } + } +} + +/// Converts the GetYamlResponse value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for GetYamlResponse { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + self.value.as_ref().map(|value| { + [ + "value".to_string(), + value.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a GetYamlResponse value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for GetYamlResponse { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub value: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing GetYamlResponse".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "value" => intermediate_rep.value.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing GetYamlResponse".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(GetYamlResponse { + value: intermediate_rep.value.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for GetYamlResponse - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into GetYamlResponse - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + +/// An object of objects + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectOfObjects { + #[serde(rename = "inner")] + #[serde(skip_serializing_if="Option::is_none")] + pub inner: Option, + +} + + +impl ObjectOfObjects { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new() -> ObjectOfObjects { + ObjectOfObjects { + inner: None, + } + } +} + +/// Converts the ObjectOfObjects value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectOfObjects { + fn to_string(&self) -> String { + let params: Vec> = vec![ + // Skipping inner in query parameter serialization + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectOfObjects value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectOfObjects { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub inner: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectOfObjects".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "inner" => intermediate_rep.inner.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjects".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectOfObjects { + inner: intermediate_rep.inner.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectOfObjects - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectOfObjects - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + + + + + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize, validator::Validate)] +#[cfg_attr(feature = "conversion", derive(frunk::LabelledGeneric))] +pub struct ObjectOfObjectsInner { + #[serde(rename = "required_thing")] + pub required_thing: String, + + #[serde(rename = "optional_thing")] + #[serde(skip_serializing_if="Option::is_none")] + pub optional_thing: Option, + +} + + +impl ObjectOfObjectsInner { + #[allow(clippy::new_without_default, clippy::too_many_arguments)] + pub fn new(required_thing: String, ) -> ObjectOfObjectsInner { + ObjectOfObjectsInner { + required_thing, + optional_thing: None, + } + } +} + +/// Converts the ObjectOfObjectsInner value to the Query Parameters representation (style=form, explode=false) +/// specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde serializer +impl std::string::ToString for ObjectOfObjectsInner { + fn to_string(&self) -> String { + let params: Vec> = vec![ + + Some("required_thing".to_string()), + Some(self.required_thing.to_string()), + + + self.optional_thing.as_ref().map(|optional_thing| { + [ + "optional_thing".to_string(), + optional_thing.to_string(), + ].join(",") + }), + + ]; + + params.into_iter().flatten().collect::>().join(",") + } +} + +/// Converts Query Parameters representation (style=form, explode=false) to a ObjectOfObjectsInner value +/// as specified in https://swagger.io/docs/specification/serialization/ +/// Should be implemented in a serde deserializer +impl std::str::FromStr for ObjectOfObjectsInner { + type Err = String; + + fn from_str(s: &str) -> std::result::Result { + /// An intermediate representation of the struct to use for parsing. + #[derive(Default)] + #[allow(dead_code)] + struct IntermediateRep { + pub required_thing: Vec, + pub optional_thing: Vec, + } + + let mut intermediate_rep = IntermediateRep::default(); + + // Parse into intermediate representation + let mut string_iter = s.split(','); + let mut key_result = string_iter.next(); + + while key_result.is_some() { + let val = match string_iter.next() { + Some(x) => x, + None => return std::result::Result::Err("Missing value while parsing ObjectOfObjectsInner".to_string()) + }; + + if let Some(key) = key_result { + #[allow(clippy::match_single_binding)] + match key { + #[allow(clippy::redundant_clone)] + "required_thing" => intermediate_rep.required_thing.push(::from_str(val).map_err(|x| x.to_string())?), + #[allow(clippy::redundant_clone)] + "optional_thing" => intermediate_rep.optional_thing.push(::from_str(val).map_err(|x| x.to_string())?), + _ => return std::result::Result::Err("Unexpected key while parsing ObjectOfObjectsInner".to_string()) + } + } + + // Get the next key + key_result = string_iter.next(); + } + + // Use the intermediate representation to return the struct + std::result::Result::Ok(ObjectOfObjectsInner { + required_thing: intermediate_rep.required_thing.into_iter().next().ok_or_else(|| "required_thing missing in ObjectOfObjectsInner".to_string())?, + optional_thing: intermediate_rep.optional_thing.into_iter().next(), + }) + } +} + +// Methods for converting between header::IntoHeaderValue and HeaderValue + +#[cfg(feature = "server")] +impl std::convert::TryFrom> for HeaderValue { + type Error = String; + + fn try_from(hdr_value: header::IntoHeaderValue) -> std::result::Result { + let hdr_value = hdr_value.to_string(); + match HeaderValue::from_str(&hdr_value) { + std::result::Result::Ok(value) => std::result::Result::Ok(value), + std::result::Result::Err(e) => std::result::Result::Err( + format!("Invalid header value for ObjectOfObjectsInner - value: {} is invalid {}", + hdr_value, e)) + } + } +} + +#[cfg(feature = "server")] +impl std::convert::TryFrom for header::IntoHeaderValue { + type Error = String; + + fn try_from(hdr_value: HeaderValue) -> std::result::Result { + match hdr_value.to_str() { + std::result::Result::Ok(value) => { + match ::from_str(value) { + std::result::Result::Ok(value) => std::result::Result::Ok(header::IntoHeaderValue(value)), + std::result::Result::Err(err) => std::result::Result::Err( + format!("Unable to convert header value '{}' into ObjectOfObjectsInner - {}", + value, err)) + } + }, + std::result::Result::Err(e) => std::result::Result::Err( + format!("Unable to convert header: {:?} to string: {}", + hdr_value, e)) + } + } +} + + + diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/src/server/mod.rs b/samples/server/petstore/rust-axum/output/rust-axum-test/src/server/mod.rs new file mode 100644 index 000000000000..b08d1c72d6a0 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/src/server/mod.rs @@ -0,0 +1,760 @@ +use std::collections::HashMap; + +use axum::{body::Body, extract::*, response::Response, routing::*}; +use axum_extra::extract::{CookieJar, Multipart}; +use bytes::Bytes; +use http::{header::CONTENT_TYPE, HeaderMap, HeaderName, HeaderValue, Method, StatusCode}; +use tracing::error; +use validator::{Validate, ValidationErrors}; + +use crate::{header, types::*}; + +#[allow(unused_imports)] +use crate::models; + +use crate::{Api, + AllOfGetResponse, + DummyGetResponse, + DummyPutResponse, + FileResponseGetResponse, + GetStructuredYamlResponse, + HtmlPostResponse, + PostYamlResponse, + RawJsonGetResponse, + SoloObjectPostResponse +}; + +/// Setup API Server. +pub fn new(api_impl: I) -> Router +where + I: AsRef + Clone + Send + Sync + 'static, + A: Api + 'static, +{ + // build our application with a route + Router::new() + .route("/allOf", + get(all_of_get::) + ) + .route("/dummy", + get(dummy_get::).put(dummy_put::) + ) + .route("/file_response", + get(file_response_get::) + ) + .route("/get-structured-yaml", + get(get_structured_yaml::) + ) + .route("/html", + post(html_post::) + ) + .route("/post-yaml", + post(post_yaml::) + ) + .route("/raw_json", + get(raw_json_get::) + ) + .route("/solo-object", + post(solo_object_post::) + ) + .with_state(api_impl) +} + + +#[tracing::instrument(skip_all)] +fn all_of_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// AllOfGet - GET /allOf +#[tracing::instrument(skip_all)] +async fn all_of_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + all_of_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().all_of_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + AllOfGetResponse::Status200_OK + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn dummy_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// DummyGet - GET /dummy +#[tracing::instrument(skip_all)] +async fn dummy_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + dummy_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().dummy_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DummyGetResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct DummyPutBodyValidator<'a> { + #[validate] + body: &'a models::DummyPutRequest, + } + + +#[tracing::instrument(skip_all)] +fn dummy_put_validation( + body: models::DummyPutRequest, +) -> std::result::Result<( + models::DummyPutRequest, +), ValidationErrors> +{ + let b = DummyPutBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// DummyPut - PUT /dummy +#[tracing::instrument(skip_all)] +async fn dummy_put( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + dummy_put_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().dummy_put( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + DummyPutResponse::Status200_Success + => { + + let mut response = response.status(200); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn file_response_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// FileResponseGet - GET /file_response +#[tracing::instrument(skip_all)] +async fn file_response_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + file_response_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().file_response_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + FileResponseGetResponse::Status200_Success + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/json").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn get_structured_yaml_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// GetStructuredYaml - GET /get-structured-yaml +#[tracing::instrument(skip_all)] +async fn get_structured_yaml( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + get_structured_yaml_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().get_structured_yaml( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + GetStructuredYamlResponse::Status200_OK + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("application/yaml").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct HtmlPostBodyValidator<'a> { + body: &'a String, + } + + +#[tracing::instrument(skip_all)] +fn html_post_validation( + body: String, +) -> std::result::Result<( + String, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// HtmlPost - POST /html +#[tracing::instrument(skip_all)] +async fn html_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: String, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + html_post_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().html_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + HtmlPostResponse::Status200_Success + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("text/html").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = body; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct PostYamlBodyValidator<'a> { + body: &'a String, + } + + +#[tracing::instrument(skip_all)] +fn post_yaml_validation( + body: String, +) -> std::result::Result<( + String, +), ValidationErrors> +{ + +Ok(( + body, +)) +} + +/// PostYaml - POST /post-yaml +#[tracing::instrument(skip_all)] +async fn post_yaml( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + body: String, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + post_yaml_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().post_yaml( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + PostYamlResponse::Status204_OK + => { + + let mut response = response.status(204); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + +#[tracing::instrument(skip_all)] +fn raw_json_get_validation( +) -> std::result::Result<( +), ValidationErrors> +{ + +Ok(( +)) +} + +/// RawJsonGet - GET /raw_json +#[tracing::instrument(skip_all)] +async fn raw_json_get( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + raw_json_get_validation( + ) + ).await.unwrap(); + + let Ok(( + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().raw_json_get( + method, + host, + cookies, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + RawJsonGetResponse::Status200_Success + (body) + => { + + let mut response = response.status(200); + { + let mut response_headers = response.headers_mut().unwrap(); + response_headers.insert( + CONTENT_TYPE, + HeaderValue::from_str("*/*").map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR })?); + } + + let body_content = tokio::task::spawn_blocking(move || + serde_json::to_vec(&body).map_err(|e| { + error!(error = ?e); + StatusCode::INTERNAL_SERVER_ERROR + })).await.unwrap()?; + response.body(Body::from(body_content)) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + + #[derive(validator::Validate)] + #[allow(dead_code)] + struct SoloObjectPostBodyValidator<'a> { + body: &'a crate::types::Object, + } + + +#[tracing::instrument(skip_all)] +fn solo_object_post_validation( + body: crate::types::Object, +) -> std::result::Result<( + crate::types::Object, +), ValidationErrors> +{ + let b = SoloObjectPostBodyValidator { body: &body }; + b.validate()?; + +Ok(( + body, +)) +} + +/// SoloObjectPost - POST /solo-object +#[tracing::instrument(skip_all)] +async fn solo_object_post( + method: Method, + host: Host, + cookies: CookieJar, + State(api_impl): State, + Json(body): Json, +) -> Result +where + I: AsRef + Send + Sync, + A: Api, +{ + + #[allow(clippy::redundant_closure)] + let validation = tokio::task::spawn_blocking(move || + solo_object_post_validation( + body, + ) + ).await.unwrap(); + + let Ok(( + body, + )) = validation else { + return Response::builder() + .status(StatusCode::BAD_REQUEST) + .body(Body::from(validation.unwrap_err().to_string())) + .map_err(|_| StatusCode::BAD_REQUEST); + }; + + let result = api_impl.as_ref().solo_object_post( + method, + host, + cookies, + body, + ).await; + + let mut response = Response::builder(); + + let resp = match result { + Ok(rsp) => match rsp { + SoloObjectPostResponse::Status204_OK + => { + + let mut response = response.status(204); + response.body(Body::empty()) + }, + }, + Err(_) => { + // Application code returned an error. This should not happen, as the implementation should + // return a valid response. + response.status(500).body(Body::empty()) + }, + }; + + resp.map_err(|e| { error!(error = ?e); StatusCode::INTERNAL_SERVER_ERROR }) +} + diff --git a/samples/server/petstore/rust-axum/output/rust-axum-test/src/types.rs b/samples/server/petstore/rust-axum/output/rust-axum-test/src/types.rs new file mode 100644 index 000000000000..cebc173ddf80 --- /dev/null +++ b/samples/server/petstore/rust-axum/output/rust-axum-test/src/types.rs @@ -0,0 +1,665 @@ +use std::{mem, str::FromStr}; + +use base64::{engine::general_purpose, Engine}; +use serde::{Deserialize, Deserializer, Serialize, Serializer}; + +#[derive(Debug, Clone, PartialEq, serde::Serialize, serde::Deserialize)] +#[allow(dead_code)] +pub struct Object(serde_json::Value); + +impl validator::Validate for Object { + fn validate(&self) -> Result<(), validator::ValidationErrors> { + Ok(()) + } +} + +impl FromStr for Object { + type Err = String; + + fn from_str(s: &str) -> Result { + Ok(Self(serde_json::Value::String(s.to_owned()))) + } +} + +/// Serde helper function to create a default `Option>` while +/// deserializing +pub fn default_optional_nullable() -> Option> { + None +} + +/// Serde helper function to deserialize into an `Option>` +pub fn deserialize_optional_nullable<'de, D, T>( + deserializer: D, +) -> Result>, D::Error> +where + D: Deserializer<'de>, + T: Deserialize<'de>, +{ + Option::::deserialize(deserializer).map(|val| match val { + Some(inner) => Some(Nullable::Present(inner)), + None => Some(Nullable::Null), + }) +} + +/// The Nullable type. Represents a value which may be specified as null on an API. +/// Note that this is distinct from a value that is optional and not present! +/// +/// Nullable implements many of the same methods as the Option type (map, unwrap, etc). +#[derive(Debug, Clone, Copy, PartialEq, PartialOrd)] +pub enum Nullable { + /// Null value + Null, + /// Value is present + Present(T), +} + +impl Nullable { + ///////////////////////////////////////////////////////////////////////// + // Querying the contained values + ///////////////////////////////////////////////////////////////////////// + + /// Returns `true` if the Nullable is a `Present` value. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_present(), true); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_present(), false); + /// ``` + #[inline] + pub fn is_present(&self) -> bool { + match *self { + Nullable::Present(_) => true, + Nullable::Null => false, + } + } + + /// Returns `true` if the Nullable is a `Null` value. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x: Nullable = Nullable::Present(2); + /// assert_eq!(x.is_null(), false); + /// + /// let x: Nullable = Nullable::Null; + /// assert_eq!(x.is_null(), true); + /// ``` + #[inline] + pub fn is_null(&self) -> bool { + !self.is_present() + } + + ///////////////////////////////////////////////////////////////////////// + // Adapter for working with references + ///////////////////////////////////////////////////////////////////////// + + /// Converts from `Nullable` to `Nullable<&T>`. + /// + /// # Examples + /// + /// Convert an `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, preserving the original. + /// The [`map`] method takes the `self` argument by value, consuming the original, + /// so this technique uses `as_ref` to first take a `Nullable` to a reference + /// to the value inside the original. + /// + /// [`map`]: enum.Nullable.html#method.map + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let num_as_str: Nullable = Nullable::Present("10".to_string()); + /// // First, cast `Nullable` to `Nullable<&String>` with `as_ref`, + /// // then consume *that* with `map`, leaving `num_as_str` on the stack. + /// let num_as_int: Nullable = num_as_str.as_ref().map(|n| n.len()); + /// println!("still can print num_as_str: {:?}", num_as_str); + /// ``` + #[inline] + pub fn as_ref(&self) -> Nullable<&T> { + match *self { + Nullable::Present(ref x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + /// Converts from `Nullable` to `Nullable<&mut T>`. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// match x.as_mut() { + /// Nullable::Present(v) => *v = 42, + /// Nullable::Null => {}, + /// } + /// assert_eq!(x, Nullable::Present(42)); + /// ``` + #[inline] + pub fn as_mut(&mut self) -> Nullable<&mut T> { + match *self { + Nullable::Present(ref mut x) => Nullable::Present(x), + Nullable::Null => Nullable::Null, + } + } + + ///////////////////////////////////////////////////////////////////////// + // Getting to contained values + ///////////////////////////////////////////////////////////////////////// + + /// Unwraps a Nullable, yielding the content of a `Nullable::Present`. + /// + /// # Panics + /// + /// Panics if the value is a [`Nullable::Null`] with a custom panic message provided by + /// `msg`. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present("value"); + /// assert_eq!(x.expect("the world is ending"), "value"); + /// ``` + /// + /// ```{.should_panic} + /// # use rust_server_test::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// x.expect("the world is ending"); // panics with `the world is ending` + /// ``` + #[inline] + pub fn expect(self, msg: &str) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => expect_failed(msg), + } + } + + /// Moves the value `v` out of the `Nullable` if it is `Nullable::Present(v)`. + /// + /// In general, because this function may panic, its use is discouraged. + /// Instead, prefer to use pattern matching and handle the `Nullable::Null` + /// case explicitly. + /// + /// # Panics + /// + /// Panics if the self value equals [`Nullable::Null`]. + /// + /// [`Nullable::Null`]: #variant.Null + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present("air"); + /// assert_eq!(x.unwrap(), "air"); + /// ``` + /// + /// ```{.should_panic} + /// # use rust_server_test::types::Nullable; + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.unwrap(), "air"); // fails + /// ``` + #[inline] + pub fn unwrap(self) -> T { + match self { + Nullable::Present(val) => val, + Nullable::Null => panic!("called `Nullable::unwrap()` on a `Nullable::Null` value"), + } + } + + /// Returns the contained value or a default. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// assert_eq!(Nullable::Present("car").unwrap_or("bike"), "car"); + /// assert_eq!(Nullable::Null.unwrap_or("bike"), "bike"); + /// ``` + #[inline] + pub fn unwrap_or(self, def: T) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => def, + } + } + + /// Returns the contained value or computes it from a closure. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let k = 10; + /// assert_eq!(Nullable::Present(4).unwrap_or_else(|| 2 * k), 4); + /// assert_eq!(Nullable::Null.unwrap_or_else(|| 2 * k), 20); + /// ``` + #[inline] + pub fn unwrap_or_else T>(self, f: F) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Transforming contained values + ///////////////////////////////////////////////////////////////////////// + + /// Maps a `Nullable` to `Nullable` by applying a function to a contained value. + /// + /// # Examples + /// + /// Convert a `Nullable<`[`String`]`>` into a `Nullable<`[`usize`]`>`, consuming the original: + /// + /// [`String`]: ../../std/string/struct.String.html + /// [`usize`]: ../../std/primitive.usize.html + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let maybe_some_string = Nullable::Present(String::from("Hello, World!")); + /// // `Nullable::map` takes self *by value*, consuming `maybe_some_string` + /// let maybe_some_len = maybe_some_string.map(|s| s.len()); + /// + /// assert_eq!(maybe_some_len, Nullable::Present(13)); + /// ``` + #[inline] + pub fn map U>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => Nullable::Present(f(x)), + Nullable::Null => Nullable::Null, + } + } + + /// Applies a function to the contained value (if any), + /// or returns a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or(42, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or(42, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or U>(self, default: U, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default, + } + } + + /// Applies a function to the contained value (if any), + /// or computes a `default` (if not). + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let k = 21; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 3); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.map_or_else(|| 2 * k, |v| v.len()), 42); + /// ``` + #[inline] + pub fn map_or_else U, F: FnOnce(T) -> U>(self, default: D, f: F) -> U { + match self { + Nullable::Present(t) => f(t), + Nullable::Null => default(), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err)`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or(0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or(0), Err(0)); + /// ``` + #[inline] + pub fn ok_or(self, err: E) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err), + } + } + + /// Transforms the `Nullable` into a [`Result`], mapping `Nullable::Present(v)` to + /// [`Ok(v)`] and `Nullable::Null` to [`Err(err())`][Err]. + /// + /// [`Result`]: ../../std/result/enum.Result.html + /// [`Ok(v)`]: ../../std/result/enum.Result.html#variant.Ok + /// [Err]: ../../std/result/enum.Result.html#variant.Err + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present("foo"); + /// assert_eq!(x.ok_or_else(|| 0), Ok("foo")); + /// + /// let x: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.ok_or_else(|| 0), Err(0)); + /// ``` + #[inline] + pub fn ok_or_else E>(self, err: F) -> Result { + match self { + Nullable::Present(v) => Ok(v), + Nullable::Null => Err(err()), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Boolean operations on the values, eager and lazy + ///////////////////////////////////////////////////////////////////////// + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Null); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present("foo"); + /// assert_eq!(x.and(y), Nullable::Present("foo")); + /// + /// let x: Nullable = Nullable::Null; + /// let y: Nullable<&str> = Nullable::Null; + /// assert_eq!(x.and(y), Nullable::Null); + /// ``` + #[inline] + pub fn and(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => optb, + Nullable::Null => Nullable::Null, + } + } + + /// Returns `Nullable::Null` if the Nullable is `Nullable::Null`, otherwise calls `f` with the + /// wrapped value and returns the result. + /// + /// Some languages call this operation flatmap. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// fn sq(x: u32) -> Nullable { Nullable::Present(x * x) } + /// fn nope(_: u32) -> Nullable { Nullable::Null } + /// + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(sq), Nullable::Present(16)); + /// assert_eq!(Nullable::Present(2).and_then(sq).and_then(nope), Nullable::Null); + /// assert_eq!(Nullable::Present(2).and_then(nope).and_then(sq), Nullable::Null); + /// assert_eq!(Nullable::Null.and_then(sq).and_then(sq), Nullable::Null); + /// ``` + #[inline] + pub fn and_then Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(x) => f(x), + Nullable::Null => Nullable::Null, + } + } + + /// Returns the Nullable if it contains a value, otherwise returns `optb`. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x = Nullable::Null; + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(100)); + /// + /// let x = Nullable::Present(2); + /// let y = Nullable::Present(100); + /// assert_eq!(x.or(y), Nullable::Present(2)); + /// + /// let x: Nullable = Nullable::Null; + /// let y = Nullable::Null; + /// assert_eq!(x.or(y), Nullable::Null); + /// ``` + #[inline] + pub fn or(self, optb: Nullable) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => optb, + } + } + + /// Returns the Nullable if it contains a value, otherwise calls `f` and + /// returns the result. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// fn nobody() -> Nullable<&'static str> { Nullable::Null } + /// fn vikings() -> Nullable<&'static str> { Nullable::Present("vikings") } + /// + /// assert_eq!(Nullable::Present("barbarians").or_else(vikings), + /// Nullable::Present("barbarians")); + /// assert_eq!(Nullable::Null.or_else(vikings), Nullable::Present("vikings")); + /// assert_eq!(Nullable::Null.or_else(nobody), Nullable::Null); + /// ``` + #[inline] + pub fn or_else Nullable>(self, f: F) -> Nullable { + match self { + Nullable::Present(_) => self, + Nullable::Null => f(), + } + } + + ///////////////////////////////////////////////////////////////////////// + // Misc + ///////////////////////////////////////////////////////////////////////// + + /// Takes the value out of the Nullable, leaving a `Nullable::Null` in its place. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let mut x = Nullable::Present(2); + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// + /// let mut x: Nullable = Nullable::Null; + /// x.take(); + /// assert_eq!(x, Nullable::Null); + /// ``` + #[inline] + pub fn take(&mut self) -> Nullable { + mem::replace(self, Nullable::Null) + } +} + +impl<'a, T: Clone> Nullable<&'a T> { + /// Maps an `Nullable<&T>` to an `Nullable` by cloning the contents of the + /// Nullable. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = 12; + /// let opt_x = Nullable::Present(&x); + /// assert_eq!(opt_x, Nullable::Present(&12)); + /// let cloned = opt_x.cloned(); + /// assert_eq!(cloned, Nullable::Present(12)); + /// ``` + pub fn cloned(self) -> Nullable { + self.map(Clone::clone) + } +} + +impl Nullable { + /// Returns the contained value or a default + /// + /// Consumes the `self` argument then, if `Nullable::Present`, returns the contained + /// value, otherwise if `Nullable::Null`, returns the default value for that + /// type. + /// + /// # Examples + /// + /// ``` + /// # use rust_server_test::types::Nullable; + /// + /// let x = Nullable::Present(42); + /// assert_eq!(42, x.unwrap_or_default()); + /// + /// let y: Nullable = Nullable::Null; + /// assert_eq!(0, y.unwrap_or_default()); + /// ``` + #[inline] + pub fn unwrap_or_default(self) -> T { + match self { + Nullable::Present(x) => x, + Nullable::Null => Default::default(), + } + } +} + +impl Default for Nullable { + /// Returns None. + #[inline] + fn default() -> Nullable { + Nullable::Null + } +} + +impl From for Nullable { + fn from(val: T) -> Nullable { + Nullable::Present(val) + } +} + +impl Serialize for Nullable +where + T: Serialize, +{ + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + match *self { + Nullable::Present(ref inner) => serializer.serialize_some(&inner), + Nullable::Null => serializer.serialize_none(), + } + } +} + +impl<'de, T> Deserialize<'de> for Nullable +where + T: serde::de::DeserializeOwned, +{ + fn deserialize(deserializer: D) -> Result, D::Error> + where + D: Deserializer<'de>, + { + // In order to deserialize a required, but nullable, value, we first have to check whether + // the value is present at all. To do this, we deserialize to a serde_json::Value, which + // fails if the value is missing, or gives serde_json::Value::Null if the value is present. + // If that succeeds as null, we can easily return a Null. + // If that succeeds as some value, we deserialize that value and return a Present. + // If that errors, we return the error. + let presence: Result<::serde_json::Value, _> = + serde::Deserialize::deserialize(deserializer); + match presence { + Ok(serde_json::Value::Null) => Ok(Nullable::Null), + Ok(some_value) => serde_json::from_value(some_value) + .map(Nullable::Present) + .map_err(serde::de::Error::custom), + Err(x) => Err(x), + } + } +} + +#[inline(never)] +#[cold] +fn expect_failed(msg: &str) -> ! { + panic!("{}", msg) +} + +#[derive(Debug, Clone, PartialEq, PartialOrd)] +/// Base64-encoded byte array +pub struct ByteArray(pub Vec); + +impl Serialize for ByteArray { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_str(&general_purpose::STANDARD.encode(&self.0)) + } +} + +impl<'de> Deserialize<'de> for ByteArray { + fn deserialize(deserializer: D) -> Result + where + D: Deserializer<'de>, + { + let s = String::deserialize(deserializer)?; + match general_purpose::STANDARD.decode(s) { + Ok(bin) => Ok(ByteArray(bin)), + _ => Err(serde::de::Error::custom("invalid base64")), + } + } +} diff --git a/samples/server/petstore/python-aiohttp-srclayout/pom.xml b/samples/server/petstore/rust-axum/pom.xml similarity index 52% rename from samples/server/petstore/python-aiohttp-srclayout/pom.xml rename to samples/server/petstore/rust-axum/pom.xml index 2dc0adaf279c..61e50dcc15a0 100644 --- a/samples/server/petstore/python-aiohttp-srclayout/pom.xml +++ b/samples/server/petstore/rust-axum/pom.xml @@ -1,10 +1,10 @@ 4.0.0 org.openapitools - PythonAiohttpSrcLayoutServer + RustServerTests pom 1.0-SNAPSHOT - Python Aiohttp Server (/src layout) + Rust Petstore Sample @@ -26,6 +26,20 @@ exec-maven-plugin 1.2.1 + + build + integration-test + + exec + + + cargo + + build + --examples + + + test integration-test @@ -33,9 +47,22 @@ exec - make + cargo + + test + + + + + clippy + integration-test + + exec + + + cargo - test-all + clippy diff --git a/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/multipart-v3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs index a031eb139ca8..a33ffe55388c 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/examples/server/server.rs @@ -112,7 +112,6 @@ impl Api for Server where C: Has + Send + Sync optional_binary_field: Option, context: &C) -> Result { - let context = context.clone(); info!("multipart_related_request_post({:?}, {:?}, {:?}) - X-Span-ID: {:?}", required_binary_field, object_field, optional_binary_field, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -125,7 +124,6 @@ impl Api for Server where C: Has + Send + Sync object_field: Option, context: &C) -> Result { - let context = context.clone(); info!("multipart_request_post(\"{}\", {:?}, {:?}, {:?}) - X-Span-ID: {:?}", string_field, binary_field, optional_string_field, object_field, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -136,7 +134,6 @@ impl Api for Server where C: Has + Send + Sync binary2: Option, context: &C) -> Result { - let context = context.clone(); info!("multiple_identical_mime_types_post({:?}, {:?}) - X-Span-ID: {:?}", binary1, binary2, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs b/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs index d296010d7210..ea0267cbe021 100644 --- a/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/multipart-v3/src/models.rs @@ -180,7 +180,7 @@ impl std::string::ToString for MultipartRequestObjectField { self.field_b.as_ref().map(|field_b| { - vec![ + [ "field_b".to_string(), field_b.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") diff --git a/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/no-example-v3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs index 55f8d608b52e..9ca6a4e5e41d 100644 --- a/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/no-example-v3/examples/server/server.rs @@ -108,7 +108,6 @@ impl Api for Server where C: Has + Send + Sync op_get_request: models::OpGetRequest, context: &C) -> Result { - let context = context.clone(); info!("op_get({:?}) - X-Span-ID: {:?}", op_get_request, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/openapi-v3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml index 10519bee5f9f..51eb55c33843 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml +++ b/samples/server/petstore/rust-server/output/openapi-v3/api/openapi.yaml @@ -654,6 +654,22 @@ components: type: string nullable: true type: array + min_item_test: + items: + type: integer + minItems: 1 + type: array + max_item_test: + items: + type: integer + maxItems: 2 + type: array + min_max_item_test: + items: + type: integer + maxItems: 3 + minItems: 1 + type: array required: - nullable type: object diff --git a/samples/server/petstore/rust-server/output/openapi-v3/docs/NullableTest.md b/samples/server/petstore/rust-server/output/openapi-v3/docs/NullableTest.md index 3644435f2e58..2512b338a5b9 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/docs/NullableTest.md +++ b/samples/server/petstore/rust-server/output/openapi-v3/docs/NullableTest.md @@ -8,6 +8,9 @@ Name | Type | Description | Notes **nullable_with_present_default** | **String** | | [optional] [default to Some(swagger::Nullable::Present("default".to_string()))] **nullable_with_no_default** | **String** | | [optional] [default to None] **nullable_array** | **Vec** | | [optional] [default to None] +**min_item_test** | **Vec** | | [optional] [default to None] +**max_item_test** | **Vec** | | [optional] [default to None] +**min_max_item_test** | **Vec** | | [optional] [default to None] [[Back to Model list]](../README.md#documentation-for-models) [[Back to API list]](../README.md#documentation-for-api-endpoints) [[Back to README]](../README.md) diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs index a66747e42db8..a7c806ff1c5d 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/client/server.rs @@ -107,7 +107,6 @@ impl CallbackApi for Server where C: Has + Send + Sync information: Option, context: &C) -> Result { - let context = context.clone(); info!("callback_callback_with_header_post({:?}) - X-Span-ID: {:?}", information, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -117,7 +116,6 @@ impl CallbackApi for Server where C: Has + Send + Sync callback_request_query_url: String, context: &C) -> Result { - let context = context.clone(); info!("callback_callback_post() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs index 1fde6bbdf1e6..d51a51417eda 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/examples/server/server.rs @@ -133,7 +133,6 @@ impl Api for Server where C: Has + Send + Sync any_of: Option<&Vec>, context: &C) -> Result { - let context = context.clone(); info!("any_of_get({:?}) - X-Span-ID: {:?}", any_of, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -143,7 +142,6 @@ impl Api for Server where C: Has + Send + Sync url: String, context: &C) -> Result { - let context = context.clone(); info!("callback_with_header_post(\"{}\") - X-Span-ID: {:?}", url, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -153,7 +151,6 @@ impl Api for Server where C: Has + Send + Sync list_of_strings: Option<&Vec>, context: &C) -> Result { - let context = context.clone(); info!("complex_query_param_get({:?}) - X-Span-ID: {:?}", list_of_strings, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -163,7 +160,6 @@ impl Api for Server where C: Has + Send + Sync path_param: models::StringEnum, context: &C) -> Result { - let context = context.clone(); info!("enum_in_path_path_param_get({:?}) - X-Span-ID: {:?}", path_param, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -173,7 +169,6 @@ impl Api for Server where C: Has + Send + Sync list_of_strings: Option<&Vec>, context: &C) -> Result { - let context = context.clone(); info!("json_complex_query_param_get({:?}) - X-Span-ID: {:?}", list_of_strings, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -183,7 +178,6 @@ impl Api for Server where C: Has + Send + Sync x_header: String, context: &C) -> Result { - let context = context.clone(); info!("mandatory_request_header_get(\"{}\") - X-Span-ID: {:?}", x_header, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -192,7 +186,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("merge_patch_json_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -202,7 +195,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("multiget_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -211,7 +203,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("multiple_auth_scheme_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -220,7 +211,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("one_of_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -229,7 +219,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("override_server_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -242,7 +231,6 @@ impl Api for Server where C: Has + Send + Sync some_list: Option, context: &C) -> Result { - let context = context.clone(); info!("paramget_get({:?}, {:?}, {:?}) - X-Span-ID: {:?}", uuid, some_object, some_list, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -251,7 +239,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("readonly_auth_scheme_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -261,7 +248,6 @@ impl Api for Server where C: Has + Send + Sync url: String, context: &C) -> Result { - let context = context.clone(); info!("register_callback_post(\"{}\") - X-Span-ID: {:?}", url, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -271,7 +257,6 @@ impl Api for Server where C: Has + Send + Sync body: swagger::ByteArray, context: &C) -> Result { - let context = context.clone(); info!("required_octet_stream_put({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -280,7 +265,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("responses_with_headers_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -289,7 +273,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("rfc7807_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -299,7 +282,6 @@ impl Api for Server where C: Has + Send + Sync object_untyped_props: Option, context: &C) -> Result { - let context = context.clone(); info!("untyped_property_get({:?}) - X-Span-ID: {:?}", object_untyped_props, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -308,7 +290,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("uuid_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -318,7 +299,6 @@ impl Api for Server where C: Has + Send + Sync duplicate_xml_object: Option, context: &C) -> Result { - let context = context.clone(); info!("xml_extra_post({:?}) - X-Span-ID: {:?}", duplicate_xml_object, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -328,7 +308,6 @@ impl Api for Server where C: Has + Send + Sync another_xml_object: Option, context: &C) -> Result { - let context = context.clone(); info!("xml_other_post({:?}) - X-Span-ID: {:?}", another_xml_object, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -338,7 +317,6 @@ impl Api for Server where C: Has + Send + Sync another_xml_array: Option, context: &C) -> Result { - let context = context.clone(); info!("xml_other_put({:?}) - X-Span-ID: {:?}", another_xml_array, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -349,7 +327,6 @@ impl Api for Server where C: Has + Send + Sync xml_array: Option, context: &C) -> Result { - let context = context.clone(); info!("xml_post({:?}) - X-Span-ID: {:?}", xml_array, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -359,7 +336,6 @@ impl Api for Server where C: Has + Send + Sync xml_object: Option, context: &C) -> Result { - let context = context.clone(); info!("xml_put({:?}) - X-Span-ID: {:?}", xml_object, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -369,7 +345,6 @@ impl Api for Server where C: Has + Send + Sync object_param: models::ObjectParam, context: &C) -> Result { - let context = context.clone(); info!("create_repo({:?}) - X-Span-ID: {:?}", object_param, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -379,7 +354,6 @@ impl Api for Server where C: Has + Send + Sync repo_id: String, context: &C) -> Result { - let context = context.clone(); info!("get_repo_info(\"{}\") - X-Span-ID: {:?}", repo_id, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs index 71a4af713398..b71408c2422f 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/client/mod.rs @@ -1165,7 +1165,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -1489,7 +1489,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs index d1e67d2949af..007c0f268f8b 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/models.rs @@ -295,7 +295,7 @@ impl std::string::ToString for AnotherXmlObject { let params: Vec> = vec![ self.inner_string.as_ref().map(|inner_string| { - vec![ + [ "inner_string".to_string(), inner_string.to_string(), ].join(",") @@ -815,7 +815,7 @@ impl std::string::ToString for DuplicateXmlObject { let params: Vec> = vec![ self.inner_string.as_ref().map(|inner_string| { - vec![ + [ "inner_string".to_string(), inner_string.to_string(), ].join(",") @@ -1233,7 +1233,7 @@ impl std::string::ToString for MultigetGet201Response { let params: Vec> = vec![ self.foo.as_ref().map(|foo| { - vec![ + [ "foo".to_string(), foo.to_string(), ].join(",") @@ -1546,6 +1546,27 @@ pub struct NullableTest { #[serde(skip_serializing_if="Option::is_none")] pub nullable_array: Option>>, + #[serde(rename = "min_item_test")] + #[validate( + length(min = 1), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub min_item_test: Option>, + + #[serde(rename = "max_item_test")] + #[validate( + length(max = 2), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub max_item_test: Option>, + + #[serde(rename = "min_max_item_test")] + #[validate( + length(min = 1, max = 3), + )] + #[serde(skip_serializing_if="Option::is_none")] + pub min_max_item_test: Option>, + } @@ -1558,6 +1579,9 @@ impl NullableTest { nullable_with_present_default: Some(swagger::Nullable::Present("default".to_string())), nullable_with_no_default: None, nullable_array: None, + min_item_test: None, + max_item_test: None, + min_max_item_test: None, } } } @@ -1574,7 +1598,7 @@ impl std::string::ToString for NullableTest { self.nullable_with_null_default.as_ref().map(|nullable_with_null_default| { - vec![ + [ "nullableWithNullDefault".to_string(), nullable_with_null_default.as_ref().map_or("null".to_string(), |x| x.to_string()), ].join(",") @@ -1582,7 +1606,7 @@ impl std::string::ToString for NullableTest { self.nullable_with_present_default.as_ref().map(|nullable_with_present_default| { - vec![ + [ "nullableWithPresentDefault".to_string(), nullable_with_present_default.as_ref().map_or("null".to_string(), |x| x.to_string()), ].join(",") @@ -1590,7 +1614,7 @@ impl std::string::ToString for NullableTest { self.nullable_with_no_default.as_ref().map(|nullable_with_no_default| { - vec![ + [ "nullableWithNoDefault".to_string(), nullable_with_no_default.as_ref().map_or("null".to_string(), |x| x.to_string()), ].join(",") @@ -1598,12 +1622,36 @@ impl std::string::ToString for NullableTest { self.nullable_array.as_ref().map(|nullable_array| { - vec![ + [ "nullableArray".to_string(), nullable_array.as_ref().map_or("null".to_string(), |x| x.iter().map(|x| x.to_string()).collect::>().join(",")), ].join(",") }), + + self.min_item_test.as_ref().map(|min_item_test| { + [ + "min_item_test".to_string(), + min_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + + self.max_item_test.as_ref().map(|max_item_test| { + [ + "max_item_test".to_string(), + max_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + + + self.min_max_item_test.as_ref().map(|min_max_item_test| { + [ + "min_max_item_test".to_string(), + min_max_item_test.iter().map(|x| x.to_string()).collect::>().join(","), + ].join(",") + }), + ]; params.into_iter().flatten().collect::>().join(",") @@ -1626,6 +1674,9 @@ impl std::str::FromStr for NullableTest { pub nullable_with_present_default: Vec, pub nullable_with_no_default: Vec, pub nullable_array: Vec>, + pub min_item_test: Vec>, + pub max_item_test: Vec>, + pub min_max_item_test: Vec>, } let mut intermediate_rep = IntermediateRep::default(); @@ -1648,6 +1699,9 @@ impl std::str::FromStr for NullableTest { "nullableWithPresentDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), "nullableWithNoDefault" => return std::result::Result::Err("Parsing a nullable type in this style is not supported in NullableTest".to_string()), "nullableArray" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "min_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "max_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), + "min_max_item_test" => return std::result::Result::Err("Parsing a container in this style is not supported in NullableTest".to_string()), _ => return std::result::Result::Err("Unexpected key while parsing NullableTest".to_string()) } } @@ -1663,6 +1717,9 @@ impl std::str::FromStr for NullableTest { nullable_with_present_default: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, nullable_with_no_default: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, nullable_array: std::result::Result::Err("Nullable types not supported in NullableTest".to_string())?, + min_item_test: intermediate_rep.min_item_test.into_iter().next(), + max_item_test: intermediate_rep.max_item_test.into_iter().next(), + min_max_item_test: intermediate_rep.min_max_item_test.into_iter().next(), }) } } @@ -1750,7 +1807,7 @@ impl std::string::ToString for ObjectHeader { self.optional_object_header.as_ref().map(|optional_object_header| { - vec![ + [ "optionalObjectHeader".to_string(), optional_object_header.to_string(), ].join(",") @@ -1895,7 +1952,7 @@ impl std::string::ToString for ObjectParam { self.optional_param.as_ref().map(|optional_param| { - vec![ + [ "optionalParam".to_string(), optional_param.to_string(), ].join(",") @@ -2189,7 +2246,7 @@ impl std::string::ToString for ObjectWithArrayOfObjects { let params: Vec> = vec![ self.object_array.as_ref().map(|object_array| { - vec![ + [ "objectArray".to_string(), object_array.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") @@ -2963,7 +3020,7 @@ impl std::string::ToString for XmlObject { let params: Vec> = vec![ self.inner_string.as_ref().map(|inner_string| { - vec![ + [ "innerString".to_string(), inner_string.to_string(), ].join(",") @@ -2971,7 +3028,7 @@ impl std::string::ToString for XmlObject { self.other_inner_rename.as_ref().map(|other_inner_rename| { - vec![ + [ "other_inner_rename".to_string(), other_inner_rename.to_string(), ].join(",") diff --git a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs index 0d8be00926b7..3808a67d7573 100644 --- a/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/openapi-v3/src/server/mod.rs @@ -257,8 +257,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for ANY_OF_GET_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, AnyOfGetResponse::AlternateSuccess (body) @@ -268,8 +268,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for ANY_OF_GET_ALTERNATE_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, AnyOfGetResponse::AnyOfSuccess (body) @@ -279,8 +279,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for ANY_OF_GET_ANY_OF_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -569,8 +569,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/merge-patch+json") .expect("Unable to create Content-Type header for MERGE_PATCH_JSON_GET_MERGE")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -605,8 +605,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for MULTIGET_GET_JSON_RSP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::XMLRsp (body) @@ -616,8 +616,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for MULTIGET_GET_XML_RSP")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::OctetRsp (body) @@ -627,8 +627,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/octet-stream") .expect("Unable to create Content-Type header for MULTIGET_GET_OCTET_RSP")); - let body = body.0; - *response.body_mut() = Body::from(body); + let body_content = body.0; + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::StringRsp (body) @@ -638,8 +638,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("text/plain") .expect("Unable to create Content-Type header for MULTIGET_GET_STRING_RSP")); - let body = body; - *response.body_mut() = Body::from(body); + let body_content = body; + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::DuplicateResponseLongText (body) @@ -649,8 +649,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for MULTIGET_GET_DUPLICATE_RESPONSE_LONG_TEXT")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::DuplicateResponseLongText_2 (body) @@ -660,8 +660,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for MULTIGET_GET_DUPLICATE_RESPONSE_LONG_TEXT_2")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, MultigetGetResponse::DuplicateResponseLongText_3 (body) @@ -671,8 +671,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for MULTIGET_GET_DUPLICATE_RESPONSE_LONG_TEXT_3")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -766,8 +766,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for ONE_OF_GET_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -888,8 +888,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for PARAMGET_GET_JSON_RSP")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -1145,8 +1145,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for RESPONSES_WITH_HEADERS_GET_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, ResponsesWithHeadersGetResponse::PreconditionFailed { @@ -1221,8 +1221,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for RFC7807_GET_OK")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, Rfc7807GetResponse::NotFound (body) @@ -1232,8 +1232,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/problem+json") .expect("Unable to create Content-Type header for RFC7807_GET_NOT_FOUND")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, Rfc7807GetResponse::NotAcceptable (body) @@ -1243,8 +1243,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/problem+xml") .expect("Unable to create Content-Type header for RFC7807_GET_NOT_ACCEPTABLE")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -1342,8 +1342,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for UUID_GET_DUPLICATE_RESPONSE_LONG_TEXT")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -1477,8 +1477,8 @@ impl hyper::service::Service<(Request, C)> for Service where // An empty string is used to indicate a global namespace in xmltree. namespaces.insert("".to_string(), models::AnotherXmlObject::NAMESPACE.to_string()); - let body = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string_with_namespaces(&body, namespaces).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, XmlOtherPostResponse::BadRequest => { @@ -1821,8 +1821,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for GET_REPO_INFO_OK")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { diff --git a/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/ops-v3/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs b/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs index 0f5e145f345a..cab1bfadc6b5 100644 --- a/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/ops-v3/examples/server/server.rs @@ -143,7 +143,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op10_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -152,7 +151,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op11_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -161,7 +159,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op12_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -170,7 +167,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op13_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -179,7 +175,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op14_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -188,7 +183,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op15_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -197,7 +191,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op16_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -206,7 +199,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op17_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -215,7 +207,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op18_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -224,7 +215,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op19_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -233,7 +223,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op1_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -242,7 +231,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op20_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -251,7 +239,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op21_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -260,7 +247,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op22_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -269,7 +255,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op23_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -278,7 +263,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op24_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -287,7 +271,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op25_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -296,7 +279,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op26_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -305,7 +287,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op27_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -314,7 +295,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op28_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -323,7 +303,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op29_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -332,7 +311,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op2_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -341,7 +319,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op30_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -350,7 +327,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op31_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -359,7 +335,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op32_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -368,7 +343,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op33_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -377,7 +351,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op34_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -386,7 +359,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op35_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -395,7 +367,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op36_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -404,7 +375,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op37_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -413,7 +383,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op3_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -422,7 +391,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op4_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -431,7 +399,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op5_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -440,7 +407,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op6_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -449,7 +415,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op7_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -458,7 +423,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op8_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -467,7 +431,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("op9_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FormatTest.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FormatTest.md index 604bf73686b8..ec568846bcbf 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FormatTest.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/FormatTest.md @@ -12,7 +12,7 @@ Name | Type | Description | Notes **string** | **String** | | [optional] [default to None] **byte** | [***swagger::ByteArray**](ByteArray.md) | | **binary** | [***swagger::ByteArray**](file.md) | | [optional] [default to None] -**date** | [***chrono::DateTime::**](date.md) | | +**date** | [***chrono::naive::NaiveDate**](date.md) | | **date_time** | [**chrono::DateTime::**](DateTime.md) | | [optional] [default to None] **uuid** | [***uuid::Uuid**](UUID.md) | | [optional] [default to None] **password** | **String** | | diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md index 1937f562e8cf..ddc0786bbe06 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/docs/fake_api.md @@ -311,7 +311,7 @@ Name | Type | Description | Notes **float** | **f32**| None | **string** | **String**| None | **binary** | **swagger::ByteArray**| None | - **date** | **chrono::DateTime::**| None | + **date** | **chrono::naive::NaiveDate**| None | **date_time** | **chrono::DateTime::**| None | **password** | **String**| None | **callback** | **String**| None | diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs index 304590c34f17..5a89df7a6b69 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/examples/server/server.rs @@ -143,7 +143,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Client, context: &C) -> Result { - let context = context.clone(); info!("test_special_tags({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -152,7 +151,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("call123example() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -162,7 +160,6 @@ impl Api for Server where C: Has + Send + Sync body: Option, context: &C) -> Result { - let context = context.clone(); info!("fake_outer_boolean_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -172,7 +169,6 @@ impl Api for Server where C: Has + Send + Sync body: Option, context: &C) -> Result { - let context = context.clone(); info!("fake_outer_composite_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -182,7 +178,6 @@ impl Api for Server where C: Has + Send + Sync body: Option, context: &C) -> Result { - let context = context.clone(); info!("fake_outer_number_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -192,7 +187,6 @@ impl Api for Server where C: Has + Send + Sync body: Option, context: &C) -> Result { - let context = context.clone(); info!("fake_outer_string_serialize({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -201,7 +195,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("fake_response_with_numerical_description() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -211,7 +204,6 @@ impl Api for Server where C: Has + Send + Sync hyphen_param: String, context: &C) -> Result { - let context = context.clone(); info!("hyphen_param(\"{}\") - X-Span-ID: {:?}", hyphen_param, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -222,7 +214,6 @@ impl Api for Server where C: Has + Send + Sync body: models::User, context: &C) -> Result { - let context = context.clone(); info!("test_body_with_query_params(\"{}\", {:?}) - X-Span-ID: {:?}", query, body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -233,7 +224,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Client, context: &C) -> Result { - let context = context.clone(); info!("test_client_model({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -251,13 +241,12 @@ impl Api for Server where C: Has + Send + Sync float: Option, string: Option, binary: Option, - date: Option>, + date: Option, date_time: Option>, password: Option, callback: Option, context: &C) -> Result { - let context = context.clone(); info!("test_endpoint_parameters({}, {}, \"{}\", {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", number, double, pattern_without_delimiter, byte, integer, int32, int64, float, string, binary, date, date_time, password, callback, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -274,7 +263,6 @@ impl Api for Server where C: Has + Send + Sync enum_form_string: Option, context: &C) -> Result { - let context = context.clone(); info!("test_enum_parameters({:?}, {:?}, {:?}, {:?}, {:?}, {:?}, {:?}) - X-Span-ID: {:?}", enum_header_string_array, enum_header_string, enum_query_string_array, enum_query_string, enum_query_integer, enum_query_double, enum_form_string, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -285,7 +273,6 @@ impl Api for Server where C: Has + Send + Sync param: std::collections::HashMap, context: &C) -> Result { - let context = context.clone(); info!("test_inline_additional_properties({:?}) - X-Span-ID: {:?}", param, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -297,7 +284,6 @@ impl Api for Server where C: Has + Send + Sync param2: String, context: &C) -> Result { - let context = context.clone(); info!("test_json_form_data(\"{}\", \"{}\") - X-Span-ID: {:?}", param, param2, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -308,7 +294,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Client, context: &C) -> Result { - let context = context.clone(); info!("test_classname({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -319,7 +304,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Pet, context: &C) -> Result { - let context = context.clone(); info!("add_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -331,7 +315,6 @@ impl Api for Server where C: Has + Send + Sync api_key: Option, context: &C) -> Result { - let context = context.clone(); info!("delete_pet({}, {:?}) - X-Span-ID: {:?}", pet_id, api_key, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -342,7 +325,6 @@ impl Api for Server where C: Has + Send + Sync status: &Vec, context: &C) -> Result { - let context = context.clone(); info!("find_pets_by_status({:?}) - X-Span-ID: {:?}", status, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -353,7 +335,6 @@ impl Api for Server where C: Has + Send + Sync tags: &Vec, context: &C) -> Result { - let context = context.clone(); info!("find_pets_by_tags({:?}) - X-Span-ID: {:?}", tags, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -364,7 +345,6 @@ impl Api for Server where C: Has + Send + Sync pet_id: i64, context: &C) -> Result { - let context = context.clone(); info!("get_pet_by_id({}) - X-Span-ID: {:?}", pet_id, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -375,7 +355,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Pet, context: &C) -> Result { - let context = context.clone(); info!("update_pet({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -388,7 +367,6 @@ impl Api for Server where C: Has + Send + Sync status: Option, context: &C) -> Result { - let context = context.clone(); info!("update_pet_with_form({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, name, status, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -401,7 +379,6 @@ impl Api for Server where C: Has + Send + Sync file: Option, context: &C) -> Result { - let context = context.clone(); info!("upload_file({}, {:?}, {:?}) - X-Span-ID: {:?}", pet_id, additional_metadata, file, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -412,7 +389,6 @@ impl Api for Server where C: Has + Send + Sync order_id: String, context: &C) -> Result { - let context = context.clone(); info!("delete_order(\"{}\") - X-Span-ID: {:?}", order_id, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -422,7 +398,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("get_inventory() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -433,7 +408,6 @@ impl Api for Server where C: Has + Send + Sync order_id: i64, context: &C) -> Result { - let context = context.clone(); info!("get_order_by_id({}) - X-Span-ID: {:?}", order_id, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -444,7 +418,6 @@ impl Api for Server where C: Has + Send + Sync body: models::Order, context: &C) -> Result { - let context = context.clone(); info!("place_order({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -455,7 +428,6 @@ impl Api for Server where C: Has + Send + Sync body: models::User, context: &C) -> Result { - let context = context.clone(); info!("create_user({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -466,7 +438,6 @@ impl Api for Server where C: Has + Send + Sync body: &Vec, context: &C) -> Result { - let context = context.clone(); info!("create_users_with_array_input({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -477,7 +448,6 @@ impl Api for Server where C: Has + Send + Sync body: &Vec, context: &C) -> Result { - let context = context.clone(); info!("create_users_with_list_input({:?}) - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -488,7 +458,6 @@ impl Api for Server where C: Has + Send + Sync username: String, context: &C) -> Result { - let context = context.clone(); info!("delete_user(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -499,7 +468,6 @@ impl Api for Server where C: Has + Send + Sync username: String, context: &C) -> Result { - let context = context.clone(); info!("get_user_by_name(\"{}\") - X-Span-ID: {:?}", username, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -511,7 +479,6 @@ impl Api for Server where C: Has + Send + Sync password: String, context: &C) -> Result { - let context = context.clone(); info!("login_user(\"{}\", \"{}\") - X-Span-ID: {:?}", username, password, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -521,7 +488,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("logout_user() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -533,7 +499,6 @@ impl Api for Server where C: Has + Send + Sync body: models::User, context: &C) -> Result { - let context = context.clone(); info!("update_user(\"{}\", {:?}) - X-Span-ID: {:?}", username, body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs index 27c40c08de79..625e7aea9fa3 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/client/mod.rs @@ -1250,7 +1250,7 @@ impl Api for Client where param_float: Option, param_string: Option, param_binary: Option, - param_date: Option>, + param_date: Option, param_date_time: Option>, param_password: Option, param_callback: Option, @@ -1320,7 +1320,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Basic(ref basic_header) => { + AuthData::Basic(basic_header) => { let auth = swagger::auth::Header(basic_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -1824,7 +1824,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -1914,7 +1914,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -2022,7 +2022,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -2127,7 +2127,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -2337,7 +2337,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -2450,7 +2450,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, @@ -2596,7 +2596,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs index f652f1580e55..17501af77f4e 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/lib.rs @@ -387,7 +387,7 @@ pub trait Api { float: Option, string: Option, binary: Option, - date: Option>, + date: Option, date_time: Option>, password: Option, callback: Option, @@ -624,7 +624,7 @@ pub trait ApiNoContext { float: Option, string: Option, binary: Option, - date: Option>, + date: Option, date_time: Option>, password: Option, callback: Option, @@ -915,7 +915,7 @@ impl + Send + Sync, C: Clone + Send + Sync> ApiNoContext for Contex float: Option, string: Option, binary: Option, - date: Option>, + date: Option, date_time: Option>, password: Option, callback: Option, diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs index beec39b5c335..c77a7acf8384 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/models.rs @@ -178,7 +178,7 @@ impl std::string::ToString for Animal { self.color.as_ref().map(|color| { - vec![ + [ "color".to_string(), color.to_string(), ].join(",") @@ -463,7 +463,7 @@ impl std::string::ToString for ApiResponse { let params: Vec> = vec![ self.code.as_ref().map(|code| { - vec![ + [ "code".to_string(), code.to_string(), ].join(",") @@ -471,7 +471,7 @@ impl std::string::ToString for ApiResponse { self.r#type.as_ref().map(|r#type| { - vec![ + [ "type".to_string(), r#type.to_string(), ].join(",") @@ -479,7 +479,7 @@ impl std::string::ToString for ApiResponse { self.message.as_ref().map(|message| { - vec![ + [ "message".to_string(), message.to_string(), ].join(",") @@ -746,7 +746,7 @@ impl std::string::ToString for ArrayOfNumberOnly { let params: Vec> = vec![ self.array_number.as_ref().map(|array_number| { - vec![ + [ "ArrayNumber".to_string(), array_number.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") @@ -894,7 +894,7 @@ impl std::string::ToString for ArrayTest { let params: Vec> = vec![ self.array_of_string.as_ref().map(|array_of_string| { - vec![ + [ "array_of_string".to_string(), array_of_string.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") @@ -906,7 +906,7 @@ impl std::string::ToString for ArrayTest { self.array_of_enum.as_ref().map(|array_of_enum| { - vec![ + [ "array_of_enum".to_string(), array_of_enum.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") @@ -1073,7 +1073,7 @@ impl std::string::ToString for Capitalization { let params: Vec> = vec![ self.small_camel.as_ref().map(|small_camel| { - vec![ + [ "smallCamel".to_string(), small_camel.to_string(), ].join(",") @@ -1081,7 +1081,7 @@ impl std::string::ToString for Capitalization { self.capital_camel.as_ref().map(|capital_camel| { - vec![ + [ "CapitalCamel".to_string(), capital_camel.to_string(), ].join(",") @@ -1089,7 +1089,7 @@ impl std::string::ToString for Capitalization { self.small_snake.as_ref().map(|small_snake| { - vec![ + [ "small_Snake".to_string(), small_snake.to_string(), ].join(",") @@ -1097,7 +1097,7 @@ impl std::string::ToString for Capitalization { self.capital_snake.as_ref().map(|capital_snake| { - vec![ + [ "Capital_Snake".to_string(), capital_snake.to_string(), ].join(",") @@ -1105,7 +1105,7 @@ impl std::string::ToString for Capitalization { self.sca_eth_flow_points.as_ref().map(|sca_eth_flow_points| { - vec![ + [ "SCA_ETH_Flow_Points".to_string(), sca_eth_flow_points.to_string(), ].join(",") @@ -1113,7 +1113,7 @@ impl std::string::ToString for Capitalization { self.att_name.as_ref().map(|att_name| { - vec![ + [ "ATT_NAME".to_string(), att_name.to_string(), ].join(",") @@ -1279,7 +1279,7 @@ impl std::string::ToString for Cat { self.color.as_ref().map(|color| { - vec![ + [ "color".to_string(), color.to_string(), ].join(",") @@ -1287,7 +1287,7 @@ impl std::string::ToString for Cat { self.declawed.as_ref().map(|declawed| { - vec![ + [ "declawed".to_string(), declawed.to_string(), ].join(",") @@ -1434,7 +1434,7 @@ impl std::string::ToString for Category { let params: Vec> = vec![ self.id.as_ref().map(|id| { - vec![ + [ "id".to_string(), id.to_string(), ].join(",") @@ -1442,7 +1442,7 @@ impl std::string::ToString for Category { self.name.as_ref().map(|name| { - vec![ + [ "name".to_string(), name.to_string(), ].join(",") @@ -1580,7 +1580,7 @@ impl std::string::ToString for ClassModel { let params: Vec> = vec![ self._class.as_ref().map(|_class| { - vec![ + [ "_class".to_string(), _class.to_string(), ].join(",") @@ -1713,7 +1713,7 @@ impl std::string::ToString for Client { let params: Vec> = vec![ self.client.as_ref().map(|client| { - vec![ + [ "client".to_string(), client.to_string(), ].join(",") @@ -1859,7 +1859,7 @@ impl std::string::ToString for Dog { self.color.as_ref().map(|color| { - vec![ + [ "color".to_string(), color.to_string(), ].join(",") @@ -1867,7 +1867,7 @@ impl std::string::ToString for Dog { self.breed.as_ref().map(|breed| { - vec![ + [ "breed".to_string(), breed.to_string(), ].join(",") @@ -2009,7 +2009,7 @@ impl std::string::ToString for DollarSpecialLeftSquareBracketModelPeriodNameRigh let params: Vec> = vec![ self.dollar_special_left_square_bracket_property_period_name_right_square_bracket.as_ref().map(|dollar_special_left_square_bracket_property_period_name_right_square_bracket| { - vec![ + [ "$special[property.name]".to_string(), dollar_special_left_square_bracket_property_period_name_right_square_bracket.to_string(), ].join(",") @@ -2155,7 +2155,7 @@ impl std::string::ToString for EnumArrays { let params: Vec> = vec![ self.just_symbol.as_ref().map(|just_symbol| { - vec![ + [ "just_symbol".to_string(), just_symbol.to_string(), ].join(",") @@ -2163,7 +2163,7 @@ impl std::string::ToString for EnumArrays { self.array_enum.as_ref().map(|array_enum| { - vec![ + [ "array_enum".to_string(), array_enum.iter().map(|x| x.to_string()).collect::>().join(","), ].join(",") @@ -2375,7 +2375,7 @@ impl std::string::ToString for EnumTest { let params: Vec> = vec![ self.enum_string.as_ref().map(|enum_string| { - vec![ + [ "enum_string".to_string(), enum_string.to_string(), ].join(",") @@ -2387,7 +2387,7 @@ impl std::string::ToString for EnumTest { self.enum_integer.as_ref().map(|enum_integer| { - vec![ + [ "enum_integer".to_string(), enum_integer.to_string(), ].join(",") @@ -2395,7 +2395,7 @@ impl std::string::ToString for EnumTest { self.enum_number.as_ref().map(|enum_number| { - vec![ + [ "enum_number".to_string(), enum_number.to_string(), ].join(",") @@ -2578,7 +2578,7 @@ pub struct FormatTest { pub binary: Option, #[serde(rename = "date")] - pub date: chrono::DateTime::, + pub date: chrono::naive::NaiveDate, #[serde(rename = "dateTime")] #[serde(skip_serializing_if="Option::is_none")] @@ -2613,7 +2613,7 @@ fn validate_byte_formattest_byte( impl FormatTest { #[allow(clippy::new_without_default)] - pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::DateTime::, password: String, ) -> FormatTest { + pub fn new(number: f64, byte: swagger::ByteArray, date: chrono::naive::NaiveDate, password: String, ) -> FormatTest { FormatTest { integer: None, int32: None, @@ -2640,7 +2640,7 @@ impl std::string::ToString for FormatTest { let params: Vec> = vec![ self.integer.as_ref().map(|integer| { - vec![ + [ "integer".to_string(), integer.to_string(), ].join(",") @@ -2648,7 +2648,7 @@ impl std::string::ToString for FormatTest { self.int32.as_ref().map(|int32| { - vec![ + [ "int32".to_string(), int32.to_string(), ].join(",") @@ -2656,7 +2656,7 @@ impl std::string::ToString for FormatTest { self.int64.as_ref().map(|int64| { - vec![ + [ "int64".to_string(), int64.to_string(), ].join(",") @@ -2668,7 +2668,7 @@ impl std::string::ToString for FormatTest { self.float.as_ref().map(|float| { - vec![ + [ "float".to_string(), float.to_string(), ].join(",") @@ -2676,7 +2676,7 @@ impl std::string::ToString for FormatTest { self.double.as_ref().map(|double| { - vec![ + [ "double".to_string(), double.to_string(), ].join(",") @@ -2684,7 +2684,7 @@ impl std::string::ToString for FormatTest { self.string.as_ref().map(|string| { - vec![ + [ "string".to_string(), string.to_string(), ].join(",") @@ -2732,7 +2732,7 @@ impl std::str::FromStr for FormatTest { pub string: Vec, pub byte: Vec, pub binary: Vec, - pub date: Vec>, + pub date: Vec, pub date_time: Vec>, pub uuid: Vec, pub password: Vec, @@ -2770,7 +2770,7 @@ impl std::str::FromStr for FormatTest { "byte" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), "binary" => return std::result::Result::Err("Parsing binary data in this style is not supported in FormatTest".to_string()), #[allow(clippy::redundant_clone)] - "date" => intermediate_rep.date.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), + "date" => intermediate_rep.date.push(::from_str(val).map_err(|x| x.to_string())?), #[allow(clippy::redundant_clone)] "dateTime" => intermediate_rep.date_time.push( as std::str::FromStr>::from_str(val).map_err(|x| x.to_string())?), #[allow(clippy::redundant_clone)] @@ -2884,7 +2884,7 @@ impl std::string::ToString for HasOnlyReadOnly { let params: Vec> = vec![ self.bar.as_ref().map(|bar| { - vec![ + [ "bar".to_string(), bar.to_string(), ].join(",") @@ -2892,7 +2892,7 @@ impl std::string::ToString for HasOnlyReadOnly { self.foo.as_ref().map(|foo| { - vec![ + [ "foo".to_string(), foo.to_string(), ].join(",") @@ -3029,7 +3029,7 @@ impl std::string::ToString for List { let params: Vec> = vec![ self.param_123_list.as_ref().map(|param_123_list| { - vec![ + [ "123-list".to_string(), param_123_list.to_string(), ].join(",") @@ -3468,7 +3468,7 @@ impl std::string::ToString for Model200Response { let params: Vec> = vec![ self.name.as_ref().map(|name| { - vec![ + [ "name".to_string(), name.to_string(), ].join(",") @@ -3476,7 +3476,7 @@ impl std::string::ToString for Model200Response { self.class.as_ref().map(|class| { - vec![ + [ "class".to_string(), class.to_string(), ].join(",") @@ -3633,7 +3633,7 @@ impl std::string::ToString for Name { self.snake_case.as_ref().map(|snake_case| { - vec![ + [ "snake_case".to_string(), snake_case.to_string(), ].join(",") @@ -3641,7 +3641,7 @@ impl std::string::ToString for Name { self.property.as_ref().map(|property| { - vec![ + [ "property".to_string(), property.to_string(), ].join(",") @@ -3649,7 +3649,7 @@ impl std::string::ToString for Name { self.param_123_number.as_ref().map(|param_123_number| { - vec![ + [ "123Number".to_string(), param_123_number.to_string(), ].join(",") @@ -3794,7 +3794,7 @@ impl std::string::ToString for NumberOnly { let params: Vec> = vec![ self.just_number.as_ref().map(|just_number| { - vec![ + [ "JustNumber".to_string(), just_number.to_string(), ].join(",") @@ -4141,7 +4141,7 @@ impl std::string::ToString for Order { let params: Vec> = vec![ self.id.as_ref().map(|id| { - vec![ + [ "id".to_string(), id.to_string(), ].join(",") @@ -4149,7 +4149,7 @@ impl std::string::ToString for Order { self.pet_id.as_ref().map(|pet_id| { - vec![ + [ "petId".to_string(), pet_id.to_string(), ].join(",") @@ -4157,7 +4157,7 @@ impl std::string::ToString for Order { self.quantity.as_ref().map(|quantity| { - vec![ + [ "quantity".to_string(), quantity.to_string(), ].join(",") @@ -4167,7 +4167,7 @@ impl std::string::ToString for Order { self.status.as_ref().map(|status| { - vec![ + [ "status".to_string(), status.to_string(), ].join(",") @@ -4175,7 +4175,7 @@ impl std::string::ToString for Order { self.complete.as_ref().map(|complete| { - vec![ + [ "complete".to_string(), complete.to_string(), ].join(",") @@ -4377,7 +4377,7 @@ impl std::string::ToString for OuterComposite { let params: Vec> = vec![ self.my_number.as_ref().map(|my_number| { - vec![ + [ "my_number".to_string(), my_number.to_string(), ].join(",") @@ -4385,7 +4385,7 @@ impl std::string::ToString for OuterComposite { self.my_string.as_ref().map(|my_string| { - vec![ + [ "my_string".to_string(), my_string.to_string(), ].join(",") @@ -4393,7 +4393,7 @@ impl std::string::ToString for OuterComposite { self.my_boolean.as_ref().map(|my_boolean| { - vec![ + [ "my_boolean".to_string(), my_boolean.to_string(), ].join(",") @@ -4699,7 +4699,7 @@ impl std::string::ToString for Pet { let params: Vec> = vec![ self.id.as_ref().map(|id| { - vec![ + [ "id".to_string(), id.to_string(), ].join(",") @@ -4719,7 +4719,7 @@ impl std::string::ToString for Pet { self.status.as_ref().map(|status| { - vec![ + [ "status".to_string(), status.to_string(), ].join(",") @@ -4875,7 +4875,7 @@ impl std::string::ToString for ReadOnlyFirst { let params: Vec> = vec![ self.bar.as_ref().map(|bar| { - vec![ + [ "bar".to_string(), bar.to_string(), ].join(",") @@ -4883,7 +4883,7 @@ impl std::string::ToString for ReadOnlyFirst { self.baz.as_ref().map(|baz| { - vec![ + [ "baz".to_string(), baz.to_string(), ].join(",") @@ -5022,7 +5022,7 @@ impl std::string::ToString for Return { let params: Vec> = vec![ self.r#return.as_ref().map(|r#return| { - vec![ + [ "return".to_string(), r#return.to_string(), ].join(",") @@ -5161,7 +5161,7 @@ impl std::string::ToString for Tag { let params: Vec> = vec![ self.id.as_ref().map(|id| { - vec![ + [ "id".to_string(), id.to_string(), ].join(",") @@ -5169,7 +5169,7 @@ impl std::string::ToString for Tag { self.name.as_ref().map(|name| { - vec![ + [ "name".to_string(), name.to_string(), ].join(",") @@ -5343,7 +5343,7 @@ impl std::string::ToString for User { let params: Vec> = vec![ self.id.as_ref().map(|id| { - vec![ + [ "id".to_string(), id.to_string(), ].join(",") @@ -5351,7 +5351,7 @@ impl std::string::ToString for User { self.username.as_ref().map(|username| { - vec![ + [ "username".to_string(), username.to_string(), ].join(",") @@ -5359,7 +5359,7 @@ impl std::string::ToString for User { self.first_name.as_ref().map(|first_name| { - vec![ + [ "firstName".to_string(), first_name.to_string(), ].join(",") @@ -5367,7 +5367,7 @@ impl std::string::ToString for User { self.last_name.as_ref().map(|last_name| { - vec![ + [ "lastName".to_string(), last_name.to_string(), ].join(",") @@ -5375,7 +5375,7 @@ impl std::string::ToString for User { self.email.as_ref().map(|email| { - vec![ + [ "email".to_string(), email.to_string(), ].join(",") @@ -5383,7 +5383,7 @@ impl std::string::ToString for User { self.password.as_ref().map(|password| { - vec![ + [ "password".to_string(), password.to_string(), ].join(",") @@ -5391,7 +5391,7 @@ impl std::string::ToString for User { self.phone.as_ref().map(|phone| { - vec![ + [ "phone".to_string(), phone.to_string(), ].join(",") @@ -5399,7 +5399,7 @@ impl std::string::ToString for User { self.user_status.as_ref().map(|user_status| { - vec![ + [ "userStatus".to_string(), user_status.to_string(), ].join(",") diff --git a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs index 72dea2e7e685..ea3e74c470f2 100644 --- a/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/petstore-with-fake-endpoints-models-for-testing/src/server/mod.rs @@ -316,8 +316,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for TEST_SPECIAL_TAGS_SUCCESSFUL_OPERATION")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -415,8 +415,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for FAKE_OUTER_BOOLEAN_SERIALIZE_OUTPUT_BOOLEAN")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -485,8 +485,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for FAKE_OUTER_COMPOSITE_SERIALIZE_OUTPUT_COMPOSITE")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -555,8 +555,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for FAKE_OUTER_NUMBER_SERIALIZE_OUTPUT_NUMBER")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -625,8 +625,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for FAKE_OUTER_STRING_SERIALIZE_OUTPUT_STRING")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -888,8 +888,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for TEST_CLIENT_MODEL_SUCCESSFUL_OPERATION")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -1302,8 +1302,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for TEST_CLASSNAME_SUCCESSFUL_OPERATION")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -1588,8 +1588,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for FIND_PETS_BY_STATUS_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, FindPetsByStatusResponse::InvalidStatusValue => { @@ -1665,8 +1665,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for FIND_PETS_BY_TAGS_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, FindPetsByTagsResponse::InvalidTagValue => { @@ -1739,8 +1739,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for GET_PET_BY_ID_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, GetPetByIdResponse::InvalidIDSupplied => { @@ -2115,8 +2115,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for UPLOAD_FILE_SUCCESSFUL_OPERATION")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -2224,8 +2224,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for GET_INVENTORY_SUCCESSFUL_OPERATION")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -2284,8 +2284,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for GET_ORDER_BY_ID_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, GetOrderByIdResponse::InvalidIDSupplied => { @@ -2366,8 +2366,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for PLACE_ORDER_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, PlaceOrderResponse::InvalidOrder => { @@ -2712,8 +2712,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for GET_USER_BY_NAME_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, GetUserByNameResponse::InvalidUsernameSupplied => { @@ -2845,8 +2845,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/xml") .expect("Unable to create Content-Type header for LOGIN_USER_SUCCESSFUL_OPERATION")); - let body = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_xml_rs::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, LoginUserResponse::InvalidUsername => { diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs index 3383a22e1ad7..4869efef56a6 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/examples/server/server.rs @@ -107,7 +107,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("ping_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs index 9ce229a207f5..22eb1b5814c8 100644 --- a/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs +++ b/samples/server/petstore/rust-server/output/ping-bearer-auth/src/client/mod.rs @@ -424,7 +424,7 @@ impl Api for Client where // Currently only authentication with Basic and Bearer are supported #[allow(clippy::single_match, clippy::match_single_binding)] match auth_data { - &AuthData::Bearer(ref bearer_header) => { + AuthData::Bearer(bearer_header) => { let auth = swagger::auth::Header(bearer_header.clone()); let header = match HeaderValue::from_str(&format!("{}", auth)) { Ok(h) => h, diff --git a/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION b/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION +++ b/samples/server/petstore/rust-server/output/rust-server-test/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs b/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs index ab9e383866b2..f9dcaa3fe262 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/examples/server/server.rs @@ -115,7 +115,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("all_of_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -125,7 +124,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("dummy_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -135,7 +133,6 @@ impl Api for Server where C: Has + Send + Sync nested_response: models::DummyPutRequest, context: &C) -> Result { - let context = context.clone(); info!("dummy_put({:?}) - X-Span-ID: {:?}", nested_response, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -145,7 +142,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("file_response_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -154,7 +150,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("get_structured_yaml() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -165,7 +160,6 @@ impl Api for Server where C: Has + Send + Sync body: String, context: &C) -> Result { - let context = context.clone(); info!("html_post(\"{}\") - X-Span-ID: {:?}", body, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -175,7 +169,6 @@ impl Api for Server where C: Has + Send + Sync value: String, context: &C) -> Result { - let context = context.clone(); info!("post_yaml(\"{}\") - X-Span-ID: {:?}", value, context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -185,7 +178,6 @@ impl Api for Server where C: Has + Send + Sync &self, context: &C) -> Result { - let context = context.clone(); info!("raw_json_get() - X-Span-ID: {:?}", context.get().0.clone()); Err(ApiError("Generic failure".into())) } @@ -196,7 +188,6 @@ impl Api for Server where C: Has + Send + Sync value: serde_json::Value, context: &C) -> Result { - let context = context.clone(); info!("solo_object_post({:?}) - X-Span-ID: {:?}", value, context.get().0.clone()); Err(ApiError("Generic failure".into())) } diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs index 96b49d463b93..0915bf515e28 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/models.rs @@ -39,7 +39,7 @@ impl std::string::ToString for ANullableContainer { let params: Vec> = vec![ self.nullable_thing.as_ref().map(|nullable_thing| { - vec![ + [ "NullableThing".to_string(), nullable_thing.as_ref().map_or("null".to_string(), |x| x.to_string()), ].join(",") @@ -225,7 +225,7 @@ impl std::string::ToString for AllOfObject { let params: Vec> = vec![ self.sample_property.as_ref().map(|sample_property| { - vec![ + [ "sampleProperty".to_string(), sample_property.to_string(), ].join(",") @@ -233,7 +233,7 @@ impl std::string::ToString for AllOfObject { self.sample_base_property.as_ref().map(|sample_base_property| { - vec![ + [ "sampleBaseProperty".to_string(), sample_base_property.to_string(), ].join(",") @@ -361,7 +361,7 @@ impl std::string::ToString for BaseAllOf { let params: Vec> = vec![ self.sample_base_property.as_ref().map(|sample_base_property| { - vec![ + [ "sampleBaseProperty".to_string(), sample_base_property.to_string(), ].join(",") @@ -493,7 +493,7 @@ impl std::string::ToString for DummyPutRequest { self.password.as_ref().map(|password| { - vec![ + [ "password".to_string(), password.to_string(), ].join(",") @@ -623,7 +623,7 @@ impl std::string::ToString for GetYamlResponse { let params: Vec> = vec![ self.value.as_ref().map(|value| { - vec![ + [ "value".to_string(), value.to_string(), ].join(",") @@ -874,7 +874,7 @@ impl std::string::ToString for ObjectOfObjectsInner { self.optional_thing.as_ref().map(|optional_thing| { - vec![ + [ "optional_thing".to_string(), optional_thing.to_string(), ].join(",") diff --git a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs index 4789b886ecde..3152eb63a364 100644 --- a/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs +++ b/samples/server/petstore/rust-server/output/rust-server-test/src/server/mod.rs @@ -182,8 +182,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for ALL_OF_GET_OK")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -320,8 +320,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/json") .expect("Unable to create Content-Type header for FILE_RESPONSE_GET_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -356,8 +356,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("application/yaml") .expect("Unable to create Content-Type header for GET_STRUCTURED_YAML_OK")); - let body = body; - *response.body_mut() = Body::from(body); + let body_content = body; + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -418,8 +418,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("text/html") .expect("Unable to create Content-Type header for HTML_POST_SUCCESS")); - let body = body; - *response.body_mut() = Body::from(body); + let body_content = body; + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { @@ -521,8 +521,8 @@ impl hyper::service::Service<(Request, C)> for Service where CONTENT_TYPE, HeaderValue::from_str("*/*") .expect("Unable to create Content-Type header for RAW_JSON_GET_SUCCESS")); - let body = serde_json::to_string(&body).expect("impossible to fail to serialize"); - *response.body_mut() = Body::from(body); + let body_content = serde_json::to_string(&body).expect("impossible to fail to serialize"); + *response.body_mut() = Body::from(body_content); }, }, Err(_) => { diff --git a/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION b/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-akka-http-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/.openapi-generator-ignore b/samples/server/petstore/scala-http4s-server/.openapi-generator-ignore new file mode 100644 index 000000000000..7484ee590a38 --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/.openapi-generator-ignore @@ -0,0 +1,23 @@ +# OpenAPI Generator Ignore +# Generated by openapi-generator https://github.com/openapitools/openapi-generator + +# Use this file to prevent files from being overwritten by the generator. +# The patterns follow closely to .gitignore or .dockerignore. + +# As an example, the C# client generator defines ApiClient.cs. +# You can make changes and tell OpenAPI Generator to ignore just this file by uncommenting the following line: +#ApiClient.cs + +# You can match any string of characters against a directory, file or extension with a single asterisk (*): +#foo/*/qux +# The above matches foo/bar/qux and foo/baz/qux, but not foo/bar/baz/qux + +# You can recursively match patterns against a directory, file or extension with a double asterisk (**): +#foo/**/qux +# This matches foo/bar/qux, foo/baz/qux, and foo/bar/baz/qux + +# You can also negate patterns with an exclamation (!). +# For example, you can ignore all files in a docs folder with the file extension .md: +#docs/*.md +# Then explicitly reverse the ignore rule for a single file: +#!docs/README.md diff --git a/samples/server/petstore/scala-http4s-server/.openapi-generator/FILES b/samples/server/petstore/scala-http4s-server/.openapi-generator/FILES new file mode 100644 index 000000000000..db5888af483a --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/.openapi-generator/FILES @@ -0,0 +1,9 @@ +build.sbt +project/build.properties +src/main/scala/org/openapitools/api.scala +src/main/scala/org/openapitools/apis/PetApi.scala +src/main/scala/org/openapitools/apis/StoreApi.scala +src/main/scala/org/openapitools/apis/UserApi.scala +src/main/scala/org/openapitools/apis/path.scala +src/main/scala/org/openapitools/apis/query.scala +src/main/scala/org/openapitools/models/types.scala diff --git a/samples/server/petstore/scala-http4s-server/.openapi-generator/VERSION b/samples/server/petstore/scala-http4s-server/.openapi-generator/VERSION new file mode 100644 index 000000000000..fff4bdd7ab59 --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/.openapi-generator/VERSION @@ -0,0 +1 @@ +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/build.sbt b/samples/server/petstore/scala-http4s-server/build.sbt new file mode 100644 index 000000000000..70c616516402 --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/build.sbt @@ -0,0 +1,27 @@ +scalaVersion := "2.13.11" +scalacOptions += "-Ymacro-annotations" + +val circeVersion = "0.14.5" +def circe(artifact: String): ModuleID = "io.circe" %% s"circe-$artifact" % circeVersion + +val http4sVersion = "0.23.23" +def http4s(artifact: String): ModuleID = "org.http4s" %% s"http4s-$artifact" % http4sVersion + +val refinedVersion = "0.9.29" +val refined = Seq( + "eu.timepit" %% "refined" % refinedVersion, + "eu.timepit" %% "refined-cats" % refinedVersion +) + +val catsVersion = "2.10.0" +val cats = Seq("org.typelevel" %% "cats-core" % catsVersion) + +lazy val compilerPlugins = Seq( + compilerPlugin("com.olegpy" %% "better-monadic-for" % "0.3.1"), + compilerPlugin("org.typelevel" %% "kind-projector" % "0.13.2" cross CrossVersion.full) +) + +libraryDependencies ++= (Seq( + http4s("core"), http4s("ember-server"), http4s("circe"), http4s("dsl"), + circe("core"), circe("generic"), circe("parser"), circe("refined") +) ++ refined ++ cats ++ compilerPlugins) diff --git a/samples/server/petstore/scala-http4s-server/pom.xml b/samples/server/petstore/scala-http4s-server/pom.xml new file mode 100644 index 000000000000..2bcbf0232eb7 --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/pom.xml @@ -0,0 +1,34 @@ + + 4.0.0 + org.openapitools + scala-http4s-server + pom + 1.0-SNAPSHOT + Scala http4s server + + + + org.codehaus.mojo + exec-maven-plugin + 1.5.0 + + + sbt-test + integration-test + + exec + + + sbt + + -ivy + ${user.home}/.ivy2 + test + + + + + + + + diff --git a/samples/server/petstore/scala-http4s-server/project/build.properties b/samples/server/petstore/scala-http4s-server/project/build.properties new file mode 100644 index 000000000000..875272df2d3c --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/project/build.properties @@ -0,0 +1 @@ +sbt.version=1.8.2 \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/api.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/api.scala new file mode 100644 index 000000000000..70d45a221b42 --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/api.scala @@ -0,0 +1,47 @@ +package org.openapitools + +import org.http4s.circe._ +import cats.Monad +import cats.syntax.all._ +import cats.data.OptionT +import cats.data.Kleisli +import org.http4s._ +import org.http4s.server._ + +import org.openapitools.apis._ + +final case class API [ + F[_]: JsonDecoder: Monad, petstore_auth, api_key +]( + petstoreAuth: Kleisli[OptionT[F, *], Request[F], petstore_auth], + apiKey: Kleisli[OptionT[F, *], Request[F], api_key], +)( + delegatePetApi: PetApiDelegate[F, petstore_auth, api_key], + delegateStoreApi: StoreApiDelegate[F, api_key], + delegateUserApi: UserApiDelegate[F, api_key], +){ + val apiKeyMiddleware = AuthMiddleware.withFallThrough(apiKey) + val petstoreAuthMiddleware = AuthMiddleware(petstoreAuth) + + val petApiRoutes = new PetApiRoutes(delegatePetApi) + val storeApiRoutes = new StoreApiRoutes(delegateStoreApi) + val userApiRoutes = new UserApiRoutes(delegateUserApi) + + val routes = + storeApiRoutes.routes <+> + userApiRoutes.routes + + val routesapi_key = apiKeyMiddleware( + petApiRoutes.routesapi_key <+> + storeApiRoutes.routesapi_key <+> + userApiRoutes.routesapi_key + ) + val routespetstore_auth = petstoreAuthMiddleware( + petApiRoutes.routespetstore_auth + ) + + val routesAll = + routes <+> + routesapi_key <+> + routespetstore_auth +} diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/PetApi.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/PetApi.scala new file mode 100644 index 000000000000..0a3c44fa3edc --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/PetApi.scala @@ -0,0 +1,361 @@ +package org.openapitools.apis + +import org.openapitools.apis.path._ +import org.openapitools.apis.query._ + +import org.openapitools.models.ApiResponse +import java.io.File +import org.openapitools.models.Pet + + +import cats.Monad +import cats.syntax.all._ + +import org.http4s._ +import org.http4s.circe._ +import org.http4s.server._ +import org.http4s.headers._ +import org.http4s.dsl.Http4sDsl +import org.http4s.circe.CirceEntityEncoder._ + +final case class PetApiRoutes[ + F[_]: JsonDecoder: Monad, petstore_auth, api_key +](delegate: PetApiDelegate[F, petstore_auth, api_key]) extends Http4sDsl[F] { + object addPet { + import PetApiDelegate.addPetResponses + + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ POST -> Root / "pet") as auth => + req.contentType match { + case Some(`Content-Type`(MediaType.application.json, _)) => + delegate.addPet.handle_petstore_auth(auth, req, req.asJsonDecode[Pet] , responses) + + case _ => + delegate.addPet.handle_petstore_auth(auth, req, responses) + + } + } + + val responses: addPetResponses[F] = new addPetResponses[F] { + def resp200(value: Pet): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp405(allow: Allow): F[Response[F]] = MethodNotAllowed(allow) + } + } + object deletePet { + import PetApiDelegate.deletePetResponses + + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ DELETE -> Root / "pet" / LongVarr(petId)) as auth => + delegate.deletePet.handle_petstore_auth(auth, req, petId, responses) + + } + + val responses: deletePetResponses[F] = new deletePetResponses[F] { + def resp400(): F[Response[F]] = BadRequest() + } + } + object findPetsByStatus { + import PetApiDelegate.findPetsByStatusResponses + + object statusQueryParam extends QuerySeqParamDecoderMatcher[String]("status") + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ GET -> Root / "pet" / "findByStatus" :? statusQueryParam(status)) as auth => + delegate.findPetsByStatus.handle_petstore_auth(auth, req, status, responses) + + } + + val responses: findPetsByStatusResponses[F] = new findPetsByStatusResponses[F] { + def resp200(value: List[Pet]): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + } + } + object findPetsByTags { + import PetApiDelegate.findPetsByTagsResponses + + object tagsQueryParam extends QuerySeqParamDecoderMatcher[String]("tags") + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ GET -> Root / "pet" / "findByTags" :? tagsQueryParam(tags)) as auth => + delegate.findPetsByTags.handle_petstore_auth(auth, req, tags, responses) + + } + + val responses: findPetsByTagsResponses[F] = new findPetsByTagsResponses[F] { + def resp200(value: List[Pet]): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + } + } + object getPetById { + import PetApiDelegate.getPetByIdResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ GET -> Root / "pet" / LongVarr(petId)) as auth => + delegate.getPetById.handle_api_key(auth, req, petId, responses) + + } + + val responses: getPetByIdResponses[F] = new getPetByIdResponses[F] { + def resp200(value: Pet): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + object updatePet { + import PetApiDelegate.updatePetResponses + + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ PUT -> Root / "pet") as auth => + req.contentType match { + case Some(`Content-Type`(MediaType.application.json, _)) => + delegate.updatePet.handle_petstore_auth(auth, req, req.asJsonDecode[Pet] , responses) + + case _ => + delegate.updatePet.handle_petstore_auth(auth, req, responses) + + } + } + + val responses: updatePetResponses[F] = new updatePetResponses[F] { + def resp200(value: Pet): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + def resp405(allow: Allow): F[Response[F]] = MethodNotAllowed(allow) + } + } + object updatePetWithForm { + import PetApiDelegate.updatePetWithFormResponses + + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ POST -> Root / "pet" / LongVarr(petId)) as auth => + delegate.updatePetWithForm.handle_petstore_auth(auth, req, petId, responses) + + } + + val responses: updatePetWithFormResponses[F] = new updatePetWithFormResponses[F] { + def resp405(allow: Allow): F[Response[F]] = MethodNotAllowed(allow) + } + } + object uploadFile { + import PetApiDelegate.uploadFileResponses + + + val routepetstore_auth = AuthedRoutes.of[petstore_auth, F] { + case (req @ POST -> Root / "pet" / LongVarr(petId) / "uploadImage") as auth => + delegate.uploadFile.handle_petstore_auth(auth, req, petId, responses) + + } + + val responses: uploadFileResponses[F] = new uploadFileResponses[F] { + def resp200(value: ApiResponse): F[Response[F]] = Ok(value) + } + } + + val routespetstore_auth = + addPet.routepetstore_auth <+> + deletePet.routepetstore_auth <+> + findPetsByStatus.routepetstore_auth <+> + findPetsByTags.routepetstore_auth <+> + updatePet.routepetstore_auth <+> + updatePetWithForm.routepetstore_auth <+> + uploadFile.routepetstore_auth + val routesapi_key = + getPetById.routeapi_key +} + +object PetApiDelegate { + trait addPetResponses[F[_]] { + def resp200(value: Pet): F[Response[F]] + def resp200(): F[Response[F]] + def resp405(allow: Allow): F[Response[F]] + } + + trait deletePetResponses[F[_]] { + def resp400(): F[Response[F]] + } + + trait findPetsByStatusResponses[F[_]] { + def resp200(value: List[Pet]): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + } + + trait findPetsByTagsResponses[F[_]] { + def resp200(value: List[Pet]): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + } + + trait getPetByIdResponses[F[_]] { + def resp200(value: Pet): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + + trait updatePetResponses[F[_]] { + def resp200(value: Pet): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + def resp405(allow: Allow): F[Response[F]] + } + + trait updatePetWithFormResponses[F[_]] { + def resp405(allow: Allow): F[Response[F]] + } + + trait uploadFileResponses[F[_]] { + def resp200(value: ApiResponse): F[Response[F]] + } + +} + +trait PetApiDelegate[F[_], petstore_auth, api_key] { + + trait addPet { + import PetApiDelegate.addPetResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + addPet: F[Pet], + responses: addPetResponses[F] + ): F[Response[F]] + + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + responses: addPetResponses[F] + ): F[Response[F]] + + } + def addPet: addPet + + + trait deletePet { + import PetApiDelegate.deletePetResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + petId: Long, + responses: deletePetResponses[F] + ): F[Response[F]] + + } + def deletePet: deletePet + + + trait findPetsByStatus { + import PetApiDelegate.findPetsByStatusResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + status: List[String], + responses: findPetsByStatusResponses[F] + ): F[Response[F]] + + } + def findPetsByStatus: findPetsByStatus + + + trait findPetsByTags { + import PetApiDelegate.findPetsByTagsResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + tags: List[String], + responses: findPetsByTagsResponses[F] + ): F[Response[F]] + + } + def findPetsByTags: findPetsByTags + + + trait getPetById { + import PetApiDelegate.getPetByIdResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + petId: Long, + responses: getPetByIdResponses[F] + ): F[Response[F]] + + } + def getPetById: getPetById + + + trait updatePet { + import PetApiDelegate.updatePetResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + updatePet: F[Pet], + responses: updatePetResponses[F] + ): F[Response[F]] + + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + responses: updatePetResponses[F] + ): F[Response[F]] + + } + def updatePet: updatePet + + + trait updatePetWithForm { + import PetApiDelegate.updatePetWithFormResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + petId: Long, + responses: updatePetWithFormResponses[F] + ): F[Response[F]] + + } + def updatePetWithForm: updatePetWithForm + + + trait uploadFile { + import PetApiDelegate.uploadFileResponses + + + def handle_petstore_auth( + auth: petstore_auth, + req: Request[F], + petId: Long, + responses: uploadFileResponses[F] + ): F[Response[F]] + + } + def uploadFile: uploadFile + +} \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/StoreApi.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/StoreApi.scala new file mode 100644 index 000000000000..2b7925d9607a --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/StoreApi.scala @@ -0,0 +1,181 @@ +package org.openapitools.apis + +import org.openapitools.apis.path._ +import org.openapitools.apis.query._ + +import org.openapitools.models.Order + +import eu.timepit.refined.api.Refined +import eu.timepit.refined.boolean.And +import eu.timepit.refined.numeric.GreaterEqual +import eu.timepit.refined.numeric.LessEqual + +import cats.Monad +import cats.syntax.all._ + +import org.http4s._ +import org.http4s.circe._ +import org.http4s.server._ +import org.http4s.headers._ +import org.http4s.dsl.Http4sDsl +import org.http4s.circe.CirceEntityEncoder._ + +final case class StoreApiRoutes[ + F[_]: JsonDecoder: Monad, api_key +](delegate: StoreApiDelegate[F, api_key]) extends Http4sDsl[F] { + object deleteOrder { + import StoreApiDelegate.deleteOrderResponses + + + val route = HttpRoutes.of[F] { + case req @ DELETE -> Root / "store" / "order" / orderId => + delegate.deleteOrder.handle(req, orderId, responses) + + } + + + val responses: deleteOrderResponses[F] = new deleteOrderResponses[F] { + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + object getInventory { + import StoreApiDelegate.getInventoryResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ GET -> Root / "store" / "inventory") as auth => + delegate.getInventory.handle_api_key(auth, req, responses) + + } + + val responses: getInventoryResponses[F] = new getInventoryResponses[F] { + def resp200(value: Map[String, Int]): F[Response[F]] = Ok(value) + } + } + object getOrderById { + import StoreApiDelegate.getOrderByIdResponses + + object orderIdVarr extends RefinedVarr[Long, GreaterEqual[1] And LessEqual[5]] + + val route = HttpRoutes.of[F] { + case req @ GET -> Root / "store" / "order" / orderIdVarr(orderId) => + delegate.getOrderById.handle(req, orderId, responses) + + } + + + val responses: getOrderByIdResponses[F] = new getOrderByIdResponses[F] { + def resp200(value: Order): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + object placeOrder { + import StoreApiDelegate.placeOrderResponses + + + val route = HttpRoutes.of[F] { + case req @ POST -> Root / "store" / "order" => + delegate.placeOrder.handle(req, req.asJsonDecode[Order] , responses) + + } + + + val responses: placeOrderResponses[F] = new placeOrderResponses[F] { + def resp200(value: Order): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + } + } + + val routes = + deleteOrder.route <+> + getOrderById.route <+> + placeOrder.route + val routesapi_key = + getInventory.routeapi_key +} + +object StoreApiDelegate { + trait deleteOrderResponses[F[_]] { + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + + trait getInventoryResponses[F[_]] { + def resp200(value: Map[String, Int]): F[Response[F]] + } + + trait getOrderByIdResponses[F[_]] { + def resp200(value: Order): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + + trait placeOrderResponses[F[_]] { + def resp200(value: Order): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + } + +} + +trait StoreApiDelegate[F[_], api_key] { + + trait deleteOrder { + import StoreApiDelegate.deleteOrderResponses + + def handle( + req: Request[F], + orderId: String, + responses: deleteOrderResponses[F] + ): F[Response[F]] + + } + def deleteOrder: deleteOrder + + + trait getInventory { + import StoreApiDelegate.getInventoryResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + responses: getInventoryResponses[F] + ): F[Response[F]] + + } + def getInventory: getInventory + + + trait getOrderById { + import StoreApiDelegate.getOrderByIdResponses + + def handle( + req: Request[F], + orderId: Refined[Long, GreaterEqual[1] And LessEqual[5]], + responses: getOrderByIdResponses[F] + ): F[Response[F]] + + } + def getOrderById: getOrderById + + + trait placeOrder { + import StoreApiDelegate.placeOrderResponses + + def handle( + req: Request[F], + placeOrder: F[Order], + responses: placeOrderResponses[F] + ): F[Response[F]] + + + } + def placeOrder: placeOrder + +} \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/UserApi.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/UserApi.scala new file mode 100644 index 000000000000..bbee7dca5deb --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/UserApi.scala @@ -0,0 +1,326 @@ +package org.openapitools.apis + +import org.openapitools.apis.path._ +import org.openapitools.apis.query._ + +import org.openapitools.models.User +import java.time.ZonedDateTime + +import eu.timepit.refined.api.Refined +import eu.timepit.refined.boolean.And +import eu.timepit.refined.string.MatchesRegex + +import cats.Monad +import cats.syntax.all._ + +import org.http4s._ +import org.http4s.circe._ +import org.http4s.server._ +import org.http4s.headers._ +import org.http4s.dsl.Http4sDsl +import org.http4s.circe.CirceEntityEncoder._ + +final case class UserApiRoutes[ + F[_]: JsonDecoder: Monad, api_key +](delegate: UserApiDelegate[F, api_key]) extends Http4sDsl[F] { + object createUser { + import UserApiDelegate.createUserResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ POST -> Root / "user") as auth => + delegate.createUser.handle_api_key(auth, req, req.asJsonDecode[User] , responses) + + } + + val responses: createUserResponses[F] = new createUserResponses[F] { + def resp200(): F[Response[F]] = Ok() + } + } + object createUsersWithArrayInput { + import UserApiDelegate.createUsersWithArrayInputResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ POST -> Root / "user" / "createWithArray") as auth => + delegate.createUsersWithArrayInput.handle_api_key(auth, req, req.asJsonDecode[List[User]] , responses) + + } + + val responses: createUsersWithArrayInputResponses[F] = new createUsersWithArrayInputResponses[F] { + def resp200(): F[Response[F]] = Ok() + } + } + object createUsersWithListInput { + import UserApiDelegate.createUsersWithListInputResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ POST -> Root / "user" / "createWithList") as auth => + delegate.createUsersWithListInput.handle_api_key(auth, req, req.asJsonDecode[List[User]] , responses) + + } + + val responses: createUsersWithListInputResponses[F] = new createUsersWithListInputResponses[F] { + def resp200(): F[Response[F]] = Ok() + } + } + object deleteUser { + import UserApiDelegate.deleteUserResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ DELETE -> Root / "user" / username) as auth => + delegate.deleteUser.handle_api_key(auth, req, username, responses) + + } + + val responses: deleteUserResponses[F] = new deleteUserResponses[F] { + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + object getUserByName { + import UserApiDelegate.getUserByNameResponses + + + val route = HttpRoutes.of[F] { + case req @ GET -> Root / "user" / username => + delegate.getUserByName.handle(req, username, responses) + + } + + + val responses: getUserByNameResponses[F] = new getUserByNameResponses[F] { + def resp200(value: User): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + object loginUser { + import UserApiDelegate.loginUserResponses + + object usernameQueryParam extends QueryParamDecoderMatcher[Refined[String, MatchesRegex["^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"]]]("username") + object passwordQueryParam extends QueryParamDecoderMatcher[String]("password") + + val route = HttpRoutes.of[F] { + case req @ GET -> Root / "user" / "login" :? usernameQueryParam(username) +& passwordQueryParam(password) => + delegate.loginUser.handle(req, username, password, responses) + + } + + + val responses: loginUserResponses[F] = new loginUserResponses[F] { + def resp200(value: String): F[Response[F]] = Ok(value) + def resp200(): F[Response[F]] = Ok() + def resp400(): F[Response[F]] = BadRequest() + } + } + object logoutUser { + import UserApiDelegate.logoutUserResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ GET -> Root / "user" / "logout") as auth => + delegate.logoutUser.handle_api_key(auth, req, responses) + + } + + val responses: logoutUserResponses[F] = new logoutUserResponses[F] { + def resp200(): F[Response[F]] = Ok() + } + } + object updateUser { + import UserApiDelegate.updateUserResponses + + + val routeapi_key = AuthedRoutes.of[api_key, F] { + case (req @ PUT -> Root / "user" / username) as auth => + delegate.updateUser.handle_api_key(auth, req, req.asJsonDecode[User] , username, responses) + + } + + val responses: updateUserResponses[F] = new updateUserResponses[F] { + def resp400(): F[Response[F]] = BadRequest() + def resp404(): F[Response[F]] = NotFound() + } + } + + val routes = + getUserByName.route <+> + loginUser.route + val routesapi_key = + createUser.routeapi_key <+> + createUsersWithArrayInput.routeapi_key <+> + createUsersWithListInput.routeapi_key <+> + deleteUser.routeapi_key <+> + logoutUser.routeapi_key <+> + updateUser.routeapi_key +} + +object UserApiDelegate { + trait createUserResponses[F[_]] { + def resp200(): F[Response[F]] + } + + trait createUsersWithArrayInputResponses[F[_]] { + def resp200(): F[Response[F]] + } + + trait createUsersWithListInputResponses[F[_]] { + def resp200(): F[Response[F]] + } + + trait deleteUserResponses[F[_]] { + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + + trait getUserByNameResponses[F[_]] { + def resp200(value: User): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + + trait loginUserResponses[F[_]] { + def resp200(value: String): F[Response[F]] + def resp200(): F[Response[F]] + def resp400(): F[Response[F]] + } + + trait logoutUserResponses[F[_]] { + def resp200(): F[Response[F]] + } + + trait updateUserResponses[F[_]] { + def resp400(): F[Response[F]] + def resp404(): F[Response[F]] + } + +} + +trait UserApiDelegate[F[_], api_key] { + + trait createUser { + import UserApiDelegate.createUserResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + createUser: F[User], + responses: createUserResponses[F] + ): F[Response[F]] + + + } + def createUser: createUser + + + trait createUsersWithArrayInput { + import UserApiDelegate.createUsersWithArrayInputResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + createUsersWithArrayInput: F[List[User]], + responses: createUsersWithArrayInputResponses[F] + ): F[Response[F]] + + + } + def createUsersWithArrayInput: createUsersWithArrayInput + + + trait createUsersWithListInput { + import UserApiDelegate.createUsersWithListInputResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + createUsersWithListInput: F[List[User]], + responses: createUsersWithListInputResponses[F] + ): F[Response[F]] + + + } + def createUsersWithListInput: createUsersWithListInput + + + trait deleteUser { + import UserApiDelegate.deleteUserResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + username: String, + responses: deleteUserResponses[F] + ): F[Response[F]] + + } + def deleteUser: deleteUser + + + trait getUserByName { + import UserApiDelegate.getUserByNameResponses + + def handle( + req: Request[F], + username: String, + responses: getUserByNameResponses[F] + ): F[Response[F]] + + } + def getUserByName: getUserByName + + + trait loginUser { + import UserApiDelegate.loginUserResponses + + def handle( + req: Request[F], + username: Refined[String, MatchesRegex["^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"]], + password: String, + responses: loginUserResponses[F] + ): F[Response[F]] + + } + def loginUser: loginUser + + + trait logoutUser { + import UserApiDelegate.logoutUserResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + responses: logoutUserResponses[F] + ): F[Response[F]] + + } + def logoutUser: logoutUser + + + trait updateUser { + import UserApiDelegate.updateUserResponses + + + def handle_api_key( + auth: api_key, + req: Request[F], + updateUser: F[User], + username: String, + responses: updateUserResponses[F] + ): F[Response[F]] + + + } + def updateUser: updateUser + +} \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/path.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/path.scala new file mode 100644 index 000000000000..ea838424fece --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/path.scala @@ -0,0 +1,62 @@ +package org.openapitools.apis + +import cats.syntax.all._ +import cats.data.ValidatedNel + +import eu.timepit.refined._ +import eu.timepit.refined.api.Refined +import eu.timepit.refined.api.Validate + +import java.time.LocalDate +import java.time.LocalDateTime +import java.time.ZonedDateTime +import java.util.UUID + +import scala.util.Try + +object path { + trait Varrr[T] { + def unapply(str: String): Option[T] + } + + implicit val LocalDateVarr: Varrr[LocalDate] = new Varrr[LocalDate] { + def unapply(str: String): Option[LocalDate] = Try(LocalDate.parse(str)).toOption + } + + implicit val LocalDateTimeVarr: Varrr[LocalDateTime] = new Varrr[LocalDateTime] { + def unapply(str: String): Option[LocalDateTime] = Try(LocalDateTime.parse(str)).toOption + } + + implicit val ZonedDateTimeVarr: Varrr[ZonedDateTime] = new Varrr[ZonedDateTime] { + def unapply(str: String): Option[ZonedDateTime] = Try(ZonedDateTime.parse(str)).toOption + } + + implicit val UUIDVarr: Varrr[UUID] = new Varrr[UUID] { + def unapply(str: String): Option[UUID] = Try(java.util.UUID.fromString(str)).toOption + } + + implicit val IntVarr: Varrr[Int] = new Varrr[Int] { + def unapply(str: String): Option[Int] = Try(str.toInt).toOption + } + + implicit val LongVarr: Varrr[Long] = new Varrr[Long] { + def unapply(str: String): Option[Long] = Try(str.toLong).toOption + } + + implicit val DoubleVarr: Varrr[Double] = new Varrr[Double] { + def unapply(str: String): Option[Double] = Try(str.toDouble).toOption + } + + implicit val BigDecimalVarr: Varrr[BigDecimal] = new Varrr[BigDecimal] { + def unapply(str: String): Option[BigDecimal] = Try(BigDecimal(str)).toOption + } + + implicit val StringVarr: Varrr[String] = new Varrr[String] { + def unapply(str: String): Option[String] = str.some + } + + abstract class RefinedVarr[T, P](implicit varrr: Varrr[T], validate: Validate[T, P]) extends Varrr[Refined[T, P]] { + def unapply(str: String): Option[Refined[T, P]] = + varrr.unapply(str).flatMap(x => refineV(x).toOption) + } +} diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/query.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/query.scala new file mode 100644 index 000000000000..efc86b959e0c --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/apis/query.scala @@ -0,0 +1,59 @@ +package org.openapitools.apis + +import cats.data.NonEmptyList +import cats.data.ValidatedNel +import cats.syntax.all._ + +import eu.timepit.refined._ +import eu.timepit.refined.api.Refined +import eu.timepit.refined.api.Validate + +import org.http4s.ParseFailure +import org.http4s.QueryParamDecoder +import org.http4s.QueryParameterValue + +import java.time._ +import java.util.UUID + +object query { + implicit def rrrefinedQueryParamDecoder[T, P]( + implicit tDecoder: QueryParamDecoder[T], validate: Validate[T, P] + ): QueryParamDecoder[Refined[T, P]] = new QueryParamDecoder[Refined[T, P]] { + def decode(value: QueryParameterValue): ValidatedNel[ParseFailure,Refined[T, P]] = + tDecoder.decode(value).withEither(t => t.flatMap(x => + refineV(x).leftMap(err => NonEmptyList.one(ParseFailure(err, err))) + )) + } + + abstract class QuerySeqParamDecoderMatcher[T: QueryParamDecoder](name: String) { + def unapply(params: Map[String, Seq[String]]): Option[List[T]] = + params + .get(name) + .flatMap(values => + values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption)) + } + + abstract class OptionalQuerySeqParamDecoderMatcher[T: QueryParamDecoder](name: String) { + def unapply(params: Map[String, List[String]]): Option[Option[List[T]]] = + params + .get(name) + .flatMap(values => + values.toList.traverse(s => QueryParamDecoder[T].decode(QueryParameterValue(s)).toOption)) + .fold(List.empty[T].some.some)(_.some.some) + } + + implicit lazy val BigDecimalQueryParamDecoder: QueryParamDecoder[BigDecimal] = + QueryParamDecoder.fromUnsafeCast[BigDecimal](x => BigDecimal(x.value))("BigDecimal") + + implicit lazy val LocalDateTimeQueryParamDecoder: QueryParamDecoder[LocalDateTime] = + QueryParamDecoder.fromUnsafeCast[LocalDateTime](x => LocalDateTime.parse(x.value))("LocalDateTime") + + implicit lazy val LocalDateQueryParamDecoder: QueryParamDecoder[LocalDate] = + QueryParamDecoder.fromUnsafeCast[LocalDate](x => LocalDate.parse(x.value))("LocalDateTime") + + implicit lazy val ZonedDateTimeQueryParamDecoder: QueryParamDecoder[ZonedDateTime] = + QueryParamDecoder.fromUnsafeCast[ZonedDateTime](x => ZonedDateTime.parse(x.value))("ZonedDateTime") + + implicit lazy val UUIDQueryParamDecoder: QueryParamDecoder[UUID] = + QueryParamDecoder.fromUnsafeCast[UUID](x => UUID.fromString(x.value))("UUID") +} \ No newline at end of file diff --git a/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/models/types.scala b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/models/types.scala new file mode 100644 index 000000000000..4db7ce57363f --- /dev/null +++ b/samples/server/petstore/scala-http4s-server/src/main/scala/org/openapitools/models/types.scala @@ -0,0 +1,134 @@ +package org.openapitools.models + +import java.time._ + +import io.circe.refined._ +import io.circe.syntax._ +import io.circe.{ Decoder, Encoder } +import io.circe.generic.semiauto.{ deriveDecoder, deriveEncoder } + +import eu.timepit.refined.api.Refined +import eu.timepit.refined.boolean.And +import eu.timepit.refined.string.MatchesRegex +import java.time.ZonedDateTime + +/** +* Describes the result of uploading an image resource +* @param code +* @param _type +* @param message +*/ + +case class ApiResponse( + code: Option[Int], + _type: Option[String], + message: Option[String] +) +object ApiResponse { + implicit val encoderApiResponse: Encoder[ApiResponse] = deriveEncoder[ApiResponse].mapJson(_.dropNullValues) + implicit val decoderApiResponse: Decoder[ApiResponse] = deriveDecoder[ApiResponse] +} + +/** +* A category for a pet +* @param id +* @param name +*/ + +case class Category( + id: Option[Long], + name: Option[Refined[String, MatchesRegex["^[a-zA-Z0-9]+[a-zA-Z0-9\\.\\-_]*[a-zA-Z0-9]+$"]]] +) +object Category { + implicit val encoderCategory: Encoder[Category] = deriveEncoder[Category].mapJson(_.dropNullValues) + implicit val decoderCategory: Decoder[Category] = deriveDecoder[Category] +} + +/** +* An order for a pets from the pet store +* @param id +* @param petId +* @param quantity +* @param shipDate +* @param status Order Status +* @param complete +*/ + +case class Order( + id: Option[Long], + petId: Option[Long], + quantity: Option[Int], + shipDate: Option[ZonedDateTime], + status: Option[String], + complete: Option[Boolean] +) +object Order { + implicit val encoderOrder: Encoder[Order] = deriveEncoder[Order].mapJson(_.dropNullValues) + implicit val decoderOrder: Decoder[Order] = deriveDecoder[Order] +} + +/** +* A pet for sale in the pet store +* @param id +* @param category +* @param name +* @param photoUrls +* @param tags +* @param status pet status in the store +*/ + +case class Pet( + id: Option[Long], + category: Option[Category], + name: String, + photoUrls: List[String], + tags: Option[List[Tag]], + status: Option[String] +) +object Pet { + implicit val encoderPet: Encoder[Pet] = deriveEncoder[Pet].mapJson(_.dropNullValues) + implicit val decoderPet: Decoder[Pet] = deriveDecoder[Pet] +} + +/** +* A tag for a pet +* @param id +* @param name +*/ + +case class Tag( + id: Option[Long], + name: Option[String] +) +object Tag { + implicit val encoderTag: Encoder[Tag] = deriveEncoder[Tag].mapJson(_.dropNullValues) + implicit val decoderTag: Decoder[Tag] = deriveDecoder[Tag] +} + +/** +* A User who is purchasing from the pet store +* @param id +* @param username +* @param firstName +* @param lastName +* @param email +* @param password +* @param phone +* @param userStatus User Status +*/ + +case class User( + id: Option[Long], + username: Option[String], + firstName: Option[String], + lastName: Option[String], + email: Option[String], + password: Option[String], + phone: Option[String], + userStatus: Option[Int] +) +object User { + implicit val encoderUser: Encoder[User] = deriveEncoder[User].mapJson(_.dropNullValues) + implicit val decoderUser: Decoder[User] = deriveDecoder[User] +} + diff --git a/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION +++ b/samples/server/petstore/scala-pekko-http-server/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/.openapi-generator/VERSION b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java index c39f0b2dd1b1..e25ea2b15df5 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java index e2a4f6e93af1..85a5ad3e6b1a 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index a487f8f3a234..762e4bc05dde 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java index 301398fd36da..648980913217 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java index 76d5b25fc96b..b713e40cc703 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java index 1cdf275e81f1..8fda12a0801e 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -88,7 +88,7 @@ ResponseEntity createUser( ) ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) throws Exception; @@ -115,7 +115,7 @@ ResponseEntity createUsersWithArrayInput( ) ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) throws Exception; diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/ArrayTest.java index 9f1e50085dac..32a273fe3286 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @Schema(name = "array_array_of_model", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/FormatTest.java index dfc230959b20..a820d6f30a0b 100644 --- a/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/spring-boot-defaultInterface-unhandledException/src/main/java/org/openapitools/model/FormatTest.java @@ -409,7 +409,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/spring-boot-nullable-set/.openapi-generator/VERSION b/samples/server/petstore/spring-boot-nullable-set/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/spring-boot-nullable-set/.openapi-generator/VERSION +++ b/samples/server/petstore/spring-boot-nullable-set/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java index 44bc2d6253be..5a61f677bfb9 100644 --- a/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java +++ b/samples/server/petstore/spring-boot-nullable-set/src/main/java/org/openapitools/api/NullableApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/FILES b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/FILES index f3691a72bd48..95a549621f7f 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java index 46b30fbcd28b..baee5462923b 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java index 00ece07e0c19..c22571254468 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 248b6e0608b0..8f393ab68155 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java index 201f97dab98c..622027619bc1 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java index fc2985582875..2e42138d043b 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java index 9dc1ddab1657..f67123b5cb0e 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -85,7 +85,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -115,7 +115,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/ArrayTest.java index d1e1f1dd95db..dae0301137ca 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/FormatTest.java index d0c9f78571d5..d6eb693ef1cc 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/java/org/openapitools/model/FormatTest.java @@ -409,7 +409,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-beanvalidation-no-nullable/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES index 3ac88a992f94..5e2378b3ee8c 100644 --- a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-beanvalidation/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java index 46b30fbcd28b..baee5462923b 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java index 00ece07e0c19..c22571254468 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 248b6e0608b0..8f393ab68155 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java index 201f97dab98c..622027619bc1 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java index fc2985582875..2e42138d043b 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java index 9dc1ddab1657..f67123b5cb0e 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -85,7 +85,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -115,7 +115,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-beanvalidation/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-beanvalidation/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/FILES b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/FILES index fc1d5a0fa9ec..d568b26f5bef 100644 --- a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/FILES @@ -3,23 +3,17 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate-j8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index d75eb06d4bb1..e2a93ca680df 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java index c45620b8dae1..2cbf3a81f37b 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index b7189e45a0a9..b49408130c18 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java index 196d586ed8b5..f821f4046baa 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java index 82a4a7921d11..ecd8cbedb770 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java index 3348d016fb1d..81cd592944f8 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -80,7 +80,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithArrayInput(user); } @@ -109,7 +109,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithListInput(user); } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiDelegate.java index 8f4502411c53..a67248a54f31 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -47,7 +47,7 @@ default ResponseEntity createUser(User user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default ResponseEntity createUsersWithArrayInput(List user) { + default ResponseEntity createUsersWithArrayInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -60,7 +60,7 @@ default ResponseEntity createUsersWithArrayInput(List user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default ResponseEntity createUsersWithListInput(List user) { + default ResponseEntity createUsersWithListInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-delegate-j8/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-delegate-j8/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/FILES b/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/FILES index 4e2214f1e7f2..8b682c5e7ceb 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/FILES @@ -4,13 +4,10 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate-no-response-entity/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/PetApi.java index 2ce6cb412a2c..bee833800d01 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/StoreApi.java index 1a0a00c4c355..34fae39df0b8 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApi.java index afee2557af81..4bf4fe038e7b 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -88,7 +88,7 @@ default void createUser( @ResponseStatus(HttpStatus.OK) default void createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { getDelegate().createUsersWithArrayInput(user); } @@ -121,7 +121,7 @@ default void createUsersWithArrayInput( @ResponseStatus(HttpStatus.OK) default void createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { getDelegate().createUsersWithListInput(user); } diff --git a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApiDelegate.java index 502ea48610bd..cb52516e68b6 100644 --- a/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate-no-response-entity/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -46,7 +46,7 @@ default void createUser(User user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default void createUsersWithArrayInput(List user) { + default void createUsersWithArrayInput(List<@Valid User> user) { throw new IllegalArgumentException("Not implemented"); } @@ -59,7 +59,7 @@ default void createUsersWithArrayInput(List user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default void createUsersWithListInput(List user) { + default void createUsersWithListInput(List<@Valid User> user) { throw new IllegalArgumentException("Not implemented"); } diff --git a/samples/server/petstore/springboot-delegate/.openapi-generator/FILES b/samples/server/petstore/springboot-delegate/.openapi-generator/FILES index fc1d5a0fa9ec..d568b26f5bef 100644 --- a/samples/server/petstore/springboot-delegate/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-delegate/.openapi-generator/FILES @@ -3,23 +3,17 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-delegate/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java index d75eb06d4bb1..e2a93ca680df 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java index c45620b8dae1..2cbf3a81f37b 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index b7189e45a0a9..b49408130c18 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java index 196d586ed8b5..f821f4046baa 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java index 82a4a7921d11..ecd8cbedb770 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java index 3348d016fb1d..81cd592944f8 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -80,7 +80,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithArrayInput(user); } @@ -109,7 +109,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return getDelegate().createUsersWithListInput(user); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java index 8f4502411c53..a67248a54f31 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -47,7 +47,7 @@ default ResponseEntity createUser(User user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default ResponseEntity createUsersWithArrayInput(List user) { + default ResponseEntity createUsersWithArrayInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -60,7 +60,7 @@ default ResponseEntity createUsersWithArrayInput(List user) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default ResponseEntity createUsersWithListInput(List user) { + default ResponseEntity createUsersWithListInput(List<@Valid User> user) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-delegate/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-delegate/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES index baf10ab6b83b..f309423544f7 100644 --- a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/FILES @@ -4,11 +4,8 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/model/Category.java src/main/java/org/openapitools/model/ModelApiResponse.java diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java index ba4b0a79d892..680c13f94230 100644 --- a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java index 312c65eb077c..5ad4bd3ac598 100644 --- a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java index 7b99a0122ea0..fcf70bacf748 100644 --- a/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-implicitHeaders-annotationLibrary/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -65,7 +65,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -86,7 +86,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Valid @RequestBody List user + @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES index f3691a72bd48..95a549621f7f 100644 --- a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-implicitHeaders/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java index 46b30fbcd28b..baee5462923b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java index c1dca403316b..19c25749b83b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 248b6e0608b0..8f393ab68155 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java index d44c170496ff..cd6d80f0a460 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java index fc2985582875..2e42138d043b 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java index 9dc1ddab1657..f67123b5cb0e 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -85,7 +85,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -115,7 +115,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-implicitHeaders/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/FILES b/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/FILES index 64711ce47178..93297148e9b7 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/FILES @@ -3,23 +3,17 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/VERSION b/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/AnotherFakeApi.java index b9ef983e22ad..a9793d9694d9 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeApi.java index 73aa18cc37c8..405d068fb9cc 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 50bce3298f56..c8995937f265 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/PetApi.java index f4a8febb5196..5a63a5f0321d 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/StoreApi.java index d4ac3d4ef0d3..f5a755e220c2 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/UserApi.java index f3abec9ba9b2..60fed709537e 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-reactive-noResponseEntity/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-reactive/.openapi-generator/FILES b/samples/server/petstore/springboot-reactive/.openapi-generator/FILES index 64711ce47178..93297148e9b7 100644 --- a/samples/server/petstore/springboot-reactive/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-reactive/.openapi-generator/FILES @@ -3,23 +3,17 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-reactive/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java index 50297537ff55..da315bc6b4f1 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java index 57dc231624a7..af1bc29c8e3c 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 81c899fbf3cd..972f8875509b 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java index 4e27e38ad5ca..3b07502bac41 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java index fbb19ea57776..c43cfff04f4c 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java index 6071e2701f55..2b012c2100da 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-reactive/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-reactive/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/FILES b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/FILES index f41a04cca5d5..ade930debbfb 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/FILES @@ -3,26 +3,19 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/api/VersioningApi.java -src/main/java/org/openapitools/api/VersioningApiController.java src/main/java/org/openapitools/api/VersioningApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index 064a43317ee9..8e1d343af0f3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java index 96dce92fe570..7f66cb20daf3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 5e55dcc9ef0f..a5ec80e5f732 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java index ccc406434c16..3cb4d3a8185e 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 9b3fe4da4706..daffc5c6c8ef 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java index 6c96e70f7be4..d3000555c3b0 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -77,7 +77,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return getDelegate().createUsersWithArrayInput(body); } @@ -104,7 +104,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return getDelegate().createUsersWithListInput(body); } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiDelegate.java index 6bd822603bda..8c1d3425acf0 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -46,7 +46,7 @@ default ResponseEntity createUser(User body) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default ResponseEntity createUsersWithArrayInput(List body) { + default ResponseEntity createUsersWithArrayInput(List<@Valid User> body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -58,7 +58,7 @@ default ResponseEntity createUsersWithArrayInput(List body) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default ResponseEntity createUsersWithListInput(List body) { + default ResponseEntity createUsersWithListInput(List<@Valid User> body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/VersioningApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/VersioningApi.java index 099ee547b449..c7844421a26d 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/VersioningApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/api/VersioningApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern-without-j8/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/FILES b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/FILES index f41a04cca5d5..ade930debbfb 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/FILES @@ -3,26 +3,19 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/AnotherFakeApiDelegate.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeApiDelegate.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApiDelegate.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/PetApiDelegate.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/StoreApiDelegate.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/UserApiDelegate.java src/main/java/org/openapitools/api/VersioningApi.java -src/main/java/org/openapitools/api/VersioningApiController.java src/main/java/org/openapitools/api/VersioningApiDelegate.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java index 064a43317ee9..8e1d343af0f3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java index 96dce92fe570..7f66cb20daf3 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 5e55dcc9ef0f..a5ec80e5f732 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java index ccc406434c16..3cb4d3a8185e 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java index 9b3fe4da4706..daffc5c6c8ef 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java index 6c96e70f7be4..d3000555c3b0 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -77,7 +77,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return getDelegate().createUsersWithArrayInput(body); } @@ -104,7 +104,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return getDelegate().createUsersWithListInput(body); } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiDelegate.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiDelegate.java index 6bd822603bda..8c1d3425acf0 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiDelegate.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/UserApiDelegate.java @@ -46,7 +46,7 @@ default ResponseEntity createUser(User body) { * @return successful operation (status code 200) * @see UserApi#createUsersWithArrayInput */ - default ResponseEntity createUsersWithArrayInput(List body) { + default ResponseEntity createUsersWithArrayInput(List<@Valid User> body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } @@ -58,7 +58,7 @@ default ResponseEntity createUsersWithArrayInput(List body) { * @return successful operation (status code 200) * @see UserApi#createUsersWithListInput */ - default ResponseEntity createUsersWithListInput(List body) { + default ResponseEntity createUsersWithListInput(List<@Valid User> body) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/VersioningApi.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/VersioningApi.java index c0b9e1728507..3d5c5d24f949 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/VersioningApi.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/api/VersioningApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-spring-pageable-delegatePattern/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/FILES b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/FILES index 3eb92a4787f5..166ece42f552 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/FILES @@ -3,20 +3,13 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/VersioningApi.java -src/main/java/org/openapitools/api/VersioningApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java index d8d420d0f9da..09cb03b35261 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java index b6cb0c0b58a4..593da8a8a293 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index a86c37507861..93994152522a 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java index 57e506ba5a39..4e3a224f572b 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java index 8540b17e0eb4..1dc1bd295067 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java index 38033c4e763f..473a3215ce4d 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -82,7 +82,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -110,7 +110,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/VersioningApi.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/VersioningApi.java index c472c8a5ec4c..b8784af28778 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/VersioningApi.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/api/VersioningApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-spring-pageable-without-j8/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/FILES b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/FILES index 3eb92a4787f5..166ece42f552 100644 --- a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/FILES @@ -3,20 +3,13 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/api/VersioningApi.java -src/main/java/org/openapitools/api/VersioningApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-pageable/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java index d8d420d0f9da..09cb03b35261 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java index b6cb0c0b58a4..593da8a8a293 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index a86c37507861..93994152522a 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java index 57e506ba5a39..4e3a224f572b 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java index 8540b17e0eb4..1dc1bd295067 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java index 38033c4e763f..473a3215ce4d 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -82,7 +82,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -110,7 +110,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List body + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/VersioningApi.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/VersioningApi.java index cc15e05ab106..1f01710dec94 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/VersioningApi.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/api/VersioningApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..9adba59cfbea 100644 --- a/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-spring-pageable/src/main/java/org/openapitools/model/FormatTest.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/FILES b/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/FILES index 86abe7f3936f..59748a69ffba 100644 --- a/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/FILES @@ -4,7 +4,6 @@ src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java src/main/java/org/openapitools/model/Category.java diff --git a/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/VERSION b/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-spring-provide-args/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-spring-provide-args/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-spring-provide-args/src/main/java/org/openapitools/api/UserApi.java index a7bef45dc8a8..ce5ef2945f63 100644 --- a/samples/server/petstore/springboot-spring-provide-args/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-spring-provide-args/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/.openapi-generator/FILES b/samples/server/petstore/springboot-useoptional/.openapi-generator/FILES index f3691a72bd48..95a549621f7f 100644 --- a/samples/server/petstore/springboot-useoptional/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-useoptional/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-useoptional/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java index 46b30fbcd28b..baee5462923b 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java index b7765e99b8f0..d4ec26130cb7 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -98,7 +98,7 @@ default ResponseEntity createXmlItem( ) default ResponseEntity fakeOuterBooleanSerialize( - @ApiParam(value = "Input boolean as post body") @Valid @RequestBody(required = false) Boolean body + @ApiParam(value = "Input boolean as post body") @Valid @RequestBody(required = false) Optional body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -130,7 +130,7 @@ default ResponseEntity fakeOuterBooleanSerialize( ) default ResponseEntity fakeOuterCompositeSerialize( - @ApiParam(value = "Input composite as post body") @Valid @RequestBody(required = false) OuterComposite outerComposite + @ApiParam(value = "Input composite as post body") @Valid @RequestBody(required = false) Optional outerComposite ) { getRequest().ifPresent(request -> { for (MediaType mediaType: MediaType.parseMediaTypes(request.getHeader("Accept"))) { @@ -171,7 +171,7 @@ default ResponseEntity fakeOuterCompositeSerialize( ) default ResponseEntity fakeOuterNumberSerialize( - @ApiParam(value = "Input number as post body") @Valid @RequestBody(required = false) BigDecimal body + @ApiParam(value = "Input number as post body") @Valid @RequestBody(required = false) Optional body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -203,7 +203,7 @@ default ResponseEntity fakeOuterNumberSerialize( ) default ResponseEntity fakeOuterStringSerialize( - @ApiParam(value = "Input string as post body") @Valid @RequestBody(required = false) String body + @ApiParam(value = "Input string as post body") @Valid @RequestBody(required = false) Optional body ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 248b6e0608b0..8f393ab68155 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java index f2d7bb655a34..a7a52d7ea70e 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java index fc2985582875..2e42138d043b 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java index 9dc1ddab1657..f67123b5cb0e 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -85,7 +85,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -115,7 +115,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List user + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java index bd218422f919..ce5edf05f3a3 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesAnyType.java @@ -26,10 +26,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesAnyType { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesAnyType name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -40,11 +40,11 @@ public AdditionalPropertiesAnyType name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesArray.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesArray.java index 548dad9a0401..a50265d5e8b1 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesArray.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesArray.java @@ -27,10 +27,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesArray { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesArray name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -41,11 +41,11 @@ public AdditionalPropertiesArray name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesBoolean.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesBoolean.java index 7eff631b3864..71b8012aa8c5 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesBoolean.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesBoolean.java @@ -26,10 +26,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesBoolean { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesBoolean name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -40,11 +40,11 @@ public AdditionalPropertiesBoolean name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java index 4a668d53474f..b5b0b66c10ec 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesClass.java @@ -53,11 +53,11 @@ public class AdditionalPropertiesClass { @Valid private Map> mapMapAnytype = new HashMap<>(); - private Object anytype1; + private Optional anytype1 = Optional.empty(); private JsonNullable anytype2 = JsonNullable.undefined(); - private Object anytype3; + private Optional anytype3 = Optional.empty(); public AdditionalPropertiesClass mapString(Map mapString) { this.mapString = mapString; @@ -284,7 +284,7 @@ public void setMapMapAnytype(Map> mapMapAnytype) { } public AdditionalPropertiesClass anytype1(Object anytype1) { - this.anytype1 = anytype1; + this.anytype1 = Optional.of(anytype1); return this; } @@ -295,11 +295,11 @@ public AdditionalPropertiesClass anytype1(Object anytype1) { @ApiModelProperty(value = "") @JsonProperty("anytype_1") - public Object getAnytype1() { + public Optional getAnytype1() { return anytype1; } - public void setAnytype1(Object anytype1) { + public void setAnytype1(Optional anytype1) { this.anytype1 = anytype1; } @@ -324,7 +324,7 @@ public void setAnytype2(JsonNullable anytype2) { } public AdditionalPropertiesClass anytype3(Object anytype3) { - this.anytype3 = anytype3; + this.anytype3 = Optional.of(anytype3); return this; } @@ -335,11 +335,11 @@ public AdditionalPropertiesClass anytype3(Object anytype3) { @ApiModelProperty(value = "") @JsonProperty("anytype_3") - public Object getAnytype3() { + public Optional getAnytype3() { return anytype3; } - public void setAnytype3(Object anytype3) { + public void setAnytype3(Optional anytype3) { this.anytype3 = anytype3; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesInteger.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesInteger.java index 53a7354098c5..028535c51faf 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesInteger.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesInteger.java @@ -26,10 +26,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesInteger { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesInteger name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -40,11 +40,11 @@ public AdditionalPropertiesInteger name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesNumber.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesNumber.java index d9c197156a88..76fecc687bf7 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesNumber.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesNumber.java @@ -27,10 +27,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesNumber { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesNumber name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -41,11 +41,11 @@ public AdditionalPropertiesNumber name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesObject.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesObject.java index a0b695f115ad..791ae228623e 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesObject.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesObject.java @@ -27,10 +27,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesObject { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesObject name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -41,11 +41,11 @@ public AdditionalPropertiesObject name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesString.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesString.java index 2ef5cd4f06bd..20d7a455eefe 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesString.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/AdditionalPropertiesString.java @@ -26,10 +26,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class AdditionalPropertiesString { - private String name; + private Optional name = Optional.empty(); public AdditionalPropertiesString name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -40,11 +40,11 @@ public AdditionalPropertiesString name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } /** diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Animal.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Animal.java index 5916ecd79f9e..7646c8831244 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Animal.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Animal.java @@ -38,7 +38,7 @@ public class Animal { private String className; - private String color = "red"; + private Optional color = Optional.of("red"); public Animal() { super(); @@ -72,7 +72,7 @@ public void setClassName(String className) { } public Animal color(String color) { - this.color = color; + this.color = Optional.of(color); return this; } @@ -83,11 +83,11 @@ public Animal color(String color) { @ApiModelProperty(value = "") @JsonProperty("color") - public String getColor() { + public Optional getColor() { return color; } - public void setColor(String color) { + public void setColor(Optional color) { this.color = color; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ArrayTest.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ArrayTest.java index 7d3308d4f7ad..67ca138961c9 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ArrayTest.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ArrayTest.java @@ -33,7 +33,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -91,7 +91,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -111,11 +111,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/BigCat.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/BigCat.java index 5a0f52ce89f6..96ead30a3d4a 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/BigCat.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/BigCat.java @@ -67,7 +67,7 @@ public static KindEnum fromValue(String value) { } } - private KindEnum kind; + private Optional kind = Optional.empty(); public BigCat() { super(); @@ -81,7 +81,7 @@ public BigCat(String className) { } public BigCat kind(KindEnum kind) { - this.kind = kind; + this.kind = Optional.of(kind); return this; } @@ -92,11 +92,11 @@ public BigCat kind(KindEnum kind) { @ApiModelProperty(value = "") @JsonProperty("kind") - public KindEnum getKind() { + public Optional getKind() { return kind; } - public void setKind(KindEnum kind) { + public void setKind(Optional kind) { this.kind = kind; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Capitalization.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Capitalization.java index feb0d643c5e5..5549c8966ea0 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Capitalization.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Capitalization.java @@ -22,20 +22,20 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Capitalization { - private String smallCamel; + private Optional smallCamel = Optional.empty(); - private String capitalCamel; + private Optional capitalCamel = Optional.empty(); - private String smallSnake; + private Optional smallSnake = Optional.empty(); - private String capitalSnake; + private Optional capitalSnake = Optional.empty(); - private String scAETHFlowPoints; + private Optional scAETHFlowPoints = Optional.empty(); - private String ATT_NAME; + private Optional ATT_NAME = Optional.empty(); public Capitalization smallCamel(String smallCamel) { - this.smallCamel = smallCamel; + this.smallCamel = Optional.of(smallCamel); return this; } @@ -46,16 +46,16 @@ public Capitalization smallCamel(String smallCamel) { @ApiModelProperty(value = "") @JsonProperty("smallCamel") - public String getSmallCamel() { + public Optional getSmallCamel() { return smallCamel; } - public void setSmallCamel(String smallCamel) { + public void setSmallCamel(Optional smallCamel) { this.smallCamel = smallCamel; } public Capitalization capitalCamel(String capitalCamel) { - this.capitalCamel = capitalCamel; + this.capitalCamel = Optional.of(capitalCamel); return this; } @@ -66,16 +66,16 @@ public Capitalization capitalCamel(String capitalCamel) { @ApiModelProperty(value = "") @JsonProperty("CapitalCamel") - public String getCapitalCamel() { + public Optional getCapitalCamel() { return capitalCamel; } - public void setCapitalCamel(String capitalCamel) { + public void setCapitalCamel(Optional capitalCamel) { this.capitalCamel = capitalCamel; } public Capitalization smallSnake(String smallSnake) { - this.smallSnake = smallSnake; + this.smallSnake = Optional.of(smallSnake); return this; } @@ -86,16 +86,16 @@ public Capitalization smallSnake(String smallSnake) { @ApiModelProperty(value = "") @JsonProperty("small_Snake") - public String getSmallSnake() { + public Optional getSmallSnake() { return smallSnake; } - public void setSmallSnake(String smallSnake) { + public void setSmallSnake(Optional smallSnake) { this.smallSnake = smallSnake; } public Capitalization capitalSnake(String capitalSnake) { - this.capitalSnake = capitalSnake; + this.capitalSnake = Optional.of(capitalSnake); return this; } @@ -106,16 +106,16 @@ public Capitalization capitalSnake(String capitalSnake) { @ApiModelProperty(value = "") @JsonProperty("Capital_Snake") - public String getCapitalSnake() { + public Optional getCapitalSnake() { return capitalSnake; } - public void setCapitalSnake(String capitalSnake) { + public void setCapitalSnake(Optional capitalSnake) { this.capitalSnake = capitalSnake; } public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { - this.scAETHFlowPoints = scAETHFlowPoints; + this.scAETHFlowPoints = Optional.of(scAETHFlowPoints); return this; } @@ -126,16 +126,16 @@ public Capitalization scAETHFlowPoints(String scAETHFlowPoints) { @ApiModelProperty(value = "") @JsonProperty("SCA_ETH_Flow_Points") - public String getScAETHFlowPoints() { + public Optional getScAETHFlowPoints() { return scAETHFlowPoints; } - public void setScAETHFlowPoints(String scAETHFlowPoints) { + public void setScAETHFlowPoints(Optional scAETHFlowPoints) { this.scAETHFlowPoints = scAETHFlowPoints; } public Capitalization ATT_NAME(String ATT_NAME) { - this.ATT_NAME = ATT_NAME; + this.ATT_NAME = Optional.of(ATT_NAME); return this; } @@ -146,11 +146,11 @@ public Capitalization ATT_NAME(String ATT_NAME) { @ApiModelProperty(value = "Name of the pet ") @JsonProperty("ATT_NAME") - public String getATTNAME() { + public Optional getATTNAME() { return ATT_NAME; } - public void setATTNAME(String ATT_NAME) { + public void setATTNAME(Optional ATT_NAME) { this.ATT_NAME = ATT_NAME; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Cat.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Cat.java index e44f574d69b4..8474ef1cbd36 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Cat.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Cat.java @@ -35,7 +35,7 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Cat extends Animal { - private Boolean declawed; + private Optional declawed = Optional.empty(); public Cat() { super(); @@ -49,7 +49,7 @@ public Cat(String className) { } public Cat declawed(Boolean declawed) { - this.declawed = declawed; + this.declawed = Optional.of(declawed); return this; } @@ -60,11 +60,11 @@ public Cat declawed(Boolean declawed) { @ApiModelProperty(value = "") @JsonProperty("declawed") - public Boolean getDeclawed() { + public Optional getDeclawed() { return declawed; } - public void setDeclawed(Boolean declawed) { + public void setDeclawed(Optional declawed) { this.declawed = declawed; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Category.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Category.java index 18c9bee66c00..a2af14bc5199 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Category.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Category.java @@ -22,7 +22,7 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Category { - private Long id; + private Optional id = Optional.empty(); private String name = "default-name"; @@ -38,7 +38,7 @@ public Category(String name) { } public Category id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -49,11 +49,11 @@ public Category id(Long id) { @ApiModelProperty(value = "") @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ChildWithNullable.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ChildWithNullable.java index 49094e267a20..3fc1f3a2274e 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ChildWithNullable.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ChildWithNullable.java @@ -30,10 +30,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ChildWithNullable extends ParentWithNullable { - private String otherProperty; + private Optional otherProperty = Optional.empty(); public ChildWithNullable otherProperty(String otherProperty) { - this.otherProperty = otherProperty; + this.otherProperty = Optional.of(otherProperty); return this; } @@ -44,11 +44,11 @@ public ChildWithNullable otherProperty(String otherProperty) { @ApiModelProperty(value = "") @JsonProperty("otherProperty") - public String getOtherProperty() { + public Optional getOtherProperty() { return otherProperty; } - public void setOtherProperty(String otherProperty) { + public void setOtherProperty(Optional otherProperty) { this.otherProperty = otherProperty; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ClassModel.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ClassModel.java index 2c511abe3ecb..1534abdaa28f 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ClassModel.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ClassModel.java @@ -23,10 +23,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ClassModel { - private String propertyClass; + private Optional propertyClass = Optional.empty(); public ClassModel propertyClass(String propertyClass) { - this.propertyClass = propertyClass; + this.propertyClass = Optional.of(propertyClass); return this; } @@ -37,11 +37,11 @@ public ClassModel propertyClass(String propertyClass) { @ApiModelProperty(value = "") @JsonProperty("_class") - public String getPropertyClass() { + public Optional getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { + public void setPropertyClass(Optional propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Client.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Client.java index a6bfdf58db7f..e1cea9ab3372 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Client.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Client.java @@ -22,10 +22,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Client { - private String client; + private Optional client = Optional.empty(); public Client client(String client) { - this.client = client; + this.client = Optional.of(client); return this; } @@ -36,11 +36,11 @@ public Client client(String client) { @ApiModelProperty(value = "") @JsonProperty("client") - public String getClient() { + public Optional getClient() { return client; } - public void setClient(String client) { + public void setClient(Optional client) { this.client = client; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Dog.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Dog.java index 278b2aee4c15..866f5148e546 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Dog.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Dog.java @@ -27,7 +27,7 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Dog extends Animal { - private String breed; + private Optional breed = Optional.empty(); public Dog() { super(); @@ -41,7 +41,7 @@ public Dog(String className) { } public Dog breed(String breed) { - this.breed = breed; + this.breed = Optional.of(breed); return this; } @@ -52,11 +52,11 @@ public Dog breed(String breed) { @ApiModelProperty(value = "") @JsonProperty("breed") - public String getBreed() { + public Optional getBreed() { return breed; } - public void setBreed(String breed) { + public void setBreed(Optional breed) { this.breed = breed; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumArrays.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumArrays.java index 0479937750d1..47392d12be50 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumArrays.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumArrays.java @@ -61,7 +61,7 @@ public static JustSymbolEnum fromValue(String value) { } } - private JustSymbolEnum justSymbol; + private Optional justSymbol = Optional.empty(); /** * Gets or Sets arrayEnum @@ -102,7 +102,7 @@ public static ArrayEnumEnum fromValue(String value) { private List arrayEnum; public EnumArrays justSymbol(JustSymbolEnum justSymbol) { - this.justSymbol = justSymbol; + this.justSymbol = Optional.of(justSymbol); return this; } @@ -113,11 +113,11 @@ public EnumArrays justSymbol(JustSymbolEnum justSymbol) { @ApiModelProperty(value = "") @JsonProperty("just_symbol") - public JustSymbolEnum getJustSymbol() { + public Optional getJustSymbol() { return justSymbol; } - public void setJustSymbol(JustSymbolEnum justSymbol) { + public void setJustSymbol(Optional justSymbol) { this.justSymbol = justSymbol; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumTest.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumTest.java index 427020a13a25..06ecf24f8cdc 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumTest.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/EnumTest.java @@ -63,7 +63,7 @@ public static EnumStringEnum fromValue(String value) { } } - private EnumStringEnum enumString; + private Optional enumString = Optional.empty(); /** * Gets or Sets enumStringRequired @@ -139,7 +139,7 @@ public static EnumIntegerEnum fromValue(Integer value) { } } - private EnumIntegerEnum enumInteger; + private Optional enumInteger = Optional.empty(); /** * Gets or Sets enumNumber @@ -176,9 +176,9 @@ public static EnumNumberEnum fromValue(Double value) { } } - private EnumNumberEnum enumNumber; + private Optional enumNumber = Optional.empty(); - private OuterEnum outerEnum; + private Optional outerEnum = Optional.empty(); public EnumTest() { super(); @@ -192,7 +192,7 @@ public EnumTest(EnumStringRequiredEnum enumStringRequired) { } public EnumTest enumString(EnumStringEnum enumString) { - this.enumString = enumString; + this.enumString = Optional.of(enumString); return this; } @@ -203,11 +203,11 @@ public EnumTest enumString(EnumStringEnum enumString) { @ApiModelProperty(value = "") @JsonProperty("enum_string") - public EnumStringEnum getEnumString() { + public Optional getEnumString() { return enumString; } - public void setEnumString(EnumStringEnum enumString) { + public void setEnumString(Optional enumString) { this.enumString = enumString; } @@ -232,7 +232,7 @@ public void setEnumStringRequired(EnumStringRequiredEnum enumStringRequired) { } public EnumTest enumInteger(EnumIntegerEnum enumInteger) { - this.enumInteger = enumInteger; + this.enumInteger = Optional.of(enumInteger); return this; } @@ -243,16 +243,16 @@ public EnumTest enumInteger(EnumIntegerEnum enumInteger) { @ApiModelProperty(value = "") @JsonProperty("enum_integer") - public EnumIntegerEnum getEnumInteger() { + public Optional getEnumInteger() { return enumInteger; } - public void setEnumInteger(EnumIntegerEnum enumInteger) { + public void setEnumInteger(Optional enumInteger) { this.enumInteger = enumInteger; } public EnumTest enumNumber(EnumNumberEnum enumNumber) { - this.enumNumber = enumNumber; + this.enumNumber = Optional.of(enumNumber); return this; } @@ -263,16 +263,16 @@ public EnumTest enumNumber(EnumNumberEnum enumNumber) { @ApiModelProperty(value = "") @JsonProperty("enum_number") - public EnumNumberEnum getEnumNumber() { + public Optional getEnumNumber() { return enumNumber; } - public void setEnumNumber(EnumNumberEnum enumNumber) { + public void setEnumNumber(Optional enumNumber) { this.enumNumber = enumNumber; } public EnumTest outerEnum(OuterEnum outerEnum) { - this.outerEnum = outerEnum; + this.outerEnum = Optional.of(outerEnum); return this; } @@ -283,11 +283,11 @@ public EnumTest outerEnum(OuterEnum outerEnum) { @Valid @ApiModelProperty(value = "") @JsonProperty("outerEnum") - public OuterEnum getOuterEnum() { + public Optional getOuterEnum() { return outerEnum; } - public void setOuterEnum(OuterEnum outerEnum) { + public void setOuterEnum(Optional outerEnum) { this.outerEnum = outerEnum; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/File.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/File.java index fedeea1c6389..a7dddddbe16e 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/File.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/File.java @@ -23,10 +23,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class File { - private String sourceURI; + private Optional sourceURI = Optional.empty(); public File sourceURI(String sourceURI) { - this.sourceURI = sourceURI; + this.sourceURI = Optional.of(sourceURI); return this; } @@ -37,11 +37,11 @@ public File sourceURI(String sourceURI) { @ApiModelProperty(value = "Test capitalization") @JsonProperty("sourceURI") - public String getSourceURI() { + public Optional getSourceURI() { return sourceURI; } - public void setSourceURI(String sourceURI) { + public void setSourceURI(Optional sourceURI) { this.sourceURI = sourceURI; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FileSchemaTestClass.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FileSchemaTestClass.java index bc7f7e2fa979..a7b77af60778 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FileSchemaTestClass.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FileSchemaTestClass.java @@ -26,13 +26,13 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class FileSchemaTestClass { - private File file; + private Optional file = Optional.empty(); @Valid private List<@Valid File> files; public FileSchemaTestClass file(File file) { - this.file = file; + this.file = Optional.of(file); return this; } @@ -43,11 +43,11 @@ public FileSchemaTestClass file(File file) { @Valid @ApiModelProperty(value = "") @JsonProperty("file") - public File getFile() { + public Optional getFile() { return file; } - public void setFile(File file) { + public void setFile(Optional file) { this.file = file; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FormatTest.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FormatTest.java index 7a7c86d8be76..7fbc7fc6d3ac 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FormatTest.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/FormatTest.java @@ -30,35 +30,35 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class FormatTest { - private Integer integer; + private Optional<@Min(10) @Max(100) Integer> integer = Optional.empty(); - private Integer int32; + private Optional<@Min(20) @Max(200) Integer> int32 = Optional.empty(); - private Long int64; + private Optional int64 = Optional.empty(); private BigDecimal number; - private Float _float; + private Optional<@DecimalMin("54.3") @DecimalMax("987.6") Float> _float = Optional.empty(); - private Double _double; + private Optional<@DecimalMin("67.8") @DecimalMax("123.4") Double> _double = Optional.empty(); - private String string; + private Optional<@Pattern(regexp = "/[a-z]/i") String> string = Optional.empty(); private byte[] _byte; - private org.springframework.core.io.Resource binary; + private Optional binary = Optional.empty(); @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) private LocalDate date; @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private OffsetDateTime dateTime; + private Optional dateTime = Optional.empty(); - private UUID uuid; + private Optional uuid = Optional.empty(); private String password; - private BigDecimal bigDecimal; + private Optional bigDecimal = Optional.empty(); public FormatTest() { super(); @@ -75,7 +75,7 @@ public FormatTest(BigDecimal number, byte[] _byte, LocalDate date, String passwo } public FormatTest integer(Integer integer) { - this.integer = integer; + this.integer = Optional.of(integer); return this; } @@ -85,19 +85,19 @@ public FormatTest integer(Integer integer) { * maximum: 100 * @return integer */ - @Min(10) @Max(100) + @ApiModelProperty(value = "") @JsonProperty("integer") - public Integer getInteger() { + public Optional<@Min(10) @Max(100) Integer> getInteger() { return integer; } - public void setInteger(Integer integer) { + public void setInteger(Optional integer) { this.integer = integer; } public FormatTest int32(Integer int32) { - this.int32 = int32; + this.int32 = Optional.of(int32); return this; } @@ -107,19 +107,19 @@ public FormatTest int32(Integer int32) { * maximum: 200 * @return int32 */ - @Min(20) @Max(200) + @ApiModelProperty(value = "") @JsonProperty("int32") - public Integer getInt32() { + public Optional<@Min(20) @Max(200) Integer> getInt32() { return int32; } - public void setInt32(Integer int32) { + public void setInt32(Optional int32) { this.int32 = int32; } public FormatTest int64(Long int64) { - this.int64 = int64; + this.int64 = Optional.of(int64); return this; } @@ -130,11 +130,11 @@ public FormatTest int64(Long int64) { @ApiModelProperty(value = "") @JsonProperty("int64") - public Long getInt64() { + public Optional getInt64() { return int64; } - public void setInt64(Long int64) { + public void setInt64(Optional int64) { this.int64 = int64; } @@ -161,7 +161,7 @@ public void setNumber(BigDecimal number) { } public FormatTest _float(Float _float) { - this._float = _float; + this._float = Optional.of(_float); return this; } @@ -171,19 +171,19 @@ public FormatTest _float(Float _float) { * maximum: 987.6 * @return _float */ - @DecimalMin("54.3") @DecimalMax("987.6") + @ApiModelProperty(value = "") @JsonProperty("float") - public Float getFloat() { + public Optional<@DecimalMin("54.3") @DecimalMax("987.6") Float> getFloat() { return _float; } - public void setFloat(Float _float) { + public void setFloat(Optional _float) { this._float = _float; } public FormatTest _double(Double _double) { - this._double = _double; + this._double = Optional.of(_double); return this; } @@ -193,19 +193,19 @@ public FormatTest _double(Double _double) { * maximum: 123.4 * @return _double */ - @DecimalMin("67.8") @DecimalMax("123.4") + @ApiModelProperty(value = "") @JsonProperty("double") - public Double getDouble() { + public Optional<@DecimalMin("67.8") @DecimalMax("123.4") Double> getDouble() { return _double; } - public void setDouble(Double _double) { + public void setDouble(Optional _double) { this._double = _double; } public FormatTest string(String string) { - this.string = string; + this.string = Optional.of(string); return this; } @@ -213,14 +213,14 @@ public FormatTest string(String string) { * Get string * @return string */ - @Pattern(regexp = "/[a-z]/i") + @ApiModelProperty(value = "") @JsonProperty("string") - public String getString() { + public Optional<@Pattern(regexp = "/[a-z]/i") String> getString() { return string; } - public void setString(String string) { + public void setString(Optional string) { this.string = string; } @@ -245,7 +245,7 @@ public void setByte(byte[] _byte) { } public FormatTest binary(org.springframework.core.io.Resource binary) { - this.binary = binary; + this.binary = Optional.of(binary); return this; } @@ -256,11 +256,11 @@ public FormatTest binary(org.springframework.core.io.Resource binary) { @Valid @ApiModelProperty(value = "") @JsonProperty("binary") - public org.springframework.core.io.Resource getBinary() { + public Optional getBinary() { return binary; } - public void setBinary(org.springframework.core.io.Resource binary) { + public void setBinary(Optional binary) { this.binary = binary; } @@ -285,7 +285,7 @@ public void setDate(LocalDate date) { } public FormatTest dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; + this.dateTime = Optional.of(dateTime); return this; } @@ -296,16 +296,16 @@ public FormatTest dateTime(OffsetDateTime dateTime) { @Valid @ApiModelProperty(value = "") @JsonProperty("dateTime") - public OffsetDateTime getDateTime() { + public Optional getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { + public void setDateTime(Optional dateTime) { this.dateTime = dateTime; } public FormatTest uuid(UUID uuid) { - this.uuid = uuid; + this.uuid = Optional.of(uuid); return this; } @@ -316,11 +316,11 @@ public FormatTest uuid(UUID uuid) { @Valid @ApiModelProperty(example = "72f98069-206d-4f12-9f12-3d1e525a8e84", value = "") @JsonProperty("uuid") - public UUID getUuid() { + public Optional getUuid() { return uuid; } - public void setUuid(UUID uuid) { + public void setUuid(Optional uuid) { this.uuid = uuid; } @@ -345,7 +345,7 @@ public void setPassword(String password) { } public FormatTest bigDecimal(BigDecimal bigDecimal) { - this.bigDecimal = bigDecimal; + this.bigDecimal = Optional.of(bigDecimal); return this; } @@ -356,11 +356,11 @@ public FormatTest bigDecimal(BigDecimal bigDecimal) { @Valid @ApiModelProperty(value = "") @JsonProperty("BigDecimal") - public BigDecimal getBigDecimal() { + public Optional getBigDecimal() { return bigDecimal; } - public void setBigDecimal(BigDecimal bigDecimal) { + public void setBigDecimal(Optional bigDecimal) { this.bigDecimal = bigDecimal; } @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/HasOnlyReadOnly.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/HasOnlyReadOnly.java index 21a424459798..5fe7575c4449 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/HasOnlyReadOnly.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/HasOnlyReadOnly.java @@ -24,12 +24,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class HasOnlyReadOnly { - private String bar; + private Optional bar = Optional.empty(); - private String foo; + private Optional foo = Optional.empty(); public HasOnlyReadOnly bar(String bar) { - this.bar = bar; + this.bar = Optional.of(bar); return this; } @@ -40,16 +40,16 @@ public HasOnlyReadOnly bar(String bar) { @ApiModelProperty(readOnly = true, value = "") @JsonProperty("bar") - public String getBar() { + public Optional getBar() { return bar; } - public void setBar(String bar) { + public void setBar(Optional bar) { this.bar = bar; } public HasOnlyReadOnly foo(String foo) { - this.foo = foo; + this.foo = Optional.of(foo); return this; } @@ -60,11 +60,11 @@ public HasOnlyReadOnly foo(String foo) { @ApiModelProperty(readOnly = true, value = "") @JsonProperty("foo") - public String getFoo() { + public Optional getFoo() { return foo; } - public void setFoo(String foo) { + public void setFoo(Optional foo) { this.foo = foo; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java index 075d281eb4bc..9495232ee3e0 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/MixedPropertiesAndAdditionalPropertiesClass.java @@ -28,16 +28,16 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class MixedPropertiesAndAdditionalPropertiesClass { - private UUID uuid; + private Optional uuid = Optional.empty(); @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private OffsetDateTime dateTime; + private Optional dateTime = Optional.empty(); @Valid private Map map = new HashMap<>(); public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { - this.uuid = uuid; + this.uuid = Optional.of(uuid); return this; } @@ -48,16 +48,16 @@ public MixedPropertiesAndAdditionalPropertiesClass uuid(UUID uuid) { @Valid @ApiModelProperty(value = "") @JsonProperty("uuid") - public UUID getUuid() { + public Optional getUuid() { return uuid; } - public void setUuid(UUID uuid) { + public void setUuid(Optional uuid) { this.uuid = uuid; } public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateTime) { - this.dateTime = dateTime; + this.dateTime = Optional.of(dateTime); return this; } @@ -68,11 +68,11 @@ public MixedPropertiesAndAdditionalPropertiesClass dateTime(OffsetDateTime dateT @Valid @ApiModelProperty(value = "") @JsonProperty("dateTime") - public OffsetDateTime getDateTime() { + public Optional getDateTime() { return dateTime; } - public void setDateTime(OffsetDateTime dateTime) { + public void setDateTime(Optional dateTime) { this.dateTime = dateTime; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Model200Response.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Model200Response.java index 193231f85457..2580ba9e9bdd 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Model200Response.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Model200Response.java @@ -25,12 +25,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Model200Response { - private Integer name; + private Optional name = Optional.empty(); - private String propertyClass; + private Optional propertyClass = Optional.empty(); public Model200Response name(Integer name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -41,16 +41,16 @@ public Model200Response name(Integer name) { @ApiModelProperty(value = "") @JsonProperty("name") - public Integer getName() { + public Optional getName() { return name; } - public void setName(Integer name) { + public void setName(Optional name) { this.name = name; } public Model200Response propertyClass(String propertyClass) { - this.propertyClass = propertyClass; + this.propertyClass = Optional.of(propertyClass); return this; } @@ -61,11 +61,11 @@ public Model200Response propertyClass(String propertyClass) { @ApiModelProperty(value = "") @JsonProperty("class") - public String getPropertyClass() { + public Optional getPropertyClass() { return propertyClass; } - public void setPropertyClass(String propertyClass) { + public void setPropertyClass(Optional propertyClass) { this.propertyClass = propertyClass; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelApiResponse.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelApiResponse.java index 693e1669879c..912e53baac50 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelApiResponse.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelApiResponse.java @@ -24,14 +24,14 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ModelApiResponse { - private Integer code; + private Optional code = Optional.empty(); - private String type; + private Optional type = Optional.empty(); - private String message; + private Optional message = Optional.empty(); public ModelApiResponse code(Integer code) { - this.code = code; + this.code = Optional.of(code); return this; } @@ -42,16 +42,16 @@ public ModelApiResponse code(Integer code) { @ApiModelProperty(value = "") @JsonProperty("code") - public Integer getCode() { + public Optional getCode() { return code; } - public void setCode(Integer code) { + public void setCode(Optional code) { this.code = code; } public ModelApiResponse type(String type) { - this.type = type; + this.type = Optional.of(type); return this; } @@ -62,16 +62,16 @@ public ModelApiResponse type(String type) { @ApiModelProperty(value = "") @JsonProperty("type") - public String getType() { + public Optional getType() { return type; } - public void setType(String type) { + public void setType(Optional type) { this.type = type; } public ModelApiResponse message(String message) { - this.message = message; + this.message = Optional.of(message); return this; } @@ -82,11 +82,11 @@ public ModelApiResponse message(String message) { @ApiModelProperty(value = "") @JsonProperty("message") - public String getMessage() { + public Optional getMessage() { return message; } - public void setMessage(String message) { + public void setMessage(Optional message) { this.message = message; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelList.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelList.java index 7853f3d408a0..8b6c4972d1cb 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelList.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelList.java @@ -24,10 +24,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ModelList { - private String _123list; + private Optional _123list = Optional.empty(); public ModelList _123list(String _123list) { - this._123list = _123list; + this._123list = Optional.of(_123list); return this; } @@ -38,11 +38,11 @@ public ModelList _123list(String _123list) { @ApiModelProperty(value = "") @JsonProperty("123-list") - public String get123list() { + public Optional get123list() { return _123list; } - public void set123list(String _123list) { + public void set123list(Optional _123list) { this._123list = _123list; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelReturn.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelReturn.java index b6f106cea222..56d05cff4e64 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelReturn.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ModelReturn.java @@ -25,10 +25,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ModelReturn { - private Integer _return; + private Optional _return = Optional.empty(); public ModelReturn _return(Integer _return) { - this._return = _return; + this._return = Optional.of(_return); return this; } @@ -39,11 +39,11 @@ public ModelReturn _return(Integer _return) { @ApiModelProperty(value = "") @JsonProperty("return") - public Integer getReturn() { + public Optional getReturn() { return _return; } - public void setReturn(Integer _return) { + public void setReturn(Optional _return) { this._return = _return; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Name.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Name.java index 72cdb4dbd1f8..c5b02de8b561 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Name.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Name.java @@ -25,11 +25,11 @@ public class Name { private Integer name; - private Integer snakeCase; + private Optional snakeCase = Optional.empty(); - private String property; + private Optional property = Optional.empty(); - private Integer _123number; + private Optional _123number = Optional.empty(); public Name() { super(); @@ -63,7 +63,7 @@ public void setName(Integer name) { } public Name snakeCase(Integer snakeCase) { - this.snakeCase = snakeCase; + this.snakeCase = Optional.of(snakeCase); return this; } @@ -74,16 +74,16 @@ public Name snakeCase(Integer snakeCase) { @ApiModelProperty(readOnly = true, value = "") @JsonProperty("snake_case") - public Integer getSnakeCase() { + public Optional getSnakeCase() { return snakeCase; } - public void setSnakeCase(Integer snakeCase) { + public void setSnakeCase(Optional snakeCase) { this.snakeCase = snakeCase; } public Name property(String property) { - this.property = property; + this.property = Optional.of(property); return this; } @@ -94,16 +94,16 @@ public Name property(String property) { @ApiModelProperty(value = "") @JsonProperty("property") - public String getProperty() { + public Optional getProperty() { return property; } - public void setProperty(String property) { + public void setProperty(Optional property) { this.property = property; } public Name _123number(Integer _123number) { - this._123number = _123number; + this._123number = Optional.of(_123number); return this; } @@ -114,11 +114,11 @@ public Name _123number(Integer _123number) { @ApiModelProperty(readOnly = true, value = "") @JsonProperty("123Number") - public Integer get123number() { + public Optional get123number() { return _123number; } - public void set123number(Integer _123number) { + public void set123number(Optional _123number) { this._123number = _123number; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/NumberOnly.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/NumberOnly.java index 1e3f9e15421d..72a9cb3e32b6 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/NumberOnly.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/NumberOnly.java @@ -23,10 +23,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class NumberOnly { - private BigDecimal justNumber; + private Optional justNumber = Optional.empty(); public NumberOnly justNumber(BigDecimal justNumber) { - this.justNumber = justNumber; + this.justNumber = Optional.of(justNumber); return this; } @@ -37,11 +37,11 @@ public NumberOnly justNumber(BigDecimal justNumber) { @Valid @ApiModelProperty(value = "") @JsonProperty("JustNumber") - public BigDecimal getJustNumber() { + public Optional getJustNumber() { return justNumber; } - public void setJustNumber(BigDecimal justNumber) { + public void setJustNumber(Optional justNumber) { this.justNumber = justNumber; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Order.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Order.java index b24c70c07808..4db8c1d64104 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Order.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Order.java @@ -25,14 +25,14 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Order { - private Long id; + private Optional id = Optional.empty(); - private Long petId; + private Optional petId = Optional.empty(); - private Integer quantity; + private Optional quantity = Optional.empty(); @DateTimeFormat(iso = DateTimeFormat.ISO.DATE_TIME) - private OffsetDateTime shipDate; + private Optional shipDate = Optional.empty(); /** * Order Status @@ -71,12 +71,12 @@ public static StatusEnum fromValue(String value) { } } - private StatusEnum status; + private Optional status = Optional.empty(); - private Boolean complete = false; + private Optional complete = Optional.of(false); public Order id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -87,16 +87,16 @@ public Order id(Long id) { @ApiModelProperty(value = "") @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Order petId(Long petId) { - this.petId = petId; + this.petId = Optional.of(petId); return this; } @@ -107,16 +107,16 @@ public Order petId(Long petId) { @ApiModelProperty(value = "") @JsonProperty("petId") - public Long getPetId() { + public Optional getPetId() { return petId; } - public void setPetId(Long petId) { + public void setPetId(Optional petId) { this.petId = petId; } public Order quantity(Integer quantity) { - this.quantity = quantity; + this.quantity = Optional.of(quantity); return this; } @@ -127,16 +127,16 @@ public Order quantity(Integer quantity) { @ApiModelProperty(value = "") @JsonProperty("quantity") - public Integer getQuantity() { + public Optional getQuantity() { return quantity; } - public void setQuantity(Integer quantity) { + public void setQuantity(Optional quantity) { this.quantity = quantity; } public Order shipDate(OffsetDateTime shipDate) { - this.shipDate = shipDate; + this.shipDate = Optional.of(shipDate); return this; } @@ -147,16 +147,16 @@ public Order shipDate(OffsetDateTime shipDate) { @Valid @ApiModelProperty(value = "") @JsonProperty("shipDate") - public OffsetDateTime getShipDate() { + public Optional getShipDate() { return shipDate; } - public void setShipDate(OffsetDateTime shipDate) { + public void setShipDate(Optional shipDate) { this.shipDate = shipDate; } public Order status(StatusEnum status) { - this.status = status; + this.status = Optional.of(status); return this; } @@ -167,16 +167,16 @@ public Order status(StatusEnum status) { @ApiModelProperty(value = "Order Status") @JsonProperty("status") - public StatusEnum getStatus() { + public Optional getStatus() { return status; } - public void setStatus(StatusEnum status) { + public void setStatus(Optional status) { this.status = status; } public Order complete(Boolean complete) { - this.complete = complete; + this.complete = Optional.of(complete); return this; } @@ -187,11 +187,11 @@ public Order complete(Boolean complete) { @ApiModelProperty(value = "") @JsonProperty("complete") - public Boolean getComplete() { + public Optional getComplete() { return complete; } - public void setComplete(Boolean complete) { + public void setComplete(Optional complete) { this.complete = complete; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/OuterComposite.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/OuterComposite.java index ade2b9150190..e75ef1c3c084 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/OuterComposite.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/OuterComposite.java @@ -23,14 +23,14 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class OuterComposite { - private BigDecimal myNumber; + private Optional myNumber = Optional.empty(); - private String myString; + private Optional myString = Optional.empty(); - private Boolean myBoolean; + private Optional myBoolean = Optional.empty(); public OuterComposite myNumber(BigDecimal myNumber) { - this.myNumber = myNumber; + this.myNumber = Optional.of(myNumber); return this; } @@ -41,16 +41,16 @@ public OuterComposite myNumber(BigDecimal myNumber) { @Valid @ApiModelProperty(value = "") @JsonProperty("my_number") - public BigDecimal getMyNumber() { + public Optional getMyNumber() { return myNumber; } - public void setMyNumber(BigDecimal myNumber) { + public void setMyNumber(Optional myNumber) { this.myNumber = myNumber; } public OuterComposite myString(String myString) { - this.myString = myString; + this.myString = Optional.of(myString); return this; } @@ -61,16 +61,16 @@ public OuterComposite myString(String myString) { @ApiModelProperty(value = "") @JsonProperty("my_string") - public String getMyString() { + public Optional getMyString() { return myString; } - public void setMyString(String myString) { + public void setMyString(Optional myString) { this.myString = myString; } public OuterComposite myBoolean(Boolean myBoolean) { - this.myBoolean = myBoolean; + this.myBoolean = Optional.of(myBoolean); return this; } @@ -81,11 +81,11 @@ public OuterComposite myBoolean(Boolean myBoolean) { @ApiModelProperty(value = "") @JsonProperty("my_boolean") - public Boolean getMyBoolean() { + public Optional getMyBoolean() { return myBoolean; } - public void setMyBoolean(Boolean myBoolean) { + public void setMyBoolean(Optional myBoolean) { this.myBoolean = myBoolean; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ParentWithNullable.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ParentWithNullable.java index 88477c887c25..392f917f3743 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ParentWithNullable.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ParentWithNullable.java @@ -71,12 +71,12 @@ public static TypeEnum fromValue(String value) { } } - private TypeEnum type; + private Optional type = Optional.empty(); private JsonNullable nullableProperty = JsonNullable.undefined(); public ParentWithNullable type(TypeEnum type) { - this.type = type; + this.type = Optional.of(type); return this; } @@ -87,11 +87,11 @@ public ParentWithNullable type(TypeEnum type) { @ApiModelProperty(value = "") @JsonProperty("type") - public TypeEnum getType() { + public Optional getType() { return type; } - public void setType(TypeEnum type) { + public void setType(Optional type) { this.type = type; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Pet.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Pet.java index 203d6bf1d543..4a7cd4eefcbd 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Pet.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Pet.java @@ -31,9 +31,9 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Pet { - private Long id; + private Optional id = Optional.empty(); - private Category category; + private Optional category = Optional.empty(); private String name; @@ -81,7 +81,7 @@ public static StatusEnum fromValue(String value) { } @Deprecated - private StatusEnum status; + private Optional status = Optional.empty(); public Pet() { super(); @@ -96,7 +96,7 @@ public Pet(String name, Set photoUrls) { } public Pet id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -107,16 +107,16 @@ public Pet id(Long id) { @ApiModelProperty(value = "") @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Pet category(Category category) { - this.category = category; + this.category = Optional.of(category); return this; } @@ -127,11 +127,11 @@ public Pet category(Category category) { @Valid @ApiModelProperty(value = "") @JsonProperty("category") - public Category getCategory() { + public Optional getCategory() { return category; } - public void setCategory(Category category) { + public void setCategory(Optional category) { this.category = category; } @@ -213,7 +213,7 @@ public void setTags(List<@Valid Tag> tags) { } public Pet status(StatusEnum status) { - this.status = status; + this.status = Optional.of(status); return this; } @@ -226,7 +226,7 @@ public Pet status(StatusEnum status) { @ApiModelProperty(value = "pet status in the store") @JsonProperty("status") @Deprecated - public StatusEnum getStatus() { + public Optional getStatus() { return status; } @@ -234,7 +234,7 @@ public StatusEnum getStatus() { * @deprecated */ @Deprecated - public void setStatus(StatusEnum status) { + public void setStatus(Optional status) { this.status = status; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ReadOnlyFirst.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ReadOnlyFirst.java index 3eb0ebe069c1..5c5979e73ee1 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ReadOnlyFirst.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ReadOnlyFirst.java @@ -22,12 +22,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ReadOnlyFirst { - private String bar; + private Optional bar = Optional.empty(); - private String baz; + private Optional baz = Optional.empty(); public ReadOnlyFirst bar(String bar) { - this.bar = bar; + this.bar = Optional.of(bar); return this; } @@ -38,16 +38,16 @@ public ReadOnlyFirst bar(String bar) { @ApiModelProperty(readOnly = true, value = "") @JsonProperty("bar") - public String getBar() { + public Optional getBar() { return bar; } - public void setBar(String bar) { + public void setBar(Optional bar) { this.bar = bar; } public ReadOnlyFirst baz(String baz) { - this.baz = baz; + this.baz = Optional.of(baz); return this; } @@ -58,11 +58,11 @@ public ReadOnlyFirst baz(String baz) { @ApiModelProperty(value = "") @JsonProperty("baz") - public String getBaz() { + public Optional getBaz() { return baz; } - public void setBaz(String baz) { + public void setBaz(Optional baz) { this.baz = baz; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ResponseObjectWithDifferentFieldNames.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ResponseObjectWithDifferentFieldNames.java index 187960e94e4b..9205db8e8227 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ResponseObjectWithDifferentFieldNames.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/ResponseObjectWithDifferentFieldNames.java @@ -22,16 +22,16 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class ResponseObjectWithDifferentFieldNames { - private String normalPropertyName; + private Optional normalPropertyName = Optional.empty(); - private String UPPER_CASE_PROPERTY_SNAKE; + private Optional UPPER_CASE_PROPERTY_SNAKE = Optional.empty(); - private String lowerCasePropertyDashes; + private Optional lowerCasePropertyDashes = Optional.empty(); - private String propertyNameWithSpaces; + private Optional propertyNameWithSpaces = Optional.empty(); public ResponseObjectWithDifferentFieldNames normalPropertyName(String normalPropertyName) { - this.normalPropertyName = normalPropertyName; + this.normalPropertyName = Optional.of(normalPropertyName); return this; } @@ -42,16 +42,16 @@ public ResponseObjectWithDifferentFieldNames normalPropertyName(String normalPro @ApiModelProperty(value = "") @JsonProperty("normalPropertyName") - public String getNormalPropertyName() { + public Optional getNormalPropertyName() { return normalPropertyName; } - public void setNormalPropertyName(String normalPropertyName) { + public void setNormalPropertyName(Optional normalPropertyName) { this.normalPropertyName = normalPropertyName; } public ResponseObjectWithDifferentFieldNames UPPER_CASE_PROPERTY_SNAKE(String UPPER_CASE_PROPERTY_SNAKE) { - this.UPPER_CASE_PROPERTY_SNAKE = UPPER_CASE_PROPERTY_SNAKE; + this.UPPER_CASE_PROPERTY_SNAKE = Optional.of(UPPER_CASE_PROPERTY_SNAKE); return this; } @@ -62,16 +62,16 @@ public ResponseObjectWithDifferentFieldNames UPPER_CASE_PROPERTY_SNAKE(String UP @ApiModelProperty(value = "") @JsonProperty("UPPER_CASE_PROPERTY_SNAKE") - public String getUPPERCASEPROPERTYSNAKE() { + public Optional getUPPERCASEPROPERTYSNAKE() { return UPPER_CASE_PROPERTY_SNAKE; } - public void setUPPERCASEPROPERTYSNAKE(String UPPER_CASE_PROPERTY_SNAKE) { + public void setUPPERCASEPROPERTYSNAKE(Optional UPPER_CASE_PROPERTY_SNAKE) { this.UPPER_CASE_PROPERTY_SNAKE = UPPER_CASE_PROPERTY_SNAKE; } public ResponseObjectWithDifferentFieldNames lowerCasePropertyDashes(String lowerCasePropertyDashes) { - this.lowerCasePropertyDashes = lowerCasePropertyDashes; + this.lowerCasePropertyDashes = Optional.of(lowerCasePropertyDashes); return this; } @@ -82,16 +82,16 @@ public ResponseObjectWithDifferentFieldNames lowerCasePropertyDashes(String lowe @ApiModelProperty(value = "") @JsonProperty("lower-case-property-dashes") - public String getLowerCasePropertyDashes() { + public Optional getLowerCasePropertyDashes() { return lowerCasePropertyDashes; } - public void setLowerCasePropertyDashes(String lowerCasePropertyDashes) { + public void setLowerCasePropertyDashes(Optional lowerCasePropertyDashes) { this.lowerCasePropertyDashes = lowerCasePropertyDashes; } public ResponseObjectWithDifferentFieldNames propertyNameWithSpaces(String propertyNameWithSpaces) { - this.propertyNameWithSpaces = propertyNameWithSpaces; + this.propertyNameWithSpaces = Optional.of(propertyNameWithSpaces); return this; } @@ -102,11 +102,11 @@ public ResponseObjectWithDifferentFieldNames propertyNameWithSpaces(String prope @ApiModelProperty(value = "") @JsonProperty("property name with spaces") - public String getPropertyNameWithSpaces() { + public Optional getPropertyNameWithSpaces() { return propertyNameWithSpaces; } - public void setPropertyNameWithSpaces(String propertyNameWithSpaces) { + public void setPropertyNameWithSpaces(Optional propertyNameWithSpaces) { this.propertyNameWithSpaces = propertyNameWithSpaces; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/SpecialModelName.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/SpecialModelName.java index bf67444d3cb7..3b500f2983bc 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/SpecialModelName.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/SpecialModelName.java @@ -24,10 +24,10 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class SpecialModelName { - private Long $specialPropertyName; + private Optional $specialPropertyName = Optional.empty(); public SpecialModelName $specialPropertyName(Long $specialPropertyName) { - this.$specialPropertyName = $specialPropertyName; + this.$specialPropertyName = Optional.of($specialPropertyName); return this; } @@ -38,11 +38,11 @@ public class SpecialModelName { @ApiModelProperty(value = "") @JsonProperty("$special[property.name]") - public Long get$SpecialPropertyName() { + public Optional get$SpecialPropertyName() { return $specialPropertyName; } - public void set$SpecialPropertyName(Long $specialPropertyName) { + public void set$SpecialPropertyName(Optional $specialPropertyName) { this.$specialPropertyName = $specialPropertyName; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Tag.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Tag.java index 527e777278e2..5256d11d3f8f 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Tag.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/Tag.java @@ -22,12 +22,12 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class Tag { - private Long id; + private Optional id = Optional.empty(); - private String name; + private Optional name = Optional.empty(); public Tag id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -38,16 +38,16 @@ public Tag id(Long id) { @ApiModelProperty(value = "") @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public Tag name(String name) { - this.name = name; + this.name = Optional.of(name); return this; } @@ -58,11 +58,11 @@ public Tag name(String name) { @ApiModelProperty(value = "") @JsonProperty("name") - public String getName() { + public Optional getName() { return name; } - public void setName(String name) { + public void setName(Optional name) { this.name = name; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/User.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/User.java index 36d29ba307d0..4b38c1bc4cc0 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/User.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/User.java @@ -22,24 +22,24 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class User { - private Long id; + private Optional id = Optional.empty(); - private String username; + private Optional username = Optional.empty(); - private String firstName; + private Optional firstName = Optional.empty(); - private String lastName; + private Optional lastName = Optional.empty(); - private String email; + private Optional email = Optional.empty(); - private String password; + private Optional password = Optional.empty(); - private String phone; + private Optional phone = Optional.empty(); - private Integer userStatus; + private Optional userStatus = Optional.empty(); public User id(Long id) { - this.id = id; + this.id = Optional.of(id); return this; } @@ -50,16 +50,16 @@ public User id(Long id) { @ApiModelProperty(value = "") @JsonProperty("id") - public Long getId() { + public Optional getId() { return id; } - public void setId(Long id) { + public void setId(Optional id) { this.id = id; } public User username(String username) { - this.username = username; + this.username = Optional.of(username); return this; } @@ -70,16 +70,16 @@ public User username(String username) { @ApiModelProperty(value = "") @JsonProperty("username") - public String getUsername() { + public Optional getUsername() { return username; } - public void setUsername(String username) { + public void setUsername(Optional username) { this.username = username; } public User firstName(String firstName) { - this.firstName = firstName; + this.firstName = Optional.of(firstName); return this; } @@ -90,16 +90,16 @@ public User firstName(String firstName) { @ApiModelProperty(value = "") @JsonProperty("firstName") - public String getFirstName() { + public Optional getFirstName() { return firstName; } - public void setFirstName(String firstName) { + public void setFirstName(Optional firstName) { this.firstName = firstName; } public User lastName(String lastName) { - this.lastName = lastName; + this.lastName = Optional.of(lastName); return this; } @@ -110,16 +110,16 @@ public User lastName(String lastName) { @ApiModelProperty(value = "") @JsonProperty("lastName") - public String getLastName() { + public Optional getLastName() { return lastName; } - public void setLastName(String lastName) { + public void setLastName(Optional lastName) { this.lastName = lastName; } public User email(String email) { - this.email = email; + this.email = Optional.of(email); return this; } @@ -130,16 +130,16 @@ public User email(String email) { @ApiModelProperty(value = "") @JsonProperty("email") - public String getEmail() { + public Optional getEmail() { return email; } - public void setEmail(String email) { + public void setEmail(Optional email) { this.email = email; } public User password(String password) { - this.password = password; + this.password = Optional.of(password); return this; } @@ -150,16 +150,16 @@ public User password(String password) { @ApiModelProperty(value = "") @JsonProperty("password") - public String getPassword() { + public Optional getPassword() { return password; } - public void setPassword(String password) { + public void setPassword(Optional password) { this.password = password; } public User phone(String phone) { - this.phone = phone; + this.phone = Optional.of(phone); return this; } @@ -170,16 +170,16 @@ public User phone(String phone) { @ApiModelProperty(value = "") @JsonProperty("phone") - public String getPhone() { + public Optional getPhone() { return phone; } - public void setPhone(String phone) { + public void setPhone(Optional phone) { this.phone = phone; } public User userStatus(Integer userStatus) { - this.userStatus = userStatus; + this.userStatus = Optional.of(userStatus); return this; } @@ -190,11 +190,11 @@ public User userStatus(Integer userStatus) { @ApiModelProperty(value = "User Status") @JsonProperty("userStatus") - public Integer getUserStatus() { + public Optional getUserStatus() { return userStatus; } - public void setUserStatus(Integer userStatus) { + public void setUserStatus(Optional userStatus) { this.userStatus = userStatus; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/XmlItem.java b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/XmlItem.java index 592030bb8800..a73719c8528b 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/XmlItem.java +++ b/samples/server/petstore/springboot-useoptional/src/main/java/org/openapitools/model/XmlItem.java @@ -26,24 +26,24 @@ @Generated(value = "org.openapitools.codegen.languages.SpringCodegen") public class XmlItem { - private String attributeString; + private Optional attributeString = Optional.empty(); - private BigDecimal attributeNumber; + private Optional attributeNumber = Optional.empty(); - private Integer attributeInteger; + private Optional attributeInteger = Optional.empty(); - private Boolean attributeBoolean; + private Optional attributeBoolean = Optional.empty(); @Valid private List wrappedArray; - private String nameString; + private Optional nameString = Optional.empty(); - private BigDecimal nameNumber; + private Optional nameNumber = Optional.empty(); - private Integer nameInteger; + private Optional nameInteger = Optional.empty(); - private Boolean nameBoolean; + private Optional nameBoolean = Optional.empty(); @Valid private List nameArray; @@ -51,13 +51,13 @@ public class XmlItem { @Valid private List nameWrappedArray; - private String prefixString; + private Optional prefixString = Optional.empty(); - private BigDecimal prefixNumber; + private Optional prefixNumber = Optional.empty(); - private Integer prefixInteger; + private Optional prefixInteger = Optional.empty(); - private Boolean prefixBoolean; + private Optional prefixBoolean = Optional.empty(); @Valid private List prefixArray; @@ -65,13 +65,13 @@ public class XmlItem { @Valid private List prefixWrappedArray; - private String namespaceString; + private Optional namespaceString = Optional.empty(); - private BigDecimal namespaceNumber; + private Optional namespaceNumber = Optional.empty(); - private Integer namespaceInteger; + private Optional namespaceInteger = Optional.empty(); - private Boolean namespaceBoolean; + private Optional namespaceBoolean = Optional.empty(); @Valid private List namespaceArray; @@ -79,13 +79,13 @@ public class XmlItem { @Valid private List namespaceWrappedArray; - private String prefixNsString; + private Optional prefixNsString = Optional.empty(); - private BigDecimal prefixNsNumber; + private Optional prefixNsNumber = Optional.empty(); - private Integer prefixNsInteger; + private Optional prefixNsInteger = Optional.empty(); - private Boolean prefixNsBoolean; + private Optional prefixNsBoolean = Optional.empty(); @Valid private List prefixNsArray; @@ -94,7 +94,7 @@ public class XmlItem { private List prefixNsWrappedArray; public XmlItem attributeString(String attributeString) { - this.attributeString = attributeString; + this.attributeString = Optional.of(attributeString); return this; } @@ -105,16 +105,16 @@ public XmlItem attributeString(String attributeString) { @ApiModelProperty(example = "string", value = "") @JsonProperty("attribute_string") - public String getAttributeString() { + public Optional getAttributeString() { return attributeString; } - public void setAttributeString(String attributeString) { + public void setAttributeString(Optional attributeString) { this.attributeString = attributeString; } public XmlItem attributeNumber(BigDecimal attributeNumber) { - this.attributeNumber = attributeNumber; + this.attributeNumber = Optional.of(attributeNumber); return this; } @@ -125,16 +125,16 @@ public XmlItem attributeNumber(BigDecimal attributeNumber) { @Valid @ApiModelProperty(example = "1.234", value = "") @JsonProperty("attribute_number") - public BigDecimal getAttributeNumber() { + public Optional getAttributeNumber() { return attributeNumber; } - public void setAttributeNumber(BigDecimal attributeNumber) { + public void setAttributeNumber(Optional attributeNumber) { this.attributeNumber = attributeNumber; } public XmlItem attributeInteger(Integer attributeInteger) { - this.attributeInteger = attributeInteger; + this.attributeInteger = Optional.of(attributeInteger); return this; } @@ -145,16 +145,16 @@ public XmlItem attributeInteger(Integer attributeInteger) { @ApiModelProperty(example = "-2", value = "") @JsonProperty("attribute_integer") - public Integer getAttributeInteger() { + public Optional getAttributeInteger() { return attributeInteger; } - public void setAttributeInteger(Integer attributeInteger) { + public void setAttributeInteger(Optional attributeInteger) { this.attributeInteger = attributeInteger; } public XmlItem attributeBoolean(Boolean attributeBoolean) { - this.attributeBoolean = attributeBoolean; + this.attributeBoolean = Optional.of(attributeBoolean); return this; } @@ -165,11 +165,11 @@ public XmlItem attributeBoolean(Boolean attributeBoolean) { @ApiModelProperty(example = "true", value = "") @JsonProperty("attribute_boolean") - public Boolean getAttributeBoolean() { + public Optional getAttributeBoolean() { return attributeBoolean; } - public void setAttributeBoolean(Boolean attributeBoolean) { + public void setAttributeBoolean(Optional attributeBoolean) { this.attributeBoolean = attributeBoolean; } @@ -202,7 +202,7 @@ public void setWrappedArray(List wrappedArray) { } public XmlItem nameString(String nameString) { - this.nameString = nameString; + this.nameString = Optional.of(nameString); return this; } @@ -213,16 +213,16 @@ public XmlItem nameString(String nameString) { @ApiModelProperty(example = "string", value = "") @JsonProperty("name_string") - public String getNameString() { + public Optional getNameString() { return nameString; } - public void setNameString(String nameString) { + public void setNameString(Optional nameString) { this.nameString = nameString; } public XmlItem nameNumber(BigDecimal nameNumber) { - this.nameNumber = nameNumber; + this.nameNumber = Optional.of(nameNumber); return this; } @@ -233,16 +233,16 @@ public XmlItem nameNumber(BigDecimal nameNumber) { @Valid @ApiModelProperty(example = "1.234", value = "") @JsonProperty("name_number") - public BigDecimal getNameNumber() { + public Optional getNameNumber() { return nameNumber; } - public void setNameNumber(BigDecimal nameNumber) { + public void setNameNumber(Optional nameNumber) { this.nameNumber = nameNumber; } public XmlItem nameInteger(Integer nameInteger) { - this.nameInteger = nameInteger; + this.nameInteger = Optional.of(nameInteger); return this; } @@ -253,16 +253,16 @@ public XmlItem nameInteger(Integer nameInteger) { @ApiModelProperty(example = "-2", value = "") @JsonProperty("name_integer") - public Integer getNameInteger() { + public Optional getNameInteger() { return nameInteger; } - public void setNameInteger(Integer nameInteger) { + public void setNameInteger(Optional nameInteger) { this.nameInteger = nameInteger; } public XmlItem nameBoolean(Boolean nameBoolean) { - this.nameBoolean = nameBoolean; + this.nameBoolean = Optional.of(nameBoolean); return this; } @@ -273,11 +273,11 @@ public XmlItem nameBoolean(Boolean nameBoolean) { @ApiModelProperty(example = "true", value = "") @JsonProperty("name_boolean") - public Boolean getNameBoolean() { + public Optional getNameBoolean() { return nameBoolean; } - public void setNameBoolean(Boolean nameBoolean) { + public void setNameBoolean(Optional nameBoolean) { this.nameBoolean = nameBoolean; } @@ -338,7 +338,7 @@ public void setNameWrappedArray(List nameWrappedArray) { } public XmlItem prefixString(String prefixString) { - this.prefixString = prefixString; + this.prefixString = Optional.of(prefixString); return this; } @@ -349,16 +349,16 @@ public XmlItem prefixString(String prefixString) { @ApiModelProperty(example = "string", value = "") @JsonProperty("prefix_string") - public String getPrefixString() { + public Optional getPrefixString() { return prefixString; } - public void setPrefixString(String prefixString) { + public void setPrefixString(Optional prefixString) { this.prefixString = prefixString; } public XmlItem prefixNumber(BigDecimal prefixNumber) { - this.prefixNumber = prefixNumber; + this.prefixNumber = Optional.of(prefixNumber); return this; } @@ -369,16 +369,16 @@ public XmlItem prefixNumber(BigDecimal prefixNumber) { @Valid @ApiModelProperty(example = "1.234", value = "") @JsonProperty("prefix_number") - public BigDecimal getPrefixNumber() { + public Optional getPrefixNumber() { return prefixNumber; } - public void setPrefixNumber(BigDecimal prefixNumber) { + public void setPrefixNumber(Optional prefixNumber) { this.prefixNumber = prefixNumber; } public XmlItem prefixInteger(Integer prefixInteger) { - this.prefixInteger = prefixInteger; + this.prefixInteger = Optional.of(prefixInteger); return this; } @@ -389,16 +389,16 @@ public XmlItem prefixInteger(Integer prefixInteger) { @ApiModelProperty(example = "-2", value = "") @JsonProperty("prefix_integer") - public Integer getPrefixInteger() { + public Optional getPrefixInteger() { return prefixInteger; } - public void setPrefixInteger(Integer prefixInteger) { + public void setPrefixInteger(Optional prefixInteger) { this.prefixInteger = prefixInteger; } public XmlItem prefixBoolean(Boolean prefixBoolean) { - this.prefixBoolean = prefixBoolean; + this.prefixBoolean = Optional.of(prefixBoolean); return this; } @@ -409,11 +409,11 @@ public XmlItem prefixBoolean(Boolean prefixBoolean) { @ApiModelProperty(example = "true", value = "") @JsonProperty("prefix_boolean") - public Boolean getPrefixBoolean() { + public Optional getPrefixBoolean() { return prefixBoolean; } - public void setPrefixBoolean(Boolean prefixBoolean) { + public void setPrefixBoolean(Optional prefixBoolean) { this.prefixBoolean = prefixBoolean; } @@ -474,7 +474,7 @@ public void setPrefixWrappedArray(List prefixWrappedArray) { } public XmlItem namespaceString(String namespaceString) { - this.namespaceString = namespaceString; + this.namespaceString = Optional.of(namespaceString); return this; } @@ -485,16 +485,16 @@ public XmlItem namespaceString(String namespaceString) { @ApiModelProperty(example = "string", value = "") @JsonProperty("namespace_string") - public String getNamespaceString() { + public Optional getNamespaceString() { return namespaceString; } - public void setNamespaceString(String namespaceString) { + public void setNamespaceString(Optional namespaceString) { this.namespaceString = namespaceString; } public XmlItem namespaceNumber(BigDecimal namespaceNumber) { - this.namespaceNumber = namespaceNumber; + this.namespaceNumber = Optional.of(namespaceNumber); return this; } @@ -505,16 +505,16 @@ public XmlItem namespaceNumber(BigDecimal namespaceNumber) { @Valid @ApiModelProperty(example = "1.234", value = "") @JsonProperty("namespace_number") - public BigDecimal getNamespaceNumber() { + public Optional getNamespaceNumber() { return namespaceNumber; } - public void setNamespaceNumber(BigDecimal namespaceNumber) { + public void setNamespaceNumber(Optional namespaceNumber) { this.namespaceNumber = namespaceNumber; } public XmlItem namespaceInteger(Integer namespaceInteger) { - this.namespaceInteger = namespaceInteger; + this.namespaceInteger = Optional.of(namespaceInteger); return this; } @@ -525,16 +525,16 @@ public XmlItem namespaceInteger(Integer namespaceInteger) { @ApiModelProperty(example = "-2", value = "") @JsonProperty("namespace_integer") - public Integer getNamespaceInteger() { + public Optional getNamespaceInteger() { return namespaceInteger; } - public void setNamespaceInteger(Integer namespaceInteger) { + public void setNamespaceInteger(Optional namespaceInteger) { this.namespaceInteger = namespaceInteger; } public XmlItem namespaceBoolean(Boolean namespaceBoolean) { - this.namespaceBoolean = namespaceBoolean; + this.namespaceBoolean = Optional.of(namespaceBoolean); return this; } @@ -545,11 +545,11 @@ public XmlItem namespaceBoolean(Boolean namespaceBoolean) { @ApiModelProperty(example = "true", value = "") @JsonProperty("namespace_boolean") - public Boolean getNamespaceBoolean() { + public Optional getNamespaceBoolean() { return namespaceBoolean; } - public void setNamespaceBoolean(Boolean namespaceBoolean) { + public void setNamespaceBoolean(Optional namespaceBoolean) { this.namespaceBoolean = namespaceBoolean; } @@ -610,7 +610,7 @@ public void setNamespaceWrappedArray(List namespaceWrappedArray) { } public XmlItem prefixNsString(String prefixNsString) { - this.prefixNsString = prefixNsString; + this.prefixNsString = Optional.of(prefixNsString); return this; } @@ -621,16 +621,16 @@ public XmlItem prefixNsString(String prefixNsString) { @ApiModelProperty(example = "string", value = "") @JsonProperty("prefix_ns_string") - public String getPrefixNsString() { + public Optional getPrefixNsString() { return prefixNsString; } - public void setPrefixNsString(String prefixNsString) { + public void setPrefixNsString(Optional prefixNsString) { this.prefixNsString = prefixNsString; } public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { - this.prefixNsNumber = prefixNsNumber; + this.prefixNsNumber = Optional.of(prefixNsNumber); return this; } @@ -641,16 +641,16 @@ public XmlItem prefixNsNumber(BigDecimal prefixNsNumber) { @Valid @ApiModelProperty(example = "1.234", value = "") @JsonProperty("prefix_ns_number") - public BigDecimal getPrefixNsNumber() { + public Optional getPrefixNsNumber() { return prefixNsNumber; } - public void setPrefixNsNumber(BigDecimal prefixNsNumber) { + public void setPrefixNsNumber(Optional prefixNsNumber) { this.prefixNsNumber = prefixNsNumber; } public XmlItem prefixNsInteger(Integer prefixNsInteger) { - this.prefixNsInteger = prefixNsInteger; + this.prefixNsInteger = Optional.of(prefixNsInteger); return this; } @@ -661,16 +661,16 @@ public XmlItem prefixNsInteger(Integer prefixNsInteger) { @ApiModelProperty(example = "-2", value = "") @JsonProperty("prefix_ns_integer") - public Integer getPrefixNsInteger() { + public Optional getPrefixNsInteger() { return prefixNsInteger; } - public void setPrefixNsInteger(Integer prefixNsInteger) { + public void setPrefixNsInteger(Optional prefixNsInteger) { this.prefixNsInteger = prefixNsInteger; } public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { - this.prefixNsBoolean = prefixNsBoolean; + this.prefixNsBoolean = Optional.of(prefixNsBoolean); return this; } @@ -681,11 +681,11 @@ public XmlItem prefixNsBoolean(Boolean prefixNsBoolean) { @ApiModelProperty(example = "true", value = "") @JsonProperty("prefix_ns_boolean") - public Boolean getPrefixNsBoolean() { + public Optional getPrefixNsBoolean() { return prefixNsBoolean; } - public void setPrefixNsBoolean(Boolean prefixNsBoolean) { + public void setPrefixNsBoolean(Optional prefixNsBoolean) { this.prefixNsBoolean = prefixNsBoolean; } diff --git a/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-useoptional/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot-virtualan/.openapi-generator/FILES b/samples/server/petstore/springboot-virtualan/.openapi-generator/FILES index 1f44133fbd09..629a3cc7437b 100644 --- a/samples/server/petstore/springboot-virtualan/.openapi-generator/FILES +++ b/samples/server/petstore/springboot-virtualan/.openapi-generator/FILES @@ -6,18 +6,12 @@ src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringDocConfiguration.java src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java -src/main/java/org/openapitools/virtualan/api/AnotherFakeApiController.java src/main/java/org/openapitools/virtualan/api/ApiUtil.java src/main/java/org/openapitools/virtualan/api/FakeApi.java -src/main/java/org/openapitools/virtualan/api/FakeApiController.java src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/virtualan/api/PetApi.java -src/main/java/org/openapitools/virtualan/api/PetApiController.java src/main/java/org/openapitools/virtualan/api/StoreApi.java -src/main/java/org/openapitools/virtualan/api/StoreApiController.java src/main/java/org/openapitools/virtualan/api/UserApi.java -src/main/java/org/openapitools/virtualan/api/UserApiController.java src/main/java/org/openapitools/virtualan/model/AdditionalPropertiesAnyType.java src/main/java/org/openapitools/virtualan/model/AdditionalPropertiesArray.java src/main/java/org/openapitools/virtualan/model/AdditionalPropertiesBoolean.java diff --git a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot-virtualan/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java index f9a9b237c0ad..b41ee0e9b2f0 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java index cdabe80efd83..5632f8a04c73 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java index 2671d846df9a..c3bb2ff6c7f8 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java index c19d7e98bf0e..9bc7fb99ec3b 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java index 13e89f50f204..f8016efc399d 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java index 0324a3ddfe3d..4f767ded5cc0 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -100,7 +100,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -131,7 +131,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List user + @Parameter(name = "User", description = "List of user object", required = true) @Valid @RequestBody List<@Valid User> user ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/ArrayTest.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/ArrayTest.java index 8270593e04c8..bc97c662644f 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/ArrayTest.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/ArrayTest.java @@ -32,7 +32,7 @@ public class ArrayTest { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTest arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -90,7 +90,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTest arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -110,11 +110,11 @@ public ArrayTest addArrayArrayOfModelItem(List<@Valid ReadOnlyFirst> arrayArrayO @Valid @Schema(name = "array_array_of_model", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/FormatTest.java b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/FormatTest.java index 11e1f03b3130..46de399ce273 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/FormatTest.java +++ b/samples/server/petstore/springboot-virtualan/src/main/java/org/openapitools/virtualan/model/FormatTest.java @@ -409,7 +409,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml b/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml index 3ebfb97645f2..adb3ff3f6021 100644 --- a/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml +++ b/samples/server/petstore/springboot-virtualan/src/main/resources/openapi.yaml @@ -1902,6 +1902,10 @@ components: otherProperty: type: string type: object + example: + otherProperty: otherProperty + nullableProperty: nullableProperty + type: ChildWithNullable StringBooleanMap: additionalProperties: type: boolean diff --git a/samples/server/petstore/springboot/.openapi-generator/FILES b/samples/server/petstore/springboot/.openapi-generator/FILES index 17c1e122b6b5..bee80ebd189f 100644 --- a/samples/server/petstore/springboot/.openapi-generator/FILES +++ b/samples/server/petstore/springboot/.openapi-generator/FILES @@ -3,18 +3,12 @@ pom.xml src/main/java/org/openapitools/OpenApiGeneratorApplication.java src/main/java/org/openapitools/RFC3339DateFormat.java src/main/java/org/openapitools/api/AnotherFakeApi.java -src/main/java/org/openapitools/api/AnotherFakeApiController.java src/main/java/org/openapitools/api/ApiUtil.java src/main/java/org/openapitools/api/FakeApi.java -src/main/java/org/openapitools/api/FakeApiController.java src/main/java/org/openapitools/api/FakeClassnameTestApi.java -src/main/java/org/openapitools/api/FakeClassnameTestApiController.java src/main/java/org/openapitools/api/PetApi.java -src/main/java/org/openapitools/api/PetApiController.java src/main/java/org/openapitools/api/StoreApi.java -src/main/java/org/openapitools/api/StoreApiController.java src/main/java/org/openapitools/api/UserApi.java -src/main/java/org/openapitools/api/UserApiController.java src/main/java/org/openapitools/configuration/EnumConverterConfiguration.java src/main/java/org/openapitools/configuration/HomeController.java src/main/java/org/openapitools/configuration/SpringFoxConfiguration.java diff --git a/samples/server/petstore/springboot/.openapi-generator/VERSION b/samples/server/petstore/springboot/.openapi-generator/VERSION index 40e36364ab27..fff4bdd7ab59 100644 --- a/samples/server/petstore/springboot/.openapi-generator/VERSION +++ b/samples/server/petstore/springboot/.openapi-generator/VERSION @@ -1 +1 @@ -7.1.0-SNAPSHOT \ No newline at end of file +7.3.0-SNAPSHOT \ No newline at end of file diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java index b1e1c11f7072..6ad0ca374111 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/AnotherFakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java index 770ca405dae0..f25e693b974e 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java index 8b0aaf1d7d27..80b01705ef35 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/FakeClassnameTestApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java index 323dabc8568d..09048247311e 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/PetApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java index 051ce4c42aa3..003a86e31f76 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/StoreApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java index 7d8ef02238b3..c444a38fdf2b 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/api/UserApi.java @@ -1,5 +1,5 @@ /** - * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.1.0-SNAPSHOT). + * NOTE: This class is auto generated by OpenAPI Generator (https://openapi-generator.tech) (7.3.0-SNAPSHOT). * https://openapi-generator.tech * Do not edit the class manually. */ @@ -85,7 +85,7 @@ default ResponseEntity createUser( ) default ResponseEntity createUsersWithArrayInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List userDto + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid UserDto> userDto ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); @@ -115,7 +115,7 @@ default ResponseEntity createUsersWithArrayInput( ) default ResponseEntity createUsersWithListInput( - @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List userDto + @ApiParam(value = "List of user object", required = true) @Valid @RequestBody List<@Valid UserDto> userDto ) { return new ResponseEntity<>(HttpStatus.NOT_IMPLEMENTED); diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/ArrayTestDto.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/ArrayTestDto.java index 961e58338975..38f4ccc7b193 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/ArrayTestDto.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/ArrayTestDto.java @@ -35,7 +35,7 @@ public class ArrayTestDto { private List> arrayArrayOfInteger; @Valid - private List> arrayArrayOfModel; + private List> arrayArrayOfModel; public ArrayTestDto arrayOfString(List arrayOfString) { this.arrayOfString = arrayOfString; @@ -93,7 +93,7 @@ public void setArrayArrayOfInteger(List> arrayArrayOfInteger) { this.arrayArrayOfInteger = arrayArrayOfInteger; } - public ArrayTestDto arrayArrayOfModel(List> arrayArrayOfModel) { + public ArrayTestDto arrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; return this; } @@ -113,11 +113,11 @@ public ArrayTestDto addArrayArrayOfModelItem(List<@Valid ReadOnlyFirstDto> array @Valid @ApiModelProperty(value = "") @JsonProperty("array_array_of_model") - public List> getArrayArrayOfModel() { + public List> getArrayArrayOfModel() { return arrayArrayOfModel; } - public void setArrayArrayOfModel(List> arrayArrayOfModel) { + public void setArrayArrayOfModel(List> arrayArrayOfModel) { this.arrayArrayOfModel = arrayArrayOfModel; } diff --git a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTestDto.java b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTestDto.java index c223be2f2e12..8cbfd70550f4 100644 --- a/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTestDto.java +++ b/samples/server/petstore/springboot/src/main/java/org/openapitools/model/FormatTestDto.java @@ -410,7 +410,7 @@ public String toString() { sb.append(" date: ").append(toIndentedString(date)).append("\n"); sb.append(" dateTime: ").append(toIndentedString(dateTime)).append("\n"); sb.append(" uuid: ").append(toIndentedString(uuid)).append("\n"); - sb.append(" password: ").append(toIndentedString(password)).append("\n"); + sb.append(" password: ").append("*").append("\n"); sb.append(" bigDecimal: ").append(toIndentedString(bigDecimal)).append("\n"); sb.append("}"); return sb.toString(); diff --git a/website/docusaurus.config.js b/website/docusaurus.config.js index dd0d10d703f9..1eb30346855c 100755 --- a/website/docusaurus.config.js +++ b/website/docusaurus.config.js @@ -56,8 +56,8 @@ const docusaurusConfig = { }, algolia: { - appId: 'MVE1LN4DBI', - apiKey: '3c3f7f355de15fa3f392264b2e7a5300', + appId: '51ITDG8FYN', + apiKey: '68eb9329427345f267486fd4f2d67b89', indexName: 'openapi-generator', }, diff --git a/website/i18n/en.json b/website/i18n/en.json index af769f8ec269..1599045b79f9 100644 --- a/website/i18n/en.json +++ b/website/i18n/en.json @@ -458,6 +458,10 @@ "title": "Config Options for scala-akka", "sidebar_label": "scala-akka" }, + "generators/scala-pekko": { + "title": "Config Options for scala-pekko", + "sidebar_label": "scala-pekko" + }, "generators/scala-finch": { "title": "Config Options for scala-finch", "sidebar_label": "scala-finch" diff --git a/website/src/dynamic/sponsors.yml b/website/src/dynamic/sponsors.yml index ae1de21047d7..9c6c3261be40 100644 --- a/website/src/dynamic/sponsors.yml +++ b/website/src/dynamic/sponsors.yml @@ -83,3 +83,18 @@ image: "img/companies/dmtech.jpeg" infoLink: "https://www.dm-jobs.com/" bronze: true +- + caption: "Adyen" + image: "img/companies/adyen.png" + infoLink: "https://adyen.com/" + bronze: true +- + caption: "Fornex" + image: "img/companies/fornex.png" + infoLink: "https://fornex.com/" + bronze: true +- + caption: "Alloy Automation" + image: "img/companies/alloyautomation.png" + infoLink: "https://runalloy.com/signup?utm_source=github&utm_medium=referral&utm_campaign=1524_openapigenerator" + bronze: true diff --git a/website/src/dynamic/users.yml b/website/src/dynamic/users.yml index ccf60cbb81b9..4e22ea2f4e54 100644 --- a/website/src/dynamic/users.yml +++ b/website/src/dynamic/users.yml @@ -403,6 +403,11 @@ image: "img/companies/paxos.png" infoLink: "https://www.paxos.com/" pinned: false +- + caption: "Passgenau Digital" + image: "img/companies/passgenau_digital.svg" + infoLink: "https://passgenau.digital/en" + pinned: false - caption: "PLAID, Inc." image: "img/companies/plaidcojp.jpg" @@ -478,6 +483,11 @@ image: "img/companies/rest-united.png" infoLink: "https://restunited.com/" pinned: false +- + caption: Robocorp + image: "img/companies/robocorp.svg" + infoLink: "https://www.robocorp.com" + pinned: false - caption: "Shotstack" image: "img/companies/shotstack.svg" @@ -593,6 +603,11 @@ image: "img/companies/wbt_solutions.png" infoLink: "https://www.wbt-solutions.de/" pinned: false +- + caption: we-make.ai + image: "img/companies/wemakeai.svg" + infoLink: "https://we-make.ai/" + pinned: false - caption: Woleet image: "img/companies/woleet.png" diff --git a/website/static/img/companies/adyen.png b/website/static/img/companies/adyen.png index 1c150e2220d1..db03b791f230 100644 Binary files a/website/static/img/companies/adyen.png and b/website/static/img/companies/adyen.png differ diff --git a/website/static/img/companies/alloyautomation.png b/website/static/img/companies/alloyautomation.png new file mode 100644 index 000000000000..a3ea81aaf3b1 Binary files /dev/null and b/website/static/img/companies/alloyautomation.png differ diff --git a/website/static/img/companies/fornex.png b/website/static/img/companies/fornex.png new file mode 100644 index 000000000000..c4cde1c8bd36 Binary files /dev/null and b/website/static/img/companies/fornex.png differ diff --git a/website/static/img/companies/passgenau_digital.svg b/website/static/img/companies/passgenau_digital.svg new file mode 100644 index 000000000000..3172afece0f3 --- /dev/null +++ b/website/static/img/companies/passgenau_digital.svg @@ -0,0 +1,113 @@ + + + + diff --git a/website/static/img/companies/robocorp.svg b/website/static/img/companies/robocorp.svg new file mode 100644 index 000000000000..98798ed78057 --- /dev/null +++ b/website/static/img/companies/robocorp.svg @@ -0,0 +1,68 @@ + + + + + + + + + + + + + + + + + + + + + diff --git a/website/static/img/companies/wemakeai.svg b/website/static/img/companies/wemakeai.svg new file mode 100644 index 000000000000..c3e28e969be8 --- /dev/null +++ b/website/static/img/companies/wemakeai.svg @@ -0,0 +1,69 @@ + +image/svg+xml \ No newline at end of file diff --git a/website/yarn.lock b/website/yarn.lock index 4d6f77f9d2fa..4af573fcc54f 100644 --- a/website/yarn.lock +++ b/website/yarn.lock @@ -3889,9 +3889,9 @@ flux@^4.0.1: fbjs "^3.0.1" follow-redirects@^1.0.0, follow-redirects@^1.14.7: - version "1.15.2" - resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.2.tgz#b460864144ba63f2681096f274c4e57026da2c13" - integrity sha512-VQLG33o04KaQ8uYi2tVNbdrWp1QWxNNea+nmIB4EVM28v0hmP17z7aG1+wAkNzVq4KeXTq3221ye5qTJP91JwA== + version "1.15.4" + resolved "https://registry.yarnpkg.com/follow-redirects/-/follow-redirects-1.15.4.tgz#cdc7d308bf6493126b17ea2191ea0ccf3e535adf" + integrity sha512-Cr4D/5wlrb0z9dgERpUL3LrmPKVDsETIJhaCMeDfuFYcqa5bldGV6wBsAN6X/vxlXQtFBMrXdXxdL8CbDTGniw== fork-ts-checker-webpack-plugin@^6.5.0: version "6.5.2"